Skip to content

Commit

Permalink
feat(primitives): implement oid type
Browse files Browse the repository at this point in the history
  • Loading branch information
tangdrew committed Jan 21, 2019
1 parent f4b3ccd commit 72bc500
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/primitives/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { DateType, date } from "./date";
import { DecimalType, decimal } from "./decimal";
import { InstantType, instant } from "./instant";
import { IntegerType, integer } from "./integer";
import { OIDType, oid } from "./oid";
import { StringType, string } from "./string";
import { TimeType, time } from "./time";
import { URIType, uri } from "./uri";
Expand All @@ -32,6 +33,8 @@ export {
InstantType,
integer,
IntegerType,
oid,
OIDType,
string,
StringType,
time,
Expand Down
22 changes: 22 additions & 0 deletions packages/primitives/src/oid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* OID FHIR Primitive Runtime Type
*/

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

const OID_REGEX = /urn:oid:[0-2](\.(0|[1-9][0-9]*))+/;

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

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

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

describe("OIDType", () => {
it("should succeed validating a valid value", () => {
const T = oid;
const input = "urn:oid:1.2.3.4.5";
assertSuccess(T.decode(input));
});

it("should return the same reference if validation succeeded and nothing changed", () => {
const T = oid;
const value = "urn:oid:1.2.3.4.5";
assertStrictEqual(T.decode(value), value);
});

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

it("should fail validating a string that doesn't match regex", () => {
const T = oid;
assertFailure(T.decode("https://www.hl7.org/fhir/datatypes.html"), [
'Invalid value "https://www.hl7.org/fhir/datatypes.html" supplied to : oid'
]);
});

it("should type guard", () => {
const T = oid;
expect(T.is("urn:oid:1.2.3.4.5")).toEqual(true);
expect(T.is(2)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit 72bc500

Please sign in to comment.