Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Expose format errors functions #33

Merged
merged 2 commits into from
Jun 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,36 @@ yarn add io-ts-reporters

## Example

See [the tests](./tests/index.test.ts).
```ts
import * as t from 'io-ts';
import reporter, { formatValidationErrors } from 'io-ts-reporters';
import * as E from 'fp-ts/lib/Either';

const User = t.interface({ name: t.string });

// When decoding fails, the errors are reported
reporter.report(User.decode({ nam: 'Jane' }));
//=> ['Expecting string at name but instead got: undefined']

// Nothing gets reported on success
reporter.report(User.decode({ name: 'Jane' }));
//=> []
```

If you want to report the errors on the `Left` only use `formatValidationErrors` instead.

```ts
import * as t from 'io-ts';
import { formatValidationErrors } from 'io-ts-reporters';
import * as E from 'fp-ts/lib/Either';
import { pipe } from 'fp-ts/lib/pipeable';

const User = t.interface({ name: t.string });

pipe({ nam: 'Jane' }, User.decode, E.mapLeft(formatValidationErrors));
```

For more examples see [the tests](./tests/index.test.ts).

## Testing

Expand All @@ -31,3 +60,7 @@ yarn run test
```

[io-ts]: https://github.com/gcanti/io-ts#error-reporters

## Credits

This library was created by [OliverJAsh](https://github.com/OliverJAsh).
37 changes: 27 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as O from 'fp-ts/lib/Option';
import * as R from 'fp-ts/lib/Record';
import { pipe } from 'fp-ts/lib/pipeable';
import * as t from 'io-ts';
import { Reporter } from 'io-ts/lib/Reporter';

import { takeUntil } from './utils';

Expand Down Expand Up @@ -94,7 +95,7 @@ const formatValidationErrorOfUnion = (
: O.none;
};

const formatValidationError = (path: string, error: t.ValidationError) =>
const formatValidationCommonError = (path: string, error: t.ValidationError) =>
pipe(
error,
getErrorFromCtx,
Expand All @@ -103,25 +104,41 @@ const formatValidationError = (path: string, error: t.ValidationError) =>
)
);

const groupByKey = NEA.groupBy((error: t.ValidationError) =>
pipe(error.context, takeUntil(isUnionType), keyPath)
);

const format = (path: string, errors: NEA.NonEmptyArray<t.ValidationError>) =>
NEA.tail(errors).length > 0
? formatValidationErrorOfUnion(path, errors)
: formatValidationError(path, NEA.head(errors));
: formatValidationCommonError(path, NEA.head(errors));

const groupByKey = NEA.groupBy((error: t.ValidationError) =>
pipe(error.context, takeUntil(isUnionType), keyPath)
);
// Kept for backwards compatibility.
export const formatValidationError = (error: t.ValidationError) =>
formatValidationCommonError(keyPath(error.context), error);

export const formatValidationErrors = (errors: t.Errors) =>
pipe(
errors,
groupByKey,
R.mapWithIndex(format),
R.compact,
R.toArray,
A.map(([_key, error]) => error)
);

export const reporter = <T>(validation: t.Validation<T>) =>
pipe(
validation,
E.mapLeft(groupByKey),
E.mapLeft(R.mapWithIndex(format)),
E.mapLeft(R.compact),
E.mapLeft(R.toArray),
E.mapLeft(A.map(([_key, error]) => error)),
E.mapLeft(formatValidationErrors),
E.fold(
errors => errors,
() => []
)
);

const prettyReporter: Reporter<string[]> = {
report: reporter
};

export default prettyReporter;
16 changes: 9 additions & 7 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,29 @@ import test from 'ava';
import * as iots from 'io-ts';
import { withMessage } from 'io-ts-types/lib/withMessage';

import { reporter } from '../src';
import Reporter from '../src';

test('reports an empty array when the result doesn’t contain errors', t => {
const PrimitiveType = iots.string;
const result = PrimitiveType.decode('foo');

t.deepEqual(reporter(result), []);
t.deepEqual(Reporter.report(result), []);
});

test('formats a top-level primitve type correctly', t => {
const PrimitiveType = iots.string;
const result = PrimitiveType.decode(42);

t.deepEqual(reporter(result), ['Expecting string but instead got: 42']);
t.deepEqual(Reporter.report(result), [
'Expecting string but instead got: 42'
]);
});

test('formats array items', t => {
const NumberGroups = iots.array(iots.array(iots.number));
const result = NumberGroups.decode({});

t.deepEqual(reporter(result), [
t.deepEqual(Reporter.report(result), [
'Expecting Array<Array<number>> but instead got: {}'
]);
});
Expand All @@ -31,7 +33,7 @@ test('formats nested array item mismatches correctly', t => {
const NumberGroups = iots.array(iots.array(iots.number));
const result = NumberGroups.decode([[{}]]);

t.deepEqual(reporter(result), [
t.deepEqual(Reporter.report(result), [
'Expecting number at 0.0 but instead got: {}'
]);
});
Expand All @@ -47,7 +49,7 @@ test('formats branded types correctly', t => {
'Positive'
);

t.deepEqual(reporter(Positive.decode(-1)), [
t.deepEqual(Reporter.report(Positive.decode(-1)), [
'Expecting Positive but instead got: -1'
]);

Expand All @@ -56,7 +58,7 @@ test('formats branded types correctly', t => {
_i => `Don't be so negative!`
);

t.deepEqual(reporter(PatronizingPositive.decode(-1)), [
t.deepEqual(Reporter.report(PatronizingPositive.decode(-1)), [
"Expecting Positive but instead got: -1 (Don't be so negative!)"
]);
});
39 changes: 21 additions & 18 deletions tests/unions.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import test from 'ava';
import * as iots from 'io-ts';

import { reporter } from '../src';
import Reporter from '../src';

test('formats keyof unions as "regular" types', t => {
const WithKeyOf = iots.interface({
oneOf: iots.keyof({ a: null, b: null, c: null })
});

t.deepEqual(reporter(WithKeyOf.decode({ oneOf: '' })), [
t.deepEqual(Reporter.report(WithKeyOf.decode({ oneOf: '' })), [
'Expecting "a" | "b" | "c" at oneOf but instead got: ""'
]);
});

test('union of string literals (no key)', t => {
t.deepEqual(reporter(Gender.decode('male')), [
t.deepEqual(Reporter.report(Gender.decode('male')), [
[
'Expecting one of:',
' "Male"',
Expand All @@ -32,7 +32,7 @@ test('union of interfaces', t => {
]);
const WithUnion = iots.interface({ data: UnionOfInterfaces });

t.deepEqual(reporter(WithUnion.decode({})), [
t.deepEqual(Reporter.report(WithUnion.decode({})), [
[
'Expecting one of:',
' { key: string }',
Expand All @@ -41,7 +41,7 @@ test('union of interfaces', t => {
].join('\n')
]);

t.deepEqual(reporter(WithUnion.decode({ data: '' })), [
t.deepEqual(Reporter.report(WithUnion.decode({ data: '' })), [
[
'Expecting one of:',
' { key: string }',
Expand All @@ -50,7 +50,7 @@ test('union of interfaces', t => {
].join('\n')
]);

t.deepEqual(reporter(WithUnion.decode({ data: {} })), [
t.deepEqual(Reporter.report(WithUnion.decode({ data: {} })), [
[
'Expecting one of:',
' { key: string }',
Expand All @@ -59,7 +59,7 @@ test('union of interfaces', t => {
].join('\n')
]);

t.deepEqual(reporter(WithUnion.decode({ data: { code: '123' } })), [
t.deepEqual(Reporter.report(WithUnion.decode({ data: { code: '123' } })), [
[
'Expecting one of:',
' { key: string }',
Expand All @@ -78,7 +78,7 @@ const Gender = iots.union([
test('string union when provided undefined', t => {
const Person = iots.interface({ name: iots.string, gender: Gender });

t.deepEqual(reporter(Person.decode({ name: 'Jane' })), [
t.deepEqual(Reporter.report(Person.decode({ name: 'Jane' })), [
[
'Expecting one of:',
' "Male"',
Expand All @@ -92,17 +92,20 @@ test('string union when provided undefined', t => {
test('string union when provided another string', t => {
const Person = iots.interface({ name: iots.string, gender: Gender });

t.deepEqual(reporter(Person.decode({ name: 'Jane', gender: 'female' })), [
t.deepEqual(
Reporter.report(Person.decode({ name: 'Jane', gender: 'female' })),
[
'Expecting one of:',
' "Male"',
' "Female"',
' "Other"',
'at gender but instead got: "female"'
].join('\n')
]);
[
'Expecting one of:',
' "Male"',
' "Female"',
' "Other"',
'at gender but instead got: "female"'
].join('\n')
]
);

t.deepEqual(reporter(Person.decode({ name: 'Jane' })), [
t.deepEqual(Reporter.report(Person.decode({ name: 'Jane' })), [
[
'Expecting one of:',
' "Male"',
Expand All @@ -120,7 +123,7 @@ test('string union deeply nested', t => {
});

t.deepEqual(
reporter(
Reporter.report(
Person.decode({
name: 'Jane',
children: [{}, { gender: 'Whatever' }]
Expand Down