Express 我可以使用 fast-json-stringify 代替 express.json 吗?

问题描述 投票:0回答:1

JSON fast stringify 非常快,我想问你可以将中间件express.json 替换为 json-fast-stringify/fast json parse 吗?

如果是,我该如何使用中间件来做到这一点?

Ps:我看到了一些基准测试,当任何人使用 json fast stringify 或 fast json (parse) 时,改进都非常好

node.js express
1个回答
0
投票

是的,你可以!您需要为每个 api 定义一个响应模式并为该 api 构建一个 stringify 函数,例如:

const express = require('express')
const fastJson = require('fast-json-stringify')

const app = express()

const apiResponseSchema = {
  title: 'Example Schema',
  type: 'object',
  properties: {
    foo: {
      type: 'string'
    }
}
const stringifyFunction = fastJson(apiResponseSchema)

app.get('/my-api', function (req, res) {
  const responseData = { foo: 'bar' }
  res.type('json');
  res.send(stringifyFunction(responseData));
})
© www.soinside.com 2019 - 2024. All rights reserved.