Skip to content

powerkernel/sls-utils

Repository files navigation

sls-utils

Maintainability Test Coverage Build Status Dependency Status Download Status

Power Kernel utils for serverless

Installation

npm install @powerkernel/sls-utils --save

Documentation

Common utils to use with serverless framework

Available utils

The following utils are svailable: response

Auto add headers

headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Credentials': true,
}

Success response

response.success = ({ headers = {}, code = 200, data = {} });

Failure response

response.failure = ({ headers = {}, code = 500, error = {} });

Complete Example

Here's an example of a serverless function that uses response to output the response.

import { response } from "@powerkernel/sls-utils";

import uuid from "uuid";
import * as dynamoDbLib from "./libs/dynamodb-lib";

export async function main(event, context) {
  const data = JSON.parse(event.body);
  const params = {
    TableName: process.env.tableName,
    Item: {
      userId: event.requestContext.identity.cognitoIdentityId,
      noteId: uuid.v1(),
      content: data.content,
      attachment: data.attachment,
      createdAt: Date.now()
    }
  };

  try {
    await dynamoDbLib.call("put", params);
    return response.success({ data: params.Item});
  } catch (e) {
    return response.failure({ error: { message: "Something went wrong." }});
  }

License

Copyright (c) 2020 Power Kernel

Licensed under the MIT license.