import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { MyViewsRepository } from '@task-stream/api/tracker/application'; import { MyViewReadModel } from '@task-stream/api/tracker/domain'; import { Model } from 'mongoose'; import { MyViewDoc, ReadModels, fromDoc } from './read-model.schemas'; @Injectable() export class MongoMyViewsRepository extends MyViewsRepository { constructor( @InjectModel(ReadModels.MyView) private readonly views: Model, ) { super(); } async findByOwner(ownerId: string): Promise { const docs = await this.views .find({ ownerId }) .sort({ name: 1 }) .lean(); return docs.map(toView); } async findById(id: string): Promise { const doc = await this.views.findOne({ id }).lean(); return doc ? toView(doc) : null; } countByOwner(ownerId: string): Promise { return this.views.countDocuments({ ownerId }); } async insert(view: MyViewReadModel): Promise { await this.views.create(view); } async delete(id: string): Promise { await this.views.deleteOne({ id }); } } /** Mongo leaves empty objects out: a view with no criteria has none. */ function toView(doc: MyViewDoc): MyViewReadModel { const view = fromDoc(doc) as MyViewReadModel; return { ...view, criteria: view.criteria ?? {} }; }