Last active
July 20, 2022 14:05
-
-
Save glommer/cbff2c1a7514d7088d47353f2691a24e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from "../models/Client"; | |
import { Entry } from "../models/Entry"; | |
import { Space } from "../models/Space"; | |
type UserValue = { | |
op: 'del'; | |
key: string; | |
} | { | |
op: 'put'; | |
key: string; | |
value: unknown; | |
}; | |
function transformEntry(entry: Entry) : UserValue { | |
if (entry.deleted) { | |
return { "op" : "del", "key": entry.key}; | |
} else { | |
const value = JSON.parse(entry.value) | |
return { "op": "put", "key": entry.key, "value": value }; | |
} | |
} | |
export default async function (req: Request) : Promise<Response> { | |
const url = new URL(req.url); | |
const spaceID = url.searchParams.get("spaceID"); | |
const pull = await req.json(); | |
let requestCookie = pull.cookie ?? 0; | |
const clientID = pull.clientID; | |
const lastMutationID = (await Client.findOne({ clientID }))?.lastmutationid; | |
const responseCookie = (await Space.findOne({ spaceID }))?.version; | |
const patch = Entry.cursor().filter((entry) => | |
entry.spaceid == spaceID && entry.version > requestCookie | |
).map(x => transformEntry(x)); | |
return { | |
lastMutationID: lastMutationID ?? 0, | |
cookie: responseCookie ?? 0, | |
patch, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment