Files
crates/crates/api/pg.ts
T
2025-04-29 18:52:36 +10:00

92 lines
2.3 KiB
TypeScript

import * as bcrypt from "https://deno.land/x/bcrypt@v0.4.1/mod.ts"
import { load } from "$std/dotenv/mod.ts"
import { PrismaClient } from "prisma/generated/index.js";
// Load environment variables
await load({ export: true })
// Create and export the Prisma client
const DATABASE_URL = Deno.env.get("DATABASE_URL")
console.log("DATABASE_URL", { DATABASE_URL })
export const prisma = new PrismaClient({
datasources: {
db: {
url: DATABASE_URL,
},
},
});
export interface UserCreateParams {
email: string
password: string
discogs?: string
data?: Record<string, unknown>
}
export function createPg(log: Console) {
async function userFindId(id: string) {
return prisma.user.findUnique({ where: { id } })
}
async function userFindEmail(email: string) {
return prisma.user.findUnique({ where: { email } })
}
async function userWants(user: any) {
const wants = await prisma.want.findMany({
where: { userId: user.id },
include: { _count: { select: { offers: true } } },
})
// Sort by artist and title
return wants.sort((a, b) => {
const aKey = `${a.data.artists_sort} - ${a.data.title}`
const bKey = `${b.data.artists_sort} - ${b.data.title}`
return aKey.localeCompare(bKey)
})
}
async function userOffers(user: any) {
return prisma.offer.findMany({
where: {
userId: user.id,
status: { not: "declined" } // Assuming Status.Declined is "declined"
},
include: {
want: true,
},
orderBy: [
{ updatedAt: "asc" },
{ total: "asc" },
{ listingId: "asc" },
],
})
}
async function userCreate(params: UserCreateParams) {
const password = await bcrypt.hash(params.password)
const data = {
email: params.email,
password,
data: params.data || {},
}
return prisma.user.create({
data,
})
}
return {
userFindId,
userFindEmail,
userCreate,
userWants,
userOffers,
// Add more functions as needed
}
}
// Export type Pg for type checking
export type Pg = ReturnType<typeof createPg>