forked from rudderlabs/rudder-transformer
-
Notifications
You must be signed in to change notification settings - Fork 2
/
testRouter.js
221 lines (200 loc) · 6.97 KB
/
testRouter.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
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
/* eslint-disable camelcase */
/* eslint-disable import/no-dynamic-require */
/* eslint-disable global-require */
/* eslint-disable no-shadow */
const fs = require("fs");
const path = require("path");
const Router = require("koa-router");
const { sendToDestination, userTransformHandler } = require("./routerUtils");
const version = "v0";
const API_VERSION = "1";
const isSupportedContentType = contentType => {
let supported = false;
const SUPPORTED_CONTENT_TYPES = [
"application/xml",
"application/json",
"text"
];
if (contentType) {
SUPPORTED_CONTENT_TYPES.some(type => {
if (contentType.toLowerCase().includes(type)) {
supported = true;
return true;
}
return false;
});
}
return supported;
};
const testRouter = new Router({ prefix: "/test-router" });
const getDestHandler = (version, destination) => {
return require(`./${version}/destinations/${destination}/transform`);
};
const getDestinations = () => {
return fs.readdirSync(path.resolve(__dirname, version, "destinations"));
};
const transformDestination = dest => {
function capitalize(s) {
return s === "id"
? s.toUpperCase()
: s.charAt(0).toUpperCase() + s.slice(1);
}
const transformedObj = {};
const { destinationDefinition } = dest;
Object.keys(dest).forEach(key => {
transformedObj[capitalize(key)] = dest[key];
});
const destDef = {};
Object.keys(destinationDefinition).forEach(key => {
destDef[capitalize(key)] = destinationDefinition[key];
});
transformedObj.DestinationDefinition = destDef;
return transformedObj;
};
const handleTestEvent = async (ctx, dest) => {
try {
const { events } = ctx.request.body;
if (!events || !Array.isArray(events)) {
throw new Error("events array is required in payload");
}
const respList = [];
ctx.set("apiVersion", API_VERSION);
await Promise.all(
events.map(async event => {
const { message, destination, stage, libraries } = event;
const ev = {
message,
destination: transformDestination(destination),
libraries
};
let response = {};
let errorFound = false;
if (stage.user_transform) {
let librariesVersionIDs = [];
if (event.libraries) {
librariesVersionIDs = events[0].libraries.map(
library => library.versionId
);
}
const transformationVersionId =
ev.destination &&
ev.destination.Transformations &&
ev.destination.Transformations[0] &&
ev.destination.Transformations[0].versionId;
if (transformationVersionId) {
try {
const destTransformedEvents = await userTransformHandler()(
[ev],
transformationVersionId,
librariesVersionIDs
);
const userTransformedEvent = destTransformedEvents[0];
if (userTransformedEvent.error) {
throw new Error(userTransformedEvent.error);
}
response.user_transformed_payload =
userTransformedEvent.transformedEvent;
ev.message = userTransformedEvent.transformedEvent;
} catch (err) {
errorFound = true;
response.user_transformed_payload = {
error: err.message || JSON.stringify(err)
};
}
} else {
response.user_transformed_payload = {
error: "Transformation VersionID not found"
};
}
}
if (stage.dest_transform) {
if (!errorFound) {
try {
const desthandler = getDestHandler(version, dest);
const transformedOutput = await desthandler.process(ev);
if (Array.isArray(transformedOutput)) {
response.dest_transformed_payload = transformedOutput;
} else {
response.dest_transformed_payload = [transformedOutput];
}
} catch (err) {
errorFound = true;
response.dest_transformed_payload = {
error: err.message || JSON.stringify(err)
};
}
} else {
response.dest_transformed_payload = {
error: "error encountered in user_transformation stage. Aborting."
};
}
}
// const transformerStatuses = [];
if (stage.dest_transform && stage.send_to_destination) {
// send event to destination only after transformation
if (!errorFound) {
const destResponses = [];
const destResponseStatuses = [];
const transformedPayloads = response.dest_transformed_payload;
// eslint-disable-next-line no-restricted-syntax
for (const payload of transformedPayloads) {
// eslint-disable-next-line no-await-in-loop
const parsedResponse = await sendToDestination(dest, payload);
let contentType = "";
let response = "";
if (parsedResponse.headers) {
contentType = parsedResponse.headers["content-type"];
if (isSupportedContentType(contentType)) {
response = parsedResponse.response;
}
} else if (parsedResponse.networkFailure) {
response = parsedResponse.response;
}
destResponses.push(response);
destResponseStatuses.push(parsedResponse.status);
// TODO: Use updated handleResponseTransform function
// Removing the below part, because transformerStatus is not
// currently being returned by test api response
// call response transform here
// const ctxMock = {
// request: {
// body: parsedResponse
// }
// };
// handleResponseTransform(version, dest, ctxMock);
// const { output } = ctxMock.body;
// transformerStatuses.push(output.status);
}
response = {
...response,
destination_response: destResponses,
destination_response_status: destResponseStatuses
};
} else {
response.destination_response = {
error: "error encountered in dest_transformation stage. Aborting."
};
}
}
respList.push(response);
})
);
ctx.body = respList;
} catch (err) {
// fail-safety error response
ctx.body = {
error: err.message || JSON.stringify(err)
};
ctx.status = 400;
}
};
getDestinations().forEach(async destination => {
testRouter.post(`/${version}/${destination}`, async ctx => {
await handleTestEvent(ctx, destination);
return ctx;
});
});
testRouter.get(`/${version}/health`, ctx => {
ctx.body = "OK";
});
module.exports = { testRouter, handleTestEvent };