fp/services/our/src/plugins/slots.ts.old

97 lines
2.6 KiB
TypeScript

import { PrismaClient } from '../../generated/prisma'
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { withAccelerate } from "@prisma/extension-accelerate"
const prisma = new PrismaClient().$extends(withAccelerate())
interface SlotPatchQuery {
slot_number: number
waifu_id: number
}
export default async function slotsRoutes(
fastify: FastifyInstance,
): Promise<void> {
fastify.get('/slots', async function (request: FastifyRequest, reply: FastifyReply) {
const userId = request.session.get('user_id')
if (!userId) throw new Error(`failed to find user_id in session. please log in again.`);
// const slots = await prisma.slot.findMany({
// where: {
// userId: userId
// }
// })
const slots = await prisma.slot.findMany({
where: {
userId: userId,
},
include: {
waifu: true, // 👈 includes the full waifu record
},
});
reply.send(slots)
})
fastify.patch('/slots', async function (request: FastifyRequest<{ Querystring: SlotPatchQuery }>, reply: FastifyReply) {
const userId = request.session.get('user_id')
if (!userId) throw new Error(`failed to find user_id in session. please log in again.`);
const slot_number = Number(request.query.slot_number)
const waifu_id = Number(request.query.waifu_id)
if (isNaN(slot_number)) throw new Error('slot_number must be a number');
if (isNaN(waifu_id)) throw new Error('waifu_id must be a number');
if (!slot_number) throw new Error('slot_number was missing in query.');
if (!waifu_id) throw new Error('waifu_id was missing in query.');
const updatedOrCreatedSlot = await prisma.slot.upsert({
where: {
userId_index: {
userId,
index: slot_number,
},
},
update: {
waifu: {
connect: {
id: waifu_id,
},
},
},
create: {
userId,
index: slot_number,
waifuId: waifu_id,
}
})
// const updatedSlot = await prisma.slot.update({
// where: {
// userId_index: { userId, index: slot_number }
// },
// data: {
// waifu: { connect: { id: waifu_id } }
// }
// })
reply.send(updatedOrCreatedSlot)
})
}