newsnow/server/api/me/sync.ts

36 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-10-24 20:50:30 +08:00
import process from "node:process"
2024-10-15 12:05:03 +08:00
import { verifyPrimitiveMetadata } from "@shared/verify"
import { UserTable } from "#/database/user"
export default defineEventHandler(async (event) => {
try {
const { id } = event.context.user
const db = useDatabase()
if (!db) throw new Error("Not found database")
const userTable = new UserTable(db)
2024-10-24 20:50:30 +08:00
if (process.env.INIT_TABLE !== "false") await userTable.init()
2024-10-15 12:05:03 +08:00
if (event.method === "GET") {
const { data, updated } = await userTable.getData(id)
return {
data: data ? JSON.parse(data) : undefined,
updatedTime: updated,
}
} else if (event.method === "POST") {
const body = await readBody(event)
verifyPrimitiveMetadata(body)
const { updatedTime, data } = body
await userTable.setData(id, JSON.stringify(data), updatedTime)
return {
success: true,
updatedTime,
}
}
} catch (e) {
logger.error(e)
throw createError({
statusCode: 500,
message: e instanceof Error ? e.message : "Internal Server Error",
})
}
})