Skip to content

Instantly share code, notes, and snippets.

@cindywu
Created June 22, 2021 22:10
Show Gist options
  • Select an option

  • Save cindywu/a7f71fcab2ffd83d092400b1dfa0af72 to your computer and use it in GitHub Desktop.

Select an option

Save cindywu/a7f71fcab2ffd83d092400b1dfa0af72 to your computer and use it in GitHub Desktop.
pages/api/replicache-pull.ts
import { getDB } from '../../db'
// eslint-disable-next-line import/no-anonymous-default-export
export default async (req: any, res: any) => {
const pull = req.body
console.log(`Processing pull`, JSON.stringify(pull, null, ''))
const t0 = Date.now()
try {
const db = await getDB()
db.tx(async t => {
const lastMutationID = parseInt(
(
await db.oneOrNone(
'SELECT last_mutation_id FROM trunk_mini_replicache_client where id = $1',
pull.clientID,
)
)?.last_mutation_id ?? '0',
)
const changed = await db.manyOrNone(
'SELECT id, abbreviation, title, ord FROM trunk_mini WHERE version > $1',
parseInt(pull.cookie ?? 0),
)
const cookie = (
await db.one('SELECT max(version) AS verison FROM trunk_mini')
).version
console.log({cookie, lastMutationID, changed})
const patch = []
if (pull.cookie === null) {
patch.push({
op: 'clear',
})
}
patch.push(...changed.map(row => ({
op: 'put',
key: `ref/${row.id}`,
value: {
abbreviation: row.abbreviation,
title: row.title,
order: parseInt(row.ord),
}
})))
res.json({
lastMutationID,
cookie,
patch
})
res.end()
})
} catch (e) {
console.error(e)
res.status(500).send(e.toString())
} finally {
console.log('Processed pull in', Date.now() - t0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment