🚨 Shai-Hulud Strikes Again:834 Packages Compromised.Technical Analysis
Socket
Book a DemoInstallSign in
Socket

simple-lambda-actions

Package Overview
Dependencies
Maintainers
1
Versions
81
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

simple-lambda-actions

Library for common lambda actions

Source
npmnpm
Version
1.2.45
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

Common Lambda Actions

A collection of common operations done with AWS Lambda

Table of Contents

Intro

DynamoDB

Secrets Manager

Auth With Secrets Manager

Auth Without Secrets Manager

Responder

Schemas

Examples

Intro

This library aims to centralize your commonly performed actions. They are designed to reduce the amount of times you have to write the same get, put, functions for projects utilizing the AWS-SDK.

Responses {#intro-responses}

Almost of these helpers utilize promises. You must await the return of the promise to get the proper response

Errors {#intro-errors}

Returned errors will contain a standard and a custom property.

The standard is what is sounds like. The general description for the status code.

The custom will have any available message thrown by the error it originated from.

Example:

// code 400
{
  "standard": "Bad request",
  "custom": "One of the required keys was not given a value"
}

DynamoDB

These are mainly wrappers around DynamoDB actions, abstracting as much as possible.

Get Item

Arguments

NameTypeDescription
tableNameStringName of the table you're searching
keyObjectThe key schema for the searched for item
shouldLogParamsBooleanOptional flag for logging the params before the operation

Import Path

const { getItem } = require('simple-lambda-actions/dist/dynamo')

Response

Returns a promise, which will resolve to:

{
  // your item
  superImportantAttribute: 'YAAAAAASSSS'
}

Errors

Error CodeTextDescription
400Bad RequestUsually thrown when you pass a tableName that cannot be found
404Not FoundThrown when the key schema provided did not match any records
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const getItem = require('simple-lambda-actions/dist/dynamo')

exports.handler = async event => {
  const item = await getItem(tableName, keySchema)
  // finish and return response
}

Put Item

Arguments

NameTypeDescription
tableNameStringName of the table you're searching
itemObjectThe item you wish to write, must contain partition key
shouldLogParamsBooleanOptional flag for logging the params before the operation

Import Path

const { putItem } = require('simple-lambda-actions/dist/dynamo')

Response

Returns a promise, which will resolve to an empty object. This comes directly from DynamoDB.

Errors

Error CodeTextDescription
400Bad RequestUsually thrown when you pass a tableName that cannot be found, or if you omit a required key
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const putItem = require('simple-lambda-actions/dist/dynamo')

exports.handler = async event => {
  await putItem(tableName, parsedBody, true)
  // parsedBody is what was written
}

Update Item

Arguments

NameTypeDescription
tableNameStringName of the table you're searching
configObjectThe configuration for updating the record. Schema can be found here
shouldLogParamsBooleanOptional flag for logging the params before the operation

Import Path

const { updateItem } = require('simple-lambda-actions/dist/dynamo')

Response

Returns a promise, which will resolve to an empty object. This comes directly from DynamoDB.

Errors

Error CodeTextDescription
400Bad RequestUsually thrown when you pass a tableName that cannot be found, or if you omit a required key
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const updateItem = require('simple-lambda-actions/dist/dynamo')

exports.handler = async event => {
  await updateItem(tableName, parsedBody, true)
  // parsedBody is what was written
}

Query Item

Arguments

NameTypeDescription
paramsObjectThe params configuration for querying the records. Schema can be found here
shouldLogParamsBooleanOptional flag for logging the params before the operation

Import Path

const { queryItem } = require('simple-lambda-actions/dist/dynamo')

Response

Returns a promise, which will resolve to the object containing the array of items meeting your criteria, as well as the counts.

{
    "Items": [
        {
           // your item
        }
    ],
    "Count": 1,
    "ScannedCount": 1
}

Errors

Error CodeTextDescription
400Bad RequestUsually thrown when you pass a tableName that cannot be found, or if you omit a required key
404Not FoundWhen no records match your provided query
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const queryItem = require('simple-lambda-actions/dist/dynamo')

exports.handler = async event => {
  const items = await queryItem(params)
  // parsedBody is what was written
}

Transact Write

This library supports the following actions:

  • ConditionCheck
  • Delete
  • Put
  • Update

Arguments

NameTypeDescription
operationsArrayArray of transactional operations. The expected schema can be found here
shouldLogParamsBooleanOptional flag for logging the params before the operation

Import Path

const { transactWrite } = require('simple-lambda-actions/dist/dynamo')

Response

Returns a promise, which will resolve to an empty object.

Errors

Error CodeTextDescription
400Bad RequestUsually thrown when you pass a tableName that cannot be found, or if you omit a required key
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const transactWrite = require('simple-lambda-actions/dist/dynamo')

const operationsConfig = [
  {
    operationType: 'update',
    TableName: 'TEST_TABLE',
    itemSpecificInfo: {
      partitionKey: '...',
      sortKey: '121212'
    },
    // otherParams will be spread on the operation
    otherParams: {
      UpdateExpression: 'set #a = :x + :y',
      ConditionExpression: '#a < :MAX',
      ExpressionAttributeNames: {'#a' : 'Sum'},
      ExpressionAttributeValues: {
        ':x' : 20,
        ':y' : 45,
        ':MAX' : 100,
      }
    }
  }
]

exports.handler = async event => {
  try {
    await transactWrite(operationsConfig) // will return a promise with an empty object
  } catch (error){
    const { message, statusCode } = error
    // bubble gum in a dish, do what you wish
  }
}

Authentication With Secrets Manager

These functions are integrated with Secrets Manager, and will fetch the signing key, then perform the auth action in one function call

Secret Validate Token

Arguments

NameTypeDescription
secretIdStringThe name of your secret key
givenTokenStringThe token you wish to validate

Import Path

const { validateTokenWithSecretsManager } = require('simple-lambda-actions/dist/auth')

Response

Returns a promise, which will resolve to:

{
  // your decoded token
}

Errors

Error CodeTextDescription
403UnauthorizedWhen the token is invalid, or not provided
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const { validateToken } = require('simple-lambda-actions/dist/auth')
const secretId = '...'

exports.handler = async event => {
  const givenToken = event.headers.Authorization
  const decodedPayload = await validateToken(secretId, givenToken)
  // finish and return response
}

Secret Generate Token

Arguments

NameTypeDescription
secretIdStringID of the secret key you will use to sign the token
payloadToEncodeObjectWhat you wish to include inside of the token
expiresInStringDuration of token validity. A more comprehensive solution can be found here and here

Import Path

const { generateTokenWithSecretsManager } = require('simple-lambda-actions/dist/auth')

Response

Returns the token in the form of a string.

{
  token: 'eyasbdjbqjbh12312i7uebkjb' // your token
}

Errors

Error CodeTextDescription
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const { generateToken } = require('simple-lambda-actions/dist/auth')
const secretId = '...'

exports.handler = async event => {
  const parsedBody = JSON.parse(event.body)
  const expiresIn = '24h'
  const decodedPayload = await generateToken(secretId, parsedBody, expiresIn )
  // finish and return response
}

Authentication Without Secrets Manager

These functions are standalone operations. They are the underlying blocks for the integration with Secrets Manager

Non Secret Validate Token

Arguments

NameTypeDescription
tokenStringThe token you want to validate
signingKeyStringThe secret key you want to use to validate tokens

Import Path

const { validateToken } = require('simple-lambda-actions/dist/auth/lib')

Response

Returns a promise, which will resolve to:

{
  // your decoded token
}

Errors

Error CodeTextDescription
403UnauthorizedWhen the token is invalid, or not provided
500Internal ErrorGeneric internal server error given when error does not provide code

Example

const { validateToken } = require('simple-lambda-actions/dist/auth')
const signingKey = '...'

exports.handler = async event => {
  const givenToken = event.headers.Authorization
  const decodedPayload = await validateToken(givenToken, signingKey)
  // finish and return response
}

Schemas

Update Item Config

The following must be provided to the updateItem function as the config

NameTypeDescriptionExampleRequired
KeyObjectThe key schema of the item being updatedKeyYes
ExpressionAttributeNamesObjectHow DynamoDB will reference the attribute name of the item being changedExpression NameYes
ExpressionAttributeValuesObjectHow DynamoDB will reference the attribute value being changedExpression ValuesYes
UpdateExpressionStringThis comma delimited list determines which operations are performedUpdate ExpressionYes
ReturnValuesStringUpdate ExpressionYes

Transact Write Operation

The following is the schema of a single operation inside of an array which will be executed sequentially in the transactWrite helper

NameTypeDescriptionExampleRequired
operationTypeStringEnum mapping for the type of operation the operation will be performing. Not case sensitivedeleteYes
TableNameStringName of the table that this operation will be performed ondevelopment-userTableYes
itemSpecificInfoObjectThe data specific to this operation, such as primary key, or the item being writtenKey or ItemYes
otherParamsObjectOther parameters specific to your operation that may be needed for the specific use case.Update Expression, Expression Values, etcNo

Query Items

The following is the schema for the params of querying items. If using a range ( sort ) key, all of the range parameters are required. You can however omit them, and just query based on the partition.

NameTypeDescriptionExampleRequired
partitionKeyNameStringName of the partition key on the table you're queryingemailAddressYes
partitionKeySearchTermStringValue of partition key you are querying. MUST match exactlyyo.mama@lit.liveYes
rangeKeyNameStringName of the range key on the table you're queryingroleNo
rangeKeySearchTermStringValue of range key you are queryingadminNo
rangeKeyComparisonOperatorStringEnum of available comparison operators. List of supported options herebegins_withNo

Examples

Various examples where space might have been limited

DynamoDB

Key Schema

{
  "partitionKey": "yo ho, yo ho",
  "rangeKey": "a pirates life for me"
}

Expression Attribute Name

In this example, #key_to_update represents the attribute you are targeting for change, where keyToUpdate is the actual attribute name.

Dynamo creates a reference to this key through the first value, and will use it to reference your item attribute.

{ 
  "#key_to_update": "keyToUpdate",
  // more
}

Expression Attribute Values

In this example, :nv represents the new value in the same way Expression Name's work. :nv is mapped to newValue and will represent it in further operations

{
  ":nv": "newValue",
  // more
}

Update Expression

Here we are performing the set operation, on the key previously determined, setting the new value to the mapped result of :nv

const UpdateExpression = 'set #new_key = :nv,more...'

Supported Comparison Operators

More information can be found here

Currently the following operators are supported, anything else will throw an error.

The limiting factor is due to uniformity on how the condition expression is formulated.

  • =
  • <
  • >
  • <=
  • >=
  • attribute_exists
  • attribute_not_exists
  • begins_with
  • contains

Various examples where space might have been limited

DynamoDB

Key Schema

{
  "partitionKey": "yo ho, yo ho",
  "rangeKey": "a pirates life for me"
}

Expression Attribute Name

In this example, #key_to_update represents the attribute you are targeting for change, where keyToUpdate is the actual attribute name.

Dynamo creates a reference to this key through the first value, and will use it to reference your item attribute.

{ 
  "#key_to_update": "keyToUpdate",
  // more
}

Expression Attribute Values

In this example, :nv represents the new value in the same way Expression Name's work. :nv is mapped to newValue and will represent it in further operations

{
  ":nv": "newValue",
  // more
}

Update Expression

Here we are performing the set operation, on the key previously determined, setting the new value to the mapped result of :nv

const UpdateExpression = 'set #new_key = :nv,more...'

Supported Comparison Operators

More information can be found here

Currently the following operators are supported, anything else will throw an error.

The limiting factor is due to uniformity on how the condition expression is formulated.

  • =
  • <
  • >
  • <=
  • >=
  • attribute_exists
  • attribute_not_exists
  • begins_with
  • contains

FAQs

Package last updated on 05 Feb 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts