Skip to content

Commit

Permalink
feat: comment reader
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <[email protected]>
  • Loading branch information
Innei committed Sep 14, 2024
1 parent 70d6e28 commit 107ade7
Show file tree
Hide file tree
Showing 13 changed files with 93 additions and 34 deletions.
3 changes: 2 additions & 1 deletion apps/core/src/common/guards/roles.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ export class RolesGuard extends AuthGuard implements CanActivate {
} catch {}

const session = await this.authService.getSessionUser(request.raw)

if (session) {
const readerId = session.userId
const readerId = session.user.id
request.readerId = readerId

Object.assign(request.raw, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

import * as cls from 'cls-hooked'
import type { NestMiddleware } from '@nestjs/common'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { ServerResponse } from 'node:http'

import { Injectable } from '@nestjs/common'

import { BizIncomingMessage } from '~/transformers/get-req.transformer'

import { RequestContext } from '../contexts/request.context'

@Injectable()
export class RequestContextMiddleware implements NestMiddleware {
use(req: IncomingMessage, res: ServerResponse, next: () => any) {
use(req: BizIncomingMessage, res: ServerResponse, next: () => any) {
const requestContext = new RequestContext(req, res)

const session =
Expand Down
4 changes: 3 additions & 1 deletion apps/core/src/modules/activity/activity.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,9 @@ export class ActivityService implements OnModuleInit, OnModuleDestroy {

let reader: ReaderModel | null = null
if (readerId) {
reader = await this.readerService.findReaderInIds([readerId])[0]
reader = await this.readerService
.findReaderInIds([readerId])
.then((res) => res[0])
}

try {
Expand Down
48 changes: 43 additions & 5 deletions apps/core/src/modules/comment/comment.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isUndefined } from 'lodash'
import { isUndefined, keyBy } from 'lodash'
import type { DocumentType } from '@typegoose/typegoose'
import type { Document, FilterQuery } from 'mongoose'
import type { CommentModel } from './comment.model'
Expand All @@ -7,7 +7,9 @@ import {
Body,
Delete,
ForbiddenException,
forwardRef,
Get,
Inject,
Param,
Patch,
Post,
Expand All @@ -34,6 +36,8 @@ import { transformDataToPaginate } from '~/transformers/paginate.transformer'
import { scheduleManager } from '~/utils/schedule.util'

import { ConfigsService } from '../configs/configs.service'
import { ReaderModel } from '../reader/reader.model'
import { ReaderService } from '../reader/reader.service'
import { UserModel } from '../user/user.model'
import {
CommentDto,
Expand All @@ -55,15 +59,33 @@ export class CommentController {
private readonly commentService: CommentService,
private readonly eventManager: EventManagerService,
private readonly configsService: ConfigsService,
@Inject(forwardRef(() => ReaderService))
private readonly readerService: ReaderService,
) {}

@Get('/')
@Auth()
async getRecentlyComments(@Query() query: PagerDto) {
const { size = 10, page = 1, state = 0 } = query
return transformDataToPaginate(
await this.commentService.getComments({ size, page, state }),

const comments = await this.commentService.getComments({
size,
page,
state,
})
const readers = await this.readerService.findReaderInIds(
comments.docs.map((doc) => doc.readerId).filter(Boolean) as string[],
)
const readerMap = new Map<string, ReaderModel>()
for (const reader of readers) {
readerMap.set(reader._id.toHexString(), reader)
}

const res = transformDataToPaginate(comments)
Object.assign(res, {
readers: keyBy(readers, 'id'),
})
return res
}

@Get('/:id')
Expand All @@ -87,12 +109,18 @@ export class CommentController {
}

await this.commentService.fillAndReplaceAvatarUrl([data])
if (data.readerId) {
const reader = await this.readerService.findReaderInIds([data.readerId])
Object.assign(data, {
reader: reader[0],
})
}

return data
}

// 面向 C 端的评论查询接口
@Get('/ref/:id')
@HTTPDecorators.Paginator
async getCommentsByRefId(
@Param() params: MongoIdDto,
@Query() query: PagerDto,
Expand Down Expand Up @@ -162,7 +190,17 @@ export class CommentController {

await this.commentService.fillAndReplaceAvatarUrl(comments.docs)
this.commentService.cleanDirtyData(comments.docs)
return comments
const result = transformDataToPaginate(comments)
const readerIds = comments.docs
.map((comment) => comment.readerId)
.filter((id) => !!id) as string[]
const readers = await this.readerService.findReaderInIds(readerIds)

Object.assign(result, {
readers: keyBy(readers, 'id'),
})

return result
}

@Post('/:id')
Expand Down
9 changes: 1 addition & 8 deletions apps/core/src/modules/comment/comment.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { BaseModel } from '~/shared/model/base.model'
import { NoteModel } from '../note/note.model'
import { PageModel } from '../page/page.model'
import { PostModel } from '../post/post.model'
import { ReaderModel } from '../reader/reader.model'
import { RecentlyModel } from '../recently/recently.model'

export enum CommentState {
Expand Down Expand Up @@ -129,12 +128,6 @@ export class CommentModel extends BaseModel {

@prop()
meta?: string

@prop({
ref: () => ReaderModel,
justOne: true,
foreignField: '_id',
localField: 'readerId',
})
@prop({})
readerId?: string
}
8 changes: 7 additions & 1 deletion apps/core/src/modules/comment/comment.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { forwardRef, Module } from '@nestjs/common'

import { GatewayModule } from '~/processors/gateway/gateway.module'

import { ReaderModule } from '../reader/reader.module'
import { ServerlessModule } from '../serverless/serverless.module'
import { UserModule } from '../user/user.module'
import { CommentController } from './comment.controller'
Expand All @@ -11,6 +12,11 @@ import { CommentService } from './comment.service'
controllers: [CommentController],
providers: [CommentService],
exports: [CommentService],
imports: [UserModule, GatewayModule, forwardRef(() => ServerlessModule)],
imports: [
UserModule,
GatewayModule,
forwardRef(() => ServerlessModule),
forwardRef(() => ReaderModule),
],
})
export class CommentModule {}
2 changes: 2 additions & 0 deletions apps/core/src/modules/comment/comment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export class CommentService implements OnModuleInit {
private readonly serverlessService: ServerlessService,
private readonly eventManager: EventManagerService,
private readonly barkService: BarkPushService,
@Inject(forwardRef(() => ReaderService))
private readonly readerService: ReaderService,
) {}

Expand Down Expand Up @@ -162,6 +163,7 @@ export class CommentService implements OnModuleInit {
type?: CollectionRefTypes,
) {
const readerId = RequestContext.currentRequest()?.readerId

let reader: ReaderModel | null = null
if (readerId) {
reader = await this.readerService
Expand Down
8 changes: 5 additions & 3 deletions apps/core/src/modules/reader/reader.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,10 @@ export class ReaderService {
.updateOne({ _id: new Types.ObjectId(id) }, { $set: { isOwner: false } })
}
async findReaderInIds(ids: string[]) {
return this.readerModel.find({
_id: { $in: ids.map((id) => new Types.ObjectId(id)) },
})
return this.readerModel
.find({
_id: { $in: ids.map((id) => new Types.ObjectId(id)) },
})
.lean()
}
}
15 changes: 9 additions & 6 deletions packages/api-client/controllers/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { IRequestAdapter } from '~/interfaces/adapter'
import type { IController } from '~/interfaces/controller'
import type { PaginationParams } from '~/interfaces/params'
import type { IRequestHandler } from '~/interfaces/request'
import type { ReaderModel } from '~/models'
import type { PaginateResult } from '~/models/base'
import type { CommentModel } from '~/models/comment'
import type { HTTPClient } from '../core'
Expand Down Expand Up @@ -31,7 +32,7 @@ export class CommentController<ResponseWrapper> implements IController {
}

/**
* 根据 comment id 获取评论, 包括子评论
* 根据 comment id 获取评论包括子评论
*/
getById(id: string) {
return this.proxy(id).get<CommentModel & { ref: string }>()
Expand All @@ -43,11 +44,13 @@ export class CommentController<ResponseWrapper> implements IController {
*/
getByRefId(refId: string, pagination: PaginationParams = {}) {
const { page, size } = pagination
return this.proxy
.ref(refId)
.get<PaginateResult<CommentModel & { ref: string }>>({
params: { page: page || 1, size: size || 10 },
})
return this.proxy.ref(refId).get<
PaginateResult<CommentModel & { ref: string }> & {
readers: Record<string, ReaderModel>
}
>({
params: { page: page || 1, size: size || 10 },
})
}
/**
* 评论
Expand Down
13 changes: 6 additions & 7 deletions packages/api-client/controllers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,27 +72,26 @@ export const allControllerNames = [
] as const

export {
AIController,
AckController,
ActivityController,
AggregateController,
AIController,
CategoryController,
CommentController,
LinkController,
NoteController,
PageController,
PostController,
ProjectController,
// Enum
RecentlyAttitudeEnum,
RecentlyAttitudeResultEnum,
RecentlyController,
SayController,
SearchController,
SnippetController,
ServerlessController,
SnippetController,
SubscribeController,
UserController,
TopicController,

// Enum
RecentlyAttitudeEnum,
RecentlyAttitudeResultEnum,
UserController,
}
1 change: 1 addition & 0 deletions packages/api-client/models/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface CommentModel extends BaseModel {
location?: string

source?: string
readerId?: string
}
export interface CommentRef {
id: string
Expand Down
1 change: 1 addition & 0 deletions packages/api-client/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export * from './note'
export * from './page'
export * from './post'
export * from './project'
export * from './reader'
export * from './recently'
export * from './say'
export * from './setting'
Expand Down
9 changes: 9 additions & 0 deletions packages/api-client/models/reader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface ReaderModel {
email: string
name: string
handle: string

image: string

isOwner: boolean
}

0 comments on commit 107ade7

Please sign in to comment.