@bgcbrasil/shared v2.12.0
bgc-shared
Common utilities used in multiple BGC projects.
Table of contents
- bgc-shared
- Table of contents
- Install
- Usage
- generateAuthResponse
- startStepFunction
- websocketResponse
- CustomError
- DateHelper
- EventHelper
- ErrorHelper
- Logger
- StringHelper
- Validator
- dynamooseQuery
- checkPermissions
- getOwnerPrincipalGroup
- getPrincipalGroup
- Api Response
- Handler
- RDS Response
- NotifyDiscord
- parseEvent
- validateEvent
- Request
- Sleep
- divideArrayInBatches
- findMatchedNames
- Issue Reporting
Install
$ npm install @bgcbrasil/shared
Usage
generateAuthResponse
Parses policy parameters
import { CustomError } from '@bgcbrasil/shared'
generateAuthResponse({
principalId: 'client:cognitoId:clientId',
effect: 'Allow',
methodArd: 'arn::lambda',
contextProps = { // optional
type: 'alex'
}
})
startStepFunction
Starts a step function with a random name and stringified input
import { startStepFunction } from "@bgcbrasil/shared";
import { StepFunction } from "aws";
const stepFunctionService = new StepFunction();
startStepFunction({
input: {
param1: "alex",
},
name: "step",
arn: "arn:123",
stepFunctionService,
});
websocketResponse
Handles a response for a websocket connection
import { websocketResponse } from '@bgcbrasil/shared'
import { ApiGatewayManagementApi } from 'aws'
const apiGatewayManagementApi = new ApiGatewayManagementApi()
websocketResponse({
connectionId: '123' // optional, it will exit gracefully it not provided,
action: 'mywebsocketaction',
data: {
param1: 'alex'
}
apiGatewayManagementApi,
})
CustomError
Returns a custom error
CustomError class expects 3 params: message, status and name
import { CustomError } from "@bgcbrasil/shared";
const err = new CustomError("message", 400, "TestError");
throw err;
DateHelper
DateHelper.now()
Returns the current date in ISO8601 format and 'America/Sao_Paulo' timezone
import { DateHelper } from "@bgcbrasil/shared";
const date = DateHelper.now();
console.log(date); // 2021-04-26T11:44:22-03:00
DateHelper.toIsoFormat(date)
Returns the payload date in ISO8601 format and 'America/Sao_Paulo' timezone
date is a javascript date
import { DateHelper } from "@bgcbrasil/shared";
const date = 1619627754231; // a javascript date
const dateFormated = DateHelper.toIsoFormat(date);
console.log(dateFormated); // 2000-01-01T11:44:22-03:00
DateHelper.toZonedTime(date)
Changes date to 'America/Sao_Paulo' timezone
import { DateHelper } from "@bgcbrasil/shared";
const toZonedTime = DateHelper.toZonedTime(new Date());
DateHelper.isValid(date)
Verify if date is a valid date
import { DateHelper } from "@bgcbrasil/shared";
DateHelper.isValid("12/12/2021", "dd/MM/yyyy");
DateHelper.format(date)
Changes date format
import { DateHelper } from "@bgcbrasil/shared";
const formated = DateHelper.format("12/12/2020", "dd/MM/yyyy", "dd-MM-yyyy");
DateHelper.toDate(date, format)
Receives a string and transforms in a date instance
import { DateHelper } from "@bgcbrasil/shared";
const formated = DateHelper.toDate("12/12/2020", "dd/MM/yyyy");
DateHelper.isAfter(date, dateToCompare)
Returns if the first date is after the second one
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date();
const after = addHours(now, 1);
const isAfter = DateHelper.isAfter(now, after); // false
DateHelper.subtract(date, duration)
Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date(); // Wed Oct 27 2021 22:45:44
const sub = DateHelper.subtract(now, {
hours: 2,
}); // Wed Oct 27 2021 20:45:44
DateHelper.add(date, duration)
Add the specified years, months, weeks, days, hours, minutes and seconds from the given date
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date(); // Wed Oct 27 2021 20:45:44
const add = DateHelper.add(now, {
hours: 2,
}); // Wed Oct 27 2021 22:45:44
DateHelper.valueOf(date)
Get the milliseconds timestamp of the given date
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date(); // Wed Oct 27 2021 22:45:44
const value = DateHelper.valueOf(now); // 1635385544143
DateHelper.startOfDay(date)
Return the start of a day for the given date
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date(); // Wed Oct 27 2021 22:45:44
const startOfDay = DateHelper.startOfDay(now); // Wed Oct 27 2021 00:00:00:000
DateHelper.endOfDay(date)
Return the end of a day for the given date
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date(); // Wed Oct 27 2021 22:45:44
const endOfDay = DateHelper.endOfDay(now); // Wed Oct 27 2021 23:59:59:999
DateHelper.diff(dateLeft, dateRight)
Get the number of milliseconds between the given dates
import { DateHelper } from "@bgcbrasil/shared";
const now = new Date(); // 1635385544143 in milliseconds
const after = addMilliseconds(now, 100); // 1635385544243 in milliseconds
const diff = DateHelper.diff(after, now); // 100
EventHelper
EventHelper.parse({ queryStringSkipParseParameters? })
Parse Lambda event body, request context and query string parameters skipping the ones specified
import { EventHelper } from "@bgcbrasil/shared";
const helper = new EventHelper(event);
const parsedEvent = helper.parse({ queryStringSkipParseParameters: ["cpf"] });
EventHelper.validate({ bodySchema?, pathParameters? })
Validates Lambda event body, and path parameters based on options
import { EventHelper } from "@bgcbrasil/shared";
const helper = new EventHelper(event);
const schema = {
type: "object",
required: ["a"],
properties: {
a: {
type: "string",
},
},
};
helper.validate({ bodySchema: schema, pathParameters: ["searchId"] });
EventHelper.handle({ alwaysValidate? = false, queryStringSkipParseParameters?, bodySchema?, pathParameters? })
Join functionallity of both validate and parse functions. If alwaysValidate is true will validate everyway, else will only validate non API Gateway calls.
import { EventHelper } from "@bgcbrasil/shared";
const helper = new EventHelper(event);
const schema = {
type: "object",
required: ["a"],
properties: {
a: {
type: "string",
},
},
};
const parsedEvent = helper.handle({
alwaysValidate: false,
queryStringSkipParseParameters: ["cpf"],
bodySchema: schema,
pathParameters: ["searchId"],
});
ErrorHelper
ErrorHelper.handleError(message, ,infos, ,local)
Returns errors informations
import { ErrorHelper } from "@bgcbrasil/shared";
const helper = new ErrorHelper([
{ name: "SequelizeUniqueConstraintError", status: 409 },
]);
const { message, status } = helper.handleError(err);
Logger
Logger.info(message, ,infos, ,local, ,depth)
Displays informational massages on console
message string message to be displayed
infos object(s) to be displayed (optional)
local if true only shows logs in local environment (defaults to false)
depth number of recursive calls in objects
Logger.info("info", { info }, true, 2);
Logger.error(message, ,infos, ,local, ,depth)
Displays error massages on console
message string message to be displayed
infos object(s) to be displayed (optional)
local if true only shows logs in local environment (defaults to false)
depth number of recursive calls in objects
Logger.error("error", { error });
Logger.warning(message, ,infos, ,local, ,depth)
Displays warning massages on console
message string message to be displayed
infos object(s) to be displayed (optional)
local if true only shows logs in local environment (defaults to false)
depth number of recursive calls in objects
Logger.warning("warning", { info });
StringHelper
String functions
StringHelper.normalize()
import { StringHelper } from "@bgcbrasil/shared";
const string = new StringHelper("áéíóú").normalize();
console.log(string); // aeiou
StringHelper.camelize()
import { StringHelper } from "@bgcbrasil/shared";
const string = new StringHelper("A B C").camelize();
console.log(string); // aBC
StringHelper.pascalize()
import { StringHelper } from "@bgcbrasil/shared";
const string = new StringHelper("12 3 4 5").pascalize();
console.log(string); // 12345
StringHelper.removeMultipleLineBreaks()
import { StringHelper } from "@bgcbrasil/shared";
const string = new StringHelper(`
A B
C D
`).removeMultipleLineBreaks();
console.log(string); // A B C D
StringHelper.compare(b)
import { StringHelper } from "@bgcbrasil/shared";
const { percentageMatch, levenshtein, similarity } = new StringHelper(
"Ana"
).compare("banana");
Validator
Class to validate params
validator.isCpfValid
Returns if a cpf is valid
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.isCpfValid("55085456033");
validator.isCnpjValid
Returns if a cnpj is valid
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.isCnpjValid("55085456033");
validator.isEmailValid
Returns if a email is valid
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.isEmailValid("pessoa@gmail.com.br");
validator.isNameValid
Returns if a name is valid
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.isNameValid("alex dos santos fulano da silva");
validator.isURLValid
Returns if a url is valid
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.isURLValid("https://google.com.br");
validator.isPhoneValid
Returns if a phone number is valid
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.isPhoneValid("21999998888");
validator.matchSchema
Returns if an object is valid given a JSON Schema object
params:
- object
- schema
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.matchSchema(
{
productId: "1",
productName: "chocolate quente",
number: 1,
phone: "(800)12345667",
},
schema
);
validator.objectHasKeys
Returns if an object contains all keys
import { Validator } from "@bgcbrasil/shared";
const validator = new Validator();
validator.objectHasKeys({ a: "testing", b: 2 }, ["a", "b"], "pathParameters");
dynamooseQuery
Creates and executes a query based on params end model
import { dynamooseQuery } from "@bgcbrasil/shared";
import * as dynamoose from "dynamoose";
const schema = new dynamoose.Schema(
{
id: {
type: String,
},
ownerPrincipalGroup: {
type: String,
required: true,
index: {
name: "ownerPrincipalGroupIndex",
global: true,
},
},
},
{
timestamps: false,
}
);
const model = dynamoose.model(process.env.dynamodbTable, schema, {
create: false,
waitForActive: false,
});
dynamooseQuery({
params: {
ownerPrincipalGroup: "client:4",
},
model,
});
checkPermissions
Checks if users has permission to acess a resource
import { checkPermissions } from "@bgcbrasil/shared";
checkPermissions({
ownerPrincipalGroup: "client:4",
principalGroup: "client:4",
organizationGroups: [], // opcional
});
getOwnerPrincipalGroup
Retunrs user most important group, useful for create searches
import { getOwnerPrincipalGroup } from "@bgcbrasil/shared";
getOwnerPrincipalGroup({
ownerPrincipalGroup: "client:4",
principalGroup: "client:4",
organizationGroups: [], // opcional
});
getPrincipalGroup
Returns user group(s), useful for consults
import { getPrincipalGroup } from "@bgcbrasil/shared";
getPrincipalGroup({
ownerPrincipalGroup: "client:4",
principalGroup: "client:4",
organizationGroups: [], // opcional
});
Api Response
apiResponse(statusCode, , params)
Provides a response object for api's
statusCode the status code of the request
params
header (custom response header)
body (custom response body)
apiResponse(statusCode, { body: { message: "Hi!" } });
Handler
Lambda handler responsible for dealing with errors and event parsing / validation
import { handler } from '@bgcbrasil/shared'
const main = handler(lambda);
const schema = {
type: 'object',
required: ['a'],
properties: {
a: {
type: 'string'
},
}
};
const options = {
errorHelper = new ErrorHelper(),
successCallback = async () => { return; },
errorCallback = async () => { return; },
alwaysValidate: true,
bodySchema: schema,
pathParameters: ['searchId'],
queryStringSkipParseParameters: ['limit'],
};
const response = await main(event, options);
NotifyDiscord
Used to create notifications on discord, sending cloudWatch log url if (requestId and functionName) passed
import { notifyDiscord } from "@bgcbrasil/shared";
async function main(event, context) {
const params = {
content: {
title: "I Hate Alex",
description: "He is so annoying",
color: 16711680,
fields: [{ name: "I am just kidding", value: "He is kinda nice" }],
},
url: "https://discord.com/api/webhooks/842732702344282122/ajN1so4swQ7z_76wfYsLNq87VBWzJ3OzKkRV2D-8b4daV6Mf87vWJQrCof9hlet9j9Pq",
requestId: context.awsRequestId,
functionName, // same name defined in the sls function
};
notifyDiscord(params);
}
parseEvent
Returns a parsed event
import { parseEvent } from "@bgcbrasil/shared";
const event = {
body: { a: "test body" },
queryStringParameters: { a: "test string parameters" },
pathParameters: { a: "test path parameters" },
requestContext: { a: "test request context" },
};
const result = await parseEvent(event);
validateEvent
Validates an event based on options
import { validateEvent } from "@bgcbrasil/shared";
const event = {
body: { a: "test body" },
pathParameters: { a: "test path parameters" },
};
const schema = {
type: "object",
required: ["a"],
properties: {
a: {
type: "string",
},
},
};
await validateEvent(event, { bodySchema: Schema, pathParameters: ["b"] });
Request
import { request } from "@bgcbrasil/shared";
const result = await request({
method: "GET",
url: "https://url.com.br",
data: {
a: "test",
},
headers: {
b: "test",
},
});
Sleep
sleep(miliseconds)
Provides an asyncronous timed sleep
miliseconds the period that the execution will be sleeping
import { sleep } from "@bgcbrasil/shared";
// waits for 100 ms then logs "olá"
await sleep(100);
console.log("olá!");
divideArrayInBatches
Receives an array and divides it in smallers arrays with same length
import { divideArrayInBatches } from "@bgcbrasil/shared";
const formated = divideArrayInBatches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2);
/*
[
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
]
*/
findMatchedNames
Receives an array of names and a name, and returns the names inside the array that matches the name given
import { findMatchedNames } from "@bgcbrasil/shared";
const response = findMatchedNames(["Gustavo", "Lucas"], "Gustavo");
/*
[
"Gustavo"
]
*/
Issue Reporting
If you have found a bug or if you have a feature request, please report them at this repository issues section or directly to the responsible team.
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago