Skip to content

Commit

Permalink
Add Sync Client for sharing contact form (#11)
Browse files Browse the repository at this point in the history
* Added issuSyncToken

* Added transferCallResolve

* Updated README
  • Loading branch information
GPaoloni authored Jun 8, 2020
1 parent c3c28b4 commit 0d08b94
Show file tree
Hide file tree
Showing 7 changed files with 606 additions and 157 deletions.
24 changes: 17 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,27 @@ Repository for serverless functions living on the Twilio Serverless Toolkit
`git clone https://github.com/tech-matters/serverless && cd serverless`
2- Install dependencies:
`npm install`
3- create a .env file with propper ACCOUNT_SID=<account_sid_value> AUTH_TOKEN=<auth_token_value> (can be found inside the twilio console, depending on the enviroment we want to deploy to)
3- create a .env file with all the .env variables ([below is the whole list](#environment-variables))
4- run typescript compiler (as Twilio ST serves the .js files) and start local server:
`npm start`

For help on twilio-run commands run:
`npm run tr -- help`

To deploy:
`npm run tr:deploy`
## Environment variables
| Variable Name | Expected Value |
| ----------------------------------- | -------------------------------------------- |
| `ACCOUNT_SID` | sid of the Twilio account |
| `AUTH_TOKEN` | auth token of the above account |
| `TWILIO_WORKSPACE_SID` | workspace sid for the taskrouter |
| `TWILIO_CHAT_TRANSFER_WORKFLOW_SID` | workflow sid within above workspace |
| `SYNC_SERVICE_SID` | sync service sid for use as temporary storage |
| `SYNC_SERVICE_API_KEY` | api resource to use above sync client |
| `SYNC_SERVICE_API_SECRET` | api secret of the above resource |
| `CHAT_SERVICE_SID` | programmable chat sid used for chat tasks |

## Deployment
To deploy (dev environment): `npm run tr:deploy`
[More about deploying](https://www.twilio.com/docs/labs/serverless-toolkit/deploying)


Expand All @@ -33,15 +45,13 @@ Explanation
"with_uri_params_if_any": append to the uri "param1=<value_1>&param2=<value_2>"
"and_valid_Token": finally append to the uri "Token=<valid_token>"

Token generator util is a work in progress

## tech-matters-serverless-helpers
This are helpers and functions reused across the various serverless functions.
They are packed as npm package because it's the easiest way to reuse the code within a Twilio Serverless Toolkit Project and preserve the typing information TS provides.

It's currenty deployed with Gian's npm account, [contact him](https://github.com/GPaoloni) to deploy new versions!

To deploy:
once inside the project folder (`cd tech-matters-serverless-helpers`)
1- `npm run build`
once inside the project folder (`cd tech-matters-serverless-helpers`)
1- `npm run build`
2- `npm publish` (must be logged in npm cli)
66 changes: 66 additions & 0 deletions functions/issueSyncToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import '@twilio-labs/serverless-runtime-types';
import {
Context,
ServerlessCallback,
ServerlessFunctionSignature,
} from '@twilio-labs/serverless-runtime-types/types';
import { responseWithCors, bindResolve, error500, success } from 'tech-matters-serverless-helpers';

const TokenValidator = require('twilio-flex-token-validator').functionValidator;

type EnvVars = {
ACCOUNT_SID: string;
SYNC_SERVICE_API_KEY: string;
SYNC_SERVICE_API_SECRET: string;
SYNC_SERVICE_SID: string;
};

// This is added to event by TokenValidator (if a valid Token was provided) https://www.npmjs.com/package/twilio-flex-token-validator#token-result
export type AuthEvent = {
TokenResult: {
identity: string;
};
};

export const handler: ServerlessFunctionSignature = TokenValidator(
async (context: Context<EnvVars>, event: AuthEvent, callback: ServerlessCallback) => {
const response = responseWithCors();
const resolve = bindResolve(callback)(response);

try {
const { identity } = event.TokenResult;

const {
ACCOUNT_SID,
SYNC_SERVICE_API_KEY,
SYNC_SERVICE_API_SECRET,
SYNC_SERVICE_SID,
} = context;

if (!identity) {
throw new Error('Identity is missing, something is wrong with the token provided');
}
if (!(SYNC_SERVICE_API_KEY && SYNC_SERVICE_API_SECRET && SYNC_SERVICE_SID)) {
throw new Error('Sync Service information missing, set your env vars');
}

const { AccessToken } = Twilio.jwt;
const { SyncGrant } = AccessToken;

const syncGrant = new SyncGrant({ serviceSid: SYNC_SERVICE_SID });

const accessToken = new AccessToken(
ACCOUNT_SID,
SYNC_SERVICE_API_KEY,
SYNC_SERVICE_API_SECRET,
{ identity },
);

accessToken.addGrant(syncGrant);

resolve(success({ token: accessToken.toJwt() }));
} catch (err) {
resolve(error500(err));
}
},
);
66 changes: 66 additions & 0 deletions functions/transferCallResolve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import '@twilio-labs/serverless-runtime-types';
import {
Context,
ServerlessCallback,
ServerlessFunctionSignature,
} from '@twilio-labs/serverless-runtime-types/types';
import {
responseWithCors,
bindResolve,
error400,
error500,
success,
} from 'tech-matters-serverless-helpers';

const TokenValidator = require('twilio-flex-token-validator').functionValidator;

type EnvVars = {
TWILIO_WORKSPACE_SID: string;
};

export type Body = {
taskSid?: string;
reservationSid?: string;
};

async function closeReservation(context: Context<EnvVars>, body: Required<Body>) {
const client = context.getTwilioClient();

const closedReservation = await client.taskrouter
.workspaces(context.TWILIO_WORKSPACE_SID)
.tasks(body.taskSid)
.reservations(body.reservationSid)
.update({
reservationStatus: 'completed',
});

return closedReservation;
}

export const handler: ServerlessFunctionSignature = TokenValidator(
async (context: Context<EnvVars>, event: Body, callback: ServerlessCallback) => {
const response = responseWithCors();
const resolve = bindResolve(callback)(response);

const { taskSid, reservationSid } = event;

try {
if (taskSid === undefined) {
resolve(error400('taskSid'));
return;
}
if (reservationSid === undefined) {
resolve(error400('reservationSid'));
return;
}

const validBody = { taskSid, reservationSid };

const closedReservation = await closeReservation(context, validBody);

resolve(success({ closed: closedReservation.sid }));
} catch (err) {
resolve(error500(err));
}
},
);
Loading

0 comments on commit 0d08b94

Please sign in to comment.