-
-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathindex.js
More file actions
221 lines (203 loc) · 5.52 KB
/
index.js
File metadata and controls
221 lines (203 loc) · 5.52 KB
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
// Copyright 2017 - 2026 will Farrell, Luciano Mammino, and Middy contributors.
// SPDX-License-Identifier: MIT
import { Transform } from "node:stream";
import { TransformStream } from "node:stream/web";
import {
executionContextKeys,
isExecutionModeDurable,
lambdaContextKeys,
} from "@middy/util";
const defaults = {
logger: (message) => {
console.log(JSON.stringify(message));
},
executionContext: false,
lambdaContext: false,
omitPaths: [],
mask: undefined,
};
const inputOutputLoggerMiddleware = (opts = {}) => {
const { logger, executionContext, lambdaContext, omitPaths, mask } = {
...defaults,
...opts,
};
if (typeof logger !== "function") {
throw new Error("logger must be a function", {
cause: {
package: "@middy/input-output-logger",
},
});
}
const omitPathTree = buildPathTree(omitPaths);
// needs `omitPathTree`, `logger`
const omitAndLog = (param, request) => {
const message = { [param]: request[param] };
if (executionContext) {
if (isExecutionModeDurable(request.context)) {
message.context ??= {};
message.context.executionContext = pick(
request.context.executionContext,
executionContextKeys,
);
} else {
message.context = pick(request.context, executionContextKeys);
}
}
if (lambdaContext) {
if (isExecutionModeDurable(request.context)) {
message.context ??= {};
message.context.lambdaContext = pick(
request.context.lambdaContext,
lambdaContextKeys,
);
} else {
message.context = pick(request.context, lambdaContextKeys);
}
}
let cloneMessage = message;
if (omitPaths.length) {
cloneMessage = structuredClone(message); // Full clone to prevent nested mutations
omit(cloneMessage, { [param]: omitPathTree[param] });
}
logger(cloneMessage);
};
// needs `mask`
const omit = (obj, pathTree = {}) => {
if (Array.isArray(obj) && pathTree["[]"]) {
for (let i = 0, l = obj.length; i < l; i++) {
omit(obj[i], pathTree["[]"]);
}
} else if (isObject(obj)) {
for (const key in pathTree) {
if (pathTree[key] === true) {
if (mask) {
obj[key] = mask;
} else {
delete obj[key];
}
} else {
omit(obj[key], pathTree[key]);
}
}
}
};
const inputOutputLoggerMiddlewareBefore = (request) => {
omitAndLog("event", request);
};
const inputOutputLoggerMiddlewareAfter = (request) => {
// Check for Node.js stream
if (
request.response?._readableState ??
request.response?.body?._readableState
) {
passThrough(request, omitAndLog);
}
// Check for Web stream
else if (
request.response instanceof ReadableStream ||
request.response?.body instanceof ReadableStream
) {
passThroughWebStream(request, omitAndLog);
} else {
omitAndLog("response", request);
}
};
const inputOutputLoggerMiddlewareOnError = async (request) => {
if (typeof request.response === "undefined") return;
await inputOutputLoggerMiddlewareAfter(request);
};
return {
before: inputOutputLoggerMiddlewareBefore,
after: inputOutputLoggerMiddlewareAfter,
onError: inputOutputLoggerMiddlewareOnError,
};
};
// move to util, if ever used elsewhere
const pick = (originalObject = {}, keysToPick = []) => {
const newObject = {};
for (const path of keysToPick) {
// only supports first level
if (originalObject[path] !== undefined) {
newObject[path] = originalObject[path];
}
}
return newObject;
};
const isObject = (value) =>
value && typeof value === "object" && value.constructor === Object;
const buildPathTree = (paths) => {
const tree = {};
for (let path of paths.sort().reverse()) {
// reverse to ensure conflicting paths don't cause issues
if (!Array.isArray(path)) path = path.split(".");
if (path.includes("__proto__")) continue;
path.reduce((a, b, idx) => {
if (idx < path.length - 1) {
a[b] ??= {};
return a[b];
}
a[b] = true;
return true;
}, tree);
}
return tree;
};
const passThrough = (request, omitAndLog) => {
// required because `core` remove body before `flush` is triggered
const hasBody = request.response?.body;
let body = "";
const listen = new Transform({
objectMode: false,
transform(chunk, encoding, callback) {
body += chunk;
this.push(chunk, encoding);
callback();
},
flush(callback) {
if (hasBody) {
omitAndLog("response", { response: { ...request.response, body } });
} else {
omitAndLog("response", { response: body });
}
callback();
},
});
if (hasBody) {
request.response.body = request.response.body.pipe(listen);
} else {
request.response = request.response.pipe(listen);
}
};
// Handler for Web Streams API
const passThroughWebStream = (request, omitAndLog) => {
const hasBody = request.response?.body;
let body = "";
const transformer = new TransformStream({
transform(chunk, controller) {
// For web streams, chunks could be various types
const textChunk =
typeof chunk === "string"
? chunk
: chunk instanceof Uint8Array
? new TextDecoder().decode(chunk)
: String(chunk);
body += textChunk;
controller.enqueue(chunk);
},
flush(controller) {
if (hasBody) {
omitAndLog("response", { response: { ...request.response, body } });
} else {
omitAndLog("response", { response: body });
}
},
});
if (hasBody) {
// Handle response with body property that's a ReadableStream
request.response.body = request.response.body.pipeThrough(transformer);
} else {
// Handle response that's directly a ReadableStream
request.response = request.response.pipeThrough(transformer);
}
};
export default inputOutputLoggerMiddleware;