-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhandler.test.ts
More file actions
316 lines (266 loc) 路 8.63 KB
/
Copy pathhandler.test.ts
File metadata and controls
316 lines (266 loc) 路 8.63 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
import { assert, assertEquals } from "@std/assert";
import { describe, it } from "@std/testing/bdd";
import * as results from "@eserstack/primitives/results";
import { runTask, succeed, task } from "./task.ts";
import {
type Adapter,
type AdaptError,
adaptError,
bind,
createTrigger,
type Handler,
type ResponseMapper,
} from "./handler.ts";
import type {
CliEvent,
HttpEvent,
HttpResponse,
QueueEvent,
} from "./triggers.ts";
// --- Test fixtures ---
type OrderInput = {
readonly customerId: string;
readonly items: readonly string[];
};
type Order = {
readonly id: string;
readonly customerId: string;
readonly items: readonly string[];
};
type OrderError = { readonly _tag: "OrderError"; readonly message: string };
type AppCtx = {
readonly db: {
insert: (input: OrderInput) => Order;
};
};
const createOrder: Handler<OrderInput, Order, OrderError, AppCtx> = (input) =>
task((ctx) => {
const order = ctx.db.insert(input);
return Promise.resolve(results.ok(order));
});
const mockCtx: AppCtx = {
db: {
insert: (input) => ({
id: "order-1",
customerId: input.customerId,
items: input.items,
}),
},
};
// --- Adapter Binding ---
describe("handler", () => {
describe("bind", () => {
it("binds an HTTP adapter to a handler", async () => {
const fromHttp: Adapter<HttpEvent, OrderInput> = (event) => {
if (event.method !== "POST") {
return results.fail(adaptError("Method not allowed"));
}
return results.ok(event.body as OrderInput);
};
const httpHandler = bind(createOrder, fromHttp);
const event: HttpEvent = {
method: "POST",
path: "/orders",
headers: {},
query: {},
body: { customerId: "cust-1", items: ["item-a"] },
};
const result = await runTask(httpHandler(event), mockCtx);
assert(results.isOk(result));
assertEquals(result.value.customerId, "cust-1");
assertEquals(result.value.items, ["item-a"]);
});
it("returns AdaptError when adapter rejects the event", async () => {
const fromHttp: Adapter<HttpEvent, OrderInput> = (event) => {
if (event.method !== "POST") {
return results.fail(adaptError("Method not allowed"));
}
return results.ok(event.body as OrderInput);
};
const httpHandler = bind(createOrder, fromHttp);
const event: HttpEvent = {
method: "GET",
path: "/orders",
headers: {},
query: {},
body: null,
};
const result = await runTask(httpHandler(event), mockCtx);
assert(results.isFail(result));
assertEquals((result.error as AdaptError)._tag, "AdaptError");
assertEquals(
(result.error as AdaptError).message,
"Method not allowed",
);
});
it("binds a queue adapter to the same handler", async () => {
const fromQueue: Adapter<QueueEvent, OrderInput> = (event) =>
results.ok(JSON.parse(event.body as string) as OrderInput);
const queueHandler = bind(createOrder, fromQueue);
const event: QueueEvent = {
messageId: "msg-1",
body: JSON.stringify({
customerId: "cust-2",
items: ["item-b"],
}),
attributes: {},
receiveCount: 1,
};
const result = await runTask(queueHandler(event), mockCtx);
assert(results.isOk(result));
assertEquals(result.value.customerId, "cust-2");
});
it("binds a CLI adapter to the same handler", async () => {
const fromCli: Adapter<CliEvent, OrderInput> = (event) =>
results.ok({
customerId: event.flags["customer"] as string,
items: event.args,
});
const cliHandler = bind(createOrder, fromCli);
const event: CliEvent = {
command: "create-order",
args: ["item-c", "item-d"],
flags: { customer: "cust-3" },
};
const result = await runTask(cliHandler(event), mockCtx);
assert(results.isOk(result));
assertEquals(result.value.customerId, "cust-3");
assertEquals(result.value.items, ["item-c", "item-d"]);
});
it("works with context-free handlers", async () => {
const echo: Handler<string, string, never> = (input) =>
succeed(`Echo: ${input}`);
const fromCli: Adapter<CliEvent, string> = (event) =>
results.ok(event.args.join(" "));
const cliEcho = bind(echo, fromCli);
const event: CliEvent = {
command: "echo",
args: ["hello", "world"],
flags: {},
};
const result = await runTask(cliEcho(event));
assert(results.isOk(result));
assertEquals(result.value, "Echo: hello world");
});
});
// --- adaptError ---
describe("adaptError", () => {
it("creates an AdaptError with message", () => {
const err = adaptError("Missing field");
assertEquals(err._tag, "AdaptError");
assertEquals(err.message, "Missing field");
assertEquals(err.source, undefined);
});
it("creates an AdaptError with source", () => {
const original = new Error("parse failed");
const err = adaptError("Invalid JSON", original);
assertEquals(err._tag, "AdaptError");
assertEquals(err.source, original);
});
});
// --- createTrigger ---
describe("createTrigger", () => {
it("creates a full round-trip trigger (input + output)", async () => {
const fromHttp: Adapter<HttpEvent, OrderInput> = (event) =>
results.ok(event.body as OrderInput);
const toHttpResponse: ResponseMapper<
Order,
OrderError | AdaptError,
HttpResponse
> = (result) => {
if (results.isOk(result)) {
return {
status: 201,
headers: { "content-type": "application/json" },
body: result.value,
};
}
return {
status: 400,
headers: { "content-type": "application/json" },
body: { error: result.error },
};
};
const handleHttp = createTrigger({
handler: createOrder,
adaptInput: fromHttp,
adaptOutput: toHttpResponse,
});
const event: HttpEvent = {
method: "POST",
path: "/orders",
headers: {},
query: {},
body: { customerId: "cust-1", items: ["item-a"] },
};
const response = await handleHttp(event, mockCtx);
assertEquals(response.status, 201);
assertEquals(
(response.body as Order).customerId,
"cust-1",
);
});
it("maps adapter errors to response", async () => {
const fromHttp: Adapter<HttpEvent, OrderInput> = (event) => {
if (event.method !== "POST") {
return results.fail(adaptError("Method not allowed"));
}
return results.ok(event.body as OrderInput);
};
const toHttpResponse: ResponseMapper<
Order,
OrderError | AdaptError,
HttpResponse
> = (result) => {
if (results.isOk(result)) {
return { status: 201, headers: {}, body: result.value };
}
const error = result.error;
if ("_tag" in error && error._tag === "AdaptError") {
return { status: 400, headers: {}, body: { error: error.message } };
}
return { status: 500, headers: {}, body: { error: "Internal error" } };
};
const handleHttp = createTrigger({
handler: createOrder,
adaptInput: fromHttp,
adaptOutput: toHttpResponse,
});
const event: HttpEvent = {
method: "GET",
path: "/orders",
headers: {},
query: {},
body: null,
};
const response = await handleHttp(event, mockCtx);
assertEquals(response.status, 400);
assertEquals(
(response.body as { error: string }).error,
"Method not allowed",
);
});
it("works with context-free handler", async () => {
const echo: Handler<string, string, never> = (input) =>
succeed(`Echo: ${input}`);
const fromCli: Adapter<CliEvent, string> = (event) =>
results.ok(event.args.join(" "));
const toText: ResponseMapper<string, never | AdaptError, string> = (
result,
) => results.isOk(result) ? result.value : `Error: ${result.error}`;
const handleCli = createTrigger({
handler: echo,
adaptInput: fromCli,
adaptOutput: toText,
});
const event: CliEvent = {
command: "echo",
args: ["hello"],
flags: {},
};
const response = await handleCli(event);
assertEquals(response, "Echo: hello");
});
});
});