Coder Social home page Coder Social logo

fast-json-stringify-compiler's Introduction

@fastify/fast-json-stringify-compiler

Build and manage the fast-json-stringify instances for the fastify framework. This package is responsible for compiling the application's response JSON schemas into optimized functions to speed up the response time.

js-standard-style CI

Versions

@fastify/fast-json-stringify-compiler fast-json-stringify Supported fastify
v1.x v3.x ^3.x
v2.x v3.x ^4.x
v3.x v4.x ^4.x
v4.x v5.x ^4.x

fast-json-stringify Configuration

The fast-json-stringify configuration is the default one. You can check it the default settings in the fast-json-stringify option documentation.

You can also override the default configuration by passing the serializerOpts configuration to the Fastify instance.

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.

fast-json-stringify Standalone

[email protected] 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:

  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.

const { StandaloneSerializer } = require('@fastify/fast-json-stringify-compiler')

const factory = StandaloneSerializer({
  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.
const { StandaloneSerializer } = require('@fastify/fast-json-stringify-compiler')

const factory = StandaloneSerializer({
  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 functions.

License

Licensed under MIT.

fast-json-stringify-compiler's People

Contributors

climba03003 avatar dependabot[bot] avatar eomm avatar fdawgs avatar ivan-tymoshenko avatar mcollina avatar uzlopak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fast-json-stringify-compiler's Issues

Updating for v5

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

๐Ÿ‘‹ I'm Matteo, and would like to work on this.
Coming from Fastify issue #5116 (fastify/fastify#5116)

From what I've understood, I need to:

  • Update any NPM dependencies that might be updated
  • Update the workflow to use the version 4 of plugins-ci

If there's anything I'm missing, please do let me know

Compiled serializer is huged because of `serializerState`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the regression has not already been reported

Last working version

4.20

Stopped working in version

4.3.0

Node.js version

20.x

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

๐Ÿ’ฅ Regression Report

Every compiled schema contains a stringified version of the schema. Issue is when the schema is huged.
Today it almost kills the advantage of compilation.

It comes from the bump to v5.7.0 of fast-json-stringify.
And to be specific if comes from : fastify/fast-json-stringify#617.

It seems that this getState() of the serializer is never used.

Steps to Reproduce

async function main() {
  const app = fastify({
    exposeHeadRoutes: false,
    jsonShorthand: false,
    schemaController: {
      compilersFactory: {
        buildSerializer: writeSerializerFactory,
      },
    },
    logger: {
      level: 'debug'
    }
  });

  addAllSchemas(app);

  await app.register(async api => {
    api.register(... all handlers ...)
  });

  await app.ready().then(() => {
    app.log.info('Ready, all serializer compiled');
    app.close();
  });
}


export const writeSerializerFactory = StandaloneSerializer({
  readMode: false,
  storeFunction(routeOpts, schemaSerializationCode) {
    if (routeOpts.method === 'HEAD') {
      return;
    }
    writeFileSync(generateSerializerFilePath(routeOps), schemaSerializationCode);
  },
});

Expected Behavior

Why have this serializerState ? Is does not seem to be used at all ?

Bump fast-json-stringify dependency to 4.1.0

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.0.1

Plugin version

3.0.0

Node.js version

16.14.2

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Unrelated

Description

In fastify/fastify@cf46dea a new fast-json-stringify version is used but only as a dev dependency. I have an older project upgraded to Fastify 4.0.1, but the fast-json-stringify version in my package-lock remained at 4.0.0 instead of 4.1.0, so bumping the version here seems appropriate.

Steps to Reproduce

Upgrading a project with a lock made prior to the 4.1.0 release.

Expected Behavior

No response

Is type `SerializerCompiler` correct ?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hello,

From my research, I have the feeling that the declared SerializerCompiler might be wrong.

In fastify, compiler is eventually called this way :

serializerCompiler({
    schema,
    method,
    url,
    httpStatus,
    contentType
  })

In fast-json-stringify-compiler; with jfsOpts being already bounded,

function responseSchemaCompiler (fjsOpts, { schema /* method, url, httpStatus */ }) { ... }

My conclusion is that SerializerCompiler should be:

export type SerializerCompiler = (routeDef : RouteDefinition) => Serializer;

What do you think ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.