| 19 | * @see {@link https://orpc.dev/docs/plugins/compression Compression Plugin Docs} |
| 20 | */ |
| 21 | export class CompressionPlugin<T extends Context> implements NodeHttpHandlerPlugin<T> { |
| 22 | private readonly compressionHandler: ReturnType<typeof compression> |
| 23 | |
| 24 | constructor(options: CompressionPluginOptions = {}) { |
| 25 | this.compressionHandler = compression({ |
| 26 | ...options, |
| 27 | filter: (req, res) => { |
| 28 | const hasContentDisposition = res.hasHeader('content-disposition') |
| 29 | const contentType = res.getHeader('content-type')?.toString() |
| 30 | |
| 31 | /** |
| 32 | * Never compress Event Iterator responses. |
| 33 | */ |
| 34 | if (!hasContentDisposition && contentType?.startsWith('text/event-stream')) { |
| 35 | return false |
| 36 | } |
| 37 | |
| 38 | return options.filter |
| 39 | ? options.filter(req, res) |
| 40 | : compression.filter(req, res) |
| 41 | }, |
| 42 | }) |
| 43 | } |
| 44 | |
| 45 | initRuntimeAdapter(options: NodeHttpHandlerOptions<T>): void { |
| 46 | options.adapterInterceptors ??= [] |
| 47 | |
| 48 | /** |
| 49 | * use `unshift` to ensure this runs before user-defined adapter interceptors |
| 50 | */ |
| 51 | options.adapterInterceptors.unshift(async (options) => { |
| 52 | let resolve: (value: Awaited<ReturnType<typeof options.next>>) => void |
| 53 | let reject: (reason?: any) => void |
| 54 | const promise = new Promise<Awaited<ReturnType<typeof options.next>>>((res, rej) => { |
| 55 | resolve = res |
| 56 | reject = rej |
| 57 | }) |
| 58 | |
| 59 | /** |
| 60 | * These methods are proxied by the compression handler, so we need to |
| 61 | * store the original methods to call them after compression is done |
| 62 | * to prevent side effects to other code outside of this plugin. |
| 63 | * https://github.com/expressjs/compression/blob/master/index.js#L97-L153 |
| 64 | */ |
| 65 | const originalWrite = options.response.write |
| 66 | const originalEnd = options.response.end |
| 67 | const originalOn = options.response.on |
| 68 | |
| 69 | this.compressionHandler( |
| 70 | options.request as any, |
| 71 | options.response as any, |
| 72 | async (err) => { |
| 73 | /* v8 ignore next 3 - this never happen in realtime: https://github.com/expressjs/compression/blob/master/index.js#L243 */ |
| 74 | if (err) { |
| 75 | reject(err) |
| 76 | } |
| 77 | else { |
| 78 | try { |
nothing calls this directly
no outgoing calls
no test coverage detected