-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathproducts.controller.ts
143 lines (134 loc) · 3.87 KB
/
products.controller.ts
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
import {
Controller,
Get,
Logger,
UseGuards,
Headers,
InternalServerErrorException,
Query,
BadRequestException
} from '@nestjs/common';
import {
ApiOperation,
ApiOkResponse,
ApiTags,
ApiForbiddenResponse,
ApiInternalServerErrorResponse,
ApiHeader,
ApiQuery
} from '@nestjs/swagger';
import { AuthGuard } from '../auth/auth.guard';
import { JwtProcessorType } from '../auth/auth.service';
import { JwtType } from '../auth/jwt/jwt.type.decorator';
import { ProductDto } from './api/ProductDto';
import { ProductsService } from './products.service';
import { Product } from '../model/product.entity';
import {
API_DESC_GET_LATEST_PRODUCTS,
API_DESC_GET_PRODUCTS,
API_DESC_GET_VIEW_PRODUCT
} from './products.controller.api.desc';
@Controller('/api/products')
@ApiTags('Products controller')
export class ProductsController {
private readonly logger = new Logger(ProductsController.name);
constructor(private readonly productsService: ProductsService) {}
private parseDate(dateString: string): Date {
const dateParts = dateString.split('-');
const year = parseInt(dateParts[2], 10);
const month = parseInt(dateParts[1], 10) - 1;
const day = parseInt(dateParts[0], 10);
return new Date(year, month, day);
}
@Get()
@UseGuards(AuthGuard)
@JwtType(JwtProcessorType.RSA)
@ApiOperation({
description: API_DESC_GET_PRODUCTS
})
@ApiOkResponse({
type: ProductDto,
isArray: true
})
@ApiForbiddenResponse({
schema: {
type: 'object',
properties: {
statusCode: { type: 'number' },
message: { type: 'string' },
error: { type: 'string' }
}
}
})
@ApiQuery({ name: 'date_from', example: '02-05-2001', required: false })
@ApiQuery({ name: 'date_to', example: '02-05-2024', required: false })
async getProducts(
@Query('date_from') dateFrom: string,
@Query('date_to') dateTo: string
): Promise<ProductDto[]> {
this.logger.debug('Get all products.');
let df = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
let dt = new Date(new Date().setDate(new Date().getDate() + 1));
if (dateFrom) {
df = this.parseDate(dateFrom);
}
if (dateTo) {
dt = this.parseDate(dateTo);
}
if (isNaN(df.getTime()) || isNaN(dt.getTime())) {
throw new BadRequestException('Invalid date format');
}
const allProducts = await this.productsService.findAll(df, dt);
return allProducts.map((p: Product) => new ProductDto(p));
}
@Get('latest')
@ApiQuery({ name: 'limit', example: 3, required: false })
@ApiOperation({
description: API_DESC_GET_LATEST_PRODUCTS
})
@ApiOkResponse({
type: ProductDto,
isArray: true
})
async getLatestProducts(
@Query('limit') limit: number
): Promise<ProductDto[]> {
this.logger.debug('Get latest products.');
if (limit && isNaN(limit)) {
throw new BadRequestException('Limit must be a number');
}
if (limit && limit < 0) {
throw new BadRequestException('Limit must be positive');
}
const products = await this.productsService.findLatest(limit || 3);
return products.map((p: Product) => new ProductDto(p));
}
@Get('views')
@ApiHeader({ name: 'x-product-name', example: 'Amethyst' })
@ApiOperation({
description: API_DESC_GET_VIEW_PRODUCT
})
@ApiOkResponse()
@ApiInternalServerErrorResponse({
schema: {
type: 'object',
properties: {
error: { type: 'string' },
location: { type: 'string' }
}
}
})
async viewProduct(
@Headers('x-product-name') productName: string
): Promise<void> {
try {
const query = `UPDATE product SET views_count = views_count + 1 WHERE name = '${productName}'`;
return await this.productsService.updateProduct(query);
} catch (err) {
throw new InternalServerErrorException({
error: err.message,
location: __filename
});
}
}
}