diff --git a/packages/primitives/src/canonical.ts b/packages/primitives/src/canonical.ts new file mode 100644 index 0000000..e113efd --- /dev/null +++ b/packages/primitives/src/canonical.ts @@ -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 { + 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(); diff --git a/packages/primitives/src/index.ts b/packages/primitives/src/index.ts index d9d8adb..4b48ddf 100644 --- a/packages/primitives/src/index.ts +++ b/packages/primitives/src/index.ts @@ -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"; @@ -12,6 +13,8 @@ import { URLType, url } from "./url"; export { boolean, BooleanType, + canonical, + CanonicalType, decimal, DecimalType, integer, diff --git a/packages/primitives/test/canonical.test.ts b/packages/primitives/test/canonical.test.ts new file mode 100644 index 0000000..1542ee8 --- /dev/null +++ b/packages/primitives/test/canonical.test.ts @@ -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); + }); +});