-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookController.ts
425 lines (366 loc) · 8.63 KB
/
bookController.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import { Request, Response } from 'express';
import prisma from '#instances/prisma';
import { __ } from "#helpers/i18n";
import { isHentai, isMobile } from '#helpers/index';
import { CATALOG_BOOKS_COUNT_MOBILE, CATALOG_BOOKS_COUNT_DESK, DEFAULT_BOOKS_ORDER_BY, DEFAULT_BOOKS_SORT } from '#config/index';
import { Book, Bookmark, EnBookStatus, EnBookType } from '@prisma/client';
import _isArray from 'lodash/isArray';
import _has from 'lodash/has';
import { EnBookOrderBy } from '#enums/BookOrderByEnum';
import { EnSort } from '#enums/SortEnum';
import _isEmpty from 'lodash/isEmpty';
import intersection from 'lodash/intersection';
interface IntSearch {
types?: string | string[];
genres?: string | string[];
tags?: string | string[];
persons?: string | string[];
serie?: string;
orderBy?: string;
}
export interface IntFilters {
types?: string | string[];
genres?: string | string[];
tags?: string | string[];
persons?: string | string[];
serie?: string;
}
export interface IntFilterData {
types?: EnBookType[] | null;
genres?: number[] | null;
tags?: number[] | null;
persons?: number[] | null;
serie?: number | null;
}
const getItem = async (req: Request, res: Response) => {
const slug = req.params.slug || '';
const book = await prisma.book.findUnique({
where: {
slug,
},
});
res.json(book);
}
const getItems = async (req: Request, res: Response) => {
const searchParams = req.query as IntSearch;
const userId = req.userId || 0;
const {orderBy, sort, ...searchFilterParams} = searchParams && _has(searchParams, 'orderBy')
? {
...searchParams,
orderBy: searchParams.orderBy?.replace('-', '') as EnBookOrderBy || DEFAULT_BOOKS_ORDER_BY,
sort: searchParams.orderBy?.includes('-') ? EnSort.DESC : EnSort.ASC,
}
: {
...searchParams,
orderBy: DEFAULT_BOOKS_ORDER_BY,
sort: DEFAULT_BOOKS_SORT,
};
const getOrderBy = () => {
switch (orderBy) {
case EnBookOrderBy.BOOKMARKS: {
return [{
bookStat: {
countBookmarks: sort,
}
}];
}
case EnBookOrderBy.VIEWS: {
return [{
bookStat: {
countViews: sort,
}
}];
}
case EnBookOrderBy.LIKES: {
return [{
bookStat: {
countLikes: sort,
}
}];
}
case EnBookOrderBy.NEW:
case EnBookOrderBy.UPDATE:
default:
return {
[orderBy]: sort,
};
}
};
const getFiltersData = (params: IntFilters): IntFilterData => {
const data: IntFilterData = {};
Object.keys(params).map(key => {
switch (key) {
case 'types': {
data.types = Array.isArray(params[key]) ?
(params[key] as string[]).map(v => v as EnBookType) : [params[key] as EnBookType];
return key;
}
case 'serie': {
data.serie = Number(params[key]);
return key;
}
case 'persons':
case 'tags':
case 'genres': {
data[key] = Array.isArray(params[key]) ?
(params[key] as string[]).map(v => Number(v)) : [Number(params[key])];
return key;
}
default: {
return key;
}
}
});
return data;
};
const filtersData = getFiltersData(searchFilterParams);
const getTags = () => {
let tags: number[] = [];
if (filtersData.tags) {
tags = [...tags, ...filtersData.tags];
}
if (filtersData.persons) {
tags = [...tags, ...filtersData.persons];
}
return tags;
};
const page = Number(req.query.page) || 1;
const mobile = isMobile(req.get('user-agent') || '');
const limit = mobile ? CATALOG_BOOKS_COUNT_MOBILE : CATALOG_BOOKS_COUNT_DESK;
const filterBookGenres = async (genres: number[]) => {
const genreGroups = await prisma.bookGenre.groupBy({
by: ['bookId'],
where: {
genreId: {
in: genres
},
},
orderBy: {
bookId: 'desc'
},
having: {
bookId: {
_count: {
equals: genres.length,
}
}
},
});
return genreGroups.map(b => b.bookId);
};
const filterBookTags = async (tagIds: number[]) => {
const tagGroups = await prisma.bookTag.groupBy({
by: ['bookId'],
where: {
tagId: {
in: tagIds
},
},
orderBy: {
bookId: 'desc'
},
having: {
bookId: {
_count: {
equals: tagIds.length,
}
}
},
});
return tagGroups.map(b => b.bookId);
};
const bookIdGenres = filtersData.genres ? await filterBookGenres(filtersData.genres) : [];
const tags = getTags();
const bookIdTags = !_isEmpty(tags) ? await filterBookTags(tags) : [];
const bookIds = !_isEmpty(tags) && filtersData.genres ? intersection(bookIdGenres, bookIdTags) : (
(_isEmpty(tags) && !filtersData.genres ? undefined : (
filtersData.genres ? bookIdGenres : bookIdTags
))
);
const books = await prisma.book.findMany({
where: {
id: bookIds ? {
in: bookIds
} : undefined,
status: {
not: EnBookStatus.DRAFT
},
isHentai: isHentai(req.get('host') || ''),
serieBooks: filtersData.serie ? {
some: {
serieId: filtersData.serie,
}
} : undefined,
type: filtersData.types ? {
in: filtersData.types.map(t => t.toUpperCase() as EnBookType)
} : undefined,
},
include: userId ? {
bookmarks: {
where: {
userId,
}
},
} : undefined,
orderBy: getOrderBy(),
take: limit,
skip: (page - 1) * limit,
});
res.json(books.map(b => {
const {bookmarks = [], ...book} = b as Book & {bookmarks?: Bookmark[]};
return {...book, bookmark: _isEmpty(bookmarks) ? null : bookmarks[0]};
}));
}
const getBookmark = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const userId = req.userId || 0;
const includes = req.query.includes || '';
const bookmark = await prisma.bookmark.findUnique({
where: {
userId_bookId: {
userId,
bookId
}
},
include: includes === 'chapter' ? {
chapter: true,
} : undefined
});
res.json(bookmark);
}
const getCollections = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const collections = await prisma.collectionBook.findMany({
where: {
bookId,
},
include: {
collection: true,
}
});
res.json(collections.map(col => col.collection));
}
const createCollections = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const ids = req.body.ids as number[];
const data = [];
for (let i = 0; i < ids.length; i++) {
data.push({bookId, collectionId: ids[i]});
}
await prisma.collectionBook.createMany({
data,
});
res.json([]);
}
const deleteCollections = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const ids = req.body as number[];
await prisma.collectionBook.deleteMany({
where: {
bookId,
collectionId: {
in: ids,
}
},
});
res.json([]);
}
const getSeries = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const series = await prisma.serieBook.findMany({
where: {
bookId,
},
include: {
serie: true,
}
});
res.json(series.map(col => col.serie));
}
const createSeries = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const ids = req.body.ids as number[];
const data = [];
for (let i = 0; i < ids.length; i++) {
data.push({bookId, serieId: ids[i]});
}
await prisma.serieBook.createMany({
data,
});
res.json([]);
}
const deleteSeries = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const ids = req.body as number[];
await prisma.serieBook.deleteMany({
where: {
bookId,
serieId: {
in: ids,
}
},
});
res.json([]);
}
const getTags = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const tags = await prisma.bookTag.findMany({
where: {
bookId,
},
include: {
tag: true,
}
});
res.json(tags.map(tag => tag.tag));
}
const createTags = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const ids = req.body.ids as number[];
const data = [];
for (let i = 0; i < ids.length; i++) {
const tag = await prisma.bookTag.findUnique({
where: {
bookId_tagId: {
bookId,
tagId: ids[i],
}
}
});
if (tag) {
return res.status(400).send({ error: 'Такой тег уже существует в этой книге'});
}
data.push({bookId, tagId: ids[i]});
}
await prisma.bookTag.createMany({
data,
});
res.json([]);
}
const deleteTags = async (req: Request, res: Response) => {
const bookId = +(req.params.bookId || '0');
const ids = req.body as number[];
await prisma.bookTag.deleteMany({
where: {
bookId,
tagId: {
in: ids,
}
},
});
res.json([]);
}
export default {
getItem,
getItems,
getBookmark,
getCollections,
createCollections,
deleteCollections,
getSeries,
createSeries,
deleteSeries,
getTags,
createTags,
deleteTags,
}