Skip to content

Commit

Permalink
feat(dates): Added dateISO and dateJSON decoders
Browse files Browse the repository at this point in the history
  • Loading branch information
kofno committed Dec 9, 2020
1 parent cbf22df commit 685744c
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 39 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
"dependencies": {
"maybeasy": "^2.6.0",
"resulty": "^3.0.0",
"weakset": "^1.0.0"
"weakset": "^1.0.0",
"date-fns": "^2.16.1"
},
"peerDependencies": {
"maybeasy": "^2.6.0",
Expand Down
5 changes: 2 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# jsonous

[![Build Status](https://travis-ci.org/kofno/jsonous.svg?branch=master)](https://travis-ci.org/kofno/jsonous)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)

If you're building a web application, you're eventually going to need a reliable
Expand Down Expand Up @@ -73,8 +72,8 @@ Of course, your code editor may try to reformat this code.

```typescript
field('userId', number)
.andThen(id =>
field('emailAddress', string).andThen(email => succeed({ id, email }))
.andThen((id) =>
field('emailAddress', string).andThen((email) => succeed({ id, email }))
)
.decodeAny({ userId: 213, emailAddress: '[email protected]' });
// --> Ok({ id: 213, email: '[email protected]'})
Expand Down
47 changes: 46 additions & 1 deletion src/Decoder.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isValid, parseISO, parseJSON } from 'date-fns';
import { just, Maybe, nothing } from 'maybeasy';
import { err, Err, ok, Result } from 'resulty';
import { stringify } from './Internal/ErrorStringify';
Expand Down Expand Up @@ -196,6 +197,9 @@ export const boolean: Decoder<boolean> = new Decoder<boolean>((value) => {
*
* Date decoder expects a value that is a number or a string. It will then try
* to construct a JavaScript date object from the value.
*
* This decoder use the Date constructor, and so assumes the same cross browser
* inconsistencies.
*/
export const date: Decoder<Date> = new Decoder<Date>((value) => {
const errMsg = (v: any): string =>
Expand All @@ -207,6 +211,47 @@ export const date: Decoder<Date> = new Decoder<Date>((value) => {
.mapError(() => errMsg(value));
});

/**
* Date ISO decoder
*
* The Date ISO decoder expects a value that is a string formatted in some
* variation of ISO 8601. It will fail if the date is invalid or is not a
* recognized ISO 8601 format.
*
* Relies on parseISO from date-fns
* https://date-fns.org/v2.16.1/docs/parseISO
*/
export const dateISO: Decoder<Date> = new Decoder<Date>((value) => {
return ok<string, unknown>(value)
.andThen((v) => string.decodeAny(v))
.map(parseISO)
.andThen((d) =>
isValid(d)
? ok(d)
: err(`I expected an ISO date but instead I found ${stringify(value)}`)
);
});

/**
* Date JSON decoder
*
* This decoder parses date formats common in JSON APIs
*
* See parseJSON from date-fns for more information on supported formats
* https://date-fns.org/v2.16.1/docs/parseJSON
*
*/
export const dateJSON: Decoder<Date> = new Decoder<Date>((value) => {
return ok<string, unknown>(value)
.andThen((v) => string.decodeAny(v))
.map(parseJSON)
.andThen((d) =>
isValid(d)
? ok(d)
: err(`I expected an JSON date but instead I found ${stringify(value)}`)
);
});

/**
* Applies the `decoder` to all of the elements of an array.
*/
Expand All @@ -216,7 +261,7 @@ export const array = <A>(decoder: Decoder<A>): Decoder<A[]> =>
const errorMsg = `I expected an array but instead I found ${stringify(
value
)}`;
return err(errorMsg) as Result<string, A[]>;
return err(errorMsg);
}

let result: Result<string, A[]> = ok([]);
Expand Down
30 changes: 30 additions & 0 deletions tests/Decoder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {
at,
boolean,
date,
dateISO,
dateJSON,
dict,
field,
keyValuePairs,
Expand Down Expand Up @@ -76,6 +78,34 @@ test('date decoder', (t) => {
t.end();
});

test('dateISO decoder', (t) => {
dateISO.decodeAny('2020-12-25').cata({
Err: (m) => t.fail(`date iso decoder should have passed: ${m}`),
Ok: (v) => t.pass(`date iso decoder worked on ${v}`),
});

dateISO.decodeAny('2020-12-32').cata({
Err: (m) => t.pass(`date iso decoder failed as expected: ${m}`),
Ok: (v) => t.fail(`date iso decoder should have failed: ${v}`),
});

t.end();
});

test('dateJSON decoder', (t) => {
dateJSON.decodeAny('2020-12-25T05:20:10.123Z').cata({
Err: (m) => t.fail(`date iso decoder should have passed: ${m}`),
Ok: (v) => t.pass(`date iso decoder worked on ${v}`),
});

dateJSON.decodeAny('2020-12-25').cata({
Err: (m) => t.pass(`date iso decoder failed as expected: ${m}`),
Ok: (v) => t.fail(`date iso decoder should have failed: ${v}`),
});

t.end();
});

test('array decoder', (t) => {
array(string)
.decodeJson('["foo", "bar", "baz"]')
Expand Down
41 changes: 7 additions & 34 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1020,6 +1020,11 @@ dashdash@^1.12.0:
dependencies:
assert-plus "^1.0.0"

date-fns@^2.16.1:
version "2.16.1"
resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.16.1.tgz#05775792c3f3331da812af253e1a935851d3834b"
integrity sha512-sAJVKx/FqrLYHAQeN7VpJrPhagZc9R4ImZIWYRFZaaohR3KzmuK88touwsSwSVT8Qcbd4zoDsnGfX4GFB4imyQ==

dateformat@^3.0.0:
version "3.0.3"
resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae"
Expand All @@ -1046,7 +1051,7 @@ debug@^3.1.0:
dependencies:
ms "^2.1.1"

debuglog@*, debuglog@^1.0.1:
debuglog@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/debuglog/-/debuglog-1.0.1.tgz#aa24ffb9ac3df9a2351837cfb2d279360cd78492"
integrity sha1-qiT/uaw9+aI1GDfPstJ5NgzXhJI=
Expand Down Expand Up @@ -1983,7 +1988,7 @@ import-lazy@^2.1.0:
resolved "https://registry.yarnpkg.com/import-lazy/-/import-lazy-2.1.0.tgz#05698e3d45c88e8d7e9d92cb0584e77f096f3e43"
integrity sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=

imurmurhash@*, imurmurhash@^0.1.4:
imurmurhash@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
integrity sha1-khi5srkoojixPcT7a21XbyMUU+o=
Expand Down Expand Up @@ -2624,11 +2629,6 @@ lockfile@^1.0.4:
dependencies:
signal-exit "^3.0.2"

lodash._baseindexof@*:
version "3.1.0"
resolved "https://registry.yarnpkg.com/lodash._baseindexof/-/lodash._baseindexof-3.1.0.tgz#fe52b53a1c6761e42618d654e4a25789ed61822c"
integrity sha1-/lK1OhxnYeQmGNZU5KJXie1hgiw=

lodash._baseuniq@~4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/lodash._baseuniq/-/lodash._baseuniq-4.6.0.tgz#0ebb44e456814af7905c6212fa2c9b2d51b841e8"
Expand All @@ -2637,33 +2637,11 @@ lodash._baseuniq@~4.6.0:
lodash._createset "~4.0.0"
lodash._root "~3.0.0"

lodash._bindcallback@*:
version "3.0.1"
resolved "https://registry.yarnpkg.com/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz#e531c27644cf8b57a99e17ed95b35c748789392e"
integrity sha1-5THCdkTPi1epnhftlbNcdIeJOS4=

lodash._cacheindexof@*:
version "3.0.2"
resolved "https://registry.yarnpkg.com/lodash._cacheindexof/-/lodash._cacheindexof-3.0.2.tgz#3dc69ac82498d2ee5e3ce56091bafd2adc7bde92"
integrity sha1-PcaayCSY0u5ePOVgkbr9Ktx73pI=

lodash._createcache@*:
version "3.1.2"
resolved "https://registry.yarnpkg.com/lodash._createcache/-/lodash._createcache-3.1.2.tgz#56d6a064017625e79ebca6b8018e17440bdcf093"
integrity sha1-VtagZAF2JeeevKa4AY4XRAvc8JM=
dependencies:
lodash._getnative "^3.0.0"

lodash._createset@~4.0.0:
version "4.0.3"
resolved "https://registry.yarnpkg.com/lodash._createset/-/lodash._createset-4.0.3.tgz#0f4659fbb09d75194fa9e2b88a6644d363c9fe26"
integrity sha1-D0ZZ+7CddRlPqeK4imZE02PJ/iY=

lodash._getnative@*, lodash._getnative@^3.0.0:
version "3.9.1"
resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5"
integrity sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=

lodash._root@~3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692"
Expand Down Expand Up @@ -2699,11 +2677,6 @@ lodash.isstring@^4.0.1:
resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451"
integrity sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=

lodash.restparam@*:
version "3.6.1"
resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805"
integrity sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=

lodash.toarray@^4.4.0:
version "4.4.0"
resolved "https://registry.yarnpkg.com/lodash.toarray/-/lodash.toarray-4.4.0.tgz#24c4bfcd6b2fba38bfd0594db1179d8e9b656561"
Expand Down

0 comments on commit 685744c

Please sign in to comment.