server: improve get views

This commit is contained in:
fantasticit 2022-05-26 21:42:51 +08:00
parent 5c4019c102
commit 802f7c9228
2 changed files with 16 additions and 8 deletions

View File

@ -624,7 +624,7 @@ export class DocumentService {
const [views, createUser] = await Promise.all([ const [views, createUser] = await Promise.all([
await this.viewService.getDocumentTotalViews(documentId), await this.viewService.getDocumentTotalViews(documentId),
doc && doc.createUserId ? await this.userService.findById(doc.createUserId) : null, await this.userService.findById(doc.createUserId),
]); ]);
return { return {

View File

@ -33,8 +33,17 @@ export class ViewService {
} }
async getDocumentTotalViews(documentId) { async getDocumentTotalViews(documentId) {
const [, total] = await this.viewRepo.findAndCount({ documentId }); try {
return total; const count = await this.viewRepo.query(
`SELECT COUNT(1)
FROM view
WHERE view.documentId = '${documentId}'
`
);
return count[0]['COUNT(1)'];
} catch (e) {
return 0;
}
} }
async getDocumentViews(documentId, pagination: IPagination) { async getDocumentViews(documentId, pagination: IPagination) {
@ -64,15 +73,14 @@ export class ViewService {
}> }>
> { > {
const count = 20; const count = 20;
const ret = await this.viewRepo.query( const ret = await this.viewRepo.query(
` `
SELECT v.documentId, v.visitedAt FROM ( SELECT v.documentId, v.visitedAt FROM (
SELECT ANY_VALUE(documentId) as documentId, ANY_VALUE(created_at) as visitedAt SELECT ANY_VALUE(documentId) as documentId, ANY_VALUE(created_at) as visitedAt
FROM view FROM view
WHERE view.userId = '${userId}' WHERE view.userId = '${userId}'
GROUP BY visitedAt GROUP BY visitedAt
ORDER BY visitedAt DESC ORDER BY visitedAt DESC
) v ) v
GROUP BY v.documentId GROUP BY v.documentId
LIMIT ${count} LIMIT ${count}