Skip to content

Commit

Permalink
Fix multipart fields validation
Browse files Browse the repository at this point in the history
  • Loading branch information
LoicPoullain committed Apr 8, 2020
1 parent 470dbb3 commit 98fab68
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 14 deletions.
46 changes: 33 additions & 13 deletions packages/storage/src/validate-multipart-form-data-body.hook.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,15 @@ describe('ValidateMultipartFormDataBody', () => {
const actual: { body: any } = { body: null };
const app = createAppWithHook({
fields: {
properties: {
name: { type: 'string' }
},
type: 'object',
name: { type: 'string' }
},
files: {}
}, actual);

await request(app)
.post('/')
.field('name', 'hello')
.field('unexpectedName', 'world')
.expect(200);

deepStrictEqual(actual.body.fields, {
Expand Down Expand Up @@ -114,13 +112,10 @@ describe('ValidateMultipartFormDataBody', () => {
rmdirSync('uploaded');
});

it('should return an HttpResponseBadRequest.', async () => {
it('should return an HttpResponseBadRequest (invalid values).', async () => {
const app = createAppWithHook({
fields: {
properties: {
name: { type: 'boolean' }
},
type: 'object',
name: { type: 'boolean' }
},
files: {}
}, { body: null });
Expand All @@ -144,13 +139,38 @@ describe('ValidateMultipartFormDataBody', () => {
});
});

it('should return an HttpResponseBadRequest (missing values).', async () => {
const app = createAppWithHook({
fields: {
name: { type: 'string' },
name2: { type: 'string' }
},
files: {}
}, { body: null });

await request(app)
.post('/')
.field('name', 'hello')
.expect(400)
.expect({
body: [
{
dataPath: '',
keyword: 'required',
message: 'should have required property \'name2\'',
params: {
missingProperty: 'name2'
},
schemaPath: '#/required',
}
]
});
});

it('should not have uploaded the files.', async () => {
const app = createAppWithHook({
fields: {
properties: {
name: { type: 'boolean' }
},
type: 'object',
name: { type: 'boolean' }
},
files: {
foobar: { required: false, multiple: true, saveTo: 'images' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,13 @@ const hook = (schema: MultipartFormDataSchema): HookDecorator => {

// Validate the fields
const ajv = getAjvInstance();
if (schema.fields && !ajv.validate(schema.fields, fields)) {
const ajvSchema = {
additionalProperties: false,
properties: schema.fields,
required: Object.keys(schema.fields || {}),
type: 'object',
};
if (schema.fields && !ajv.validate(ajvSchema, fields)) {
await deleteUploadedFiles();
return new HttpResponseBadRequest({ body: ajv.errors });
}
Expand Down

0 comments on commit 98fab68

Please sign in to comment.