Skip to content

Commit

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

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

// TODO: This regex seems too permissive
const DATE_REGEX = /([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2][0-9]|3[0-1]))?)?/;

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

export const date = new DateType();
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 { DateType, date } from "./date";
import { DecimalType, decimal } from "./decimal";
import { InstantType, instant } from "./instant";
import { IntegerType, integer } from "./integer";
Expand All @@ -19,6 +20,8 @@ export {
BooleanType,
canonical,
CanonicalType,
date,
DateType,
decimal,
DecimalType,
instant,
Expand Down
38 changes: 38 additions & 0 deletions packages/primitives/test/date.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Tests for Date Runtime Type
*/

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

describe("DateType", () => {
it("should succeed validating a valid value", () => {
const T = date;
assertSuccess(T.decode("1905-08-23"));
});

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

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

it("should fail validating non YYYY, YYYY-MM, or YYYY-MM-DD formatted date", () => {
const T = date;
assertFailure(T.decode("08/23"), [
'Invalid value "08/23" supplied to : date'
]);
});

it("should type guard", () => {
const T = date;
expect(T.is("1905-08-23")).toEqual(true);
expect(T.is(true)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit 93835ce

Please sign in to comment.