-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-pipeline.js
More file actions
73 lines (61 loc) · 2 KB
/
4-pipeline.js
File metadata and controls
73 lines (61 loc) · 2 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
'use strict';
const { randomUUID } = require('node:crypto');
const generateRequestId = () => `req-${Date.now()}-${randomUUID()}`;
const appendTrace = (context, step) => {
const { trace = [] } = context;
return [...trace, step];
};
const pipeline =
(...steps) =>
(context) => {
const initial = Promise.resolve(context);
const next = (chain, mw) => chain.then((ctx) => mw(ctx));
return steps.reduce(next, initial);
};
const tracing = (context) => {
const { console } = context;
const next = {
...context,
requestId: context.requestId ?? generateRequestId(),
trace: appendTrace(context, 'tracing'),
};
console.log(`[${next.requestId}] trace: ${next.trace.join(' -> ')}`);
return Promise.resolve(next);
};
const auth = (context) => {
const { console, headers } = context;
const user = headers?.user ?? { name: 'anonymous', role: 'guest' };
console.log(`[${context.requestId}] auth: ${user.name}`);
return Promise.resolve({ ...context, user });
};
const accessPolicy = (context) => {
const permissions = {
admin: ['read:balance', 'read:transactions'],
user: ['read:balance'],
guest: [],
};
const check = (role, permission) => permissions[role]?.includes(permission);
return Promise.resolve({
...context,
accessPolicy: { check, permissions },
});
};
const getBalance = (context) => {
const { console, accessPolicy, user, requestId } = context;
if (!accessPolicy.check(user.role, 'read:balance')) {
console.error(`[${requestId}] Access denied for ${user.name}`);
return Promise.resolve({ ...context, status: 403, body: null });
}
console.log(`[${requestId}] Balance for ${user.name}`);
const result = { ...context, status: 200, body: { balance: 15420.5 } };
return Promise.resolve(result);
};
// Usage
const execute = pipeline(tracing, auth, accessPolicy, getBalance);
const context = {
console,
headers: { user: { name: 'Marcus', role: 'admin' } },
};
execute(context).then((ctx) => {
console.log('Response:', ctx.status, ctx.body);
});