forked from DistinctCodes/AssetsUp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasset-history.service.ts
More file actions
77 lines (67 loc) · 2.33 KB
/
Copy pathasset-history.service.ts
File metadata and controls
77 lines (67 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, EntityManager, LessThanOrEqual, MoreThanOrEqual, Repository } from 'typeorm';
import {
AssetHistoryAction,
AssetHistoryEvent,
} from './entities/asset-history-event.entity';
export interface RecordHistoryInput {
assetId: string;
action: AssetHistoryAction;
description: string;
previousValue?: Record<string, unknown> | null;
newValue?: Record<string, unknown> | null;
performedById?: string;
}
export interface AssetHistoryFilters {
action?: AssetHistoryAction;
startDate?: string;
endDate?: string;
search?: string;
}
@Injectable()
export class AssetHistoryService {
constructor(
@InjectRepository(AssetHistoryEvent)
private readonly historyRepo: Repository<AssetHistoryEvent>,
) {}
/**
* Persist a history event. Pass `manager` to enlist the write in the caller's
* transaction so the event and the asset mutation commit together.
*/
async record(
input: RecordHistoryInput,
manager?: EntityManager,
): Promise<AssetHistoryEvent> {
const repo = manager ? manager.getRepository(AssetHistoryEvent) : this.historyRepo;
const event = repo.create({
assetId: input.assetId,
action: input.action,
description: input.description,
previousValue: input.previousValue ?? null,
newValue: input.newValue ?? null,
performedById: input.performedById,
});
return repo.save(event);
}
async findByAsset(
assetId: string,
filters?: AssetHistoryFilters,
): Promise<AssetHistoryEvent[]> {
const where: Record<string, unknown> = { assetId };
if (filters?.action) where.action = filters.action;
const start = filters?.startDate ? new Date(filters.startDate) : undefined;
const end = filters?.endDate ? new Date(filters.endDate) : undefined;
if (start && end) where.createdAt = Between(start, end);
else if (start) where.createdAt = MoreThanOrEqual(start);
else if (end) where.createdAt = LessThanOrEqual(end);
const events = await this.historyRepo.find({
where,
relations: ['performedBy'],
order: { createdAt: 'DESC' },
});
if (!filters?.search) return events;
const needle = filters.search.toLowerCase();
return events.filter((e) => e.description?.toLowerCase().includes(needle));
}
}