0

I have some JS files that I'd like to modify before serving them.

They are called with a parameter and I want that parameter to be in the file when served.

Example:

<script src="myjavascript.js?key=mykey"></script

myjavascript.js

var key = ${key} // <-- replaced with request.query.key
console.log(key)

Route:

fastify.get('/include.js', async (request, reply) => {
    let key
    if (request.query.key) {
      key = request.query.key
    }
    if (!key.length == 20) reply.code(400)

    reply.view('server/assets/include.js', { key: key })
  })
HypeWolf
  • 750
  • 12
  • 29

1 Answers1

1

From the reply.view I guess, that you trying to use the point-of-view plugin. The problem with this is that you need to setup a view engine with it which will serve html. You can pass params to the html templates if that is your goal. Please see the examples in the linked repo.

If your goal is serve and generate a file on the fly, then you can achive it with template literals. Please also note, that you need to call send after you setting the reply.code:

const fastify = require('fastify')()

fastify
  .get('/', (request, reply) => {
    const { key } = request.query
    if (key.length !== 20) reply.code(404).send({ error: 'Not Found' })
    reply
      .type('application/javascript; charset=UTF-8')
      .send(`var key = ${key}; console.log(key);`)
  })

fastify.listen(3000, err => {
  if (err) throw err
  console.log('Server is listening on port 3000')
})
lependu
  • 1,160
  • 8
  • 18
  • Would that work for large javascript file? This example have only 2 lines so your solution is clever, but if I have 100 lines, could I use the same approach? – HypeWolf Nov 14 '18 at 15:50
  • 1
    Take a look at the [common-tags](https://github.com/declandewet/common-tags) module. They are using template literals for all kind of tasks. And the advanced section gives you some tips how can you create your own templates. But be careful, these are experimental features, so check it twice before deploy them in production. – lependu Nov 14 '18 at 16:06