npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lambda-things

v1.22.6

Published

Lambda Things

Downloads

194

Readme

Lambda-Things

This library has useful tools for lambda functions.

Changes

  • 1.22.5

    • Html type added to response options
    • Headers added to response options
  • 1.22.4

    • Add Get Day/Week/Month Series for Postgres Queries to tools
  • 1.22.3

    • Add DelaySeconds to Queue options
  • 1.22.0

    • Added Multipart Parse functions
      • Parse
      • getBoundary
  • 1.21.0

    • Added functions to Tools
      • sort
      • shuffle
      • removeItem
      • removeDuplicates
  • 1.20.0

    • Added capitalize function to Tools
  • 1.19.0

    • Added random number generator function to Tools
  • 1.18.0

    • Update Secret System Parameter function
  • 1.17.20

    • Allow for Updates to have arrays for fields in the where clause
  • 1.17.17

    • Add CONFLICT on Postgres options for Inserts
  • 1.17.10

    • Fixed some Postgres query bugs
  • 1.17.1

    • Postgres Update function now has an optional options property that can specify a "returning"
  • 1.17.0

    • Date formatting function
  • 1.16.1

    • Allow brackets
  • 1.16.0

    • Added convertToSnakeCase method
  • 1.15.2

    • Added PostgresProxy function which uses AWS RDS Proxy
  • 1.14.17

    • Added tools
  • 1.14.9

    • Improved docs
  • 1.14.5

    • Added Crypto methods
      • crypto.encrypt : encrypts a string using AES 256
      • crypto.decrypt : decrypts a string using AES 256
      • crypto.saltHashPassword : Creates Salt and Hash for a string
      • crypto.validatePassword : Validates a string against a Hash and Salt
  • 1.14.0

    • Added two Redis methods
      • createExpiringList, createExpiringHash
    • Removed
      • createExpiringKey
  • 1.13.0

    • Pass key store config parameters into Postgres constructor instead of actual key values
  • 1.10.0

    • If "returning" is specified in an INSERT query it will return the specified keys.
  • 1.9.11

    • Specify status code
    • Path Params
  • 1.9.0

    • Removed callbacks from functions.
    • Streamlined promise functions.
  • 1.7.4

    • Queue invoke method changed. Added call function.
  • 1.7.2

    • Added new Expiry methods to redis lib.
  • 1.7.1

    • Queue method has changed. Instantiate queue and call send. Returns Promise. Callback can be provided in which case listen for callback.
  • 1.6.7

    • postgres.select has optional options parameter where limit, order and offset can be defined.

To install:

npm install lambda-things
const _ = require('lambda-things');

Multipart Parser

Parses multipart form data

let parser = new _.multipart(event);

parser.on('field', (key, value) => {
    console.log('received field', key, value);
});

parser.on('file', file => {
    console.log('file', file);
});

parser.on('finish', async result => {
    // result.files // (array of file streams)
    // result.fields //(object of field key/values)

    let files = result.files;
    let fields = result.fields;
});

parser.parse();

Date Formatter

Formats a Date object into a string

_.dates.format(new Date(), 'The date is {MM}/{dd}/{yyyy}!'));

Tools

Simple functions that do stuff

const cleanedString = _.cleanString('my \t string is \n full of stuff');

Crypto

Provides methods for encrypting, decrypting data and creating salts and hashes for passwords

const crypto = new _.crypto();

// 256 bit secret
const key = 'dkghwjrn5kgrjsfDFbfd34dsfgvasdfg';

// Encrypting data
let encryptedData = crypto.encrypt('This is secret text', key);
console.log('Encrypted Data', encryptedData);

// Decrypting data
let decryptedData = crypto.decrypt(encryptedData, key);
console.log('Decrypted Data', decryptedData);

// Create Salt and Hash for password
let saltHash = crypto.saltHashPassword('mypassword123');
console.log('Salt Hash', saltHash);

// Check password against Salt and Hash - Success
let passwordCheck = crypto.validatePassword(
    'mypassword123',
    saltHash.hash,
    saltHash.salt
);
console.log('Password mypassword123', passwordCheck);

// Check password against Salt and Hash - Failure
let passwordCheck2 = crypto.validatePassword(
    'mypassword124',
    saltHash.hash,
    saltHash.salt
);
console.log('Password mypassword124', passwordCheck2);

Payload Parser

Parses the 'event' argument and returns the following structure.

let payload = _.payload(event);

{
	authorizerPrincipalId, // if the user has authenticated
    user_id, // if user_id present in jwt token
    data : {
		// These are all the QueryString, Path Params and Body arguments
	},
	context : {
		// contains information like user IP
	}
}

Response

Formats the Response object for internal invocation or API Gateway requests.

try {
    let result = await processPayload(payload);
    return _.response(null, result, {
        event: event,
        basic: true,
        html: true,
        headers : {
            header1 : value1,
            header2: value2
        }
    });
} catch (err) {
    return _.response(err, null, { event: event });
}

// Returns

// basic: true

{
    my : 'info'
}

// basic : false

{
    result : {
        my : 'info'
    },
    err : {}
}

Invoke Lambda Function

This will invoke a Lambda function.


let invoke = new _.invoke();

const result = await invoke.call(
	'<name of lambda function>',
	{
		some : 'arguments';
	});

Postgres

Basic Query

Will execute a query on Postgresql.
If "limit 1" is used in the query the result will be a single object. If not then result will be an array.

Instantiate the postgres object

var postgres = new _.postgres(
    {
        user: 'user_key_name',
        database: 'dbname_key_name',
        password: 'password_key_name',
        host: 'host_key_name',
        port: 'port_key_name',
        max: 100
    },
    true
);

Instantiate the postgres Proxy object

This uses the AWS RDS proxy

var postgres = new _.postgresProxy(
    {
        user: 'user_key_name',
        database: 'dbname_key_name',
        password: 'password_key_name',
        host: 'host_key_name',
        port: 'port_key_name',
        max: 100
    },
    true
);

INSERT raw query

Signature

function query(query)

Example

let result = await postgres.query(
    `insert into users (name, age) values ('bob', 42) returning id;`
);

Select Single

Signature

function select(table, fields, where, options)

Example

let result = await postgres.select(
    'table_name',
    'field1, field2',
    { field3: 'some value' },
    {
        limit: 1,
        order: 'field2 DESC',
        offset: 5
    }
);

Select Multiple

Signature

function select(table, fields, where, options)

Example

let result = await postgres.select(
    'table_name',
    'field1, field2',
    {
        field3: ['data1', 'data2']
    },
    {
        limit: 1,
        order: 'field2',
        offset: 5
    }
);

Delete

Signature

function delete(table, where)

Example

let result = await postgres.delete('table_name', { field1: 'data1' });

Update

Signature

function update(table, data, where)

Example

let result = await postgres.update(
    'table_name',
    { field1: 'data1' },
    { id: 'something' }
);

Insert Single

Signature

function insert(table, items)

Example

let result = await postgres.insert('table_name', {
    field1: 'data1',
    field2: 'data2'
});

Insert Multiple

Signature

function insert(table, items)

Example

let result = await postgres.insert('table_name', [
    {
        field1: 'data1',
        field2: 'data1.2'
    },
    {
        field1: 'data2',
        field2: 'data2.1'
    },
    {
        field1: 'data3',
        field2: 'data3.1'
    }
]);

Redis

Initialise

let redis = new _.redis(host, port);

Will execute a Redis query.

let result = await redis.hGet('name');

Create an expiring Hash

/**
 * Set Expiry on Hash
 *
 * @param {string} key
 * Redis Key
 *
 * @param {EXPIRY} expiryType
 * The Expiry Type defined in redis.EXPIRY
 *
 * @param {number} expiryPeriod
 * The number of periods as defined in expiryType
 *
 * @param {number} rounding
 * Round down to the nearest
 *
 */
let expiringHash = await redis.createExpiringHash(
    key,
    expiryType,
    expiryPeriod,
    rounding
);

Create an expiring Hash

/**
 * Set Expiry on List
 *
 * @param {string} key
 * Redis Key
 *
 * @param {EXPIRY} expiryType
 * The Expiry Type defined in redis.EXPIRY
 *
 * @param {number} expiryPeriod
 * The number of periods as defined in expiryType
 *
 * @param {number} rounding
 * Round down to the nearest
 *
 */
let expiringHash = await redis.createExpiringList(
    key,
    expiryType,
    expiryPeriod
);

Queue

Send data to a SQS Queue

let queue = new _.queue();

let result = await queue.send(
    'load-transactions',
    { name: 'lorien' },
    { queue_owner_aws_account_id: '' }
);

The lambda function that consumes the queue will receive the data in this Formats

const payload = _.payload(event);

if (payload.is_queue) {
    _.response = callback; // callback from lambdaHandler

    if (
        !payload.data.records ||
        (payload.data.records && !payload.data.records.length)
    ) {
        logger.error('no records', payload.data);
        return _.response('Invalid arguments', null, { event });
    }

    const result = processQueuePayload(payload);
} else {
    const result = processPayload(payload);
}

let processQueuePayload = async function (payload) {
    payload.data.records.forEach(data => {
        // do something with data
    });
};

let processPayload = async function (payload) {
    // process payload.data
};

Secrets

Fetches secrets from AWS parameter store

const secrets = new _.secrets();

let awsAccessKeys = await secrets.getMultiple(['secret1', 'secret2'], true);

let awsAccessKey = await secrets.get('secret1', true);