|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const t = require('node:test') |
| 4 | +const Fastify = require('fastify') |
| 5 | +const { request } = require('undici') |
| 6 | +const From = require('..') |
| 7 | +const http = require('node:http') |
| 8 | + |
| 9 | +t.test('text/event-stream proxying with custom content type parser', async (t) => { |
| 10 | + t.plan(6) |
| 11 | + |
| 12 | + // Target server that sends SSE data |
| 13 | + const target = http.createServer((req, res) => { |
| 14 | + t.assert.ok('request proxied') |
| 15 | + t.assert.strictEqual(req.method, 'POST') |
| 16 | + t.assert.match(req.headers['content-type'], /^text\/event-stream/) |
| 17 | + |
| 18 | + let data = '' |
| 19 | + req.setEncoding('utf8') |
| 20 | + req.on('data', (chunk) => { |
| 21 | + data += chunk |
| 22 | + }) |
| 23 | + req.on('end', () => { |
| 24 | + // Verify the SSE data is received |
| 25 | + t.assert.match(data, /data: test message/) |
| 26 | + t.assert.match(data, /event: custom/) |
| 27 | + |
| 28 | + res.setHeader('content-type', 'application/json') |
| 29 | + res.statusCode = 200 |
| 30 | + res.end(JSON.stringify({ received: 'sse data' })) |
| 31 | + }) |
| 32 | + }) |
| 33 | + |
| 34 | + // Fastify instance with custom text/event-stream parser |
| 35 | + const fastify = Fastify() |
| 36 | + |
| 37 | + // Register custom content type parser for text/event-stream |
| 38 | + // This allows the raw body to be passed through without parsing |
| 39 | + fastify.addContentTypeParser('text/event-stream', function (req, body, done) { |
| 40 | + done(null, body) |
| 41 | + }) |
| 42 | + |
| 43 | + fastify.register(From) |
| 44 | + |
| 45 | + fastify.post('/', (request, reply) => { |
| 46 | + reply.from(`http://localhost:${target.address().port}`) |
| 47 | + }) |
| 48 | + |
| 49 | + t.after(() => fastify.close()) |
| 50 | + t.after(() => target.close()) |
| 51 | + |
| 52 | + await fastify.listen({ port: 0 }) |
| 53 | + await target.listen({ port: 0 }) |
| 54 | + |
| 55 | + // Create SSE-like data |
| 56 | + const sseData = 'data: test message\nevent: custom\ndata: another line\n\n' |
| 57 | + |
| 58 | + // Send request with SSE data |
| 59 | + const result = await request(`http://localhost:${fastify.server.address().port}`, { |
| 60 | + method: 'POST', |
| 61 | + headers: { |
| 62 | + 'content-type': 'text/event-stream' |
| 63 | + }, |
| 64 | + body: sseData |
| 65 | + }) |
| 66 | + |
| 67 | + t.assert.deepStrictEqual(await result.body.json(), { received: 'sse data' }) |
| 68 | +}) |
0 commit comments