A utility library that accounts for the common code across most of the serverless micro-services


Keywords
library, serverless, utility
License
MIT
Install
npm install @please.com/serverless-utils@0.1.27

Documentation

@please.com/serverless-utils

A utility library that contains code usually required when working with Serverless micro-services at Please.com

📚 Documentation

The documentation is divided based on the files inside the repo.

Table of Contents

serverless-utils/db

This file contains just 1 method and that's to connect to MongoDB in a way where if we already have a connection to MongoDB we don't make a new connection on every new request.

// handler.js
const db = require('@please.com/serverless-utils/db');
// it picks up the url of MongoDB from process.env.MONGO_URL
db.connect();

It basically caches the DB connection across multiple lambda invocations.

serverless-utils/responses

It exposes successResponse() & errorResponse() functions to return back a nice API Gateway friendly response from the labmda function.

const { successResponse, errorResponse } = require('@please.com/serverless-utils/responses');
const handler = async event => {
  try {
    const result = await getResultOfMyFunction(event);
    return successResponse(result);
  } catch (error) {
    return errorResponse(error);
  }
};

NOTE: It also takes care of properly stringifying a circular object using json-stringify-safe

serverless-utils/environment

It exposes the environment variables and a few functions to validate them

const {
  env,
  isDev,
  isStaging,
  isProd,
  mongoURL,
  validateMongoEnvVars,
} = require('@please.com/serverless-utils/environment');

// NODE_ENV related
console.log(env); // => this is process.env.NODE_ENV || 'development'
console.log(isDev); // => TRUE when process.env.NODE_ENV === 'development'
console.log(isStaging); // => TRUE when process.env.NODE_ENV === 'staging'
console.log(isProd); // => TRUE when process.env.NODE_ENV === 'production'

// Mongo related
console.log(mongoURL); // => process.env.MONGO_URL

// Validation functions
validateMongoEnvVars(); // throws ERROR if `mongoURL` is empty

serverless-utils/error-with-code

It exposes a function to create and Error object with statusCode, so that if that error object is passed down API Gateway, it responds to the HTTP request with a proper HTTP status code.

const errorWithCode = require('@please.com/serverless-utils/error-with-code');
throw errorWithCode(403, 'Authentication Key is required to access this');

🎁 Contributing guidelines

We have a very small set of measures to take care of while contributing to this repo. Please make sure you go through them once.

🎓 License

MIT