Skip to content

Commit

Permalink
fix(at): at decoder handles undefined values gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
kofno committed Jun 26, 2019
1 parent a02c6dd commit 051996c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 17 deletions.
9 changes: 7 additions & 2 deletions src/Decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,9 @@ export const array = <A>(decoder: Decoder<A>): Decoder<A[]> =>
}

return value.reduce((memo: Result<string, A[]>, element, idx) => {
const result = decoder.decodeAny(element);
return memo.andThen(results => {
return result
return decoder
.decodeAny(element)
.mapError(s => `I found an error in the array at [${idx}]: ${s}`)
.map(v => results.concat([v]));
});
Expand Down Expand Up @@ -260,6 +260,11 @@ export const at = <A>(
decoder: Decoder<A>
): Decoder<A> =>
new Decoder<A>(value => {
if (value == null) {
return err(
`I found an error. Could not apply 'at' path to an undefined or null value.`
);
}
let val = value;
let idx = 0;
while (idx < path.length) {
Expand Down
23 changes: 8 additions & 15 deletions tests/Decoder.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,5 @@
import * as test from 'tape';
import {
array,
at,
boolean,
date,
dict,
field,
keyValuePairs,
maybe,
nullable,
number,
oneOf,
string,
succeed,
} from '../src/index';
import { array, at, boolean, date, dict, field, keyValuePairs, maybe, nullable, number, oneOf, string, succeed } from '../src/index';

test('string decoder', t => {
string.decodeJson('"foo"').cata({
Expand Down Expand Up @@ -148,6 +134,13 @@ test('at decoder', t => {
Ok: v => t.pass(`at is compatible with nullable`),
});

at(['foo', 0, 'bar'], number)
.decodeAny(undefined)
.cata({
Err: () => t.pass(`at-ing an undefined to should be an error, but not crash`),
Ok: () => t.fail(`at-ing an undefined should not pass`),
});

t.end();
});

Expand Down

0 comments on commit 051996c

Please # to comment.