0

I stumble upon this code snippet while working on fastify.

module.exports = async function (fastify, opts) {
  fastify.register(proxy, {
    upstream: 'htt‌ps://news.ycombinator.com/',
    async preHandler(request, reply) {
      if (request.query.token !== 'abc') {
        throw fastify.httpErrors.unauthorized();
      }
    },
  });
};

Looks like it calls fastify.register with two parameters and the second parameter is an object. The first field is upstream but I don't get what comes next. What is this syntax after async preHandler(request, reply)...?

Dai
  • 141,631
  • 28
  • 261
  • 374
han
  • 97
  • 1
  • 1
  • 5
  • It's a method. `async` means it's an async method body, so it always returns a promise and enables the usage of `await`. – VLAZ Nov 30 '21 at 11:10
  • 7
    It's just a method. It's the same as `{ preHandler: async function(request, reply) { ... } }` - [Method definitions - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) – Andreas Nov 30 '21 at 11:10
  • @VLAZ I'm looking at the ECMAScript grammar rules and the rules seem to require `async function` or `async $methodName` - I'm not seeing `async $functionName` as being permissable. – Dai Nov 30 '21 at 11:11
  • 3
    You're missing that `preHandler` is in an object. so is implicitly a function. `{async preHandler() {}}` – Liam Nov 30 '21 at 11:12
  • @Liam ahhhhh, clever – Dai Nov 30 '21 at 11:12
  • 1
    @Dai it's a shorthand method notation `{foo: function() {} }` == `{foo() {} }` it is *almost* the same. Shorthand methods cannot be called with `new` otherwise work the same as `function() {}` – VLAZ Nov 30 '21 at 11:15

1 Answers1

2

fastify.register seemingly has this signature: fastify.register(proxy, {});. So the second parameter is an object.

As stated in MDN and by Andreas in comments you can have an object that contains a method signature. So your object can be declared as:

{
   upstream: string,
   preHandler(request, reply){}
}

Where preHandler(request, reply){} is essentially a shorthand for preHandler: function(request, reply){}

You can then declare this method signature async (again as stated in docs). Which results in:

{
   async preHandler(request, reply){}
}

The above could also be declared as:

{
   preHandler: async function(request, reply){}
}
Liam
  • 27,717
  • 28
  • 128
  • 190