-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbase.service.ts
More file actions
181 lines (162 loc) · 6.01 KB
/
base.service.ts
File metadata and controls
181 lines (162 loc) · 6.01 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { EntityManager, FindOneOptions, MoreThan, LessThan, ObjectLiteral, Repository } from "typeorm";
import { mapQueryToTypeorm } from "@/db/query/typeorm-query-mapper";
import { Query } from "@/db/query/query";
import { CursorPaginationResult } from "@/db/query/cursor-pagination";
import { Logger } from "@/logging/Logger";
import opentelemetry, { Counter, Histogram } from "@opentelemetry/api";
import { ErrorCodes, HttpException } from "@/utils";
export class BaseService<
Entity extends ObjectLiteral
> {
protected logger: Logger;
protected metrics: {
operation: Counter;
duration: Histogram;
};
constructor(
protected readonly name: string,
protected readonly repository: Repository<Entity>
) {
this.logger = new Logger(`CRUD:${this.name}`);
const meter = opentelemetry.metrics.getMeter("crud");
this.metrics = {
operation: meter.createCounter("crud_operations_total", {
description: "CRUD operation"
}),
duration: meter.createHistogram("crud_operation_duration_seconds", {
description: "CRUD operation duration",
advice: {
explicitBucketBoundaries: [0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
}
})
};
}
withTransaction(manager: EntityManager): this {
const txRepo = manager.getRepository(this.repository.target);
const clone = Object.create(this) as this;
Object.defineProperty(clone, "repository", { value: txRepo, writable: false });
Object.defineProperty(clone, "logger", {
value: new Logger(`CRUD:${this.name}:TX`),
writable: false,
});
return clone;
}
async count(query: Query<Entity>) {
this.logger.debug(`${this.name}::count`, { data: { query } });
const attr = { entity: this.name, operation: "count" };
let status = "success";
const start = Date.now();
try {
return await this.repository.count(mapQueryToTypeorm(query));
} catch (e) {
status = "failure";
throw e;
} finally {
this.metrics.operation.add(1, { ...attr, status });
this.metrics.duration.record((Date.now() - start) / 1000, attr);
}
}
async list(query: Query<Entity> = {}): Promise<Entity[]> {
this.logger.debug(`${this.name}::list`, { data: { query } });
const attr = { entity: this.name, operation: "list" };
let status = "success";
const start = Date.now();
try {
return await this.repository.find(mapQueryToTypeorm(query));
} catch (e) {
status = "failure";
throw e;
} finally {
this.metrics.operation.add(1, { ...attr, status });
this.metrics.duration.record((Date.now() - start) / 1000, attr);
}
}
async get(query: Query<Entity> = {}): Promise<Entity | null> {
this.logger.debug(`${this.name}::get`, { data: { query } });
const attr = { entity: this.name, operation: "get" };
let status = "success";
const start = Date.now();
try {
return await this.repository.findOne(mapQueryToTypeorm(query) as FindOneOptions<Entity>);
} catch (e) {
status = "failure";
throw e;
} finally {
this.metrics.operation.add(1, { ...attr, status });
this.metrics.duration.record((Date.now() - start) / 1000, attr);
}
}
async getById(id: string, query: Query<Entity> = {}): Promise<Entity | null> {
this.logger.debug(`${this.name}::getById`, { data: { query } });
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (id == null) {
throw new Error("null id passed in update");
}
const attr = { entity: this.name, operation: "get_by_id" };
let status = "success";
const start = Date.now();
try {
const options = mapQueryToTypeorm(query) as FindOneOptions<Entity>;
return await this.repository.findOne({
...options,
// eslint-disable-next-line @typescript-eslint/no-misused-spread
where: { ...options.where, id } as any
});
} catch (e) {
status = "failure";
throw e;
} finally {
this.metrics.operation.add(1, { ...attr, status });
this.metrics.duration.record((Date.now() - start) / 1000, attr);
}
}
async listCursor(query: Query<Entity> = {}): Promise<CursorPaginationResult<Entity>> {
this.logger.debug(`${this.name}::listCursor`, { data: { query } });
const attr = { entity: this.name, operation: "list_cursor" };
let status = "success";
const start = Date.now();
try {
const { after, before, limit = 20, ...restQuery } = query;
if (after && before) {
throw new HttpException(400, "Cannot use both 'after' and 'before' cursors", ErrorCodes.CLIENT_ERROR);
}
// Fetch limit + 1 to check for more pages
const typeormOptions = mapQueryToTypeorm({ ...restQuery, limit: limit + 1 });
// Apply cursor filter and force id sort (cursor pagination always sorts by id)
if (after) {
// eslint-disable-next-line @typescript-eslint/no-misused-spread
typeormOptions.where = { ...typeormOptions.where, id: MoreThan(after) };
typeormOptions.order = { id: "ASC" };
} else if (before) {
// eslint-disable-next-line @typescript-eslint/no-misused-spread
typeormOptions.where = { ...typeormOptions.where, id: LessThan(before) };
typeormOptions.order = { id: "DESC" };
} else {
typeormOptions.order = { id: "ASC" };
}
let items = await this.repository.find(typeormOptions);
const hasMore = items.length > limit;
if (hasMore) {
items = items.slice(0, limit);
}
if (before) {
items = items.reverse();
}
return {
data: items,
pageInfo: {
hasNextPage: before ? true : hasMore,
hasPreviousPage: after ? true : Boolean(before && hasMore),
startCursor: items[0]?.id ?? null,
endCursor: items[items.length - 1]?.id ?? null
}
};
} catch (e) {
status = "failure";
throw e;
} finally {
this.metrics.operation.add(1, { ...attr, status });
this.metrics.duration.record((Date.now() - start) / 1000, attr);
}
}
}