Is the handler function necessary for cloud functions?

Viewed 79

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?

There is another problem that is even more serious.

For example, if the current swich statement has a path of "/users/1", usersHandler will not be called. So we want to solve that as well.

In addition, in the future, "/users/1/items" .... may exist in the future.

Would this make it tough to use a switch statement?

The easiest way to do this is to use the router function of Express, but I don't think that's a good idea because Express will be deployed as a single function when deployed to cloud functions.

Or can I just deploy multiple functions to cloud functions without creating a Handler?

For example, should I deploy getUsersFunction and deleteUsersFunction separately?

import 'reflect-metadata';
import type {HttpFunction} from '@google-cloud/functions-framework/build/src/functions';
import {TYPES} from './constants/types';
import {container} from './config/inversify-config';
import IUserService from './application/service/users/IUserService';

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

const usershandler: HttpFunction = (req, res) => {
  if (req.method === 'GET') {
    getUsersFunction(req, res); //If :id is present in the path parameters, we want to call getUserFunction.
  } 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 getUsersFunction: HttpFunction = async (req, res) => {
  const service = container.get<IUserService>(TYPES.UserService);
  res.status(200).send(await service.getUsers());
};

export const getUserFunction: HttpFunction = async (req, res) => {
  const service = container.get<IUserService>(TYPES.UserService);
  res.status(200).send(await service.getUser(id));
};
0 Answers
Related