Skip to content

feat: unify error interface & upgrade got #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
8.10
10.19.0
54 changes: 54 additions & 0 deletions examples/deploy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const { TwilioServerlessApiClient } = require('../dist');
async function run() {
const config = {
accountSid: process.env.TWILIO_ACCOUNT_SID,
authToken: process.env.TWILIO_AUTH_TOKEN,
};

const client = new TwilioServerlessApiClient(config);
console.log('Deploying');
const result = await client.deployProject({
...config,
overrideExistingService: true,
env: {
HELLO: 'ahoy',
WORLD: 'welt',
},
pkgJson: {
dependencies: {
'common-tags': '*',
'date-fns': '*',
},
},
serviceName: 'api-demo',
functionsEnv: 'test',
functions: [
{
name: 'hello-world',
path: '/hello-world',
content: `
const { stripIndent } = require('common-tags');
const { format } = require('date-fns');
exports.handler = function(context, event, callback) {
callback(null, stripIndent\`
\${context.HELLO} \${context.WORLD} \${format(new Date(2010, 4, 10), 'yyyy-MM-dd')}
\`);
};
`,
access: 'public',
},
],
assets: [
{
name: 'my-lib.js',
path: '/my-lib.js',
access: 'public',
content: 'exports.sum = (a, b) => a+b',
},
],
});
console.log('Done Deploying');
console.dir(result);
}

run().catch(console.error);
3,023 changes: 1,661 additions & 1,362 deletions npm-shrinkwrap.json

Large diffs are not rendered by default.

15 changes: 7 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,26 @@
"husky": "^3.0.0",
"jest": "^24.8.0",
"lint-staged": "^8.2.1",
"nock": "^10.0.6",
"nock": "^12.0.3",
"npm-run-all": "^4.1.5",
"prettier": "^1.18.2",
"prettier": "^2.0.4",
"rimraf": "^2.6.3",
"standard-version": "^6.0.1",
"ts-jest": "^24.0.2",
"typedoc": "^0.14.2",
"typedoc-plugin-external-module-name": "^2.0.0",
"typescript": "^3.4.2"
"typedoc": "^0.17.4",
"typedoc-plugin-external-module-name": "^3.0.0",
"typescript": "^3.8.3"
},
"dependencies": {
"@types/form-data": "^2.5.0",
"@types/got": "^9.4.1",
"@types/mime-types": "^2.1.0",
"@types/node": "^11.13.2",
"@types/recursive-readdir": "^2.2.0",
"@types/node": "^13.13.4",
"debug": "^4.1.1",
"fast-redact": "^1.5.0",
"file-type": "^10.10.0",
"form-data": "^2.5.0",
"got": "^9.6.0",
"got": "^11.0.1",
"mime-types": "^2.1.22",
"recursive-readdir": "^2.2.2",
"type-fest": "^0.3.0",
Expand Down
4 changes: 4 additions & 0 deletions src/__fixtures__/base-fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const DEFAULT_TEST_CLIENT_CONFIG = {
accountSid: 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
authToken: '<SECRET>',
};
27 changes: 13 additions & 14 deletions src/api/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '../types';
import { getContentType } from '../utils/content-type';
import { getPaginatedResource } from './utils/pagination';
import { ClientApiError } from '../utils/error';

const log = debug('twilio-serverless-api:assets');

Expand All @@ -32,15 +33,14 @@ async function createAssetResource(
client: GotClient
): Promise<AssetApiResource> {
try {
const resp = await client.post(`/Services/${serviceSid}/Assets`, {
form: true,
body: {
const resp = await client.post(`Services/${serviceSid}/Assets`, {
form: {
FriendlyName: name,
},
});
return (resp.body as unknown) as AssetApiResource;
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw new Error(`Failed to create "${name}" asset`);
}
}
Expand All @@ -59,10 +59,10 @@ export async function listAssetResources(
try {
return getPaginatedResource<AssetList, AssetApiResource>(
client,
`/Services/${serviceSid}/Assets`
`Services/${serviceSid}/Assets`
);
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw err;
}
}
Expand All @@ -84,9 +84,9 @@ export async function getOrCreateAssetResources(
const existingAssets = await listAssetResources(serviceSid, client);
const assetsToCreate: ServerlessResourceConfig[] = [];

assets.forEach(asset => {
assets.forEach((asset) => {
const existingAsset = existingAssets.find(
x => asset.name === x.friendly_name
(x) => asset.name === x.friendly_name
);
if (!existingAsset) {
assetsToCreate.push(asset);
Expand All @@ -99,7 +99,7 @@ export async function getOrCreateAssetResources(
});

const createdAssets = await Promise.all(
assetsToCreate.map(async asset => {
assetsToCreate.map(async (asset) => {
const newAsset = await createAssetResource(
asset.name,
serviceSid,
Expand Down Expand Up @@ -146,18 +146,17 @@ async function createAssetVersion(
form.append('Content', asset.content, contentOpts);

const resp = await client.post(
`/Services/${serviceSid}/Assets/${asset.sid}/Versions`,
`Services/${serviceSid}/Assets/${asset.sid}/Versions`,
{
baseUrl: 'https://serverless-upload.twilio.com/v1',
responseType: 'text',
prefixUrl: 'https://serverless-upload.twilio.com/v1',
body: form,
//@ts-ignore
json: false,
}
);

return JSON.parse(resp.body) as VersionResource;
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw new Error('Failed to upload Asset');
}
}
Expand Down
26 changes: 12 additions & 14 deletions src/api/builds.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/** @module @twilio-labs/serverless-api/dist/api */

import debug from 'debug';
import querystring from 'querystring';
import { JsonObject } from 'type-fest';
import {
BuildConfig,
Expand All @@ -11,6 +10,7 @@ import {
GotClient,
} from '../types';
import { DeployStatus } from '../types/consts';
import { ClientApiError } from '../utils/error';
import { sleep } from '../utils/sleep';
import { getPaginatedResource } from './utils/pagination';

Expand All @@ -32,7 +32,7 @@ export async function getBuild(
serviceSid: string,
client: GotClient
): Promise<BuildResource> {
const resp = await client.get(`/Services/${serviceSid}/Builds/${buildSid}`);
const resp = await client.get(`Services/${serviceSid}/Builds/${buildSid}`);
return (resp.body as unknown) as BuildResource;
}

Expand All @@ -53,7 +53,7 @@ async function getBuildStatus(
const resp = await getBuild(buildSid, serviceSid, client);
return resp.status;
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw err;
}
}
Expand All @@ -72,7 +72,7 @@ export async function listBuilds(
): Promise<BuildResource[]> {
return getPaginatedResource<BuildList, BuildResource>(
client,
`/Services/${serviceSid}/Builds`
`Services/${serviceSid}/Builds`
);
}

Expand Down Expand Up @@ -107,17 +107,16 @@ export async function triggerBuild(
body.AssetVersions = assetVersions;
}

const resp = await client.post(`/Services/${serviceSid}/Builds`, {
// @ts-ignore
json: false,
const resp = await client.post(`Services/${serviceSid}/Builds`, {
responseType: 'json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: querystring.stringify(body),
form: body,
});
return JSON.parse(resp.body) as BuildResource;
return resp.body as BuildResource;
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw err;
}
}
Expand Down Expand Up @@ -196,17 +195,16 @@ export async function activateBuild(
): Promise<any> {
try {
const resp = await client.post(
`/Services/${serviceSid}/Environments/${environmentSid}/Deployments`,
`Services/${serviceSid}/Environments/${environmentSid}/Deployments`,
{
form: true,
body: {
form: {
BuildSid: buildSid,
},
}
);
return resp.body;
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw err;
}
}
18 changes: 9 additions & 9 deletions src/api/environments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import debug from 'debug';
import { EnvironmentList, EnvironmentResource, GotClient, Sid } from '../types';
import { getPaginatedResource } from './utils/pagination';
import { ClientApiError } from '../utils/error';

const log = debug('twilio-serverless-api:environments');

Expand Down Expand Up @@ -42,7 +43,7 @@ export async function getEnvironment(
client: GotClient
): Promise<EnvironmentResource> {
const resp = await client.get(
`/Services/${serviceSid}/Environments/${environmentSid}`
`Services/${serviceSid}/Environments/${environmentSid}`
);
return (resp.body as unknown) as EnvironmentResource;
}
Expand All @@ -62,9 +63,8 @@ export async function createEnvironmentFromSuffix(
client: GotClient
): Promise<EnvironmentResource> {
const uniqueName = getUniqueNameFromSuffix(domainSuffix);
const resp = await client.post(`/Services/${serviceSid}/Environments`, {
form: true,
body: {
const resp = await client.post(`Services/${serviceSid}/Environments`, {
form: {
UniqueName: uniqueName,
DomainSuffix: domainSuffix || undefined,
// this property currently doesn't exist but for the future lets set it
Expand All @@ -85,7 +85,7 @@ export async function createEnvironmentFromSuffix(
export async function listEnvironments(serviceSid: string, client: GotClient) {
return getPaginatedResource<EnvironmentList, EnvironmentResource>(
client,
`/Services/${serviceSid}/Environments`
`Services/${serviceSid}/Environments`
);
}

Expand All @@ -105,7 +105,7 @@ export async function getEnvironmentFromSuffix(
): Promise<EnvironmentResource> {
const environments = await listEnvironments(serviceSid, client);
let foundEnvironments = environments.filter(
e =>
(e) =>
e.domain_suffix === domainSuffix ||
(domainSuffix.length === 0 && e.domain_suffix === null)
);
Expand All @@ -115,7 +115,7 @@ export async function getEnvironmentFromSuffix(
// this is an edge case where at one point you could create environments with the same domain suffix
// we'll pick the one that suits our naming convention
env = foundEnvironments.find(
e =>
(e) =>
e.domain_suffix === domainSuffix &&
e.unique_name === getUniqueNameFromSuffix(domainSuffix)
);
Expand Down Expand Up @@ -144,11 +144,11 @@ export async function createEnvironmentIfNotExists(
client: GotClient
) {
return getEnvironmentFromSuffix(domainSuffix, serviceSid, client).catch(
err => {
(err) => {
try {
return createEnvironmentFromSuffix(domainSuffix, serviceSid, client);
} catch (err) {
log('%O', err);
log('%O', new ClientApiError(err));
throw err;
}
}
Expand Down
Loading