Skip to content

Commit

Permalink
feat(primitives): implement time type
Browse files Browse the repository at this point in the history
  • Loading branch information
tangdrew committed Jan 21, 2019
1 parent 93835ce commit 7daccfe
Show file tree
Hide file tree
Showing 3 changed files with 62 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 { DecimalType, decimal } from "./decimal";
import { InstantType, instant } from "./instant";
import { IntegerType, integer } from "./integer";
import { StringType, string } from "./string";
import { TimeType, time } from "./time";
import { URIType, uri } from "./uri";
import { URLType, url } from "./url";

Expand All @@ -30,6 +31,8 @@ export {
IntegerType,
string,
StringType,
time,
TimeType,
uri,
URIType,
url,
Expand Down
21 changes: 21 additions & 0 deletions packages/primitives/src/time.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Time FHIR Primitive Runtime Type
*/

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

const TIME_REGEX = /([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\.[0-9]+)?/;

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

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

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

describe("TimeType", () => {
it("should succeed validating a valid value", () => {
const T = time;
assertSuccess(T.decode("11:48:22"));
});

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

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

it("should fail validating non hh:mm:ss formatted time", () => {
const T = time;
assertFailure(T.decode("24:00"), [
'Invalid value "24:00" supplied to : time'
]);
});

it("should type guard", () => {
const T = time;
expect(T.is("11:48:22")).toEqual(true);
expect(T.is(true)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit 7daccfe

Please sign in to comment.