Build and manage the AJV instances for the fastify framework
Installations
npm install @fastify/ajv-compiler
Developer
fastify
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
20.8.0
NPM Version
10.1.0
Statistics
18 Stars
108 Commits
9 Forks
14 Watching
2 Branches
23 Contributors
Updated on 03 Nov 2024
Languages
JavaScript (85.79%)
TypeScript (14.21%)
Total Downloads
Cumulative downloads
Total Downloads
155,346,047
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
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
@fastify/ajv-compiler
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.
Versions
@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 |
AJV Configuration
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.
Usage
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.
Customize the ajv-formats
plugin
The 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.
Customize the ajv
instance
If 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})
Fastify with JTD
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.
Fastify with JTD and serialization
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 Standalone
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:
- You must generate and save the application's compiled schemas.
- Read the compiled schemas from the file and provide them back to your Fastify application.
Generate and save the compiled schemas
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})
Read the compiled schemas functions
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:
- when you use the
readMode: true
, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them! - as you can see, you must relate the route's schema to the file name using the
routeOpts
object. You may use therouteOpts.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 })
How it works
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:
- the AJV configuration: it is one per server
- the external JSON schemas: once a new schema is added to a fastify's context, calling
fastify.addSchema()
, it will cause a new AJV inizialization
License
Licensed 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
- Info: security policy file detected: github.com/fastify/.github/SECURITY.md:1
- Info: Found linked content: github.com/fastify/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/fastify/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/fastify/.github/SECURITY.md:1
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Warn: project license file does not contain an FSF or OSI license.
Reason
SAST tool is not run on all commits -- score normalized to 9
Details
- Warn: 23 commits out of 25 are checked with a SAST tool
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
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
6.7
/10
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