raw-body.js 880 Bytes
/**
 * `registerRawBodyParser` —— JSON content-type parser,给标记了 `config.rawBody` 的路由
 * 保留原始字节(Stripe webhook 验签要求未改写的 body),其余路由正常 `JSON.parse`。
 *
 * 横切,无业务:两个 server 的装配骨架共用一份。
 */

/**
 * @param {import('fastify').FastifyInstance} app
 */
export function registerRawBodyParser(app) {
  app.addContentTypeParser(
    'application/json',
    { parseAs: 'buffer' },
    (request, /** @type {Buffer} */ body, done) => {
      if (request.routeOptions?.config?.rawBody) request.rawBody = body
      try {
        const text = body.length ? body.toString('utf8') : ''
        done(null, text === '' ? undefined : JSON.parse(text))
      } catch (err) {
        /** @type {any} */ (err).statusCode = 400
        done(/** @type {Error} */ (err), undefined)
      }
    },
  )
}