Skip to content

Commit 55e5bae

Browse files
authored
Merge pull request #2 from Sako-K/main
[FIX] - Remove option, and make false on schema work
2 parents 381dac9 + 725a222 commit 55e5bae

File tree

5 files changed

+347
-298
lines changed

5 files changed

+347
-298
lines changed

README.md

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,24 @@ fastify.register(enforceSchema, options);
4343

4444
- **exclude**: Endpoints to exclude by the _routeOptions.path_. Each exclude is an object, with a `url` and optional, `excludeSchemas` array. If the `excludeSchemas` array is not passed, validation for all 3 schemas (`body`, `respone`, `params`) is disabled.
4545

46-
- **excludeOnFalseSchema** - If your controllers aren't returning anything, make sure to set the `response` schema to false. And then, set `excludeOnFalseSchema` to `true`, so that this plugin doesn't return errors for any given controller that has a response schema set to false.
46+
### **Excluding specific schemas**
47+
48+
To disable schema validation for all three types (response, body, and params), you can set { schema: false }. If you only want to disable the schema for a specific type, you can do so by setting the corresponding key to false. For example, to disable schema validation for the response, you can use { response: false }.
4749

4850
```js
4951
await fastify.register(enforceSchema, {
50-
required: ["response"],
51-
excludeOnFalseSchema: true,
52+
required: ["response", "body", "params"],
5253
});
5354

54-
fastify.get("/foo", { schema: { response: false } }, (req, reply) => {
55+
fastify.get("/foo", { schema: false }, (req, reply) => {
5556
reply.code(200);
5657
});
58+
59+
fastify.get(
60+
"/bar",
61+
{ schema: { response: false, body: false, params: false } },
62+
(req, reply) => {
63+
reply.code(200);
64+
}
65+
);
5766
```

index.js

Lines changed: 43 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,137 +1,115 @@
1-
const fp = require("fastify-plugin");
1+
const fp = require('fastify-plugin')
22
const {
33
getErrrorMessage,
44
hasProperties,
55
initialExcludes,
66
isSchemaTypeExcluded,
7-
SCHEMA_TYPES,
8-
isHTTPVerbExcluded,
9-
} = require("./utils");
7+
SCHEMA_TYPES
8+
} = require('./utils')
109

11-
function FastifyEnforceSchema(fastify, opts, done) {
10+
function FastifyEnforceSchema (fastify, opts, done) {
1211
if (!opts) {
13-
opts = {};
12+
opts = {}
1413
}
1514

16-
if (!Object.prototype.hasOwnProperty.call(opts, "required")) {
17-
opts.required = [];
15+
if (!Object.prototype.hasOwnProperty.call(opts, 'required')) {
16+
opts.required = []
1817
}
1918

20-
if (!Object.prototype.hasOwnProperty.call(opts, "exclude")) {
21-
opts.exclude = [];
19+
if (!Object.prototype.hasOwnProperty.call(opts, 'exclude')) {
20+
opts.exclude = []
2221
}
2322

24-
if (!Object.prototype.hasOwnProperty.call(opts, 'excludeOnFalseSchema')) {
25-
opts.excludeOnFalseSchema = false;
26-
}
27-
28-
const { required, exclude, excludeOnFalseSchema } = opts;
23+
const { required, exclude } = opts
2924

30-
fastify.addHook("onRoute", (routeOptions) => {
25+
fastify.addHook('onRoute', (routeOptions) => {
3126
if (
32-
routeOptions.path === "*" ||
27+
routeOptions.path === '*' ||
3328
!routeOptions.path ||
34-
(excludeOnFalseSchema && routeOptions.schema === false)
29+
routeOptions.schema === false
3530
) {
36-
done();
37-
return;
38-
}
39-
40-
if (excludeOnFalseSchema && typeof routeOptions.schema === "object") {
41-
const excludedEntity = exclude.find(
42-
({ url }) => url === routeOptions.path
43-
);
44-
const excludedSchemas = [];
45-
46-
Object.entries(routeOptions.schema).forEach(([key, value]) => {
47-
if (value === false) {
48-
excludedSchemas.push(key);
49-
}
50-
});
51-
52-
if (excludedEntity) {
53-
excludedEntity.excludedSchemas = [
54-
...new Set([...excludedEntity.excludedSchemas, ...excludedSchemas]),
55-
];
56-
} else {
57-
exclude.push({ url: routeOptions.path, excludedSchemas });
58-
}
31+
done()
32+
return
5933
}
6034

6135
const excludedEntity = [...initialExcludes, ...exclude].find(
6236
({ url }) => url === routeOptions.path
63-
);
37+
)
6438

6539
const hasSchemas =
66-
typeof excludedEntity === "object" &&
67-
Object.prototype.hasOwnProperty.call(excludedEntity, "excludedSchemas");
40+
typeof excludedEntity === 'object' &&
41+
Object.prototype.hasOwnProperty.call(excludedEntity, 'excludedSchemas')
6842

6943
if (excludedEntity && !hasSchemas) {
70-
done();
71-
return;
44+
done()
45+
return
7246
}
7347

7448
if (!routeOptions?.schema) {
7549
throw new Error(
7650
`schema missing at the path ${routeOptions.method}: "${routeOptions.path}"`
77-
);
51+
)
7852
}
7953

8054
if (
55+
routeOptions?.schema?.response !== false &&
8156
!isSchemaTypeExcluded(excludedEntity, SCHEMA_TYPES.response) &&
8257
required.indexOf(SCHEMA_TYPES.response) !== -1
8358
) {
84-
const schema = Object.keys(routeOptions?.schema?.response || []);
59+
const schema = Object.keys(routeOptions?.schema?.response || [])
8560

8661
if (!routeOptions?.schema?.response) {
87-
throw new Error(getErrrorMessage(SCHEMA_TYPES.response, routeOptions));
62+
throw new Error(getErrrorMessage(SCHEMA_TYPES.response, routeOptions))
8863
}
8964

9065
if (
9166
routeOptions?.schema?.response &&
9267
!Object.keys(routeOptions?.schema?.response || []).length
9368
) {
94-
throw new Error(`No HTTP status codes provided in the response schema`);
69+
throw new Error('No HTTP status codes provided in the response schema')
9570
}
9671

97-
schema.forEach(value => {
72+
schema.forEach((value) => {
9873
if (!Number.isInteger(parseInt(value, 10))) {
9974
throw new Error(
10075
`"${value}" is not a number. HTTP status codes from 100 - 599 supported`
101-
);
76+
)
10277
}
10378

10479
if (value < 100 || value > 599) {
105-
throw new Error(`HTTP status codes from 100 - 599 supported`);
80+
throw new Error('HTTP status codes from 100 - 599 supported')
10681
}
107-
});
82+
})
10883
}
10984
if (
85+
routeOptions?.schema?.body !== false &&
11086
!isSchemaTypeExcluded(excludedEntity, SCHEMA_TYPES.body) &&
111-
["POST", "PUT", "PATCH"].includes(routeOptions.method) &&
87+
['POST', 'PUT', 'PATCH'].includes(routeOptions.method) &&
11288
required.indexOf(SCHEMA_TYPES.body) !== -1 &&
11389
!hasProperties(routeOptions, SCHEMA_TYPES.body)
11490
) {
115-
throw new Error(getErrrorMessage(SCHEMA_TYPES.body, routeOptions));
91+
throw new Error(getErrrorMessage(SCHEMA_TYPES.body, routeOptions))
11692
}
11793

11894
if (
95+
routeOptions?.schema?.params !== false &&
96+
new RegExp(/:\w+/).test(routeOptions.url) &&
11997
!isSchemaTypeExcluded(excludedEntity, SCHEMA_TYPES.params) &&
12098
required.indexOf(SCHEMA_TYPES.params) !== -1 &&
12199
!hasProperties(routeOptions, SCHEMA_TYPES.params)
122100
) {
123-
throw new Error(getErrrorMessage(SCHEMA_TYPES.params, routeOptions));
101+
throw new Error(getErrrorMessage(SCHEMA_TYPES.params, routeOptions))
124102
}
125-
});
103+
})
126104

127-
done();
105+
done()
128106
}
129107

130108
const _fastifyEnforceSchema = fp(FastifyEnforceSchema, {
131-
fastify: "4.x",
132-
name: "fastify-enforce-schema",
133-
});
109+
fastify: '4.x',
110+
name: 'fastify-enforce-schema'
111+
})
134112

135-
module.exports = _fastifyEnforceSchema;
136-
module.exports.FastifyEnforceSchema = _fastifyEnforceSchema;
137-
module.exports.default = _fastifyEnforceSchema;
113+
module.exports = _fastifyEnforceSchema
114+
module.exports.FastifyEnforceSchema = _fastifyEnforceSchema
115+
module.exports.default = _fastifyEnforceSchema

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "fastify-enforce-schema",
33
"url": "",
44
"author": "Aleksandar Grbic - (https://programmer.network)",
5-
"version": "1.0.6",
5+
"version": "1.0.7",
66
"description": "Enforce AJV schemas across your endpoints.",
77
"repository": {
88
"type": "git",
@@ -12,7 +12,7 @@
1212
"types": "index.d.ts",
1313
"scripts": {
1414
"coverage": "tap --cov --coverage-report=html test",
15-
"lint": "npm run lint:standard && npm run lint:typescript",
15+
"lint": "npm run lint:standard",
1616
"lint:fix": "standard --fix",
1717
"lint:standard": "standard",
1818
"lint:typescript": "standard --parser @typescript-eslint/parser --plugin @typescript-eslint/eslint-plugin test/*.ts",

0 commit comments

Comments
 (0)