- 
          
- 
                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 7 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,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; | 
  
    
      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 && 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) { | ||
|         
                  Eomm marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| throw new Error('You must provide a function for the restoreFunction-option 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
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  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.