@janiscommerce/sls-api-response

1.5.0 • Public • Published

Serverless API Response

Build Status Coverage Status npm version

A package to handle Serverless API Responses

Installation

npm install @janiscommerce/sls-api-response

Usage

'use strict';

const { ApiResponse } = require('@janiscommerce/sls-api-response');

// Successful response (default statusCode is 200)
ApiResponse.send({
	body: {
		foo: 'bar'
	}
});

// Successful response with response headers
ApiResponse.send({
	body: {
		foo: 'bar'
	},
	headers: {
		'x-foo': 'bar'
	}
});

// Successful response with simple cookie
ApiResponse.send({
	body: {
		foo: 'bar'
	},
	cookies: {
		'my-cookie': 'bar'
	}
});

// Successful response with complex cookie
ApiResponse.send({
	body: {
		foo: 'bar'
	},
	cookies: {
		'my-cookie': {
			value: 'bar',
			httpOnly: true,
			secure: true,
			path: '/',
			expires: new Date(), // Or (new Date()).toUTCString()
			domain: '.example.com'
		}
	}
});

// Error response (default statusCode is 500)
ApiResponse.sendError(new Error('We have a problem'));
// Response body: { "message": "We have a problem" }

// Error response for a request with a client
ApiResponse.sendError(new Error('We have a problem'), 'some-client-code');
// Response body: { "message": "We have a problem" }

// Error response with custom status code
const error = new Error('You have a problem');
error.statusCode = 400;
ApiResponse.sendError(error);
// Response body: { "message": "You have a problem" }

// Error response with custom response body
const error = new Error('You have a problem');
error.body = { customErrorMessage: "Bad request body" }
ApiResponse.sendError(error);
// Response body: { "customErrorMessage": "Bad request body" }

Configuration

In order to work properly, you have to set valid response templates in each function configuration. An example can be found here

Readme

Keywords

none

Package Sidebar

Install

npm i @janiscommerce/sls-api-response

Weekly Downloads

409

Version

1.5.0

License

ISC

Unpacked Size

8.28 kB

Total Files

5

Last publish

Collaborators

  • janiscommerce