shunsuke.nakamura
shunsuke.nakamura

Reputation: 93

How to get the id from the path parameter of an HTTP request in Cloud Functions (nodejs)

I'm currently developing a serverless application with GCP Cloud Functions (nodejs). In the following code, I am able to separate the behavior depending on the method of the request, but I don't know how to get the id of the path parameter.

For example, if I want to retrieve one user, the path would be /users/:id. I want to retrieve the id in the path and search the DB, but I am stuck because I cannot retrieve the id. (PUT and DELETE too) Does anyone know anything about this?

I thought I could get it with req.params.id, but I guess not....

import type {HttpFunction} from '@google-cloud/functions-framework/build/src/functions';

export const httpServer: HttpFunction = (req, res) => {
  const path = req.path;
  switch(path) {
    case '/users' :
      handleUsers(req, res);
      break;
    default: 
      res.status(200).send('Server is working');
  }
};

const handleUsers: HttpFunction = (req, res) => {

  if (req.method === 'GET') {
    res.status(200).send('Listing users...');
  } else if (req.method === 'POST') {
    res.status(201).send('Creating User...')
  } else if (req.method === 'PUT') {
    res.status(201).send('Updating User...')
  } else if (req.method === 'DELETE') {
    res.status(201).send('Delating User...')
  } else {
    res.status(404);
  }
}


export const helloWorld: HttpFunction = (req, res) => {
  res.send('Hello, World');
};

There is one more problem.

For example, handleUsers will not be called if the path is "/users/1" in the current swich statement. So we want to solve that too.

Furthermore, in the future, there may be paths like "/users/1/hogehoge" ....

Upvotes: 0

Views: 1338

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

You need to use the Express params property of the request, but you have to note the following option detailed in the doc: When a regular expression is used for the route definition, "the capture groups are provided in the array using req.params[n], where n is the nth capture group".

So the following should work:

req.params[0]


req.params actually returns { '0': '...' }

Upvotes: 1

Related Questions