-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathproducts.service.ts
More file actions
63 lines (57 loc) · 1.86 KB
/
products.service.ts
File metadata and controls
63 lines (57 loc) · 1.86 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
import { EntityManager, EntityRepository } from '@mikro-orm/core';
import { InjectRepository } from '@mikro-orm/nestjs';
import {
Injectable,
InternalServerErrorException,
Logger
} from '@nestjs/common';
import { Product } from '../model/product.entity';
@Injectable()
export class ProductsService {
private readonly logger = new Logger(ProductsService.name);
constructor(
@InjectRepository(Product)
private readonly productsRepository: EntityRepository<Product>,
private readonly em: EntityManager
) {}
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async findAll(
dateFrom: Date = new Date(
new Date().setFullYear(new Date().getFullYear() - 1)
),
dateTo: Date = new Date()
): Promise<Product[]> {
this.logger.debug(`Find all products from ${dateFrom} to ${dateTo}`);
const diffInMilliseconds = Math.abs(dateTo.getTime() - dateFrom.getTime());
const diffInYears = diffInMilliseconds / (1000 * 60 * 60 * 24 * 365);
if (diffInYears >= 2) {
await this.sleep(2000);
//This is to simulate a long query
}
return this.productsRepository.find(
{
createdAt: { $gte: dateFrom, $lte: dateTo }
},
{ orderBy: { createdAt: 'desc' } }
);
}
async findLatest(limit: number): Promise<Product[]> {
this.logger.debug(`Find ${limit} latest products`);
return this.productsRepository.find(
{},
{ limit, orderBy: { createdAt: 'desc' } }
);
}
async updateProduct(query: string): Promise<void> {
try {
this.logger.debug(`Updating products table with query "${query}"`);
await this.em.getConnection().execute(query);
return;
} catch (err) {
this.logger.warn(`Failed to execute query. Error: ${err.message}`);
throw new InternalServerErrorException(err.message);
}
}
}