简体   繁体   中英

Importing helper functions in Serverless

I want to import a helper function into a Node.js Lambda function in Serverless (AWS). I've tried using Layer functions, as well as a wrapper module for Serverless - but nothing has worked so far.

This is the function I want to use with other Lambda functions - helperFunc.js :

class HelperClass { ... } //a helper class that I want to use in other functions
module.exports = HelperClass 

This is one of my Lambda functions. It also serves an API Gateway endpoint - users.js :

"use strict";

const helperClass = require('./helperFunc') //I don't know how to do this

module.exports.get = (event, context, callback) => {

  const params = { ... } //DynamoDB Params
  // a bunch of code that uses the helper class wrapper

  callback(null, { 
    headers: {
      "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
      "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS 
    }, body: JSON.stringify(res), statusCode: 200})
  }
};

This is what my serverless.yml currently looks like:

... 
getUsers:
    handler: src/users.get
    events:
      - http:
          path: users
          method: get
          authorizer: authFunc

And this what my project directory looks like:

./ 
  serverless.yml
  ./src
      helperFunc.js
      users.js
  ./auth

UPDATE 1 : I was finally able to achieve this functionality using Lambda Layers. However, it still feels as if it's not the best way to do this mainly due to the complex directory set-up.

Here's the updated project directory:

./ 
  serverless.yml
  ./layers/helperFunc/nodejs/node_modules/helperFunc
      index.js
  ./src
      users.js
  ./auth

And here is the updated serverless.yml file:

layers:
  helperFunc:
    path: layers/helperFunc
...
functions:
  getUsers:
    handler: src/users.get
    layers:
      - {Ref: HelperFuncLambdaLayer} # referencing the layer in cf
    events:
      - http:
         path: users
         method: get
         authorizer: authFunc

The solution is to use serverless-webpack-plugin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM