forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.ts
More file actions
67 lines (56 loc) · 1.99 KB
/
Copy pathsync.ts
File metadata and controls
67 lines (56 loc) · 1.99 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
import type { Context } from 'hono'
import type { Env, PushRequest } from './types'
import { getUserById, pullChanges, pushChanges } from './db'
import { checkSyncRateLimit, getEffectivePlan } from './plan'
type SyncContext = Context<{ Bindings: Env, Variables: { userId: string } }>
async function enforceSyncRateLimit(c: SyncContext): Promise<Response | null> {
const userId = c.get(`userId`)
const user = await getUserById(c.env.DB, userId)
if (!user)
return c.json({ error: `not_found` }, 404)
const plan = getEffectivePlan(user.plan, user.plan_expires_at)
const rate = await checkSyncRateLimit(c.env.DB, userId, plan)
if (!rate.allowed) {
return c.json({
error: `rate_limit_exceeded`,
plan,
limit: rate.limit,
retryAfterSec: rate.retryAfterSec,
upgradeRequired: plan === `free`,
}, 429)
}
return null
}
export async function pullHandler(c: SyncContext) {
const blocked = await enforceSyncRateLimit(c)
if (blocked)
return blocked
const userId = c.get(`userId`)
const sinceRaw = c.req.query(`since`)
const since = Number.parseInt(sinceRaw ?? `0`, 10)
const cursor = Number.isFinite(since) && since > 0 ? since : 0
const { documents, settings, maxCursor } = await pullChanges(c.env, userId, cursor)
return c.json({ documents, settings, cursor: maxCursor })
}
export async function pushHandler(c: SyncContext) {
const blocked = await enforceSyncRateLimit(c)
if (blocked)
return blocked
const userId = c.get(`userId`)
let body: PushRequest
try {
body = await c.req.json<PushRequest>()
}
catch {
return c.json({ error: `invalid_body` }, 400)
}
const documents = Array.isArray(body.documents) ? body.documents : []
const settings = Array.isArray(body.settings) ? body.settings : []
const { documents: mergedDocs, settings: mergedSettings, maxCursor } = await pushChanges(
c.env,
userId,
documents,
settings,
)
return c.json({ documents: mergedDocs, settings: mergedSettings, cursor: maxCursor })
}