Home > front end >  How do I add parameters to long-form return requests in module.exports routes?
How do I add parameters to long-form return requests in module.exports routes?

Time:10-10

I'm coding for an API connection area, that's predominately graphql but needs to have some REST connections for certain things, and have equivalent to the following code:

foo.js

module.exports = {
  routes: () => {
    return [
      {
        method: 'GET',
        path: '/existing_endpoint',
        handler: module.exports.existing_endpoint
      }, 
      {
        method: 'POST',
        path: '/new_endpoint',
        handler: module.exports.new_endpoint // <--- this not passing variables
      }
    ]
  }, 
    existing_endpoint: async () => {
       /* endpoint that isn't the concern of this */ 
    }, 
    new_endpoint: async (req, res) => {
        console.log({req, res})
        return 1
    }
}

The existing GET endpoint works fine, but my POST endpoint always errors out with the console of {} where {req, res} should have been passed in by the router, I suspect because the POST isn't receiving. I've tried changing the POST declaration in the routes to module.exports.new_endpoint(req, res), but it tells me the variables aren't found, and the lead-in server.js does have the file (it looks more like this...), and doing similar with the server.js, also getting similar results, implying that's probably wrong too. Also, we have a really strict eslint setup, so I can't really change the format of the call.

Every example I've seen online using these libraries is some short form, or includes the function in the routes call, and isn't some long form like this. How do I do a POST in this format?

/* hapi, environment variables, apollog server, log engine, etc. */
/* preceeding library inclusions */ 
const foo = require('./routes/foo')
const other_route = require('./routes/other_route')

const startServer = async () => {
    const server = Hapi.server({port, host})

    server.route(other_route.routes())
    server.route(foo.routes())
}

CodePudding user response:

This is a bug with Hapi in node v16. I just opened an issue.

Your current solutions are either:

  • Upgrade to Hapi v20
  • Use n or another method to downgrade to node v14.16 for this project. I can confirm that POST requests do not hang in this version.
  • Related