-
-
Notifications
You must be signed in to change notification settings - Fork 5
feat: standalone mode #18
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
0a2657d
feat: standalone mode
Eomm 74f5e9a
fix: coverage
Eomm ebbb3fb
chore: fix wording
Eomm c56931f
chore: use rimraf
Eomm eb40852
chore: unuseful if
Eomm 0bf6061
Apply suggestions from code review
Eomm aceca81
wip: add typescript
Eomm 3ac0e8e
fix: typescript suggestions
Eomm 01d71c3
Apply suggestions from code review
Eomm 6042958
fix: exported interface
Eomm 46a2b0f
fix: exported interface
Eomm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,3 +15,4 @@ jobs: | |
| uses: fastify/workflows/.github/workflows/plugins-ci.yml@v3 | ||
| with: | ||
| license-check: true | ||
| lint: true | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 && !options.restoreFunction) { | ||
| throw new Error('You must provide a restoreFunction options when readMode ON') | ||
Eomm marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| if (options.readMode !== true && !options.storeFunction) { | ||
Eomm marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
Eomm marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| throw new Error('You must provide a storeFunction options when readMode OFF') | ||
Eomm marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| 'use strict' | ||
|
|
||
| const fs = require('fs') | ||
| const path = require('path') | ||
| const t = require('tap') | ||
| const fastify = require('fastify') | ||
| const sanitize = require('sanitize-filename') | ||
|
|
||
| const FjsStandaloneCompiler = require('../standalone') | ||
|
|
||
| function generateFileName (routeOpts) { | ||
| return `/fjs-generated-${sanitize(routeOpts.schema.$id)}-${routeOpts.method}-${routeOpts.httpPart}-${sanitize(routeOpts.url)}.js` | ||
| } | ||
|
|
||
| t.test('errors', t => { | ||
| t.plan(2) | ||
| t.throws(() => { | ||
| FjsStandaloneCompiler() | ||
| }, 'missing restoreFunction') | ||
| t.throws(() => { | ||
| FjsStandaloneCompiler({ readMode: false }) | ||
| }, 'missing storeFunction') | ||
| }) | ||
|
|
||
| t.test('generate standalone code', t => { | ||
| t.plan(5) | ||
|
|
||
| const base = { | ||
| $id: 'urn:schema:base', | ||
| definitions: { | ||
| hello: { type: 'string' } | ||
| }, | ||
| type: 'object', | ||
| properties: { | ||
| hello: { $ref: '#/definitions/hello' } | ||
| } | ||
| } | ||
|
|
||
| const refSchema = { | ||
| $id: 'urn:schema:ref', | ||
| type: 'object', | ||
| properties: { | ||
| hello: { $ref: 'urn:schema:base#/definitions/hello' } | ||
| } | ||
| } | ||
|
|
||
| const endpointSchema = { | ||
| schema: { | ||
| $id: 'urn:schema:endpoint', | ||
| $ref: 'urn:schema:ref' | ||
| } | ||
| } | ||
|
|
||
| const schemaMap = { | ||
| [base.$id]: base, | ||
| [refSchema.$id]: refSchema | ||
| } | ||
|
|
||
| const factory = FjsStandaloneCompiler({ | ||
| readMode: false, | ||
| storeFunction (routeOpts, schemaSerializerCode) { | ||
| t.same(routeOpts, endpointSchema) | ||
| t.type(schemaSerializerCode, 'string') | ||
| fs.writeFileSync(path.join(__dirname, '/fjs-generated.js'), schemaSerializerCode) | ||
| t.pass('stored the serializer function') | ||
| } | ||
| }) | ||
|
|
||
| const compiler = factory(schemaMap) | ||
| compiler(endpointSchema) | ||
| t.pass('compiled the endpoint schema') | ||
|
|
||
| t.test('usage standalone code', t => { | ||
| t.plan(3) | ||
| const standaloneSerializer = require('./fjs-generated') | ||
| t.ok(standaloneSerializer) | ||
|
|
||
| const valid = standaloneSerializer({ hello: 'world' }) | ||
| t.same(valid, JSON.stringify({ hello: 'world' })) | ||
|
|
||
| const invalid = standaloneSerializer({ hello: [] }) | ||
| t.same(invalid, '{"hello":""}') | ||
| }) | ||
| }) | ||
|
|
||
| t.test('fastify integration - writeMode', async t => { | ||
| t.plan(4) | ||
|
|
||
| const factory = FjsStandaloneCompiler({ | ||
| readMode: false, | ||
| storeFunction (routeOpts, schemaSerializationCode) { | ||
| const fileName = generateFileName(routeOpts) | ||
| t.ok(routeOpts) | ||
| fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) | ||
| t.pass(`stored the serializer function ${fileName}`) | ||
| }, | ||
| restoreFunction () { | ||
| t.fail('write mode ON') | ||
| } | ||
| }) | ||
|
|
||
| const app = buildApp(factory) | ||
| await app.ready() | ||
| }) | ||
|
|
||
| t.test('fastify integration - writeMode forces standalone', async t => { | ||
| t.plan(4) | ||
|
|
||
| const factory = FjsStandaloneCompiler({ | ||
| readMode: false, | ||
| storeFunction (routeOpts, schemaSerializationCode) { | ||
| const fileName = generateFileName(routeOpts) | ||
| t.ok(routeOpts) | ||
| fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) | ||
| t.pass(`stored the serializer function ${fileName}`) | ||
| }, | ||
| restoreFunction () { | ||
| t.fail('write mode ON') | ||
| } | ||
| }) | ||
|
|
||
| const app = buildApp(factory, { | ||
| mode: 'not-standalone', | ||
| rounding: 'ceil' | ||
| }) | ||
|
|
||
| await app.ready() | ||
| }) | ||
|
|
||
| t.test('fastify integration - readMode', async t => { | ||
| t.plan(6) | ||
|
|
||
| const factory = FjsStandaloneCompiler({ | ||
| readMode: true, | ||
| storeFunction () { | ||
| t.fail('read mode ON') | ||
| }, | ||
| restoreFunction (routeOpts) { | ||
| const fileName = generateFileName(routeOpts) | ||
| t.pass(`restore the serializer function ${fileName}}`) | ||
| return require(path.join(__dirname, fileName)) | ||
| } | ||
| }) | ||
|
|
||
| const app = buildApp(factory) | ||
| await app.ready() | ||
|
|
||
| let res = await app.inject({ | ||
| url: '/foo', | ||
| method: 'POST' | ||
| }) | ||
| t.equal(res.statusCode, 200) | ||
| t.equal(res.payload, JSON.stringify({ hello: 'world' })) | ||
|
|
||
| res = await app.inject({ | ||
| url: '/bar?lang=it', | ||
| method: 'GET' | ||
| }) | ||
| t.equal(res.statusCode, 200) | ||
| t.equal(res.payload, JSON.stringify({ lang: 'en' })) | ||
| }) | ||
|
|
||
| function buildApp (factory, serializerOpts) { | ||
| const app = fastify({ | ||
| exposeHeadRoutes: false, | ||
| jsonShorthand: false, | ||
| schemaController: { | ||
| compilersFactory: { | ||
| buildSerializer: factory | ||
| } | ||
| }, | ||
| serializerOpts | ||
| }) | ||
|
|
||
| app.addSchema({ | ||
| $id: 'urn:schema:foo', | ||
| type: 'object', | ||
| properties: { | ||
| name: { type: 'string' }, | ||
| id: { type: 'integer' } | ||
| } | ||
| }) | ||
|
|
||
| app.post('/foo', { | ||
| schema: { | ||
| response: { | ||
| 200: { | ||
| $id: 'urn:schema:response', | ||
| type: 'object', | ||
| properties: { | ||
| hello: { $ref: 'urn:schema:foo#/properties/name' } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }, () => { return { hello: 'world' } }) | ||
|
|
||
| app.get('/bar', { | ||
| schema: { | ||
| response: { | ||
| 200: { | ||
| $id: 'urn:schema:response:bar', | ||
| type: 'object', | ||
| properties: { | ||
| lang: { type: 'string', enum: ['it', 'en'] } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }, () => { return { lang: 'en' } }) | ||
|
|
||
| return app | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.