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

feat(oneOf): add new error types #1022

Merged
merged 6 commits into from
Sep 26, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
testRegex: 'src/.*\\.spec\\.ts',
testRegex: 'src/.*\\.spec\\.ts$',
testEnvironment: 'node',
preset: 'ts-jest',
// TS takes precedence as we want to avoid build artifacts from being required instead of up-to-date .ts file.
Expand Down
147 changes: 147 additions & 0 deletions src/middlewares/__snapshots__/one-of.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`error message can be the return of a function 1`] = `
Array [
Object {
"msg": "keep trying",
"nestedErrors": Array [
Array [
Object {
"location": "body",
"msg": "Invalid value",
"param": "foo",
"value": true,
},
],
],
"param": "_error",
},
]
`;

exports[`should let the user to choose between multiple error types grouped error type 1`] = `
Array [
Object {
"msg": "Invalid value(s)",
"nestedErrors": Array [
Array [
Object {
"location": "body",
"msg": "Invalid value",
"param": "foo",
"value": true,
},
],
Array [
Object {
"location": "body",
"msg": "Invalid value",
"param": "bar",
"value": undefined,
},
],
],
"param": "_error",
},
]
`;

exports[`should let the user to choose between multiple error types leastErroredOnly error type 1`] = `
Array [
Object {
"msg": "Invalid value(s)",
"nestedErrors": Array [
Object {
"location": "body",
"msg": "Invalid value",
"param": "foo",
"value": true,
},
],
"param": "_error",
},
]
`;

exports[`should let the user to choose between multiple error types legacy error type 1`] = `
Array [
Object {
"msg": "Invalid value(s)",
"nestedErrors": Array [
Object {
"location": "body",
"msg": "Invalid value",
"param": "foo",
"value": true,
},
Object {
"location": "body",
"msg": "Invalid value",
"param": "bar",
"value": undefined,
},
],
"param": "_error",
},
]
`;

exports[`with a list of chain groups sets a single error for the _error key 1`] = `
Array [
Object {
"msg": "Invalid value(s)",
"nestedErrors": Array [
Array [
Object {
"location": "cookies",
"msg": "Invalid value",
"param": "foo",
"value": true,
},
Object {
"location": "cookies",
"msg": "Invalid value",
"param": "bar",
"value": "def",
},
],
Array [
Object {
"location": "cookies",
"msg": "Invalid value",
"param": "baz",
"value": 123,
},
],
],
"param": "_error",
},
]
`;

exports[`with a list of chains sets a single error for the _error key 1`] = `
Array [
Object {
"msg": "Invalid value(s)",
"nestedErrors": Array [
Array [
Object {
"location": "cookies",
"msg": "Invalid value",
"param": "foo",
"value": true,
},
],
Array [
Object {
"location": "cookies",
"msg": "Invalid value",
"param": "bar",
"value": "def",
},
],
],
"param": "_error",
},
]
`;
75 changes: 48 additions & 27 deletions src/middlewares/one-of.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { InternalRequest, contextsKey } from '../base';
import { ContextRunnerImpl } from '../chain/context-runner-impl';
import { check } from './validation-chain-builders';
import { oneOf } from './one-of';
import { OneOfErrorType, OneOfOptions, oneOf } from './one-of';

const getOneOfContext = (req: InternalRequest) => {
const contexts = req[contextsKey] || [];
Expand Down Expand Up @@ -55,17 +55,7 @@ describe('with a list of chains', () => {

oneOf([check('foo').isInt(), check('bar').isInt()])(req, {}, () => {
const context = getOneOfContext(req);
expect(context.errors).toHaveLength(1);
expect(context.errors).toContainEqual(
expect.objectContaining({
param: '_error',
nestedErrors: expect.arrayContaining([
expect.objectContaining({ param: 'foo' }),
expect.objectContaining({ param: 'bar' }),
]),
}),
);

expect(context.errors).toMatchSnapshot();
done();
});
});
Expand All @@ -91,18 +81,7 @@ describe('with a list of chain groups', () => {

oneOf([[check('foo').isInt(), check('bar').isInt()], check('baz').isAlpha()])(req, {}, () => {
const context = getOneOfContext(req);
expect(context.errors).toHaveLength(1);
expect(context.errors).toContainEqual(
expect.objectContaining({
param: '_error',
nestedErrors: expect.arrayContaining([
expect.objectContaining({ param: 'foo' }),
expect.objectContaining({ param: 'bar' }),
expect.objectContaining({ param: 'baz' }),
]),
}),
);

expect(context.errors).toMatchSnapshot();
done();
});
});
Expand Down Expand Up @@ -138,7 +117,7 @@ describe('error message', () => {
body: { foo: true },
};

oneOf([check('foo').isInt()], 'not today')(req, {}, () => {
oneOf([check('foo').isInt()], { message: 'not today' })(req, {}, () => {
const context = getOneOfContext(req);
expect(context.errors[0]).toHaveProperty('msg', 'not today');
done();
Expand All @@ -151,15 +130,57 @@ describe('error message', () => {
};

const message = jest.fn(() => 'keep trying');
oneOf([check('foo').isInt()], message)(req, {}, () => {
oneOf([check('foo').isInt()], { message })(req, {}, () => {
const context = getOneOfContext(req);
expect(context.errors[0]).toHaveProperty('msg', 'keep trying');
expect(context.errors).toMatchSnapshot();
expect(message).toHaveBeenCalledWith({ req });
done();
});
});
});

describe('should let the user to choose between multiple error types', () => {
// TODO: Can't use it.each because it doesn't support done() in TypeScript
fedeci marked this conversation as resolved.
Show resolved Hide resolved
const errorTypes: OneOfErrorType[] = ['grouped', 'legacy'];
errorTypes.forEach(errorType => {
it(`${errorType} error type`, done => {
const req: InternalRequest = {
body: { foo: true },
};
const options: OneOfOptions = {
errorType,
};

oneOf([check('foo').isString(), check('bar').isFloat()], options)(req, {}, () => {
const context = getOneOfContext(req);
expect(context.errors).toMatchSnapshot();
done();
});
});
});

it('leastErroredOnly error type', done => {
const req: InternalRequest = {
body: { foo: true, bar: 'bar' },
};
const options: OneOfOptions = {
errorType: 'leastErroredOnly',
};

oneOf(
[
[check('foo').isFloat(), check('bar').isInt()],
[check('foo').isString(), check('bar').isString()],
],
options,
)(req, {}, () => {
const context = getOneOfContext(req);
expect(context.errors).toMatchSnapshot();
done();
});
});
});

describe('imperatively run oneOf', () => {
it('sets errors in context when validation fails', async () => {
const req: InternalRequest = {
Expand Down
42 changes: 33 additions & 9 deletions src/middlewares/one-of.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,19 @@ const dummyItem: ContextItem = { async run() {} };

export type OneOfCustomMessageBuilder = (options: { req: Request }) => any;

export type OneOfErrorType = 'grouped' | 'leastErroredOnly' | 'legacy';
Copy link
Member Author

@fedeci fedeci Apr 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about leastErroredOnly name, any suggestion?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No better names yet...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the name grouped as it describes well the behaviour.
What do you think of flat instead of legacy? It sounds exactly like the opposite of grouped.

As for leastErroredOnly... still no better ideas 😢

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flat sounds nice to me.


export interface OneOfOptions {
message?: OneOfCustomMessageBuilder | any;
fedeci marked this conversation as resolved.
Show resolved Hide resolved
errorType?: OneOfErrorType;
}

export function oneOf(
chains: (ValidationChain | ValidationChain[])[],
message?: OneOfCustomMessageBuilder,
): Middleware & { run: (req: Request) => Promise<void> };
export function oneOf(
chains: (ValidationChain | ValidationChain[])[],
message?: any,
): Middleware & { run: (req: Request) => Promise<void> };
options: OneOfOptions = {},
): Middleware & { run: (req: Request) => Promise<void> } {
options = { errorType: 'grouped', ...options };

export function oneOf(chains: (ValidationChain | ValidationChain[])[], message?: any) {
const middleware = async (req: InternalRequest, _res: any, next: (err?: any) => void) => {
const surrogateContext = new ContextBuilder().addItem(dummyItem).build();

Expand All @@ -45,10 +48,31 @@ export function oneOf(chains: (ValidationChain | ValidationChain[])[], message?:
const success = allErrors.some(groupErrors => groupErrors.length === 0);

if (!success) {
let error;
switch (options.errorType) {
case 'grouped':
error = allErrors;
break;
case 'leastErroredOnly':
let leastErroredIndex = 0;
for (let i = 1; i < allErrors.length; i++) {
if (allErrors[i].length < allErrors[leastErroredIndex].length) {
leastErroredIndex = i;
}
}
error = allErrors[leastErroredIndex];
break;
default:
// legacy
error = _.flatMap(allErrors);
}

// Only add an error to the context if no group of chains had success.
surrogateContext.addError(
typeof message === 'function' ? message({ req }) : message || 'Invalid value(s)',
_.flatMap(allErrors),
typeof options.message === 'function'
? options.message({ req })
: options.message || 'Invalid value(s)',
error,
);
}

Expand Down