Skip to content

Commit

Permalink
feat(primitives): implement uuid type
Browse files Browse the repository at this point in the history
  • Loading branch information
tangdrew committed Jan 21, 2019
1 parent b4e3714 commit 5012a20
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/primitives/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { TimeType, time } from "./time";
import { UnsignedIntegerType, unsignedInt } from "./unsignedInt";
import { URIType, uri } from "./uri";
import { URLType, url } from "./url";
import { UUIDType, uuid } from "./uuid";

export {
base64binary,
Expand Down Expand Up @@ -54,5 +55,7 @@ export {
uri,
URIType,
url,
URLType
URLType,
uuid,
UUIDType
};
20 changes: 20 additions & 0 deletions packages/primitives/src/uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* UUID FHIR Primitive Runtime Type
*/

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

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

export const uuid = new UUIDType();
32 changes: 32 additions & 0 deletions packages/primitives/test/uuid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Tests for UUID Runtime Type
*/

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

describe("UUIDType", () => {
it("should succeed validating a valid value", () => {
const T = uuid;
const input = "urn:uuid:c757873d-ec9a-4326-a141-556f43239520";
assertSuccess(T.decode(input));
});

it("should return the same reference if validation succeeded and nothing changed", () => {
const T = uuid;
const value = "urn:uuid:c757873d-ec9a-4326-a141-556f43239520";
assertStrictEqual(T.decode(value), value);
});

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

it("should type guard", () => {
const T = uuid;
expect(T.is("urn:uuid:c757873d-ec9a-4326-a141-556f43239520")).toEqual(true);
expect(T.is(2)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit 5012a20

Please sign in to comment.