61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
|
|
import { eq } from "drizzle-orm";
|
||
|
|
import { database } from "~/database/context";
|
||
|
|
import * as schema from "~/database/schema";
|
||
|
|
|
||
|
|
export type League = typeof schema.leagues.$inferSelect;
|
||
|
|
export type NewLeague = typeof schema.leagues.$inferInsert;
|
||
|
|
|
||
|
|
export async function createLeague(data: NewLeague): Promise<League> {
|
||
|
|
const db = database();
|
||
|
|
const [league] = await db
|
||
|
|
.insert(schema.leagues)
|
||
|
|
.values(data)
|
||
|
|
.returning();
|
||
|
|
return league;
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function findLeagueById(id: string): Promise<League | undefined> {
|
||
|
|
const db = database();
|
||
|
|
return await db.query.leagues.findFirst({
|
||
|
|
where: eq(schema.leagues.id, id),
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function findLeaguesByCreator(userId: string): Promise<League[]> {
|
||
|
|
const db = database();
|
||
|
|
return await db.query.leagues.findMany({
|
||
|
|
where: eq(schema.leagues.createdBy, userId),
|
||
|
|
orderBy: (leagues, { desc }) => [desc(leagues.createdAt)],
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function updateLeague(
|
||
|
|
id: string,
|
||
|
|
data: Partial<NewLeague>
|
||
|
|
): Promise<League> {
|
||
|
|
const db = database();
|
||
|
|
const [league] = await db
|
||
|
|
.update(schema.leagues)
|
||
|
|
.set({ ...data, updatedAt: new Date() })
|
||
|
|
.where(eq(schema.leagues.id, id))
|
||
|
|
.returning();
|
||
|
|
return league;
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function deleteLeague(id: string): Promise<void> {
|
||
|
|
const db = database();
|
||
|
|
await db.delete(schema.leagues).where(eq(schema.leagues.id, id));
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function listLeagues(options?: {
|
||
|
|
limit?: number;
|
||
|
|
offset?: number;
|
||
|
|
}): Promise<League[]> {
|
||
|
|
const db = database();
|
||
|
|
return await db.query.leagues.findMany({
|
||
|
|
limit: options?.limit,
|
||
|
|
offset: options?.offset,
|
||
|
|
orderBy: (leagues, { desc }) => [desc(leagues.createdAt)],
|
||
|
|
});
|
||
|
|
}
|