-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
79 lines (71 loc) · 2.14 KB
/
index.js
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
"use strict";
const XRay = require("aws-xray-sdk-core");
function addMetadata(subSegment, metadata) {
if(metadata) {
for(const key in metadata) {
if(metadata.hasOwnProperty(key)) {
subSegment.addMetadata(key, metadata[key]);
}
}
}
}
function addAnnotations(subSegment, annotations) {
if(annotations) {
for(const key in annotations) {
if(annotations.hasOwnProperty(key)) {
subSegment.addAnnotation(key, annotations[key]);
}
}
}
}
async function addPromiseSegment ({
annotations,
parentSegment,
promiseFactory,
metadata,
segmentName,
}) {
if (!process.env.LAMBDA_TASK_ROOT) {
console.warn('WARNING: Skipping adding subsegment because we are not executing inside of aws lambda');
return promiseFactory();
}
return new Promise((resolve, reject) => {
try {
XRay.captureAsyncFunc(segmentName, (subSegment) => {
try {
if (!subSegment) {
return promiseFactory()
.then(val => resolve(val))
.catch(err => reject(err));
} else {
addMetadata(subSegment, metadata);
addAnnotations(subSegment, annotations);
promiseFactory(subSegment)
.then(val => {
resolve(val);
subSegment.close();
})
.catch(err => {
reject(err);
subSegment.close(err);
});
}
} catch(err) {
reject(err);
}
}, parentSegment);
} catch (err) {
reject(err);
}
});
};
async function addSegment (segmentName, promise) {
return addPromiseSegment({
segmentName,
promiseFactory: () => promise
})
}
module.exports = {
addPromiseSegment,
addSegment
};