Single endpoint for get/post/put/patch/delete/head

Greetings,

Is it possible to use the same function name for get/post/put/patch/delete/head requests?

I have tried the following with no luck:

functions:
  user:
    handler: functions/user.handler
    events:
      - http: GET user/{handler}
      - http: POST user/{handler}
      - http: PATCH user/{handler}

And in my index.js I have:

exports.get = (req, res) => {
  response.status(200).send('user get request');
};

exports.post = (req, res) => {
  response.status(200).send('user post request');
};

exports.patch = (req, res) => {
  response.status(200).send('user patch request');
};

Ideally I wouldn’t have to create individual http endpoints for each of these. e.g. /user-get, /user-post

Thank you for the help!

I think the method you’re after is “ANY” but I’m struggling to find it mentioned in the docs that I can link to…

I did find it in the code so am confident it will work for you.

Thank you for the response!

So essentially, I’ll use the any method, and route by default to a single node function (e.g. exports.http) which will in turn route to the correct method by determining the request method?

Looks like the any method is not required. I was able to get it working with the following code:

serverless.yml

functions:
  user:
    handler: http
    events:
      - http: path

index.js

function get (req, res) {
  res.status(200).send('user get request');
}

function head (req, res) {
  res.status(200).send('user post request');
}

function post (req, res) {
  res.status(200).send('user post request');
}

function put (req, res) {
  res.status(200).send('user put request');
}

function patch (req, res) {
  res.status(200).send('user patch request');
}

exports.http = (req, res) => {
  switch (req.method) {
    case 'GET':
      get(req, res);
      break;
    case 'HEAD':
      head(req, res);
      break;
    case 'POST':
      post(req, res);
      break;
    case 'PUT':
      put(req, res);
      break;
    case 'PATCH':
      patch(req, res);
      break;
    default:
      res.status(500).send({ error: 'Method not supported!' });
      break;
  }
}
1 Like

ANY works. I think it’s AWS specific while @smick appears to be using GCP.

Ah, my bad! I just assumed AWS.