Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

aws-core-utils

Package Overview
Dependencies
Maintainers
1
Versions
80
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

aws-core-utils - npm Package Compare versions

Comparing version 7.2.0 to 8.0.0

CHANGES.md

138

api-lambdas.js

@@ -55,13 +55,7 @@ 'use strict';

/** Deprecated - use `succeedLambdaCallback` instead */
exports.succeedCallback = succeedCallback;
/** Deprecated - use `failLambdaCallback` instead */
exports.failCallback = failCallback;
/** Deprecated - use `failLambdaCallback` instead */
exports.failCallbackForApiGateway = failCallback; // Synonym for failCallback
/**
* Generates a handler function for your API Gateway exposed Lambda. This function still supports the legacy 5th to 9th
* parameters (logRequestResponseAtLogLevel, allowedHttpStatusCodes, invalidRequestMsg, failureMsg & successMsg) by
* adding them to an `opts` object.
* Generates a handler function for your API Gateway exposed Lambda. This function still supports some of the legacy 5th
* to 9th parameters (logRequestResponseAtLogLevel, allowedHttpStatusCodes, invalidRequestMsg, failureMsg & successMsg)
* by adding them to an `opts` object. Note that any legacy 6th allowedHttpStatusCodes argument is no longer supported
* and will be ignored.
*

@@ -71,29 +65,12 @@ * @param {(function(): (Object|StandardHandlerContext))|undefined|Object|StandardHandlerContext} [createContext] - an

* LEGACY module-scope context from which to copy an initial standard context)
* @param {(function(): (Object|StandardHandlerSettings))|undefined|Object|StandardHandlerSettings} [createSettings] - an optional
* function that will be used to create the initial standard handler settings to use (OR optional LEGACY module-scoped
* settings from which to copy initial settings to use)
* @param {(function(): (Object|StandardHandlerOptions))|undefined|Object|StandardHandlerOptions} [createOptions] - an optional
* function that will be used to create the initial standard options to use (OR optional LEGACY module-scoped
* options from which to copy initial options to use)
* @param {function(event: AWSEvent, context: StandardHandlerContext)} fn - your function that must accept the AWS event and a
* standard context and ideally return a Promise
* @param {Object|LogLevel|string|undefined} [opts] - optional opts to use (or legacy LogLevel/string
* @param {(function(): (Object|StandardHandlerSettings))|undefined|Object|StandardHandlerSettings} [createSettings] -
* an optional function that will be used to create the initial standard handler settings to use (OR optional
* LEGACY module-scoped settings from which to copy initial settings to use)
* @param {(function(): (Object|StandardHandlerOptions))|undefined|Object|StandardHandlerOptions} [createOptions] - an
* optional function that will be used to create the initial standard options to use (OR optional LEGACY module-
* scoped options from which to copy initial options to use)
* @param {function(event: AWSEvent, context: StandardHandlerContext)} fn - your function that must accept the AWS event
* and a standard context and ideally return a Promise
* @param {HandlerOpts|LogLevel|string|undefined} [opts] - optional opts to use (or a legacy LogLevel/string
* `logRequestResponseAtLogLevel` parameter)
* @param {boolean|undefined} [opts.useLambdaProxy] - whether your Lambda is using Lambda Proxy Integration or not
* (defaults to false for backward compatibility)
* @param {Object|undefined} [opts.defaultHeaders] - default custom headers (if any) to be included in a Lambda Proxy
* response
* @param {number[]|undefined} [opts.allowedHttpStatusCodes] - an optional array of HTTP status codes that are allowed
* to be returned directly to API Gateway (without conversion to either 400 or 500). NB: 400 and 500 CANNOT be
* excluded and are assumed to be present if omitted! If not defined, the app-errors module's list of supported
* HTTP status codes will be used as the allowed HTTP status codes
* @param {LogLevel|string|undefined} [opts.logRequestResponseAtLogLevel] - an optional log level at which to log the
* request (i.e. AWS event) and response; if log level is undefined or invalid, then logs neither
* @param {string|undefined} [opts.invalidRequestMsg] - an optional message to log at warn level if your given function
* (fn) throws a BadRequest
* @param {string|undefined} [opts.failureMsg] - an optional message to log at error level on failure
* @param {string|undefined} [opts.successMsg] an optional message to log at info level on success
* @param {ToErrorResponse|undefined} [opts.toErrorResponse] - an optional function to use to convert an AppError into
* an appropriate error response object (to be subsequently stringified & returned) or error response body (to be
* subsequently included in a Lambda Proxy error response to be returned)
* @returns {AwsLambdaHandlerFunction} a handler function for your API Gateway exposed Lambda

@@ -106,3 +83,3 @@ */

newOpts.logRequestResponseAtLogLevel = isString(opts) ? opts : undefined;
newOpts.allowedHttpStatusCodes = arguments[5];
// newOpts.allowedHttpStatusCodes = arguments[5]; // no longer supported
newOpts.invalidRequestMsg = arguments[6];

@@ -123,3 +100,3 @@ newOpts.failureMsg = arguments[7];

try {
context = configureHandlerContext(createContext, createSettings, createOptions, event, awsContext, opts);
context = configureHandlerContext(createContext, createSettings, createOptions, event, awsContext);

@@ -181,6 +158,5 @@ // Optionally log the request

* @param {Object} awsContext - the AWS context passed to your handler
* @param {HandlerSettings|HandlerOptions|undefined} [opts] - optional opts to use
* @return {StandardHandlerContext} the handler context to use
*/
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext, opts) {
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext) {
// Configure the context as a standard context

@@ -200,5 +176,4 @@ let context = typeof createContext === 'function' ? createContext() :

// Merge the relevant opts into handler options, then merge handler options into handler settings and finally merge
// the result into context.handler
const handlerOptions = mergeHandlerOpts(opts, (options && options.handler) || {});
// Merge the handler options into the handler settings and finally merge their result into context.handler
const handlerOptions = (options && options.handler) || {};
const handlerSettings = settings && settings.handler ?

@@ -214,3 +189,3 @@ mergeHandlerOpts(handlerOptions, settings.handler) : handlerOptions;

* ONLY if the same options or settings do NOT already exist in the `to` handler opts.
* @param {HandlerSettings|HandlerOptions|Object} from - the source handler configuration
* @param {HandlerSettings|HandlerOptions|Object|undefined} [from] - the source handler configuration
* @param {HandlerSettings|HandlerOptions} to - the destination handler configuration

@@ -432,77 +407,2 @@ */

return error && error.toJSON();
}
/**
* @deprecated Use `succeedLambdaCallback` instead
* Succeeds the given callback of an AWS Lambda, which is exposed via API Gateway, with the given response or body, by
* invoking the given lambdaCallback with a JSON stringified version of the converted app error. The given AWS context
* is used to add your Lambda's AWS request ID to the error.
*
* @param {Function} callback - the callback function passed as the last argument to your Lambda function on invocation.
* @param {Object} response - a normal or Lambda Proxy integration response to be returned
* @param {Object|undefined} [opts] - optional opts to use
* @param {boolean|undefined} [opts.useLambdaProxy] - whether your Lambda is using Lambda Proxy Integration or not (defaults to false for backward compatibility)
* @param {Object|undefined} [opts.defaultHeaders] - default custom headers to be included (if any) in a Lambda Proxy response
*/
function succeedCallback(callback, response, opts) {
if (!opts || typeof opts !== 'object') opts = {};
if (opts.useLambdaProxy) {
const statusCode = response && isNotBlank(response.statusCode) ? response.statusCode : 200;
const body = (response && response.body) || response || {};
const proxyResponse = toLambdaProxyResponse(statusCode, response && response.headers, body, opts.defaultHeaders);
callback(null, proxyResponse);
} else {
callback(null, response);
}
}
/**
* @deprecated Use `failLambdaCallback` instead
* Fails the given callback of an AWS Lambda, which is exposed via API Gateway, with the given error, by first
* attempting to convert the given error into one of the standard app errors (see {@linkcode core-functions/app-errors})
* that will be mappable on API Gateway, and then invoking the given lambdaCallback with a JSON stringified version of
* the converted app error. The given AWS context is used to add your Lambda's AWS request ID to the error.
*
* @see module:core-functions/app-errors#toAppErrorForApiGateway
*
* @param {Function} lambdaCallback - the callback function passed as the last argument to your Lambda function on invocation.
* @param {Error} error - the error with which you need to fail your Lambda
* @param {Object|undefined} [error.headers] - optional headers to include in a Lambda Proxy integration error response
* @param {string|undefined} [error.auditRef] - an optional audit reference
* @param {string|undefined} [error.awsRequestId] - an optional AWS request ID
* @param {Object|undefined} [awsContext] - the AWS context passed as the second argument to your Lambda function on invocation
* @param {string|undefined} [awsContext.awsRequestId] - the AWS context's request ID
* @param {string|undefined} [message] - an optional message (will use error's message if not specified)
* @param {string|undefined} [code] - an optional code (will use error's code if not specified)
* @param {Object|number[]|undefined} [opts] - optional opts to use (OR a legacy array of numeric `allowedHttpStatusCodes` parameter)
* @param {number[]|undefined} [opts.allowedHttpStatusCodes] - an optional array of HTTP status codes that are allowed to be returned directly to API Gateway (without conversion to either 400 or 500). NB: 400 and 500 CANNOT be excluded and are assumed to be present if omitted! If not defined, the app-errors module's list of supported HTTP status codes will be used as the allowed HTTP status codes
* @param {boolean|undefined} [opts.useLambdaProxy] - whether your Lambda is using Lambda Proxy Integration or not (defaults to false for backward compatibility)
* @param {Object|undefined} [opts.defaultHeaders] - default custom headers to be included (if any) in a Lambda Proxy response
*/
function failCallback(lambdaCallback, error, awsContext, message, code, opts) {
// Check if still using legacy `allowedHttpStatusCodes` as 6th parameter
if (!opts || typeof opts !== 'object') {
opts = {allowedHttpStatusCodes: Array.isArray(opts) ? opts : undefined};
}
// Convert the error into an "API" error
const apiError = appErrors.toAppErrorForApiGateway(error, message, code, opts.allowedHttpStatusCodes);
// Resolve the AWS request id (if available)
apiError.awsRequestId = trim(apiError.awsRequestId) || trim(error.awsRequestId) ||
(awsContext && trim(awsContext.awsRequestId)) || undefined;
// Resolve the audit reference (if available) - falling back to AWS request ID (if available)
apiError.auditRef = trim(apiError.auditRef) || trim(error.auditRef) || apiError.awsRequestId;
if (opts.useLambdaProxy) {
const statusCode = apiError.httpStatus;
const body = toDefaultErrorResponseBody(apiError);
const proxyResponse = toLambdaProxyResponse(statusCode, error.headers, body, opts.defaultHeaders);
lambdaCallback(null, proxyResponse);
} else {
const errorResponse = toDefaultErrorResponse(apiError);
lambdaCallback(JSON.stringify(errorResponse), null);
}
}

@@ -6,4 +6,2 @@ 'use strict';

const appErrors = require('core-functions/app-errors');
/**

@@ -30,5 +28,2 @@ * Utilities for working with AWS Lambda:

// Function to assist with failing the callback of an AWS Lambda (not exposed via API Gateway) and preserve the information of the error thrown
exports.failCallback = failCallback;
/**

@@ -148,26 +143,2 @@ * Returns the function name from the given AWS context

aliasOrVersion : '';
}
/**
* Fails the given callback of an AWS Lambda, which is NOT exposed via API Gateway, with the given error, by first
* attempting to convert the given error into one of the standard app errors (see {@linkcode core-functions/app-errors})
* and then invoking the given lambdaCallback with a JSON stringified version of the converted error. The given AWS
* context is used to add your Lambda's AWS request ID to the error.
*
* Note that this function must NOT be used for any Lambda invoked by API Gateway - for these you MUST instead use the
* {@linkcode aws-core-utils/api-lambdas#failCallback} function.
*
* @see core-functions/app-errors.js
*
* @param {Function} lambdaCallback - the callback function passed as the last argument to your Lambda function on invocation.
* @param {Error} error - the error with which you need to fail your Lambda
* @param {AWSContext|undefined} [awsContext] - the AWS context passed as the second argument to your Lambda function on invocation
* @param {string|undefined} [awsContext.awsRequestId] - the AWS context's request ID
* @param {string|undefined} [message] - an optional message; will use error's message if not specified and needed
* @param {string|undefined} [code] - an optional code; will use error's code if not specified and needed
*/
function failCallback(lambdaCallback, error, awsContext, message, code) {
const appError = appErrors.toAppError(error, message, code);
if (awsContext && !appError.awsRequestId) appError.awsRequestId = awsContext.awsRequestId;
lambdaCallback(JSON.stringify(appError));
}

@@ -63,12 +63,3 @@ 'use strict';

* standard context and ideally return a Promise
* @param {Object|LogLevel|string|undefined} [opts] - optional opts to use (or legacy LogLevel/string
* `logRequestResponseAtLogLevel` parameter)
* @param {LogLevel|string|undefined} [opts.logRequestResponseAtLogLevel] - an optional log level at which to log the
* request (i.e. AWS event) and response; if log level is undefined or invalid, then logs neither
* @param {string|undefined} [opts.invalidRequestMsg] - an optional message to log at warn level if your given function
* (fn) throws a BadRequest
* @param {string|undefined} [opts.failureMsg] - an optional message to log at error level on failure
* @param {string|undefined} [opts.successMsg] an optional message to log at info level on success
* @param {ToErrorResponse|undefined} [opts.toErrorResponse] - an optional function to use to convert an AppError into
* an appropriate error response object (to be subsequently stringified & returned)
* @param {HandlerOpts|Object|undefined} [opts] - optional opts to use
* @returns {AwsLambdaHandlerFunction} a handler function for your API Gateway exposed Lambda

@@ -88,3 +79,3 @@ */

try {
context = configureHandlerContext(createContext, createSettings, createOptions, event, awsContext, opts);
context = configureHandlerContext(createContext, createSettings, createOptions, event, awsContext);

@@ -146,6 +137,5 @@ // Optionally log the request

* @param {Object} awsContext - the AWS context passed to your handler
* @param {HandlerSettings|HandlerOptions|undefined} [opts] - optional opts to use
* @return {StandardHandlerContext} the handler context to use
*/
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext, opts) {
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext) {
// Configure the context as a standard context

@@ -165,5 +155,4 @@ let context = typeof createContext === 'function' ? createContext() :

// Merge the relevant opts into handler options, then merge handler options into handler settings and finally merge
// the result into context.handler
const handlerOptions = mergeHandlerOpts(opts, (options && options.handler) || {});
// Merge the handler options into the handler settings and finally merge their result into context.handler
const handlerOptions = (options && options.handler) || {};
const handlerSettings = settings && settings.handler ?

@@ -179,3 +168,3 @@ mergeHandlerOpts(handlerOptions, settings.handler) : handlerOptions;

* ONLY if the same options or settings do NOT already exist in the `to` handler opts.
* @param {HandlerSettings|HandlerOptions|Object} from - the source handler configuration
* @param {HandlerSettings|HandlerOptions|Object|undefined} [from] - the source handler configuration
* @param {HandlerSettings|HandlerOptions} to - the destination handler configuration

@@ -182,0 +171,0 @@ */

{
"name": "aws-core-utils",
"version": "7.2.0",
"version": "8.0.0",
"description": "Core utilities for working with Amazon Web Services (AWS), including ARNs, regions, stages, Lambdas, AWS errors, stream events, Kinesis, DynamoDB.DocumentClients, etc.",

@@ -14,10 +14,10 @@ "author": "Byron du Preez",

"dependencies": {
"core-functions": "3.0.22",
"core-functions": "3.0.23",
"deep-equal": "1.0.1",
"logging-utils": "4.0.22"
"logging-utils": "4.0.23"
},
"devDependencies": {
"aws-sdk": "2.190.0",
"aws-core-test-utils": "3.0.7",
"tape": "^4.8.0",
"aws-core-test-utils": "3.0.8",
"tape": "^4.9.0",
"uuid": "3.1.0"

@@ -24,0 +24,0 @@ },

@@ -1,2 +0,2 @@

# aws-core-utils v7.2.0
# aws-core-utils v8.0.0

@@ -70,17 +70,14 @@ Core utilities for working with Amazon Web Services (AWS), including ARNs, regions, stages, Lambdas, AWS errors, stream events, Kinesis, DynamoDB.DocumentClients, etc.

const BadRequest = appErrors.BadRequest;
const context = {}; // or your own pre-configured context
const standardOptions = require('./test/context-options.json'); // with whatever options you want to use to configure stage handling, logging, custom settings, ...
const standardSettings = undefined; // or whatever settings object you want to use to configure stage handling, logging, custom settings, ...
const createContext = () => ({}); // or your own pre-configured context
// To configure your handler to use Lambda Proxy integration and custom default response headers
const createOptions = () => require('./test/api-lambdas-context-options-2.json'); // with whatever options you want to use to configure your handler, stage handling, logging, custom settings, ...
const createSettings = () => undefined; // or whatever settings object you want to use to configure your handler, stage handling, logging, custom settings, ...
function exampleFunction(event, context) { /* ... */ } // implement and name your own function that does the actual work
// Simplest approach - generate your API Gateway exposed Lambda's handler function
module.exports.handler = apiLambdas.generateHandlerFunction(context, standardSettings, standardOptions, exampleFunction);
// OR ... using all optional arguments to use Lambda Proxy integration with a custom default response header and to
// change the allowed HTTP status codes and customise logging in the handler function
const opts = {
useLambdaProxy: true,
defaultHeaders: {myCustomHeader: 'myCustomHeaderValue'},
allowedHttpStatusCodes: [400, 404, 500],
logRequestResponseAtLogLevel: 'info',
logRequestResponseAtLogLevel: 'INFO',
invalidRequestMsg: 'Invalid request ...',

@@ -90,11 +87,9 @@ failureMsg: 'Failed to ...',

};
module.exports.handler = apiLambdas.generateHandlerFunction(context, standardSettings, standardOptions, exampleFunction, opts);
// Simplest approach - generate your API Gateway exposed Lambda's handler function
exports.handler = apiLambdas.generateHandlerFunction(createContext, createSettings, createOptions, exampleFunction, opts);
// OR ... develop your own Lambda handler function (e.g. simplistic example below - see apiLamdas.generateHandlerFunction for a better version)
module.exports.handler = (event, awsContext, callback) => {
// OR ... develop your own Lambda handler function (e.g. simplistic example below - see apiLamdas.generateHandlerFunction for a MUCH better version)
exports.handler = (event, awsContext, callback) => {
const opts = {
// useLambdaProxy: false,
// defaultHeaders: undefined
// allowedHttpStatusCodes: undefined,
// logRequestResponseAtLogLevel: 'info',

@@ -107,5 +102,5 @@ // invalidRequestMsg: 'Invalid request ...',

// Configure a standard context
const context = {};
let context = {};
try {
apiLambdas.configureStandardContext(context, standardSettings, standardOptions, event, awsContext);
context = apiLambdas.configureHandlerContext(createContext, createSettings, createOptions, event, awsContext);

@@ -116,3 +111,3 @@ // ... execute Lambda specific code passing the context to your functions as needed

context.info(opts.successMsg || 'Finished ...');
apiLambdas.succeedCallback(callback, response, opts);
apiLambdas.succeedLambdaCallback(callback, response, event, context);
})

@@ -127,3 +122,3 @@ .catch(err => {

}
apiLambdas.failCallback(callback, err, awsContext, undefined, undefined, opts);
apiLambdas.failLambdaCallback(callback, err, event, context);
});

@@ -135,13 +130,10 @@

context.error('Failed to ...', err);
apiLambdas.failCallback(callback, err, awsContext, undefined, undefined, opts);
apiLambdas.failLambdaCallback(callback, err, event, context);
}
};
```
ALTERNATIVE opts for `succeedCallback` & `failCallback`:
```js
const apiLambdas = require('aws-core-utils/api-lambdas');
// ...
// ALTERNATIVE handler options for `succeedLambdaCallback` & `failLambdaCallback`:
// Fail your Lambda callback: using Lambda Proxy integration; using a custom response header; and map the error to one of a specified set of HTTP status codes
const opts = {
context.handler = { // simplistic example - should rather be set through an appropriate `context-options.json` file
useLambdaProxy: true,

@@ -151,4 +143,3 @@ defaultHeaders: {MyCustomHeader: 'MyCustomHeaderValue'},

};
apiLambdas.failCallback(callback, err, awsContext, 'My error msg', 'MyErrorCode', opts);
apiLambdas.failLambdaCallback(callback, new Error('Boom'), event, context);
```

@@ -166,2 +157,4 @@

const arnResources = arns.getArnResources(arn);
assert(arnComponent && arnPartition && arnService && arnRegion && arnAccountId && arnResources);
```

@@ -172,2 +165,4 @@

const awsErrors = require('aws-core-utils/aws-errors');
assert(awsErrors);
```

@@ -232,2 +227,4 @@

const deleted = dynamoDBDocClientCache.deleteDynamoDBDocClient('eu-west-1');
assert(dynamoDBDocClient && dynamoDBDocClient1 && dynamoDBDocClient2 && optionsUsed1 && optionsUsed2 && deleted);
```

@@ -271,2 +268,4 @@

const deleted = kinesisCache.deleteKinesis('eu-west-1');
assert(kinesis && kinesis1 && kinesis2 && optionsUsed1 && optionsUsed2 && deleted);
```

@@ -309,2 +308,4 @@ * To use the KMS cache to configure and cache an AWS KMS instance per region

const deleted = kmsCache.deleteKMS('eu-west-1');
assert(kms && kms1 && kms2 && optionsUsed1 && optionsUsed2 && deleted);
```

@@ -383,2 +384,4 @@

const deleted = lambdaCache.deleteLambda('eu-west-1');
assert(lambda && lambda1 && lambda2 && optionsUsed1 && optionsUsed2 && deleted);
```

@@ -422,5 +425,3 @@

// Fail a Lambda's callback with a standard error and preserve HTTP status codes (for non-API Gateway Lambdas)
// See core-functions/app-errors.js for standard errors to use
lambdas.failCallback(lambdaCallback, error, awsContext, message, code);
assert(alias && functionName && functionVersion && functionNameVersionAndAlias && invokedFunctionArn && invokedFunctionArnFunctionName);
```

@@ -582,2 +583,2 @@

## Changes
See [release_notes.md](./release_notes.md)
See [CHANGES.md](CHANGES.md)

@@ -589,2 +589,12 @@ 'use strict';

/**
* @typedef {Object} HandlerOpts - optional opts to use when generating a handler function
* @property {LogLevel|string|undefined} [logRequestResponseAtLogLevel] - an optional log level at which to log the
* request (i.e. AWS event) and response; if log level is undefined or invalid, then logs neither
* @property {string|undefined} [invalidRequestMsg] - an optional message to log at warn level if your given function
* (fn) throws a BadRequest
* @property {string|undefined} [failureMsg] - an optional message to log at error level on failure
* @property {string|undefined} [successMsg] an optional message to log at info level on success
*/
/**
* @typedef {Object} HandlerOptions - options to be used to configure a standard handler context for an AWS Lambda

@@ -591,0 +601,0 @@ * `handler` function

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc