Skip to content

Commit

Permalink
feat(primitives): implement code type
Browse files Browse the repository at this point in the history
  • Loading branch information
tangdrew committed Jan 21, 2019
1 parent 7daccfe commit f4b3ccd
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/primitives/src/code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Code FHIR Primitive Runtime Type
*/

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

// TODO: This regex seems incorrect as well
const CODE_REGEX = /[^\s]+(\s[^\s]+)*/;

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

export const code = new CodeType();
3 changes: 3 additions & 0 deletions packages/primitives/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import { Base64BinaryType, base64binary } from "./base64binary";
import { BooleanType, boolean } from "./boolean";
import { CanonicalType, canonical } from "./canonical";
import { CodeType, code } from "./code";
import { DateType, date } from "./date";
import { DecimalType, decimal } from "./decimal";
import { InstantType, instant } from "./instant";
Expand All @@ -21,6 +22,8 @@ export {
BooleanType,
canonical,
CanonicalType,
code,
CodeType,
date,
DateType,
decimal,
Expand Down
39 changes: 39 additions & 0 deletions packages/primitives/test/code.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Tests for Code Runtime Type
*/

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

describe("CodeType", () => {
it("should succeed validating a valid value", () => {
const T = code;
assertSuccess(T.decode("55423-8"));
});

it("should return the same reference if validation succeeded and nothing changed", () => {
const T = code;
const value = "55423-8";
assertStrictEqual(T.decode(value), value);
});

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

// TODO: Improve regex so this fails
xit("should fail validating a string with invalid characters", () => {
const T = code;
assertFailure(T.decode("invalid\tcode"), [
'Invalid value "invalid\tcode" supplied to : code'
]);
});

it("should type guard", () => {
const T = code;
expect(T.is("55423-8")).toEqual(true);
expect(T.is(true)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit f4b3ccd

Please sign in to comment.