Categories
Fastify

Server-Side Development with Fastify — Hooks

Spread the love

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

preParsing Hook

The preParsing hook lets us transform the request payload stream before it’s parsed.

If it returns a value, it must return a stream.

For example, we can write:

const fastify = require('fastify')({})

fastify.addHook('preParsing', (request, reply, payload, done) => {
  done(null, payload)
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send()
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to pass payload into the done function.

Also, we can write:

const fastify = require('fastify')({})

fastify.addHook('preParsing', async (request, reply, payload) => {
  return payload
})
const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send()
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to return a promise resolving to payload .

preValidation

The preValidation hook lets us run code before validating the request.

It runs after the preParsing hook.

For instance, we can write:

const fastify = require('fastify')({})

fastify.addHook('preValidation', (request, reply, done) => {
  done()
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send()
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We can add some checks into the callback.

We can also write:

const fastify = require('fastify')({})

fastify.addHook('preValidation', async (request, reply) => {
  return
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send()
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to do the same thing.

preSerialization

The preSerialization hook letsus change or replace the payload before it’s serialized.

For instance, we can write:

const fastify = require('fastify')({})

fastify.addHook('preSerialization', (request, reply, payload, done) => {
  const err = null
  const newPayload = { wrapped: payload }
  done(err, newPayload)
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send(request.body)
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Then when we make a POST request to / with the payload:

{
    "abc": 123
}

We get:

{
    "wrapped": {
        "abc": 123
    }
}

as the response.

Equivalently, we can write:

const fastify = require('fastify')({})

fastify.addHook('preSerialization', async (request, reply, payload) => {
  return { wrapped: payload }
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send(request.body)
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

and get the same result.

This hook isn’t called if the payload is a string, buffer, stream or null .

onError

The onError hook lets us catch errors that occur in our app.

For example, we can write:

const fastify = require('fastify')({})

fastify.addHook('onError', (request, reply, error, done) => {
  done()
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send(request.body)
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to catch errors. error has the error data.

Likewise, we can write:

const fastify = require('fastify')({})

fastify.addHook('onError', async (request, reply, error) => {
  console.log(error)
})

const start = async () => {
  try {
    fastify.post('/', function (request, reply) {
      reply.send(request.body)
    })
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to do the same thing.

Conclusion

We can add hooks to listen to various events with Fastify.

Leave a Reply

Your email address will not be published. Required fields are marked *