import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { IssueReminder, IssueRemindersRepository, } from '@task-stream/api/tracker/application'; import { Model } from 'mongoose'; import { ReadModels } from './read-model.schemas'; type Stored = IssueReminder & { _id?: unknown }; const strip = ({ _id: _ignored, ...reminder }: Stored): IssueReminder => reminder; @Injectable() export class MongoIssueRemindersRepository extends IssueRemindersRepository { constructor( @InjectModel(ReadModels.IssueReminder) private readonly reminders: Model, ) { super(); } async save(reminder: IssueReminder): Promise { await this.remove(reminder.userId, reminder.issueId); await this.reminders.create(reminder); } async waitingFor( userId: string, issueId: string, ): Promise { const doc = await this.reminders .findOne({ userId, issueId, sentAt: null }) .lean(); return doc ? strip(doc) : null; } async waitingOf(userId: string): Promise { const docs = await this.reminders .find({ userId, sentAt: null }) .sort({ at: 1 }) .lean(); return docs.map(strip); } async remove(userId: string, issueId: string): Promise { await this.reminders.deleteMany({ userId, issueId, sentAt: null }); } async due(now: string, limit: number): Promise { const docs = await this.reminders .find({ sentAt: null, at: { $lte: now } }) .sort({ at: 1 }) .limit(limit) .lean(); return docs.map(strip); } async markSent(id: string, at: string): Promise { await this.reminders.updateOne({ id }, { $set: { sentAt: at } }); } }