Welcome to the Linux Foundation Forum!

fastify-reply-from with transform stream

arturo.miguel.next
edited November 19 in LFW212 Class Forum

Hello

Could someone explain to me why this does not work?

'use strict'

const {Transform, Readable} = require('stream');
const createTransformStream = () => {
  new Transform({
    transform(chunk, enc, next) {
      const uppercase = chunk.toString().toUpperCase();
      next(null, uppercase);
    }
  })
}
const uppercaseStream = createTransformStream();


module.exports = async function (fastify, opts) {
  fastify.get('/', async function (request, reply) {
    const { url } = request.query;
    try {
      new URL(url)
    } catch (error) {
      throw fastify.httpErrors.badRequest() 
    }
    await reply.from(url, {
      onResponse(req, reply, response) {
        reply.send(response.pipe(uppercaseStream));
      }
    });
  })
}

Thanks

Comments

  • I forgot to return the Transform

    'use strict'
    
    const {Transform, Readable} = require('stream');
    const createTransformStream = () => {
      return new Transform({
        transform(chunk, enc, next) {
          const uppercase = chunk.toString().toUpperCase();
          next(null, uppercase);
        }
      })
    }
    const uppercaseStream = createTransformStream();
    
    
    module.exports = async function (fastify, opts) {
      fastify.get('/', async function (request, reply) {
        const { url } = request.query;
        try {
          new URL(url)
        } catch (error) {
          throw fastify.httpErrors.badRequest() 
        }
        await reply.from(url, {
          onResponse(req, reply, response) {
            reply.send(response.pipe(uppercaseStream));
          }
        });
      })
    }
    

Categories

Upcoming Training