import {Repository} from "./Repository"; import {PlaydateModel} from "../Models/PlaydateModel"; import Playdate, {DBPlaydate} from "../Database/tables/Playdate"; import {DatabaseConnection} from "../Database/DatabaseConnection"; import {GroupRepository} from "./GroupRepository"; import {GroupModel} from "../Models/GroupModel"; import {Nullable} from "../types/Nullable"; export class PlaydateRepository extends Repository { constructor( protected readonly database: DatabaseConnection, private readonly groupRepository: GroupRepository, ) { super( database, Playdate ); } findFromGroup(group: GroupModel, all = false) { let sql = `SELECT * FROM ${this.schema.name} WHERE groupid = ?`; const params = [group.id]; if (!all) { sql += " AND time_from > ?" params.push(new Date().getTime()) } const finds = this.database.fetchAll( sql, ...params ); return finds.map((playdate) => this.convertToModelType(playdate, group)); } findPlaydatesInRange(fromDate: Date | number, toDate: Date | number | undefined = undefined, group: GroupModel | undefined = undefined) { if (fromDate instanceof Date) { fromDate = fromDate.getTime(); } if (toDate instanceof Date) { toDate = toDate.getTime(); } let sql = `SELECT * FROM ${this.schema.name} WHERE time_from > ?`; const params = [fromDate]; if (toDate) { sql = `${sql} AND time_from < ?` params.push(toDate); } if (group) { sql = `${sql} AND groupid = ?` params.push(group.id) } const finds = this.database.fetchAll( sql, ...params ); return finds.map((playdate) => this.convertToModelType(playdate, group)); } getNextPlaydateForGroup(group: GroupModel): PlaydateModel | null { const sql = `SELECT * FROM ${this.schema.name} WHERE groupid = ? AND time_from > ? ORDER BY time_from LIMIT 1`; const find = this.database.fetch( sql, group.id, Date.now() ) if (!find) { return null; } return this.convertToModelType(find, group) } protected convertToModelType(intermediateModel: DBPlaydate | undefined, fixedGroup: Nullable = null): PlaydateModel { if (!intermediateModel) { throw new Error("Unable to convert the playdate model"); } return { id: intermediateModel.id, group: fixedGroup ?? this.groupRepository.getById(intermediateModel.groupid), from_time: new Date(intermediateModel.time_from), to_time: new Date(intermediateModel.time_to), }; } protected convertToCreateObject(instance: Partial): object { return { groupid: instance.group?.id ?? null, time_from: instance.from_time?.getTime() ?? 0, time_to: instance.to_time?.getTime() ?? 0, } } }