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 query coercion issue #571

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
48 changes: 48 additions & 0 deletions src/backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,30 @@ describe('OpenAPIBackend', () => {
'/pets/{id}': {
get: {
operationId: 'getPetById',
parameters: [
{
name: 'id',
in: 'path',
required: true,
schema: {
type: 'string'
}
},
{
name: 'breed',
in: 'query',
schema: {
type: 'string'
}
},
{
name: 'age',
in: 'query',
schema: {
type: 'integer'
}
}
],
responses,
},
put: {
Expand Down Expand Up @@ -466,6 +490,30 @@ describe('OpenAPIBackend', () => {
expect(mockHandler).toBeCalled();
});
});

describe('types coercion', () => {
test('coerces query types', async () => {
const api = new OpenAPIBackend({ definition });
const dummyHandler = jest.fn((context, req, ...rest) => req);
api.register('getPetById', dummyHandler);
await api.init();

const request = {
method: 'get',
path: '/pets/1',
headers: {},
query: {
breed: 'corgi',
age: '5',
}
};

const res = await api.handleRequest(request);
expect(dummyHandler).toBeCalledTimes(1);

expect(res.query).toStrictEqual({breed: 'corgi', age: 5});
});
})
});

describe('.mockResponseForOperation', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ export class OpenAPIBackend<D extends Document = Document> {
}

// handle route
return routeHandler(context as Context<D>, ...handlerArgs);
return routeHandler(context as Context<D>, req, ...handlerArgs);
}).bind(this)();

// post response handler
Expand Down
4 changes: 4 additions & 0 deletions src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,10 @@ export class OpenAPIValidator<D extends Document = Document> {
if (validate.errors) {
result.errors.push(...validate.errors);
}
else {
// set Ajv validator coerced query to request
req.query = parameters.query
Copy link

Choose a reason for hiding this comment

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

Path params are needed to be copied too.

}
}

if (_.isEmpty(result.errors)) {
Expand Down