idea-aws 4.4.3 → 4.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/.eslintrc.js +0 -16
- package/.prettierrc +0 -9
- package/.vscode/settings.json +0 -26
- package/HOW-TO-RELEASE.md +0 -8
- package/build.sh +0 -21
- package/docs/.nojekyll +0 -1
- package/docs/assets/custom.css +0 -4
- package/docs/assets/highlight.css +0 -50
- package/docs/assets/main.js +0 -58
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1367
- package/docs/classes/Attachments.html +0 -201
- package/docs/classes/Cognito.html +0 -713
- package/docs/classes/Comprehend.html +0 -176
- package/docs/classes/DynamoDB.html +0 -584
- package/docs/classes/GenericController.html +0 -262
- package/docs/classes/HandledError.html +0 -219
- package/docs/classes/LambdaLogger.html +0 -220
- package/docs/classes/ResourceController.html +0 -957
- package/docs/classes/S3.html +0 -391
- package/docs/classes/SES.html +0 -335
- package/docs/classes/SNS.html +0 -185
- package/docs/classes/SecretsManager.html +0 -159
- package/docs/classes/StreamController.html +0 -284
- package/docs/classes/SystemsManager.html +0 -184
- package/docs/classes/Translate.html +0 -239
- package/docs/classes/UnhandledError.html +0 -252
- package/docs/functions/cleanFilename.html +0 -93
- package/docs/index.html +0 -95
- package/docs/interfaces/BasicEmailData.html +0 -145
- package/docs/interfaces/CognitoGroup.html +0 -122
- package/docs/interfaces/CognitoUserGeneric.html +0 -125
- package/docs/interfaces/CopyObjectOptions.html +0 -132
- package/docs/interfaces/CreateDownloadURLFromDataOptions.html +0 -163
- package/docs/interfaces/CreateUserOptions.html +0 -122
- package/docs/interfaces/DeleteObjectOptions.html +0 -122
- package/docs/interfaces/DetectSentimentParameters.html +0 -121
- package/docs/interfaces/EmailAttachment.html +0 -176
- package/docs/interfaces/EmailData.html +0 -188
- package/docs/interfaces/GetObjectOptions.html +0 -133
- package/docs/interfaces/HeadObjectOptions.html +0 -132
- package/docs/interfaces/InternalAPIRequestParams.html +0 -207
- package/docs/interfaces/ListObjectsOptions.html +0 -122
- package/docs/interfaces/PutObjectOptions.html +0 -173
- package/docs/interfaces/ResourceControllerOptions.html +0 -142
- package/docs/interfaces/SESParams.html +0 -152
- package/docs/interfaces/SNSCreateEndpointParams.html +0 -132
- package/docs/interfaces/SNSPublishParams.html +0 -142
- package/docs/interfaces/SignedURLOptions.html +0 -123
- package/docs/interfaces/TemplatedEmailData.html +0 -186
- package/docs/interfaces/TranslateParameters.html +0 -140
- package/docs/modules.html +0 -130
- package/docs/variables/LOG_LEVELS_PRIORITY.html +0 -81
- package/docs.style.css +0 -4
- package/src/attachments.ts +0 -41
- package/src/cognito.ts +0 -511
- package/src/comprehend.ts +0 -52
- package/src/dynamoDB.ts +0 -311
- package/src/genericController.ts +0 -103
- package/src/lambdaLogger.ts +0 -39
- package/src/metrics.ts +0 -45
- package/src/resourceController.ts +0 -645
- package/src/s3.ts +0 -334
- package/src/secretsManager.ts +0 -24
- package/src/ses.ts +0 -313
- package/src/sns.ts +0 -118
- package/src/ssm.ts +0 -33
- package/src/streamController.ts +0 -25
- package/src/translate.ts +0 -174
- package/tsconfig.json +0 -10
package/src/dynamoDB.ts
DELETED
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
import * as DDB from '@aws-sdk/lib-dynamodb';
|
|
2
|
-
import { DynamoDB as DDBClient, WriteRequest } from '@aws-sdk/client-dynamodb';
|
|
3
|
-
import * as DDBUtils from '@aws-sdk/util-dynamodb';
|
|
4
|
-
import { customAlphabet as AlphabetNanoID } from 'nanoid';
|
|
5
|
-
const NanoID = AlphabetNanoID('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 25);
|
|
6
|
-
|
|
7
|
-
import { LambdaLogger } from './lambdaLogger';
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* A wrapper for AWS DynamoDB.
|
|
11
|
-
*/
|
|
12
|
-
export class DynamoDB {
|
|
13
|
-
protected dynamo: DDB.DynamoDBDocument;
|
|
14
|
-
protected logger = new LambdaLogger();
|
|
15
|
-
|
|
16
|
-
constructor() {
|
|
17
|
-
this.dynamo = DDB.DynamoDBDocument.from(new DDBClient(), {
|
|
18
|
-
marshallOptions: { convertEmptyValues: true, removeUndefinedValues: true, convertClassInstanceToMap: true }
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Convert a JSON object from DynamoDB format to simple JSON.
|
|
24
|
-
* @data the data in DynamoDB's original format to convert in plain objects
|
|
25
|
-
* @options the options to use to convert the data
|
|
26
|
-
*/
|
|
27
|
-
unmarshall(data: Record<string, any>, options?: DDBUtils.unmarshallOptions): Record<string, any> {
|
|
28
|
-
return DDBUtils.unmarshall(data, options);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Returns an IUNID: IDEA's Unique Nano IDentifier, which is an id unique through an IDEA's AWS account and region.
|
|
33
|
-
* Note: no need of an auth check for external uses: the permissions depend from the context in which it's executed.
|
|
34
|
-
* @param project project code
|
|
35
|
-
* @return the IUNID
|
|
36
|
-
*/
|
|
37
|
-
async IUNID(project: string): Promise<string> {
|
|
38
|
-
const MAX_ATTEMPTS = 3;
|
|
39
|
-
if (!project) throw new Error('Missing project');
|
|
40
|
-
return await this.IUNIDHelper(project, 0, MAX_ATTEMPTS);
|
|
41
|
-
}
|
|
42
|
-
protected async IUNIDHelper(project: string, attempt: number, maxAttempts: number): Promise<string> {
|
|
43
|
-
if (attempt > maxAttempts) throw new Error('Operation failed');
|
|
44
|
-
|
|
45
|
-
const id = NanoID();
|
|
46
|
-
const result = `${project}_${id}`;
|
|
47
|
-
|
|
48
|
-
try {
|
|
49
|
-
await this.put({
|
|
50
|
-
TableName: 'idea_IUNID',
|
|
51
|
-
Item: { project, id },
|
|
52
|
-
ConditionExpression: 'NOT (#p = :project AND #id = :id)',
|
|
53
|
-
ExpressionAttributeNames: { '#p': 'project', '#id': 'id' },
|
|
54
|
-
ExpressionAttributeValues: { ':project': project, ':id': id }
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
return result;
|
|
58
|
-
} catch (err) {
|
|
59
|
-
// ID exists, try again
|
|
60
|
-
await this.IUNIDHelper(project, attempt + 1, maxAttempts);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Manage atomic counters (atomic autoincrement values) in IDEA's projects.
|
|
66
|
-
* They key of an atomic counter should be composed as the following: `DynamoDBTableName_uniqueKey`.
|
|
67
|
-
* @param key the key of the counter
|
|
68
|
-
*/
|
|
69
|
-
async getAtomicCounterByKey(key: string): Promise<number> {
|
|
70
|
-
this.logger.trace(`Get atomic counter for ${key}`);
|
|
71
|
-
const { Attributes } = await this.update({
|
|
72
|
-
TableName: 'idea_atomicCounters',
|
|
73
|
-
Key: { key },
|
|
74
|
-
UpdateExpression: 'ADD atomicCounter :increment',
|
|
75
|
-
ExpressionAttributeValues: { ':increment': 1 },
|
|
76
|
-
ReturnValues: 'UPDATED_NEW'
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
if (!Attributes.atomicCounter) throw new Error('Operation failed');
|
|
80
|
-
return Attributes.atomicCounter;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Get an item of a DynamoDB table.
|
|
85
|
-
* @param params the params to apply to DynamoDB's function
|
|
86
|
-
*/
|
|
87
|
-
async get(params: DDB.GetCommandInput): Promise<any> {
|
|
88
|
-
this.logger.trace(`Get ${params.TableName}`);
|
|
89
|
-
const { Item } = await this.dynamo.get(params);
|
|
90
|
-
|
|
91
|
-
if (!Item) throw new Error('Not found');
|
|
92
|
-
return Item;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Put an item in a DynamoDB table.
|
|
97
|
-
* @param params the params to apply to DynamoDB's function
|
|
98
|
-
*/
|
|
99
|
-
async put(params: DDB.PutCommandInput): Promise<DDB.PutCommandOutput> {
|
|
100
|
-
this.logger.trace(`Put ${params.TableName}`);
|
|
101
|
-
return await this.dynamo.put(params);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Update an item of a DynamoDB table.
|
|
106
|
-
* @param params the params to apply to DynamoDB's function
|
|
107
|
-
*/
|
|
108
|
-
async update(params: DDB.UpdateCommandInput): Promise<DDB.UpdateCommandOutput> {
|
|
109
|
-
this.logger.trace(`Update ${params.TableName}`);
|
|
110
|
-
return await this.dynamo.update(params);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Delete an item of a DynamoDB table.
|
|
115
|
-
* @param params the params to apply to DynamoDB's function
|
|
116
|
-
*/
|
|
117
|
-
async delete(params: DDB.DeleteCommandInput): Promise<DDB.DeleteCommandOutput> {
|
|
118
|
-
this.logger.trace(`Delete ${params.TableName}`);
|
|
119
|
-
return await this.dynamo.delete(params);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Get group of items based on their keys from DynamoDB table, avoiding the limits of DynamoDB's BatchGetItem.
|
|
124
|
-
* @param table the target DynamoDB table
|
|
125
|
-
* @param keys the keys of the objects to retrieve
|
|
126
|
-
* @param ignoreErr if set, ignore the errors and continue the bulk op.
|
|
127
|
-
*/
|
|
128
|
-
async batchGet(table: string, keys: Record<string, any>[], ignoreErr?: boolean): Promise<any[]> {
|
|
129
|
-
if (!keys.length) {
|
|
130
|
-
this.logger.trace(`Batch get ${table}: no elements to get`);
|
|
131
|
-
return [];
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
return await this.batchGetHelper(table, keys, [], Boolean(ignoreErr));
|
|
135
|
-
}
|
|
136
|
-
protected async batchGetHelper(
|
|
137
|
-
table: string,
|
|
138
|
-
keys: Record<string, any>[],
|
|
139
|
-
resultElements: Record<string, any>[],
|
|
140
|
-
ignoreErr: boolean,
|
|
141
|
-
currentChunk = 0,
|
|
142
|
-
chunkSize = 100
|
|
143
|
-
): Promise<Record<string, any>[]> {
|
|
144
|
-
const batch: DDB.BatchGetCommandInput = {
|
|
145
|
-
RequestItems: {
|
|
146
|
-
[table]: { Keys: keys.slice(currentChunk, currentChunk + chunkSize) }
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
|
|
150
|
-
this.logger.trace(`Batch get ${table}: ${currentChunk} of ${keys.length}`);
|
|
151
|
-
|
|
152
|
-
let result: DDB.BatchGetCommandOutput;
|
|
153
|
-
try {
|
|
154
|
-
result = await this.dynamo.batchGet(batch);
|
|
155
|
-
} catch (err) {
|
|
156
|
-
if (!ignoreErr) throw err;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
if (result) resultElements = resultElements.concat(result.Responses[table]);
|
|
160
|
-
|
|
161
|
-
// if there are still chunks to manage, go on recursively
|
|
162
|
-
if (currentChunk + chunkSize < keys.length)
|
|
163
|
-
return await this.batchGetHelper(table, keys, resultElements, ignoreErr, currentChunk + chunkSize, chunkSize);
|
|
164
|
-
// no more chunks to manage: we're done
|
|
165
|
-
else return resultElements;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Put an array of items in a DynamoDB table, avoiding the limits of DynamoDB's BatchWriteItem.
|
|
170
|
-
* In case of errors, it will retry with a random back-off mechanism until the timeout.
|
|
171
|
-
* Therefore, in case of timeout, there may be some elements written and some not.
|
|
172
|
-
* @param table the target DynamoDB table
|
|
173
|
-
* @param items the objects to insert
|
|
174
|
-
*/
|
|
175
|
-
async batchPut(table: string, items: Record<string, any>[]): Promise<void> {
|
|
176
|
-
if (!items.length) return this.logger.trace(`Batch write (put) ${table}: no elements to write`);
|
|
177
|
-
|
|
178
|
-
await this.batchWriteHelper(table, items, true);
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Delete an array of items from a DynamoDB table, avoiding the limits of DynamoDB's BatchWriteItem.
|
|
182
|
-
* In case of errors, it will retry with a random back-off mechanism until the timeout.
|
|
183
|
-
* Therefore, in case of timeout, there may be some elements deleted and some not.
|
|
184
|
-
* @param table the target DynamoDB table
|
|
185
|
-
* @param keys the keys to delete
|
|
186
|
-
*/
|
|
187
|
-
async batchDelete(table: string, keys: Record<string, any>[]): Promise<void> {
|
|
188
|
-
if (!keys.length) return this.logger.trace(`Batch write (delete) ${table}: no elements to write`);
|
|
189
|
-
|
|
190
|
-
await this.batchWriteHelper(table, keys, false);
|
|
191
|
-
}
|
|
192
|
-
protected async batchWriteHelper(
|
|
193
|
-
table: string,
|
|
194
|
-
itemsOrKeys: Record<string, any>[],
|
|
195
|
-
isPut: boolean,
|
|
196
|
-
currentChunk = 0,
|
|
197
|
-
chunkSize = 25
|
|
198
|
-
): Promise<void> {
|
|
199
|
-
this.logger.trace(`Batch write (${isPut ? 'put' : 'delete'}) ${table}: ${currentChunk} of ${itemsOrKeys.length}`);
|
|
200
|
-
|
|
201
|
-
let requests: WriteRequest[];
|
|
202
|
-
if (isPut)
|
|
203
|
-
requests = itemsOrKeys.slice(currentChunk, currentChunk + chunkSize).map(i => ({ PutRequest: { Item: i } }));
|
|
204
|
-
// isDelete
|
|
205
|
-
else requests = itemsOrKeys.slice(currentChunk, currentChunk + chunkSize).map(k => ({ DeleteRequest: { Key: k } }));
|
|
206
|
-
|
|
207
|
-
const batch: DDB.BatchWriteCommandInput = { RequestItems: { [table]: requests } };
|
|
208
|
-
await this.batchWriteChunkWithRetries(table, batch);
|
|
209
|
-
|
|
210
|
-
// if there are still chunks to manage, go on recursively
|
|
211
|
-
if (currentChunk + chunkSize < itemsOrKeys.length)
|
|
212
|
-
await this.batchWriteHelper(table, itemsOrKeys, isPut, currentChunk + chunkSize, chunkSize);
|
|
213
|
-
}
|
|
214
|
-
protected async batchWriteChunkWithRetries(table: string, params: DDB.BatchWriteCommandInput): Promise<void> {
|
|
215
|
-
const getRandomInt = (max: number): number => Math.floor(Math.random() * max);
|
|
216
|
-
const wait = (seconds: number): Promise<void> => new Promise(x => setTimeout((): void => x(), seconds * 1000));
|
|
217
|
-
|
|
218
|
-
let attempts = 0;
|
|
219
|
-
do {
|
|
220
|
-
const response = await this.dynamo.batchWrite(params);
|
|
221
|
-
|
|
222
|
-
if (
|
|
223
|
-
response.UnprocessedItems &&
|
|
224
|
-
response.UnprocessedItems[table] &&
|
|
225
|
-
response.UnprocessedItems[table].length > 0
|
|
226
|
-
) {
|
|
227
|
-
params.RequestItems = response.UnprocessedItems;
|
|
228
|
-
attempts++;
|
|
229
|
-
|
|
230
|
-
const waitSeconds = getRandomInt(attempts * 5);
|
|
231
|
-
this.logger.trace(`Batch write throttled: waiting ${waitSeconds} seconds to retry`);
|
|
232
|
-
await wait(waitSeconds);
|
|
233
|
-
} else {
|
|
234
|
-
params.RequestItems = null;
|
|
235
|
-
}
|
|
236
|
-
} while (params.RequestItems);
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Query a DynamoDB table, avoiding the limits of DynamoDB's Query.
|
|
241
|
-
* @param params the params to apply to DynamoDB's function
|
|
242
|
-
*/
|
|
243
|
-
async query(params: DDB.QueryCommandInput): Promise<any[]> {
|
|
244
|
-
this.logger.trace(`Query ${params.TableName}`);
|
|
245
|
-
const result = await this.queryScanHelper(params, [], true);
|
|
246
|
-
|
|
247
|
-
this.logger.trace(`Results query ${params.TableName}: ${result.length ?? 0}`);
|
|
248
|
-
return result;
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Scan a DynamoDB table, avoiding the limits of DynamoDB's Query.
|
|
252
|
-
* @param params the params to apply to DynamoDB's function
|
|
253
|
-
*/
|
|
254
|
-
async scan(params: DDB.ScanCommandInput): Promise<any[]> {
|
|
255
|
-
this.logger.trace(`Scan ${params.TableName}`);
|
|
256
|
-
const result = await this.queryScanHelper(params, [], false);
|
|
257
|
-
|
|
258
|
-
this.logger.trace(`Results scan ${params.TableName}: ${result.length ?? 0}`);
|
|
259
|
-
return result;
|
|
260
|
-
}
|
|
261
|
-
protected async queryScanHelper(
|
|
262
|
-
params: DDB.QueryCommandInput | DDB.ScanCommandInput,
|
|
263
|
-
items: Record<string, any>[],
|
|
264
|
-
isQuery: boolean
|
|
265
|
-
): Promise<Record<string, any>[]> {
|
|
266
|
-
let result;
|
|
267
|
-
if (isQuery) result = await this.dynamo.query(params);
|
|
268
|
-
else result = await this.dynamo.scan(params);
|
|
269
|
-
|
|
270
|
-
items = items.concat(result.Items);
|
|
271
|
-
|
|
272
|
-
if (result.LastEvaluatedKey) {
|
|
273
|
-
params.ExclusiveStartKey = result.LastEvaluatedKey;
|
|
274
|
-
return await this.queryScanHelper(params, items, isQuery);
|
|
275
|
-
} else return items;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* Query a DynamoDB table in the traditional way (no pagination or data mapping).
|
|
280
|
-
* @param params the params to apply to DynamoDB's function
|
|
281
|
-
*/
|
|
282
|
-
async queryClassic(params: DDB.QueryCommandInput): Promise<DDB.QueryCommandOutput> {
|
|
283
|
-
this.logger.trace(`Query classic ${params.TableName}`);
|
|
284
|
-
const result = await this.dynamo.query(params);
|
|
285
|
-
|
|
286
|
-
this.logger.trace(`Results query classic ${params.TableName}: ${result.Items.length ?? 0}`);
|
|
287
|
-
return result;
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* Scan a DynamoDB table in the traditional way (no pagination or data mapping).
|
|
291
|
-
* @param params the params to apply to DynamoDB's function
|
|
292
|
-
*/
|
|
293
|
-
async scanClassic(params: DDB.ScanCommandInput): Promise<DDB.ScanCommandOutput> {
|
|
294
|
-
this.logger.trace(`Scan classic ${params.TableName}`);
|
|
295
|
-
const result = await this.dynamo.scan(params);
|
|
296
|
-
|
|
297
|
-
this.logger.trace(`Results scan classic ${params.TableName}: ${result.Items.length ?? 0}`);
|
|
298
|
-
return result;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Execute a series of write operations in a single transaction.
|
|
303
|
-
* @param ops the operations to execute in the transaction
|
|
304
|
-
*/
|
|
305
|
-
async transactWrites(ops: { ConditionCheck?: any; Put?: any; Delete?: any; Update?: any }[]): Promise<void> {
|
|
306
|
-
if (!ops.length) return this.logger.trace('Transaction writes: no elements to write');
|
|
307
|
-
|
|
308
|
-
this.logger.trace('Transaction writes');
|
|
309
|
-
await this.dynamo.transactWrite({ TransactItems: ops });
|
|
310
|
-
}
|
|
311
|
-
}
|
package/src/genericController.ts
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import 'source-map-support/register';
|
|
2
|
-
|
|
3
|
-
import { LambdaLogger } from './lambdaLogger';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* An abstract class to inherit to manage some resources with an AWS Lambda function.
|
|
7
|
-
*/
|
|
8
|
-
export abstract class GenericController {
|
|
9
|
-
protected event: any;
|
|
10
|
-
protected callback: any;
|
|
11
|
-
|
|
12
|
-
protected logger = new LambdaLogger();
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Initialize a new GenericController helper object.
|
|
16
|
-
* @param event the event that invoked the AWS lambda function
|
|
17
|
-
* @param callback the callback to resolve or reject the execution
|
|
18
|
-
*/
|
|
19
|
-
constructor(event: any, callback: any) {
|
|
20
|
-
this.event = event;
|
|
21
|
-
this.callback = callback;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* The main function (to override), that handles the request and must terminate invoking the method `done`.
|
|
26
|
-
*/
|
|
27
|
-
async handleRequest(): Promise<void> {
|
|
28
|
-
this.logger.info('START');
|
|
29
|
-
this.done();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Default callback for the Lambda.
|
|
34
|
-
*/
|
|
35
|
-
protected done(error: Error | any = null, res?: any): void {
|
|
36
|
-
if (error) {
|
|
37
|
-
if ((error as UnhandledError).unhandled) this.logger.error('END-FAILED', error);
|
|
38
|
-
else this.logger.warn('END-FAILED', error);
|
|
39
|
-
} else this.logger.info('END-SUCCESS');
|
|
40
|
-
|
|
41
|
-
this.callback(error, res);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Remap an error to manage the logging and make sure no unhandled error is returned to the requester.
|
|
46
|
-
*/
|
|
47
|
-
protected handleControllerError(
|
|
48
|
-
err: Error | HandledError | any,
|
|
49
|
-
interceptedInContext: string,
|
|
50
|
-
replaceWithMessage: string
|
|
51
|
-
): HandledError | UnhandledError {
|
|
52
|
-
if (err instanceof HandledError) return err;
|
|
53
|
-
const error = err as UnhandledError;
|
|
54
|
-
error.unhandled = interceptedInContext;
|
|
55
|
-
error.internalMessage = error.message;
|
|
56
|
-
error.message = replaceWithMessage;
|
|
57
|
-
return error;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Get the current log level for the current Lambda function's `logger`.
|
|
62
|
-
* Note: "FATAL" means that no log will be printed.
|
|
63
|
-
*/
|
|
64
|
-
getLambdaLogLevel(): 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL' {
|
|
65
|
-
return process.env.AWS_LAMBDA_LOG_LEVEL as any;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Set the log level for the current Lambda function's `logger`.
|
|
69
|
-
*/
|
|
70
|
-
setLambdaLogLevel(logLevel: 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL'): void {
|
|
71
|
-
process.env.AWS_LAMBDA_LOG_LEVEL = logLevel;
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Raise the log level of the current Lambda function's `logger` to "FATAL", hence avoiding printing any log.
|
|
75
|
-
*/
|
|
76
|
-
silentLambdaLogs(): void {
|
|
77
|
-
process.env.AWS_LAMBDA_LOG_LEVEL = 'FATAL';
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* A specific type of error in the context of the Controller, to distinguish from "unhandled" errors.
|
|
83
|
-
*/
|
|
84
|
-
export class HandledError extends Error {
|
|
85
|
-
constructor(message: string) {
|
|
86
|
-
super(message);
|
|
87
|
-
Object.setPrototypeOf(this, HandledError.prototype);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* An unhandled error thrown inside the controller (i.e. `!(error instanceof HandledError)`) .
|
|
93
|
-
*/
|
|
94
|
-
export class UnhandledError extends Error {
|
|
95
|
-
/**
|
|
96
|
-
* The context where the unhandled error was intercepted.
|
|
97
|
-
*/
|
|
98
|
-
unhandled: string;
|
|
99
|
-
/**
|
|
100
|
-
* The original error message before it was replaced by a public-facing message.
|
|
101
|
-
*/
|
|
102
|
-
internalMessage: string;
|
|
103
|
-
}
|
package/src/lambdaLogger.ts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Manage structured logging in the context of a Lambda function.
|
|
3
|
-
* Note: the log level is controlled by each Lambda function's configuration.
|
|
4
|
-
*/
|
|
5
|
-
export class LambdaLogger {
|
|
6
|
-
// note: this is needed as long as the Lambda functions don't become reactive to changes to `AWS_LAMBDA_LOG_LEVEL`
|
|
7
|
-
shouldLog = (logLevel: 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL'): boolean =>
|
|
8
|
-
LOG_LEVELS_PRIORITY[logLevel] >= LOG_LEVELS_PRIORITY[process.env.AWS_LAMBDA_LOG_LEVEL];
|
|
9
|
-
|
|
10
|
-
trace = (summary: string, content: object = {}): void => {
|
|
11
|
-
if (this.shouldLog('TRACE')) console.trace({ summary, ...content });
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
debug = (summary: string, content: object = {}): void => {
|
|
15
|
-
if (this.shouldLog('DEBUG')) console.debug({ summary, ...content });
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
info = (summary: string, content: object = {}): void => {
|
|
19
|
-
if (this.shouldLog('INFO')) console.info({ summary, ...content });
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
warn = (summary: string, error: Error | any, content: object = {}): void => {
|
|
23
|
-
if (this.shouldLog('WARN')) console.warn({ summary, ...content, error });
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
error = (summary: string, error: Error | any, content: object = {}): void => {
|
|
27
|
-
if (this.shouldLog('ERROR')) console.error({ summary, ...content, error });
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// levels here are identical to bunyan practices (https://github.com/trentm/node-bunyan#levels)
|
|
32
|
-
export const LOG_LEVELS_PRIORITY: Record<string, number> = {
|
|
33
|
-
TRACE: 10,
|
|
34
|
-
DEBUG: 20,
|
|
35
|
-
INFO: 30,
|
|
36
|
-
WARN: 40,
|
|
37
|
-
ERROR: 50,
|
|
38
|
-
FATAL: 60
|
|
39
|
-
};
|
package/src/metrics.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* A wrapper for simple uses of CloudWatch Metrics.
|
|
5
|
-
*/
|
|
6
|
-
export class CloudWatchMetrics {
|
|
7
|
-
private metrics: Metrics;
|
|
8
|
-
|
|
9
|
-
constructor(options: { project?: string } = {}) {
|
|
10
|
-
const namespace = options.project ?? 'unknownProject';
|
|
11
|
-
this.metrics = new Metrics({ namespace });
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Get the raw Metrics object. To use for custom purposes.
|
|
16
|
-
*/
|
|
17
|
-
__raw(): Metrics {
|
|
18
|
-
return this.metrics;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Add an entry for the metrics.
|
|
22
|
-
*/
|
|
23
|
-
addMetric(metricName: string, value = 1, unit: MetricUnits = MetricUnits.Count): void {
|
|
24
|
-
this.metrics.addMetric(metricName, unit, value);
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Add a metadata useful when you want to search highly contextual information along with your metrics in your logs.
|
|
28
|
-
*/
|
|
29
|
-
addMetadata(key: string, value: string): void {
|
|
30
|
-
this.metrics.addMetadata(key, value);
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Add an additional metrics dimension.
|
|
34
|
-
*/
|
|
35
|
-
addDimension(name: string, value: string, defaultValue = '-'): void {
|
|
36
|
-
this.metrics.addDimension(name, value ?? defaultValue);
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Synchronous function to actually publish your metrics.
|
|
40
|
-
* It will create a new EMF blob and log it to be then ingested by Cloudwatch logs and processed for metrics creation.
|
|
41
|
-
*/
|
|
42
|
-
publishStoredMetrics(): void {
|
|
43
|
-
this.metrics.publishStoredMetrics();
|
|
44
|
-
}
|
|
45
|
-
}
|