Skip to content

Commit

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

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

const BASE64_BINARY_REGEX = /(\s*([0-9a-zA-Z\+\=]){4}\s*)+/;

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

export const base64binary = new Base64BinaryType();
3 changes: 3 additions & 0 deletions packages/primitives/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

import { BooleanType, boolean } from "./boolean";
import { Base64BinaryType, base64binary } from "./base64binary";
import { CanonicalType, canonical } from "./canonical";
import { DecimalType, decimal } from "./decimal";
import { IntegerType, integer } from "./integer";
Expand All @@ -11,6 +12,8 @@ import { URIType, uri } from "./uri";
import { URLType, url } from "./url";

export {
base64binary,
Base64BinaryType,
boolean,
BooleanType,
canonical,
Expand Down
38 changes: 38 additions & 0 deletions packages/primitives/test/base64binary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Tests for Base64Binary Runtime Type
*/

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

describe("Base64BinaryType", () => {
it("should succeed validating a valid value", () => {
const T = base64binary;
assertSuccess(T.decode("aGVsbG8gd29ybGQ="));
});

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

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

it("should fail validating a string with invalid characters", () => {
const T = base64binary;
assertFailure(T.decode("\0"), [
'Invalid value "\\u0000" supplied to : base64binary'
]);
});

it("should type guard", () => {
const T = base64binary;
expect(T.is("aGVsbG8gd29ybGQ=")).toEqual(true);
expect(T.is(true)).toEqual(false);
expect(T.is(undefined)).toEqual(false);
});
});

0 comments on commit 95ffb77

Please sign in to comment.