-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathproduct-category-service.ts
181 lines (166 loc) · 6.3 KB
/
product-category-service.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
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
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of the product-category-service.
*
* @module catalogue/product-categories
*/
import { FindManyOptions, IsNull, Raw } from 'typeorm';
import ProductCategory from '../entity/product/product-category';
import {
PaginatedProductCategoryResponse,
ProductCategoryResponse,
} from '../controller/response/product-category-response';
import ProductCategoryRequest from '../controller/request/product-category-request';
import QueryFilter, { FilterMapping } from '../helpers/query-filter';
import { PaginationParameters } from '../helpers/pagination';
import WithManager from '../database/with-manager';
/**
* Define productCategory filtering parameters used to filter query results.
*/
export interface ProductCategoryFilterParameters {
/**
* Filter based on product id.
*/
id?: number;
/**
* Filter based on product owner.
*/
name?: string;
/**
* Whether to only return root categories (so categories without parents)
*/
onlyRoot?: boolean;
/**
* Whether to only return leaf categories (so categories without children)
*/
onlyLeaf?: boolean;
}
/**
* Wrapper for all Product related logic.
*/
export default class ProductCategoryService extends WithManager {
/**
* Creates a productCategoryResponse from a productCategory
* @param {ProductCategory.model} productCategory - productCategory
* @returns {ProductCategoryResponse.model} - a productCategoryResponse
* created with the productCategory
*/
public static asProductCategoryResponse(productCategory: ProductCategory)
: ProductCategoryResponse {
return {
id: productCategory.id,
name: productCategory.name,
createdAt: productCategory.createdAt.toISOString(),
updatedAt: productCategory.updatedAt.toISOString(),
parent: productCategory.parent ? this.asProductCategoryResponse(productCategory.parent) : undefined,
};
}
/**
* Query for getting the productCategories.
*/
public static async getProductCategories(
filters: ProductCategoryFilterParameters = {}, pagination: PaginationParameters = {},
): Promise<PaginatedProductCategoryResponse> {
const { take, skip } = pagination;
const filterMapping: FilterMapping = {
id: 'id',
name: 'name',
};
const options: FindManyOptions<ProductCategory> = {
where: {
// Only IDs that are not found in the "parentId" column (so those IDs are not parents, i.e. are leafs)
id: filters.onlyLeaf ? Raw((columnAlias) => `${columnAlias} NOT IN (SELECT DISTINCT parentId FROM product_category WHERE parentId IS NOT NULL)`) : undefined,
parent: filters.onlyRoot ? IsNull() : undefined,
...QueryFilter.createFilterWhereClause(filterMapping, filters),
},
order: { id: 'ASC' },
};
const results = await Promise.all([
ProductCategory.find({ ...options, take, skip, relations: { parent: true } }),
ProductCategory.count(options),
]);
const records = results[0].map(
(productCategory) => (this.asProductCategoryResponse(productCategory)),
);
return {
_pagination: {
take, skip, count: results[1],
},
records,
};
}
/**
* Saves a ProductCategory to the database.
* @param request - The ProductCategoryRequest with values.
*/
public static async postProductCategory(
request: ProductCategoryRequest,
): Promise<ProductCategoryResponse> {
const parentCategory = request.parentCategoryId
? await ProductCategory.findOne({ where: { id: request.parentCategoryId } })
: undefined;
const category = new ProductCategory();
category.name = request.name;
category.parent = parentCategory;
return ProductCategory.save(category)
.then(() => this.asProductCategoryResponse(category));
}
/**
* Updates a ProductCategory in the database.
* @param id - The id of the productCategory that needs to be updated.
* @param request - The ProductCategoryRequest with updated values.
*/
public static async patchProductCategory(
id: number, request: ProductCategoryRequest,
): Promise<ProductCategoryResponse> {
const category = await ProductCategory.findOne({ where: { id } });
if (!category) return null;
const productCategory = Object.assign(category, request);
await ProductCategory.save(productCategory);
return this.asProductCategoryResponse(productCategory);
}
/**
* Deletes a ProductCategory from the database.
* @param id - The id of the productCategory that needs to be deleted.
*/
public static async deleteProductCategory(id: number): Promise<ProductCategoryResponse> {
const productCategory = await ProductCategory.findOne({ where: { id }, relations: { children: true } });
if (!productCategory || productCategory.children.length > 0) {
return null;
}
return ProductCategory.delete(id).then(() => this.asProductCategoryResponse(productCategory));
}
/**
* Verifies whether the productCategory request translates to a valid productCategory
* @param {ProductCategoryRequest.model} request
* - the productCategory request to verify
* @returns {boolean} - whether productCategory is ok or not
*/
public static async verifyProductCategory(request: ProductCategoryRequest):
Promise<boolean> {
return request.name != null && request.name !== ''
&& request.name.length <= 64
&& !(await ProductCategory.findOne({ where: { name: request.name } }))
&& !!(request.parentCategoryId !== undefined
? await ProductCategory.findOne({ where: { id: request.parentCategoryId } })
: true);
}
}