-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-immutable.js
More file actions
43 lines (34 loc) · 1.28 KB
/
6-immutable.js
File metadata and controls
43 lines (34 loc) · 1.28 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
'use strict';
const createContext = (base, data = {}) => Object.freeze({ ...base, ...data });
const withUser = (base, user) => createContext(base, { user });
const withRequest = (base, requestId) => createContext(base, { requestId });
const getBalance = (context, accountId) => {
const { console, accessPolicy, user, requestId } = context;
if (!user) {
console.error('No user in context');
return null;
}
console.log(`Request ID: ${requestId}`);
console.log(`User ${user.name} requesting balance for account ${accountId}`);
if (!accessPolicy.check(user.role, 'read:balance')) {
console.error(`Access denied for ${user.name}`);
return null;
}
return 15420.5;
};
// Usage
const accessPolicy = {
permissions: {
admin: ['read:balance'],
user: ['read:balance'],
guest: [],
},
check: (role, permission) =>
accessPolicy.permissions[role]?.includes(permission),
};
const context1 = createContext({ console, accessPolicy });
console.log('Context 1:', getBalance(context1, 'ACC-002'), '\n');
const context2 = withUser(context1, { name: 'Marcus', role: 'admin' });
console.log('Context 2:', getBalance(context2, 'ACC-002'), '\n');
const context3 = withRequest(context2, 'req-' + Date.now());
console.log('Context 3:', getBalance(context3, 'ACC-002'), '\n');