Fix condition operation passing even when the checked field isn't present in the payload (#16483)

* use requireAll in validatePayload for condition

* add/update tests
This commit is contained in:
Azri Kahar
2022-11-17 23:55:43 +08:00
committed by GitHub
parent 5d25c19836
commit ed53673b0f
3 changed files with 74 additions and 1 deletions

View File

@@ -0,0 +1,56 @@
import { describe, expect, test } from 'vitest';
import config from './index';
describe('Operations / Condition', () => {
test('returns null when condition passes', () => {
const filter = {
status: {
_eq: true,
},
};
const data = {
status: true,
};
expect(config.handler({ filter }, { data } as any)).toBe(null);
});
test('throws error array when conditions fails', () => {
const filter = {
status: {
_eq: true,
},
};
const data = {
status: false,
};
expect.assertions(2); // ensure catch block is reached
try {
config.handler({ filter }, { data } as any);
} catch (err: any) {
expect(err).toHaveLength(1);
expect(err[0]!.message).toBe(`"status" must be [true]`);
}
});
test('throws error array when condition is checking for a field that is not included in data', () => {
const filter = {
status: {
_eq: true,
},
};
const data = {};
expect.assertions(2); // ensure catch block is reached
try {
config.handler({ filter }, { data } as any);
} catch (err: any) {
expect(err).toHaveLength(1);
expect(err[0]!.message).toBe(`"status" is required`);
}
});
});

View File

@@ -9,7 +9,7 @@ export default defineOperationApi<Options>({
id: 'condition',
handler: ({ filter }, { data }) => {
const errors = validatePayload(filter, data);
const errors = validatePayload(filter, data, { requireAll: true });
if (errors.length > 0) {
throw errors;