This lib was created with the aim of simplifying the use of serverless Twilio.

Overview

Twilio Functions Utils

About

This lib was created with the aim of simplifying the use of serverless Twilio, reducing the need to apply frequent try-catches and improving context management, making it no longer necessary to return the callback() method in all functions.

How it works

useInjection

The useInjection method takes two parameters. The first to apply as a handler and the last is an object of configuration options.

[useInjection] Options

Can contain providers that will be defined, which act as use cases to perform internal actions in the handler function through the "this" method.

You can pass validateToken equal true too, to force Token validation using Twilio Flex Token Validator

useInjection(yourFunction,
  {
    providers: { create, remove },
    validateToken: true
  }
);

Twilio Flex Token Validator

When using Token Validator, the Request body must contain a valid Token from Twilio.

// Event
{
  Token: "Twilio-Token-Here"
}

Response

The responses coming from the function destined to the handler must be returned as an instance of Response.

Response recebe uma string e um number (status code):

return new Response('Your pretty answer.', 200);

There are two failure response models, BadRequest and NotFound. The use follows the same model.

const notFound = new NotFoundError('Your error message here.');
const badRequest = new BadRequestError('Your error message here.');

TwiMLResponse

There is an own response template to use with the TwiML format:

const twimlVoice = new Twilio.twiml
  .VoiceResponse();

const enqueueVoice = twimlVoice
  .enqueue({
    action,
    workflowSid,
  })
  .task('{}');

return new TwiMLResponse(twimlVoice, 201)

Install

npm install twilio-functions-utils

Usage

// File: assets/create.private.js

exports.create = async function (event) {
  // Here you can acess  Twilio Client as client and Context as props (so you can get env vars).
  const { client, props } = this

  return new Promise((resolve, reject) => {
    const random = Math.random();

    if (random >= 0.5) {
      return resolve({ sucess: 'Resolved' });
    }
  
    return reject(new Error('Unresolved'));
  });
};
// File: functions/create.js

const { useInjection, Response } = require('twilio-functions-utils');
const { create } = require(Runtime.getAssets()['/create.js'].path)

/**
 * @param { Record<string, unknown> } event
 * @this { {
 * request: Record<string, unknown>,
 * cookies: Record<string, string>,
 * client: import('twilio').Twilio,
 * props: {
 *      TWILIO_WORKFLOW_SID: string,
 *      TWILIO_WORKFLOW_SID: string,
 *      DOMAIN_NAME: string
 * },
 * providers: {
 *      create: create,
 * } } }
 * @returns { Promise<unknown> }
 */
async function createAction(event) {
  // You can perform all your "controller" level actions, as you have access to the request headers and cookies.
  const { cookies, request, client, props } = this

  // Then just call the providers you provided to handler by using useInjection.
  const providerResult = await this.providers.create(event)

  // Just put it on a Response object and you are good to go!
  return new Response(providerResult, 201);
}

exports.handler = useInjection(createAction, {
  providers: {
    create,
  },
  validateToken: true, // When using Token Validator, the Request body must contain a valid Token from Twilio.
});

Author

You might also like...

Hydra bot is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node js

Hydra bot is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node js

The most reliable WhatsApp tool for chatbots with advanced features. Hydra bot is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node js, . The most complete javascript library for Whatsapp, 100% Open Source.

Dec 25, 2022

The aim of this project is to restructure the Awesome books app code by using ES6 syntax and organising the workspace using modules.

Awesome-Books-ES6 The aim of this project is to restructure the Awesome books app code by using ES6 syntax and organising the workspace using modules.

Aug 18, 2022

this project's main aim is to restructure Awesome books app code to make it more organized by using modules and also practicing the ES6 syntax.

Awesome Books ES6 this project's main aim is to restructure Awesome books app code to make it more organized by using modules. also practicing the ES6

Sep 6, 2022

The main aim of the package is to parse Primavera xer files

This package is part of the Planner Toolkit open source project. The main aim of the package is to parse Primavera xer files. The project is open source and can be found here.

Sep 25, 2022

A JavaScript lib with more functions for the normal Date class.

A JavaScript lib with more functions for the normal Date class.

Jan 26, 2022

A Javascript lib about complex

RealComplex.js 一个关于复数的Javascript库 A Javascript lib about complex How to use it? 使用教程 导入与实例化 import { Complex } from './Complex.js'; let x = new Comple

Feb 9, 2022

Portfólio de projetos pessoais feito com NextJs e lib de animação Framer Motion

Portfólio de projetos pessoais feito com NextJs e lib de animação Framer Motion

Portfólio - Carlos Amorim Esse portfólio foi criado para mostrar meus projetos e habilidades. 🚀 Projeto criado com as seguintes tecnologias: ✔️ NextJ

May 12, 2022

Cross-runtime benchmarking lib and cli

Cross-runtime benchmarking lib and cli

mitata cross-runtime benchmarking lib Install bun add mitata npm install mitata Examples import { run, bench, group, baseline } from 'mitata'; // den

Jan 3, 2023

A lib for text highlighting by using Canvas.

canvas-highlighter 基于 canvas 实现的文本划词高亮,与文本展示的结构完全解耦,不改变文本内容的 DOM 结构。 Installation npm install canvas-highlighter Usage 最简单的实现文本划词直接高亮 import CanvasHig

Dec 24, 2022
Comments
  • build(deps): Bump moment from 2.29.3 to 2.29.4

    build(deps): Bump moment from 2.29.3 to 2.29.4

    Bumps moment from 2.29.3 to 2.29.4.

    Changelog

    Sourced from moment's changelog.

    2.29.4

    • Release Jul 6, 2022
      • #6015 [bugfix] Fix ReDoS in preprocessRFC2822 regex
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Ability to change the `Response` type method

    Ability to change the `Response` type method

    Currently it is not possible to change the method in the Response header in an easy way. It is desirable to be able to perform such an action by passing the same, for example, as a parameter.

    enhancement 
    opened by iagocalazans 0
  • Breaking change UseCase named

    Breaking change UseCase named

    Inside the function scope the this object must have useCase replaced by a more relevant name as providers are designated.

    Change from:

      const useCaseResult = await this.useCase.create(event);
    

    To this:

      const providersResult = await this.providers.create(event);
    
    enhancement 
    opened by iagocalazans 0
Releases(v2.3.0)
Owner
Iago Calazans
Senior Node.js Engineer at @stone-payments.
Iago Calazans
Open-source CD platform that helps developers to deliver applications efficiently by simplifying software releases and operations in any environment.

dyrector.io - The open source internal delivery platform Overview dyrector.io is an open-source internal delivery platform that helps developers to de

dyrector.io 160 Jan 3, 2023
Twilio sample codes for inbound and outbound using sdk.

Description Twilio inbound outbound framework boilerplate. This boilerplate contains features like outbound calls, inbound calls, recordings, get reco

Harris Gurung 5 Sep 22, 2022
An esbuild plugin for simplifying global API calls.

esbuild-plugin-global-api This plugin is still experimental, not recommended for production. It may break your code in some cases. An esbuild plugin f

null 4 Nov 15, 2022
The aim is to provide a hassle-free way to use the data to build applications to show close-to-realtime power-outage info in Mauritius

Mauritius Dataset for Electricity Dataset View Dataset The aim is to provide a hassle-free way to use the data to build applications. Example applicat

Sandeep Ramgolam 5 Dec 15, 2022
Learn Web 2.0 and Web 3.0 Development using Next.js, Typescript, AWS CDK, AWS Serverless, Ethereum and AWS Aurora Serverless

Learn Web 2.0 Cloud and Web 3.0 Development in Baby Steps In this course repo we will learn Web 2.0 cloud development using the latest state of the ar

Panacloud Multi-Cloud Internet-Scale Modern Global Apps 89 Jan 3, 2023
A Serverless GraphQL Sample project using Apollo and Serverless Framework with TypeScript and Webpack.

Serverless GraphQL Boilerplate This is a base project with a structure that includes Serverless Framework, Apollo, TypeScript and Webpack. It can be d

Ravi Souza 5 Aug 23, 2022
AWS Lambda & Serverless - Developer Guide with Hands-on Labs. Develop thousands line of aws lambda functions interact to aws serverless services with real-world hands-on labs

AWS Lambda & Serverless - Developer Guide with Hands-on Labs UDEMY COURSE WITH DISCOUNTED - Step by Step Development of this Repository -> https://www

awsrun 35 Dec 17, 2022
I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certificate. I use node-signpdf and pdf-lib library.

pdf-digital-signature-with-node-signpdf-ejs I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certif

null 5 Dec 25, 2022
BASIC is a web application contains basic applications related to studies, love, health, weather, productivity. This project aim to simply the user's life in anyway.

BASIC is a web application contains basic applications related to studies, love, health, weather, productivity. This project aim to simply the user's life in anyway. Supported by all operating system, need an internet connection for working properly.

IRUTHAYA SANTHOSE I 1 Dec 19, 2021
Cloudy is a set of constructs for the AWS Cloud Development Kit that aim to improve the DX by providing a faster and type-safe code environment.

cloudy-ts These packages aren't yet published on npm. This is still highly experimental. Need to figure out a few things before releasing the first ve

Cristian Pallarés 5 Nov 3, 2022