Files
games/packages/server/src/api.ts
2025-08-19 22:19:24 -04:00

74 lines
1.3 KiB
TypeScript

import { Elysia, t } from "elysia";
import { simpleApi } from "./games/simple";
import { human } from "./human";
import dayjs from "dayjs";
import db from "./db";
const api = new Elysia({ prefix: "/api" })
.post("/whoami", async ({ cookie: { token } }) => {
if (token.value == null) {
const newHuman = await db.human.create({
data: {},
});
token.set({
value: newHuman.token,
expires: dayjs().add(1, "year").toDate(),
httpOnly: true,
});
}
return token.value;
})
.use(human)
.post(
"/setName",
({ body: { name }, humanKey }) =>
db.human.update({
where: {
key: humanKey,
},
data: {
name,
},
}),
{
body: t.Object({
name: t.String(),
}),
}
)
.get("/profile", ({ humanKey, query: { otherHumanKey } }) =>
db.human
.findFirst({ where: { key: otherHumanKey ?? humanKey } })
.then((human) => {
if (human == null) {
return null;
}
const { token, ...safeProfile } = human;
return safeProfile;
})
)
.get("/games", () => [{ key: "simple", name: "simple" }])
.get("/instances", ({ query: { game }, humanKey }) =>
db.instance.findMany({
where: {
game: {
name: game,
},
players: {
some: {
key: humanKey,
},
},
},
select: {
id: true,
},
})
)
.use(simpleApi);
export default api;
export type Api = typeof api;