Skip to content

Commit

Permalink
feat(primitives): implement uri type
Browse files Browse the repository at this point in the history
  • Loading branch information
tangdrew committed Jan 21, 2019
1 parent 06636a6 commit 5bc26ce
Show file tree
Hide file tree
Showing 3 changed files with 57 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 @@ -6,6 +6,7 @@ import { BooleanType, boolean } from "./boolean";
import { DecimalType, decimal } from "./decimal";
import { IntegerType, integer } from "./integer";
import { StringType, string } from "./string";
import { URIType, uri } from "./uri";

export {
boolean,
Expand All @@ -15,5 +16,7 @@ export {
integer,
IntegerType,
string,
StringType
StringType,
uri,
URIType
};
21 changes: 21 additions & 0 deletions packages/primitives/src/uri.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* URI FHIR Primitive Runtime Type
*/

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

const URI_REGEX = /\S*/;

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

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

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

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

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

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

it("should type guard", () => {
const T = uri;
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 5bc26ce

Please sign in to comment.