jsonCompression.ts 1.2 KB

1234567891011121314151617181920212223242526
  1. import type Koa from 'koa'
  2. import { gzip } from 'node:zlib'
  3. import { promisify } from 'node:util'
  4. const compress = promisify(gzip)
  5. /** Compress completed API documents only; SSE must flush each event unchanged. */
  6. export const jsonCompression: Koa.Middleware = async (ctx, next) => {
  7. await next()
  8. if (!ctx.path.startsWith('/api/') || ctx.method === 'HEAD' || ctx.status !== 200
  9. || ctx.respond === false || ctx.res.headersSent || !ctx.response.is('application/json')
  10. || ctx.response.get('Content-Encoding') || ctx.body == null) return
  11. const value = ctx.body
  12. if (!Buffer.isBuffer(value) && typeof value !== 'string' && typeof value !== 'object') return
  13. if (typeof value === 'object' && !Buffer.isBuffer(value) && 'pipe' in value) return
  14. const body = Buffer.isBuffer(value) ? value : Buffer.from(typeof value === 'string' ? value : JSON.stringify(value))
  15. if (body.length < 1024) return
  16. ctx.vary('Accept-Encoding')
  17. if (ctx.acceptsEncodings('gzip', 'identity') !== 'gzip') return
  18. const compressed = await compress(body)
  19. if (compressed.length >= body.length) return
  20. ctx.set('Content-Encoding', 'gzip')
  21. ctx.remove('Content-Length')
  22. ctx.body = compressed
  23. ctx.type = 'application/json'
  24. }