54 lines
2.8 KiB
TypeScript
54 lines
2.8 KiB
TypeScript
import { toProject } from '../../../../../app/lib/logic/project'
|
|
import type { CloudMeta } from '../../../../utils/accounts'
|
|
// Save a project to the account. `baseRev` is the revision the device last
|
|
// had; if another device saved in between, this answers 409 with the newer
|
|
// version's meta, unless `force` is set.
|
|
export default defineEventHandler(async event => {
|
|
rateLimit(event, 'save', 1200, 10 * 60_000)
|
|
const user = await requireUser(event)
|
|
const id = getRouterParam(event, 'id')
|
|
if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' })
|
|
const raw = await readRawBody(event, 'utf8')
|
|
if (!raw || raw.length > 2_100_000) throw createError({ statusCode: 413, message: 'Project too large' })
|
|
let body: { project?: unknown; baseRev?: unknown; force?: unknown; link?: unknown; snapshot?: unknown }
|
|
try {
|
|
body = JSON.parse(raw)
|
|
} catch {
|
|
throw createError({ statusCode: 400, message: 'Not valid JSON' })
|
|
}
|
|
let project
|
|
try {
|
|
project = toProject(body.project)
|
|
} catch (e) {
|
|
throw createError({ statusCode: 400, message: (e as Error).message })
|
|
}
|
|
const link = body.link as CloudMeta['link']
|
|
const cleanLink = link && isShareId(link.id) ? { id: link.id, ...(typeof link.key === 'string' ? { key: link.key } : {}) } : undefined
|
|
|
|
return withLock(user.id, async () => {
|
|
const index = await readIndex(user.id)
|
|
const existing = index.projects.find(p => p.id === id)
|
|
if (existing && existing.rev !== body.baseRev && body.force !== true) {
|
|
setResponseStatus(event, 409)
|
|
return { conflict: true, meta: existing }
|
|
}
|
|
if (!existing && index.projects.length >= MAX_PROJECTS) throw createError({ statusCode: 409, message: 'Too many projects in this account' })
|
|
const size = JSON.stringify(project).length
|
|
const others = index.projects.reduce((n, p) => n + (p.id === id ? 0 : (p.size ?? 0)), 0)
|
|
if (others + size > MAX_ACCOUNT_BYTES) throw createError({ statusCode: 413, message: 'Your account is full (100 MB). Delete some projects first.' })
|
|
const meta: CloudMeta = { id, name: project.name, updated: Date.now(), rev: (existing?.rev ?? 0) + 1, size }
|
|
if (cleanLink) meta.link = cleanLink
|
|
else if (existing?.link && body.link === undefined) meta.link = existing.link
|
|
// Savegame: keep the state this save replaces.
|
|
const previous = existing && (await readProject(user.id, id))
|
|
if (existing && previous) {
|
|
await keepVersion(user.id, id, { project: previous, rev: existing.rev, at: existing.updated, name: existing.name }, body.snapshot === true)
|
|
}
|
|
await accounts().setItem(projectKey(user.id, id), project)
|
|
index.projects = [meta, ...index.projects.filter(p => p.id !== id)]
|
|
index.deleted = index.deleted.filter(d => d.id !== id)
|
|
await writeIndex(user.id, index)
|
|
return { meta }
|
|
})
|
|
})
|