Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(microservice): xRpcException and extend official exception #664

Merged
merged 8 commits into from
Feb 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 9 additions & 19 deletions apps/comments-service/src/comments-service.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { HttpStatus, Inject, Injectable } from '@nestjs/common';
import { ClientProxy, RpcException } from '@nestjs/microservices';
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { PaginateModel } from 'mongoose';
import { nextTick } from 'process';
import { InjectModel } from '~/libs/database/src/model.transformer';
import { ExceptionMessage } from '~/shared/constants/echo.constant';
import { NotificationEvents } from '~/shared/constants/event.constant';
import { ServicesEnum } from '~/shared/constants/services.constant';
import { BadRequestRpcExcption } from '~/shared/exceptions/bad-request-rpc-exception';
import { NotFoundRpcExcption } from '~/shared/exceptions/not-found-rpc-exception';
import {
CommentReactions,
CommentsModel,
Expand All @@ -22,7 +24,7 @@ export class CommentsService {

@Inject(ServicesEnum.notification)
private readonly notification: ClientProxy,
) {}
) { }

get model() {
return this.CommentsModel;
Expand Down Expand Up @@ -97,10 +99,7 @@ export class CommentsService {
async deleteComment(id: string) {
const comment = await this.CommentsModel.findOneAndDelete({ id });
if (!comment) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.CommentNotFound,
});
throw new NotFoundRpcExcption(ExceptionMessage.CommentNotFound);
}
const { parent, children } = comment;
if (children && children.length) {
Expand Down Expand Up @@ -142,10 +141,7 @@ export class CommentsService {
async replyComment(parent: string, data: CommentsModel, isMaster: boolean) {
const parentComment = await this.CommentsModel.findById(parent);
if (!parentComment) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.CommentNotFound,
});
throw new NotFoundRpcExcption(ExceptionMessage.CommentNotFound);
}
data.pid = parentComment.pid; // 防止恶意修改,强制使用父评论的pid
if (isMaster) {
Expand Down Expand Up @@ -183,17 +179,11 @@ export class CommentsService {
) {
const comment = this.CommentsModel.findById(id);
if (!comment) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.CommentNotFound,
});
throw new NotFoundRpcExcption(ExceptionMessage.CommentNotFound);
}
// 验证 reaction 是否合法
if (!Object.values(CommentReactions).includes(reaction)) {
throw new RpcException({
code: HttpStatus.BAD_REQUEST,
message: ExceptionMessage.InvalidCommentReaction,
});
throw new BadRequestRpcExcption(ExceptionMessage.InvalidCommentReaction);
}
const update = isAdd
? { $inc: { [`reaction.${reaction}`]: 1 } }
Expand Down
35 changes: 12 additions & 23 deletions apps/friends-service/src/friends-service.service.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import { HttpStatus, Inject, Injectable, Logger } from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { v4 } from 'uuid';
import { HttpService } from '~/libs/helper/src/helper.http.service';
import { InjectModel } from '~/shared/transformers/model.transformer';
import { FriendsModel, FriendStatus } from './friends.model';
import { JSDOM } from 'jsdom';
import { ConfigService } from '~/libs/config/src';
import { ClientProxy, RpcException } from '@nestjs/microservices';
import { ClientProxy } from '@nestjs/microservices';
import { ExceptionMessage } from '~/shared/constants/echo.constant';
import { nextTick } from 'process';
import { FeedParser } from '~/shared/utils';
import { isValidObjectId } from 'mongoose';
import { ServicesEnum } from '~/shared/constants/services.constant';
import { NotificationEvents } from '~/shared/constants/event.constant';
import { NotFoundRpcExcption } from '~/shared/exceptions/not-found-rpc-exception';
import { BadRequestRpcExcption } from '~/shared/exceptions/bad-request-rpc-exception';
import { UnauthorizedRpcExcption } from '~/shared/exceptions/unauthorized-rpc-exception';
@Injectable()
export class FriendsService {
constructor(
Expand All @@ -23,24 +26,18 @@ export class FriendsService {

@Inject(ServicesEnum.notification)
private readonly notification: ClientProxy,
) {}
) { }

public get model() {
return this.friendsModel;
}

private throwInvalidTokenException(): never {
throw new RpcException({
code: HttpStatus.UNAUTHORIZED,
message: ExceptionMessage.FriendLinkTokenIsInvalid,
});
throw new UnauthorizedRpcExcption(ExceptionMessage.FriendLinkTokenIsInvalid);
}

private throwNotFoundException(): never {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.FriendLinkIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.FriendLinkIsNotExist);
}

private async checkAlive(url: string) {
Expand Down Expand Up @@ -148,10 +145,7 @@ export class FriendsService {
item?.status !== FriendStatus.Trash,
)
) {
throw new RpcException({
code: HttpStatus.BAD_REQUEST,
message: ExceptionMessage.FriendLinkIsExist,
});
throw new BadRequestRpcExcption(ExceptionMessage.FriendLinkIsExist);
}
if (res.some((item) => item?.status === FriendStatus.Trash)) {
const friend = res.find((item) => item?.status === FriendStatus.Trash);
Expand All @@ -172,8 +166,7 @@ export class FriendsService {
friend.autoCheck = await this.autoCheck(input.data.link);
await friend.save();
Logger.warn(
`${friend.name} 申请友链 - 互链检测: ${
friend.autoCheck ? '通过' : '未通过'
`${friend.name} 申请友链 - 互链检测: ${friend.autoCheck ? '通过' : '未通过'
}`,
FriendsService.name,
);
Expand Down Expand Up @@ -225,8 +218,7 @@ export class FriendsService {
friend.autoCheck = await this.autoCheck(data.link); // 重新检测
await friend.save();
Logger.warn(
`${friend.name} 申请友链 - 互链检测: ${
friend.autoCheck ? '通过' : '未通过'
`${friend.name} 申请友链 - 互链检测: ${friend.autoCheck ? '通过' : '未通过'
}`,
FriendsService.name,
);
Expand Down Expand Up @@ -292,10 +284,7 @@ export class FriendsService {
async analyseAutoCheck(id: string) {
const friend = await this.friendsModel.findById(id);
if (!friend) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.FriendLinkIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.FriendLinkIsNotExist);
}
const isAlive = await this.checkAlive(friend.link);
if (!isAlive) {
Expand Down
20 changes: 6 additions & 14 deletions apps/page-service/src/category.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
* @LastEditTime: 2022-09-24 15:36:36
* Coding With IU
*/
import { HttpStatus, Inject, Injectable } from '@nestjs/common';
import { RpcException } from '@nestjs/microservices';
import { Inject, Injectable } from '@nestjs/common';
import { ReturnModelType, DocumentType } from '@typegoose/typegoose';
import { FilterQuery } from 'mongoose';
import { nextTick } from 'process';
import { InjectModel } from '~/libs/database/src/model.transformer';
import { ExceptionMessage } from '~/shared/constants/echo.constant';
import { BadRequestRpcExcption } from '~/shared/exceptions/bad-request-rpc-exception';
import { NotFoundRpcExcption } from '~/shared/exceptions/not-found-rpc-exception';
import { MultiCategoriesQueryDto } from './dto/category.dto';
import { CategoryModel, CategoryType } from './model/category.model';
import { PostModel } from './model/post.model';
Expand Down Expand Up @@ -157,10 +158,7 @@ export class CategoryService {
.populate('category');

if (!posts.length)
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.PageIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.PageIsNotExist);

return posts;
}
Expand Down Expand Up @@ -234,17 +232,11 @@ export class CategoryService {
async deleteCategory(categoryId: string) {
const category = await this.model.findById(categoryId);
if (!category) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.CategoryIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.CategoryIsNotExist);
}
const postsInCategory = await this.findPostsInCategory(category.id);
if (postsInCategory.length > 0) {
throw new RpcException({
code: HttpStatus.BAD_REQUEST,
message: ExceptionMessage.CategoryHasPost,
});
throw new BadRequestRpcExcption(ExceptionMessage.CategoryHasPost);
}
const action = this.categoryModel.deleteOne({
_id: categoryId,
Expand Down
22 changes: 8 additions & 14 deletions apps/page-service/src/page-service.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import slugify from 'slugify';
import { BadRequestException, Controller, HttpStatus } from '@nestjs/common';
import { MessagePattern, RpcException } from '@nestjs/microservices';
import { BadRequestException, Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { ApiOperation, ApiParam, ApiQuery } from '@nestjs/swagger';
import {
CategoryEvents,
Expand All @@ -19,6 +19,9 @@ import { MultiCategoriesQueryDto } from './dto/category.dto';
import { isValidObjectId } from 'mongoose';
import { ExceptionMessage } from '~/shared/constants/echo.constant';
import { CategoryModel, CategoryType } from './model/category.model';
import { NotImplementedRpcExcption } from '~/shared/exceptions/not-implemented-rpc-exception';
import { NotFoundRpcExcption } from '~/shared/exceptions/not-found-rpc-exception';
import { BadRequestRpcExcption } from '~/shared/exceptions/bad-request-rpc-exception';

@Controller()
export class PageServiceController {
Expand Down Expand Up @@ -74,10 +77,7 @@ export class PageServiceController {
// 判断必要Query参数是否存在
if (!query) {
// 如果没有query 禁止通行
throw new RpcException({
code: HttpStatus.BAD_REQUEST,
message: ExceptionMessage.QueryArgIsRequire,
});
throw new BadRequestRpcExcption(ExceptionMessage.QueryArgIsRequire);
}
if (tag === true) {
return {
Expand All @@ -100,10 +100,7 @@ export class PageServiceController {
.lean();

if (!data) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.CantFindCategory,
});
throw new NotFoundRpcExcption(ExceptionMessage.CantFindCategory);
}

const children =
Expand Down Expand Up @@ -270,9 +267,6 @@ export class PageServiceController {
@MessagePattern({ cmd: PostEvents.PostThumbUp })
@ApiOperation({ summary: '点赞文章' })
async thumbUpPost(_id: string) {
throw new RpcException({
code: HttpStatus.NOT_IMPLEMENTED,
message: 'Not Implemented',
});
throw new NotImplementedRpcExcption('Not Implemented');
}
}
22 changes: 7 additions & 15 deletions apps/page-service/src/page-service.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
* Coding With IU
*/

import { HttpStatus, Inject, Injectable } from '@nestjs/common';
import { ClientProxy, RpcException } from '@nestjs/microservices';
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { isDefined } from 'class-validator';
import { omit } from 'lodash';
Expand All @@ -18,6 +18,7 @@ import { ExceptionMessage } from '~/shared/constants/echo.constant';
import { NotificationEvents } from '~/shared/constants/event.constant';
import { ServicesEnum } from '~/shared/constants/services.constant';
import { PagerDto } from '~/shared/dto/pager.dto';
import { NotFoundRpcExcption } from '~/shared/exceptions/not-found-rpc-exception';
import { InjectModel } from '~/shared/transformers/model.transformer';
import { PageModel } from './model/page.model';

Expand All @@ -30,7 +31,7 @@ export class PageService {

@Inject(ServicesEnum.notification)
private readonly notification: ClientProxy,
) {}
) { }

public get model() {
return this.pageModel;
Expand All @@ -53,10 +54,7 @@ export class PageService {
async getPageById(id: string) {
const res = this.model.findById(id).lean({ getters: true });
if (!res) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.PageIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.PageIsNotExist);
}
return res;
}
Expand All @@ -67,10 +65,7 @@ export class PageService {
.lean({ getters: true })
.then((page) => {
if (!page) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.PageIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.PageIsNotExist);
}
if (!isMaster && page.password) {
if (!password || password !== page.password) {
Expand Down Expand Up @@ -112,10 +107,7 @@ export class PageService {
)
.lean({ getters: true });
if (!res) {
throw new RpcException({
code: HttpStatus.NOT_FOUND,
message: ExceptionMessage.PageIsNotExist,
});
throw new NotFoundRpcExcption(ExceptionMessage.PageIsNotExist);
}
this.notification.emit(NotificationEvents.SystemPageUpdate, res);
return res;
Expand Down
Loading