-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathfunctions.ts
233 lines (214 loc) · 6.16 KB
/
functions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/** @module @twilio-labs/serverless-api/dist/api */
import debug from 'debug';
import FormData from 'form-data';
import {
FunctionApiResource,
FunctionList,
FunctionResource,
ServerlessResourceConfig,
Sid,
VersionResource,
ClientConfig,
FunctionContent,
FunctionVersion,
} from '../types';
import { TwilioServerlessApiClient } from '../client';
import { getContentType } from '../utils/content-type';
import { ClientApiError } from '../utils/error';
import { getApiUrl } from './utils/api-client';
import { getPaginatedResource } from './utils/pagination';
const log = debug('twilio-serverless-api:functions');
/**
* Creates a new Function instance by calling the API
*
* @param {string} name the friendly name of the function to create
* @param {string} serviceSid the service the function should belong to
* @param {TwilioServerlessApiClient} client API client
* @returns {Promise<FunctionApiResource>}
*/
export async function createFunctionResource(
name: string,
serviceSid: string,
client: TwilioServerlessApiClient
): Promise<FunctionApiResource> {
try {
const resp = await client.request(
'post',
`Services/${serviceSid}/Functions`,
{
form: {
FriendlyName: name,
},
}
);
return (resp.body as unknown) as FunctionApiResource;
} catch (err) {
log('%O', new ClientApiError(err));
throw new Error(`Failed to create "${name}" function`);
}
}
/**
* Lists all functions associated to a service
*
* @export
* @param {string} serviceSid the service to look up
* @param {TwilioServerlessApiClient} client API client
* @returns
*/
export async function listFunctionResources(
serviceSid: string,
client: TwilioServerlessApiClient
) {
try {
return getPaginatedResource<FunctionList, FunctionApiResource>(
client,
`Services/${serviceSid}/Functions`
);
} catch (err) {
log('%O', new ClientApiError(err));
throw err;
}
}
/**
* Given a list of functions it will create the ones that don't exist and retrieves the others
*
* @export
* @param {FileInfo[]} functions list of functions to get or create
* @param {string} serviceSid service the functions belong to
* @param {TwilioServerlessApiClient} client API client
* @returns {Promise<FunctionResource[]>}
*/
export async function getOrCreateFunctionResources(
functions: ServerlessResourceConfig[],
serviceSid: string,
client: TwilioServerlessApiClient
): Promise<FunctionResource[]> {
const output: FunctionResource[] = [];
const existingFunctions = await listFunctionResources(serviceSid, client);
const functionsToCreate: ServerlessResourceConfig[] = [];
functions.forEach((fn) => {
const existingFn = existingFunctions.find(
(f) => fn.name === f.friendly_name
);
if (!existingFn) {
functionsToCreate.push({ ...fn });
} else {
output.push({
...fn,
sid: existingFn.sid,
});
}
});
const createdFunctions = await Promise.all(
functionsToCreate.map(async (fn) => {
const newFunction = await createFunctionResource(
fn.name,
serviceSid,
client
);
return {
...fn,
sid: newFunction.sid,
};
})
);
return [...output, ...createdFunctions];
}
/**
* Creates a new Version to be used for uploading a new function
*
* @param {FunctionResource} fn the function the version should be created for
* @param {string} serviceSid the service related to the function
* @param {TwilioServerlessApiClient} client API client
* @returns {Promise<VersionResource>}
*/
async function createFunctionVersion(
fn: FunctionResource,
serviceSid: string,
client: TwilioServerlessApiClient,
clientConfig: ClientConfig
): Promise<VersionResource> {
try {
const contentType =
(await getContentType(fn.content, fn.filePath || 'application/json')) ||
'application/javascript';
log('Uploading asset via form data with content-type "%s"', contentType);
const contentOpts = {
filename: fn.name,
contentType: contentType,
};
const form = new FormData();
form.append('Path', fn.path);
form.append('Visibility', fn.access);
form.append('Content', fn.content, contentOpts);
const resp = await client.request(
'post',
`Services/${serviceSid}/Functions/${fn.sid}/Versions`,
{
responseType: 'text',
prefixUrl: getApiUrl(clientConfig, 'serverless-upload'),
body: form,
}
);
return JSON.parse(resp.body) as VersionResource;
} catch (err) {
log('%O', new ClientApiError(err));
throw new Error(`Failed to upload Function ${fn.name}`);
}
}
/**
* Uploads a given function by creating a new version, reading the content if necessary and uploading the content
*
* @export
* @param {FunctionResource} fn function to be uploaded
* @param {string} serviceSid service that the function is connected to
* @param {TwilioServerlessApiClient} client API client
* @returns {Promise<Sid>}
*/
export async function uploadFunction(
fn: FunctionResource,
serviceSid: string,
client: TwilioServerlessApiClient,
clientConfig: ClientConfig
): Promise<Sid> {
const version = await createFunctionVersion(
fn,
serviceSid,
client,
clientConfig
);
return version.sid;
}
/**
* Checks if a string is an function SID by checking its prefix and length
*
* @export
* @param {string} str the string to check
* @returns
*/
export function isFunctionSid(str: string) {
return str.startsWith('ZH') && str.length === 34;
}
export async function listFunctionVersions(
serviceSid: Sid,
functionSid: Sid,
client: TwilioServerlessApiClient
): Promise<FunctionVersion[]> {
const resp = await client.request(
'get',
`Services/${serviceSid}/Functions/${functionSid}/Versions`
);
return (resp.body as unknown) as FunctionVersion[];
}
export async function downloadFunctionVersion(
serviceSid: Sid,
functionSid: Sid,
functionVersionSid: Sid,
client: TwilioServerlessApiClient
): Promise<FunctionContent> {
const resp = await client.request(
'get',
`Services/${serviceSid}/Functions/${functionSid}/Versions/${functionVersionSid}/Content`
);
return (resp.body as unknown) as FunctionContent;
}