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

Added more customisation for Fastify skipList #153

Closed
wants to merge 12 commits into from
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,14 @@ This middleware function validates the request body, headers, path parameters an

#### fastifyOptions

- `skiplist`: Endpoint paths for which validation should not be applied. An array of strings in RegExp format, e. g. `['^/pets$']`

- `skiplist`: Endpoint paths with methods for which validation should not be applied. An object with array of strings in RegExp format for every method you want to specify, e. g.:
```js
skipList: {
get: ['^/pets$', '^/ui$'],
post: ['^/cat$'],
delete: ['^/cat$']
}
```
### openapi-validator-middleware.init(pathToSwaggerFile, options)

Initialize the middleware using a swagger definition.
Expand Down
14 changes: 11 additions & 3 deletions src/frameworks/fastify.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,19 @@ function getValidator(validateRequest) {
} catch (err) {
throw new Error('Missing `uri-js` dependency. Please run "npm install uri-js" to use fastify plugin');
}
let skiplist = [];
const skiplist = {
get: [],
post: [],
put: [],
delete: [],
patch: []
};

return (pluginOptions) => {
if (pluginOptions && pluginOptions.skiplist) {
skiplist = pluginOptions.skiplist.map((regexStr) => new RegExp(regexStr));
for (const key in pluginOptions.skiplist) {
skiplist[key] = pluginOptions.skiplist[key].map((regexStr) => new RegExp(regexStr));
}
}

return fp(function (fastify, options, next) {
Expand All @@ -24,7 +32,7 @@ function getValidator(validateRequest) {

function validate(request, reply) {
const requestOptions = _getParameters(request);
if (skiplist.some((skipListRegex) => {
if (skiplist[requestOptions.method.toLowerCase()].some((skipListRegex) => {
return skipListRegex.test(requestOptions.path);
})) {
return Promise.resolve();
Expand Down
22 changes: 21 additions & 1 deletion test/fastify/fastify-test-skiplist.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ describe('fastify plugin skiplist', () => {
app = fastify({ logger: true });

app.register(inputValidation.validate({
skiplist: ['^/pets$']
skiplist: {
get: ['^/pets$']
}
}));
app.setErrorHandler(async (err, req, reply) => {
if (err instanceof inputValidation.InputValidationError) {
Expand All @@ -31,6 +33,9 @@ describe('fastify plugin skiplist', () => {
app.get('/pets', (req, reply) => {
reply.status(204).send();
});
app.post('/pets', (req, reply) => {
reply.status(201).send();
});

await app.ready();
});
Expand All @@ -52,6 +57,21 @@ describe('fastify plugin skiplist', () => {
expect(response.body).to.eql('');
});

it('POST fails if only GET validation is ignored', async () => {
const response = await app.inject()
.headers({
'api-version': '1.0'
})
.body({
age: true
})
.post('/pets');
expect(response.statusCode).to.equal(400);
expect(response.json()).to.eql({
more_info: "[{\"keyword\":\"required\",\"dataPath\":\"\",\"schemaPath\":\"#/required\",\"params\":{\"missingProperty\":\"name\"},\"message\":\"should have required property 'name'\"},{\"keyword\":\"type\",\"dataPath\":\".age\",\"schemaPath\":\"#/properties/age/type\",\"params\":{\"type\":\"integer\"},\"message\":\"should be integer\"},{\"keyword\":\"required\",\"dataPath\":\"\",\"schemaPath\":\"#/required\",\"params\":{\"missingProperty\":\"test\"},\"message\":\"should have required property 'test'\"}]"
});
});

it('Skips endpoint validation for request with multiple errors', async () => {
const response = await app.inject().get('/pets');
expect(response.statusCode).to.equal(204);
Expand Down
8 changes: 7 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@ export interface format {
}

export interface FastifyPluginOptions {
skiplist?: Array<string>;
skiplist?: {
ozonep marked this conversation as resolved.
Show resolved Hide resolved
get?: Array<string>,
post?: Array<string>
put?: Array<string>,
delete?: Array<string>,
patch?: Array<string>,
};
}

export interface ajvValidatorOptions {
Expand Down