|
| 1 | +import { IQueryHandler, QueryHandler } from "@nestjs/cqrs"; |
| 2 | +import { InjectRepository } from "@nestjs/typeorm"; |
| 3 | +import { And, LessThan, MoreThan, Repository } from "typeorm"; |
| 4 | + |
| 5 | +import { UserIdService } from "src/core/authentication"; |
| 6 | +import { map, mapArray } from "src/core/mapper"; |
| 7 | +import { QueryService } from "src/core/query"; |
| 8 | + |
| 9 | +import { JournalEntry } from "../../../infrastructure/entities/journal-entry.entity"; |
| 10 | +import { JournalDetails } from "../../contracts/dtos/journal-details.dto"; |
| 11 | +import { JournalEntryDetails } from "../../contracts/dtos/journal-entry-details.dto"; |
| 12 | +import { GetCurrentOrganizationJournalQuery } from "../../contracts/queries/get-current-organization-journal.query"; |
| 13 | + |
| 14 | +function formatCommandName(commandName: string): string { |
| 15 | + return commandName.replace(/Command$/, ""); |
| 16 | +} |
| 17 | + |
| 18 | +@QueryHandler(GetCurrentOrganizationJournalQuery) |
| 19 | +export class GetCurrentOrganizationJournalHandler |
| 20 | + implements IQueryHandler<GetCurrentOrganizationJournalQuery, JournalDetails> |
| 21 | +{ |
| 22 | + constructor( |
| 23 | + @InjectRepository(JournalEntry) |
| 24 | + private readonly journalEntries: Repository<JournalEntry>, |
| 25 | + private readonly queryService: QueryService<JournalEntry>, |
| 26 | + private readonly userIdService: UserIdService, |
| 27 | + ) {} |
| 28 | + |
| 29 | + async execute(query: GetCurrentOrganizationJournalQuery) { |
| 30 | + const userId = this.userIdService.getUserId(); |
| 31 | + |
| 32 | + const foundJournalEntries = await this.queryService.find( |
| 33 | + this.journalEntries, |
| 34 | + { |
| 35 | + default: { |
| 36 | + order: { created: "desc" }, |
| 37 | + }, |
| 38 | + query, |
| 39 | + required: { |
| 40 | + where: { |
| 41 | + created: And(LessThan(query.to), MoreThan(query.from)), |
| 42 | + userId, |
| 43 | + }, |
| 44 | + }, |
| 45 | + }, |
| 46 | + ); |
| 47 | + |
| 48 | + return map(JournalDetails, { |
| 49 | + entries: mapArray(JournalEntryDetails, foundJournalEntries, (entry) => ({ |
| 50 | + commandName: formatCommandName(entry.commandName), |
| 51 | + created: entry.created, |
| 52 | + id: entry.id, |
| 53 | + payload: entry.payload, |
| 54 | + })), |
| 55 | + }); |
| 56 | + } |
| 57 | +} |
0 commit comments