boredgame/src/lib/server/api/repositories/collections.repository.ts

84 lines
2.1 KiB
TypeScript
Raw Normal View History

import {takeFirstOrThrow} from '$lib/server/api/common/utils/repository';
import {DrizzleService} from '$lib/server/api/services/drizzle.service';
import {eq, type InferInsertModel} from 'drizzle-orm';
2024-11-12 01:14:20 +00:00
import {inject, injectable} from '@needle-di/core';
import {collections} from '../databases/postgres/tables';
export type CreateCollection = InferInsertModel<typeof collections>;
export type UpdateCollection = Partial<CreateCollection>;
@injectable()
2024-09-04 23:04:41 +00:00
export class CollectionsRepository {
2024-11-12 01:14:20 +00:00
constructor(private drizzle = inject(DrizzleService)) {}
2024-09-04 23:04:41 +00:00
async findAll(db = this.drizzle.db) {
return db.query.collections.findMany();
}
2024-09-04 23:04:41 +00:00
async findOneById(id: string, db = this.drizzle.db) {
return db.query.collections.findFirst({
where: eq(collections.id, id),
columns: {
cuid: true,
name: true,
},
});
}
2024-09-04 23:04:41 +00:00
async findOneByCuid(cuid: string, db = this.drizzle.db) {
return db.query.collections.findFirst({
where: eq(collections.cuid, cuid),
columns: {
cuid: true,
name: true,
},
});
}
2024-09-04 23:04:41 +00:00
async findOneByUserId(userId: string, db = this.drizzle.db) {
return db.query.collections.findFirst({
where: eq(collections.user_id, userId),
columns: {
cuid: true,
name: true,
},
});
}
2024-09-04 23:04:41 +00:00
async findAllByUserId(userId: string, db = this.drizzle.db) {
return db.query.collections.findMany({
where: eq(collections.user_id, userId),
columns: {
cuid: true,
name: true,
createdAt: true,
},
});
}
2024-09-16 16:07:22 +00:00
async findAllByUserIdWithDetails(userId: string, db = this.drizzle.db) {
return db.query.collections.findMany({
where: eq(collections.user_id, userId),
columns: {
cuid: true,
name: true,
},
with: {
collection_items: {
columns: {
cuid: true,
},
2024-09-16 16:07:22 +00:00
},
},
});
2024-09-16 16:07:22 +00:00
}
2024-09-04 23:04:41 +00:00
async create(data: CreateCollection, db = this.drizzle.db) {
return db.insert(collections).values(data).returning().then(takeFirstOrThrow);
}
2024-09-04 23:04:41 +00:00
async update(id: string, data: UpdateCollection, db = this.drizzle.db) {
return db.update(collections).set(data).where(eq(collections.id, id)).returning().then(takeFirstOrThrow);
}
}