Skip to content

Commit

Permalink
Merge pull request #30 from vankeisb/feature/fix-value-decoder
Browse files Browse the repository at this point in the history
fix decoder for any value
  • Loading branch information
vankeisb authored Oct 19, 2020
2 parents 2d1233d + e82ecf0 commit ac5a7c2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
32 changes: 32 additions & 0 deletions core/src/TeaCup/Decode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,35 @@ test('oneOf', () => {
test('from string', () => {
expect(num.decodeString('123')).toEqual(ok(123));
});

test('any value', () => {
const anyValue = { foo: 'bar' };
expect(Decode.value.decodeValue(anyValue)).toEqual(ok(anyValue));
});

describe('optional field', () => {
test("is present", () => {
const value = { foo: 'bar', gnu: 13 };
expect(Decode.optionalField('gnu', Decode.num).decodeValue(value)).toEqual(ok(13));
})
test("is missing", () => {
const value = { foo: 'bar' };
expect(Decode.optionalField('gnu', Decode.num).decodeValue(value)).toEqual(ok(undefined));
})

test("typical use case", () => {
type MyType = {
foo: string;
gnu?: number;
}
const value = { foo: 'bar' };
const expected: MyType = {
foo: 'bar'
};
expect(Decode.map2(
(foo, gnu) => { return { foo, gnu } },
Decode.field('foo', Decode.str),
Decode.optionalField('gnu', Decode.num)).decodeValue(value)
).toEqual(ok(expected));
})
});
14 changes: 13 additions & 1 deletion core/src/TeaCup/Decode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,18 @@ export class Decode {
return Decode.at([key], d);
}

/**
* Decoder for optinal object fields
* @param key the name of the optinal field
* @param d the decoder for the field's value
*/
static optionalField<T>(key: string, d: Decoder<T>): Decoder<T | undefined> {
return Decode.andThen(
(value) => value.map<Decoder<T | undefined>>(v => new Decoder<T>(() => d.decodeValue(v))).withDefault(Decode.succeed(undefined)),
Decode.maybe(Decode.field(key, Decode.value))
);
}

/**
* Decoder for navigable object properties
* @param keys a list of fields to navigate
Expand Down Expand Up @@ -439,7 +451,7 @@ export class Decode {
/**
* Decoder for any value
*/
static value: Decoder<any> = new Decoder<any>((o) => o);
static value: Decoder<any> = new Decoder<any>((o) => ok(o));

/**
* Decoder for null
Expand Down

0 comments on commit ac5a7c2

Please sign in to comment.