This repository was archived by the owner on Aug 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlocal.js
More file actions
88 lines (80 loc) · 1.88 KB
/
local.js
File metadata and controls
88 lines (80 loc) · 1.88 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
import { isFirstOlder } from '@logux/core'
function userName(userId, name) {
return {
payload: {
name,
userId
},
type: 'users/name'
}
}
export function local(server) {
let names = new Map()
server.options.subprotocol = '1.0.0'
server.options.supports = '^1.0.0'
server.auth(({ cookie, headers, token, userId }) => {
if (headers.error) {
throw new Error(headers.error)
} else if (token === `${userId}:good`) {
return true
} else if (cookie.token === `${userId}:good`) {
return true
} else {
return false
}
})
server.channel('users/:id', {
access(ctx) {
if (ctx.headers.error) {
throw new Error(ctx.headers.error)
} else {
return ctx.params.id === ctx.userId
}
},
load(ctx) {
if (names.has(ctx.params.id)) {
let { lastChanged, name } = names.get(ctx.params.id)
return [[userName(ctx.params.id, name), { time: lastChanged.time }]]
} else {
return []
}
}
})
server.type('error', {
access() {
throw new Error('Error in action')
}
})
server.type('users/name', {
access(ctx, action) {
if (ctx.headers.error) {
throw new Error(ctx.headers.error)
} else {
return action.payload.userId === ctx.userId
}
},
process(ctx, action, meta) {
let { lastChanged } = names.get(ctx.userId) || []
if (isFirstOlder(lastChanged, meta)) {
names.set(ctx.userId, {
lastChanged: meta,
name: action.payload.name
})
}
},
resend(ctx, action) {
return { channels: [`users/${action.payload.userId}`] }
}
})
server.type('users/clean', {
access() {
return true
},
async process() {
for (let userId of names.keys()) {
await server.process(userName(userId, ''))
}
names.clear()
}
})
}