Gathering detailed insights and metrics for @fastify/ajv-compiler
Gathering detailed insights and metrics for @fastify/ajv-compiler
Gathering detailed insights and metrics for @fastify/ajv-compiler
Gathering detailed insights and metrics for @fastify/ajv-compiler
Build and manage the AJV instances for the fastify framework
npm install @fastify/ajv-compiler
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
18 Stars
108 Commits
9 Forks
14 Watching
2 Branches
23 Contributors
Updated on 03 Nov 2024
JavaScript (85.79%)
TypeScript (14.21%)
Cumulative downloads
Total Downloads
Last day
2%
426,516
Compared to previous day
Last week
2.9%
2,223,000
Compared to previous week
Last month
22.6%
8,523,989
Compared to previous month
Last year
59.4%
80,116,184
Compared to previous year
This module manages the ajv
instances for the Fastify framework.
It isolates the ajv
dependency so that the AJV version is not tightly coupled to the Fastify version.
This allows the user to decide which version of AJV to use in their Fastify based application.
@fastify/ajv-compiler | ajv | Default in fastify |
---|---|---|
v4.x | v8.x | ^5.x |
v3.x | v8.x | ^4.x |
v2.x | v8.x | - |
v1.x | v6.x | ^3.14 |
The Fastify's default ajv
options are:
1{ 2 coerceTypes: 'array', 3 useDefaults: true, 4 removeAdditional: true, 5 uriResolver: require('fast-uri'), 6 addUsedSchema: false, 7 // Explicitly set allErrors to `false`. 8 // When set to `true`, a DoS attack is possible. 9 allErrors: false 10}
Moreover, the ajv-formats
module is included by default.
If you need to customize it, check the usage section below.
To customize the ajv
's options, see how in the Fastify official docs.
This module is already used as default by Fastify. If you need to provide to your server instance a different version, refer to the official doc.
ajv-formats
pluginThe format
keyword is not part of the official ajv
module since v7. To use it, you need to install the ajv-formats
module and this module
does it for you with the default configuration.
If you need to configure the ajv-formats
plugin you can do it using the standard Fastify configuration:
1const app = fastify({ 2 ajv: { 3 plugins: [[require('ajv-formats'), { mode: 'fast' }]] 4 } 5})
In this way, your setup will have precedence over the @fastify/ajv-compiler
default configuration.
ajv
instanceIf you need to customize the ajv
instance and take full control of its configuration, you can do it by
using the onCreate
option in the Fastify configuration that accepts a syncronous function that receives the ajv
instance:
1const app = fastify({ 2 ajv: { 3 onCreate: (ajv) => { 4 // Modify the ajv instance as you need. 5 ajv.addFormat('myFormat', (data) => typeof data === 'string') 6 } 7 } 8})
The JSON Type Definition feature is supported by AJV v8.x and you can benefit from it in your Fastify application.
With Fastify v3.20.x and higher, you can use the @fastify/ajv-compiler
module to load JSON Type Definitions like so:
1const factory = require('@fastify/ajv-compiler')() 2 3const app = fastify({ 4 jsonShorthand: false, 5 ajv: { 6 customOptions: { }, // additional JTD options 7 mode: 'JTD' 8 }, 9 schemaController: { 10 compilersFactory: { 11 buildValidator: factory 12 } 13 } 14})
The defaults AJV JTD options are the same as the Fastify's default options.
You can use JTD Schemas to serialize your response object too:
1const factoryValidator = require('@fastify/ajv-compiler')() 2const factorySerializer = require('@fastify/ajv-compiler')({ jtdSerializer: true }) 3 4const app = fastify({ 5 jsonShorthand: false, 6 ajv: { 7 customOptions: { }, // additional JTD options 8 mode: 'JTD' 9 }, 10 schemaController: { 11 compilersFactory: { 12 buildValidator: factoryValidator, 13 buildSerializer: factorySerializer 14 } 15 } 16})
AJV v8 introduces the standalone feature that let you to pre-compile your schemas and use them in your application for a faster startup.
To use this feature, you must be aware of the following:
Fastify helps you to generate the validation schemas functions and it is your choice to save them where you want.
To accomplish this, you must use a new compiler: StandaloneValidator
.
You must provide 2 parameters to this compiler:
readMode: false
: a boolean to indicate that you want generate the schemas functions string.storeFunction
" a sync function that must store the source code of the schemas functions. You may provide an async function too, but you must manage errors.When readMode: false
, the compiler is meant to be used in development ONLY.
1const { StandaloneValidator } = require('@fastify/ajv-compiler')
2const factory = StandaloneValidator({
3 readMode: false,
4 storeFunction (routeOpts, schemaValidationCode) {
5 // routeOpts is like: { schema, method, url, httpPart }
6 // schemaValidationCode is a string source code that is the compiled schema function
7 const fileName = generateFileName(routeOpts)
8 fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode)
9 }
10})
11
12const app = fastify({
13 jsonShorthand: false,
14 schemaController: {
15 compilersFactory: {
16 buildValidator: factory
17 }
18 }
19})
20
21// ... add all your routes with schemas ...
22
23app.ready().then(() => {
24 // at this stage all your schemas are compiled and stored in the file system
25 // now it is important to turn off the readMode
26})
At this stage, you should have a file for every route's schema.
To use them, you must use the StandaloneValidator
with the parameters:
readMode: true
: a boolean to indicate that you want read and use the schemas functions string.restoreFunction
" a sync function that must return a function to validate the route.Important keep away before you continue reading the documentation:
readMode: true
, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them!routeOpts
object. You may use the routeOpts.schema.$id
field to do so, it is up to you to define a unique schema identifier.1const { StandaloneValidator } = require('@fastify/ajv-compiler') 2const factory = StandaloneValidator({ 3 readMode: true, 4 restoreFunction (routeOpts) { 5 // routeOpts is like: { schema, method, url, httpPart } 6 const fileName = generateFileName(routeOpts) 7 return require(path.join(__dirname, fileName)) 8 } 9}) 10 11const app = fastify({ 12 jsonShorthand: false, 13 schemaController: { 14 compilersFactory: { 15 buildValidator: factory 16 } 17 } 18}) 19 20// ... add all your routes with schemas as before... 21 22app.listen({ port: 3000 })
This module provide a factory function to produce Validator Compilers functions.
The Fastify factory function is just one per server instance and it is called for every encapsulated context created by the application through the fastify.register()
call.
Every Validator Compiler produced, has a dedicated AJV instance, so, this factory will try to produce as less as possible AJV instances to reduce the memory footprint and the startup time.
The variables involved to choose if a Validator Compiler can be reused are:
fastify.addSchema()
, it will cause a new AJV inizializationLicensed under MIT.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 9
Details
Reason
8 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 6
Reason
Found 9/18 approved changesets -- score normalized to 5
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More