Skip to content

Commit

Permalink
feat(primitives): implement canonical type
Browse files Browse the repository at this point in the history
  • Loading branch information
tangdrew committed Jan 21, 2019
1 parent 461f587 commit 789c301
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/primitives/src/canonical.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Canonical URL FHIR Primitive Runtime Type
*/

import { uri } from "./uri";
import { Type, success, failure, identity } from "io-ts";

export class CanonicalType extends Type<string> {
readonly _tag: "CanonicalType" = "CanonicalType";
constructor() {
super(
"canonical",
uri.is,
(m, c) => (this.is(m) ? success(m) : failure(m, c)),
identity
);
}
}

export const canonical = new CanonicalType();
3 changes: 3 additions & 0 deletions packages/primitives/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

import { BooleanType, boolean } from "./boolean";
import { CanonicalType, canonical } from "./canonical";
import { DecimalType, decimal } from "./decimal";
import { IntegerType, integer } from "./integer";
import { StringType, string } from "./string";
Expand All @@ -12,6 +13,8 @@ import { URLType, url } from "./url";
export {
boolean,
BooleanType,
canonical,
CanonicalType,
decimal,
DecimalType,
integer,
Expand Down
32 changes: 32 additions & 0 deletions packages/primitives/test/canonical.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Tests for Canonical URL Runtime Type
*/

import { assertSuccess, assertFailure, assertStrictEqual } from "./helpers";
import { canonical } from "../src";

describe("CanonicalType", () => {
it("should succeed validating a valid value", () => {
const T = canonical;
const input = "http://snomed.info/sct";
assertSuccess(T.decode(input));
});

it("should return the same reference if validation succeeded and nothing changed", () => {
const T = canonical;
const value = "http://snomed.info/sct";
assertStrictEqual(T.decode(value), value);
});

it("should fail validating an invalid value", () => {
const T = canonical;
assertFailure(T.decode(2), ["Invalid value 2 supplied to : canonical"]);
});

it("should type guard", () => {
const T = canonical;
expect(T.is("http://snomed.info/sct")).toEqual(true);
expect(T.is(2)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit 789c301

Please sign in to comment.