Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ jobs:
uses: fastify/workflows/.github/workflows/plugins-ci.yml@v3
with:
license-check: true
lint: true
88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,94 @@ You can also override the default configuration by passing the [`serializerOpts`
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](https://www.fastify.io/docs/latest/Reference/Server/#schemacontroller).

### fast-json-stringify Standalone

`[email protected]` introduces the [standalone feature](https://github.com/fastify/fast-json-stringify#standalone) 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:

1. You must generate and save the application's compiled schemas.
2. 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 serialization schemas functions and it is your choice to save them where you want.
To accomplish this, you must use a new compiler: `@fastify/fast-json-stringify-compiler/standalone`.

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**.


```js
const factory = require('@fastify/fast-json-stringify-compiler/standalone')({
readMode: false,
storeFunction (routeOpts, schemaSerializationCode) {
// routeOpts is like: { schema, method, url, httpStatus }
// schemaSerializationCode is a string source code that is the compiled schema function
const fileName = generateFileName(routeOpts)
fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode)
}
})

const app = fastify({
jsonShorthand: false,
schemaController: {
compilersFactory: {
buildSerializer: factory
}
}
})

// ... add all your routes with schemas ...

app.ready().then(() => {
// at this stage all your schemas are compiled and stored in the file system
// now it is important to turn off the readMode
})
```

#### 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 `@fastify/fast-json-stringify-compiler/standalone` 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 serialize the route's payload.

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 the `routeOpts.schema.$id` field to do so, it is up to you to define a unique schema identifier.

```js
const factory = require('@fastify/fast-json-stringify-compiler/standalone')({
readMode: true,
restoreFunction (routeOpts) {
// routeOpts is like: { schema, method, url, httpStatus }
const fileName = generateFileName(routeOpts)
return require(path.join(__dirname, fileName))
}
})

const app = fastify({
jsonShorthand: false,
schemaController: {
compilersFactory: {
buildSerializer: factory
}
}
})

// ... add all your routes with schemas as before...

app.listen({ port: 3000 })
```

### How it works

This module provide a factory function to produce [Serializer Compilers](https://www.fastify.io/docs/latest/Reference/Server/#serializercompiler) functions.
Expand Down
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"lint": "standard",
"lint:fix": "standard --fix",
"unit": "tap --100 test/**/*.test.js",
"test": "standard && npm run unit && npm run test:typescript",
"unit": "tap test/**/*.test.js",
"test": "npm run unit && npm run test:typescript",
"posttest": "rimraf test/fjs-generated*.js",
"test:typescript": "tsd"
},
"repository": {
Expand All @@ -23,6 +25,8 @@
"homepage": "https://github.com/fastify/fast-json-stringify-compiler#readme",
"devDependencies": {
"fastify": "^4.0.0",
"rimraf": "^3.0.2",
"sanitize-filename": "^1.6.3",
"standard": "^17.0.0",
"tap": "^16.0.0",
"tsd": "^0.22.0"
Expand Down
16 changes: 16 additions & 0 deletions standalone.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { SerializerCompiler } from './index'

export type RouteDefinition = {
method: string,
url: string,
httpStatus: string,
schema?: unknown,
}

interface Option {
readMode: Boolean,
storeFunction?(opts: RouteDefinition, schemaSerializationCode: string): void,
restoreFunction?(opts: RouteDefinition): void,
}

export declare function StandaloneSerializer(Options): SerializerCompiler;
41 changes: 41 additions & 0 deletions standalone.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict'

const SerializerSelector = require('./index')

function StandaloneSerializer (options = { readMode: true }) {
if (options.readMode === true && typeof options.restoreFunction !== 'function') {
throw new Error('You must provide a function for the restoreFunction-option when readMode ON')
}

if (options.readMode !== true && !options.storeFunction) {
throw new Error('You must provide a function for the restoreFunction-option when readMode OFF')
}

if (options.readMode === true) {
// READ MODE: it behalf only in the restore function provided by the user
return function wrapper () {
return function (opts) {
return options.restoreFunction(opts)
}
}
}

// WRITE MODE: it behalf on the default SerializerSelector, wrapping the API to run the Ajv Standalone code generation
const factory = SerializerSelector()
return function wrapper (externalSchemas, serializerOpts = {}) {
// to generate the serialization source code, this option is mandatory
serializerOpts.mode = 'standalone'

const compiler = factory(externalSchemas, serializerOpts)
return function (opts) { // { schema/*, method, url, httpPart */ }
const serializeFuncCode = compiler(opts)

options.storeFunction(opts, serializeFuncCode)

// eslint-disable-next-line no-new-func
return new Function(serializeFuncCode)
}
}
}

module.exports = StandaloneSerializer
4 changes: 1 addition & 3 deletions test/plugin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ const externalSchemas2 = Object.freeze({
}
})

const fastifyFjsOptionsDefault = Object.freeze({
customOptions: {}
})
const fastifyFjsOptionsDefault = Object.freeze({})

t.test('basic usage', t => {
t.plan(1)
Expand Down
Loading