Skip to content

Commit

Permalink
feat: 3.6.2
Browse files Browse the repository at this point in the history
  • Loading branch information
surmon-china committed Dec 7, 2021
1 parent 8468e73 commit 287edf0
Show file tree
Hide file tree
Showing 27 changed files with 174 additions and 98 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

All notable changes to this project will be documented in this file.

### v3.6.2 (2021-12-07)

**Feature**

- Remove `mongoose-paginate`
- Remove `APP.LIMIT` config
- Improve `AutoIncrementID.Config`
- Improve global paginate config

### v3.6.0 (2021-12-06)

**Feature**
Expand Down
4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nodepress",
"version": "3.6.0",
"version": "3.6.2",
"description": "RESTful API service for Surmon.me blog",
"author": {
"name": "Surmon",
Expand Down Expand Up @@ -62,7 +62,6 @@
"lodash": "^4.17.21",
"moment": "^2.29.1",
"mongoose": "~6.0.14",
"mongoose-paginate": "https://github.com/surmon-china/mongoose-paginate",
"node-schedule": "^2.1.0",
"nodemailer": "^6.7.2",
"passport": "^0.5.0",
Expand All @@ -83,7 +82,6 @@
"@types/express": "^4.17.13",
"@types/jest": "27.0.3",
"@types/lodash": "^4.14.177",
"@types/mongoose-paginate": "^5.0.10",
"@types/node": "^16.11.12",
"@types/node-schedule": "^1.3.2",
"@types/passport-jwt": "^3.0.6",
Expand Down
1 change: 0 additions & 1 deletion src/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const ROOT_PATH = path.join(__dirname, '..')
const packageJSON = require(path.resolve(ROOT_PATH, 'package.json'))

export const APP = {
LIMIT: 16,
PORT: 8000,
MASTER: 'Surmon',
NAME: 'Surmon.me',
Expand Down
21 changes: 21 additions & 0 deletions src/constants/increment.constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @file Increment ID collection constant
* @description 用于自增表的配置
* @module constant/increment
* @author Surmon <https://github.com/surmon-china>
*/

import { AutoIncrementIDOptions } from '@typegoose/auto-increment'

export const generalAutoIncrementIDConfig: AutoIncrementIDOptions = {
field: 'id',
startAt: 1,
incrementBy: 1,
trackerCollection: 'identitycounters',
trackerModelName: 'identitycounter',
// https://github.com/typegoose/auto-increment
// https://github.com/typegoose/auto-increment/blob/master/src/autoIncrement.ts
// https://github.com/typegoose/auto-increment/issues/11
// fieldKey: 'field',
// modelNameKey: 'modelName',
}
9 changes: 6 additions & 3 deletions src/decorators/query-params.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { HttpForbiddenError } from '@app/errors/forbidden.error'
import { HttpBadRequestError } from '@app/errors/bad-request.error'
import { PublishState, PublicState, OriginState, CommentState, SortType } from '@app/interfaces/biz.interface'
import { PaginateOptions } from '@app/utils/paginate'

// 预置转换器可选字段
export enum QueryParamsField {
Expand All @@ -26,7 +27,7 @@ export enum QueryParamsField {
}

// 内部参数类型
export interface QueryParamsConfig {
export interface QueryParamsConfig extends Omit<PaginateOptions, 'populate' | 'select'> {
[key: string]: string | number | boolean | Types.ObjectId | Date | RegExp | QueryParamsConfig
}

Expand Down Expand Up @@ -165,11 +166,13 @@ export const QueryParams = createParamDecorator(
{
name: '每页数量/per_page',
field: QueryParamsField.PerPage,
isAllowed: lodash.isUndefined(per_page) || (lodash.isInteger(per_page) && Number(per_page) > 0),
isAllowed:
lodash.isUndefined(per_page) ||
(lodash.isInteger(per_page) && Number(per_page) > 0 && Number(per_page) <= 50),
isIllegal: false,
setValue() {
if (per_page != null) {
options.limit = per_page
options.perPage = per_page
}
},
},
Expand Down
18 changes: 10 additions & 8 deletions src/interceptors/transform.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@

import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { PaginateResult } from 'mongoose'
import { Reflector } from '@nestjs/core'
import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common'
import { HttpResponseSuccess, HttpPaginateResult, ResponseStatus } from '@app/interfaces/http.interface'
import { ResponseMessage } from '@app/interfaces/http.interface'
import { PaginateResult } from '@app/utils/paginate'
import * as META from '@app/constants/meta.constant'
import * as TEXT from '@app/constants/text.constant'

// 转换为标准的数据结构
export function transformDataToPaginate<T>(data: PaginateResult<T>, request?: any): HttpPaginateResult<T[]> {
return {
data: data.docs,
params: request ? request.queryParams : null,
params: request?.queryParams || null,
pagination: {
total: data.total,
current_page: data.page,
total_page: data.pages,
per_page: data.limit,
per_page: data.perPage,
total_page: data.totalPage,
},
}
}
Expand All @@ -40,13 +40,15 @@ export class TransformInterceptor<T> implements NestInterceptor<T, HttpResponseS
const call$ = next.handle()
const target = context.getHandler()
const request = context.switchToHttp().getRequest()
const message =
this.reflector.get<ResponseMessage>(META.HTTP_SUCCESS_MESSAGE, target) || TEXT.HTTP_DEFAULT_SUCCESS_TEXT
const message = this.reflector.get<ResponseMessage>(META.HTTP_SUCCESS_MESSAGE, target)
const usePaginate = this.reflector.get<boolean>(META.HTTP_RES_TRANSFORM_PAGINATE, target)
return call$.pipe(
map((data: any) => {
const result = !usePaginate ? data : transformDataToPaginate<T>(data, request)
return { status: ResponseStatus.Success, message, result }
return {
result: usePaginate ? transformDataToPaginate<T>(data, request) : data,
status: ResponseStatus.Success,
message: message || TEXT.HTTP_DEFAULT_SUCCESS_TEXT,
}
})
)
}
Expand Down
3 changes: 2 additions & 1 deletion src/interfaces/mongoose.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* @author Surmon <https://github.com/surmon-china>
*/

import { Document } from 'mongoose'
import { ModelType } from '@typegoose/typegoose/lib/types'
import { PaginateModel, Document } from 'mongoose'
import { PaginateModel } from '@app/utils/paginate'

export type MongooseModel<T> = ModelType<T> & PaginateModel<T & Document>
6 changes: 3 additions & 3 deletions src/modules/announcement/announcement.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
*/

import lodash from 'lodash'
import { PaginateResult } from 'mongoose'
import { Controller, Get, Put, Post, Delete, Body, UseGuards } from '@nestjs/common'
import { JwtAuthGuard } from '@app/guards/auth.guard'
import { HumanizedJwtAuthGuard } from '@app/guards/humanized-auth.guard'
import { QueryParams, QueryParamsField as QueryField } from '@app/decorators/query-params.decorator'
import { QueryParams, QueryParamsField } from '@app/decorators/query-params.decorator'
import { HttpProcessor } from '@app/decorators/http.decorator'
import { PaginateResult } from '@app/utils/paginate'
import { Announcement, AnnouncementsPayload } from './announcement.model'
import { AnnouncementService } from './announcement.service'

Expand All @@ -23,7 +23,7 @@ export class AnnouncementController {
@HttpProcessor.paginate()
@HttpProcessor.handle('获取公告')
getAnnouncements(
@QueryParams([QueryField.State]) { querys, options, origin }
@QueryParams([QueryParamsField.State]) { querys, options, origin }
): Promise<PaginateResult<Announcement>> {
const keyword = lodash.trim(origin.keyword)
if (keyword) {
Expand Down
5 changes: 3 additions & 2 deletions src/modules/announcement/announcement.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import { Types } from 'mongoose'
import { AutoIncrementID } from '@typegoose/auto-increment'
import { prop, plugin, modelOptions } from '@typegoose/typegoose'
import { IsString, IsInt, IsIn, IsDefined, IsNotEmpty, IsArray, ArrayNotEmpty, ArrayUnique } from 'class-validator'
import { mongoosePaginate } from '@app/transformers/mongoose.transformer'
import { generalAutoIncrementIDConfig } from '@app/constants/increment.constant'
import { getProviderByTypegooseClass } from '@app/transformers/model.transformer'
import { mongoosePaginate } from '@app/utils/paginate'
import { PublishState } from '@app/interfaces/biz.interface'

@plugin(mongoosePaginate)
@plugin(AutoIncrementID, { field: 'id', startAt: 1 })
@plugin(AutoIncrementID, generalAutoIncrementIDConfig)
@modelOptions({
schemaOptions: {
timestamps: {
Expand Down
5 changes: 3 additions & 2 deletions src/modules/announcement/announcement.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
* @author Surmon <https://github.com/surmon-china>
*/

import { PaginateResult, Types } from 'mongoose'
import { Types } from 'mongoose'
import { Injectable } from '@nestjs/common'
import { InjectModel } from '@app/transformers/model.transformer'
import { MongooseModel } from '@app/interfaces/mongoose.interface'
import { PaginateResult, PaginateOptions } from '@app/utils/paginate'
import { Announcement } from './announcement.model'

@Injectable()
Expand All @@ -18,7 +19,7 @@ export class AnnouncementService {
) {}

// 请求公告列表
public getList(querys, options): Promise<PaginateResult<Announcement>> {
public getList(querys, options: PaginateOptions): Promise<PaginateResult<Announcement>> {
return this.announcementModel.paginate(querys, options)
}

Expand Down
3 changes: 1 addition & 2 deletions src/modules/archive/archive.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,10 @@ export class ArchiveService {
return this.categoryModel.find().sort({ _id: SortType.Desc }).exec()
}

private getAllArticles(limit?: number): Promise<Article[]> {
private getAllArticles(): Promise<Article[]> {
return this.articleModel
.find({ state: PublishState.Published, public: PublicState.Public })
.sort({ _id: SortType.Desc })
.limit(limit)
.exec()
}

Expand Down
2 changes: 1 addition & 1 deletion src/modules/article/article.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
*/

import lodash from 'lodash'
import { PaginateResult } from 'mongoose'
import { Controller, Get, Put, Post, Patch, Delete, Body, UseGuards, HttpStatus } from '@nestjs/common'
import { QueryParams, QueryParamsField as QueryField } from '@app/decorators/query-params.decorator'
import { HttpProcessor } from '@app/decorators/http.decorator'
Expand All @@ -14,6 +13,7 @@ import { HumanizedJwtAuthGuard } from '@app/guards/humanized-auth.guard'
import { SortType } from '@app/interfaces/biz.interface'
import { TagService } from '@app/modules/tag/tag.service'
import { CategoryService } from '@app/modules/category/category.service'
import { PaginateResult } from '@app/utils/paginate'
import { Article, ArticlesPayload, ArticlesStatePayload } from './article.model'
import { ArticleService } from './article.service'

Expand Down
5 changes: 3 additions & 2 deletions src/modules/article/article.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import { Types } from 'mongoose'
import { AutoIncrementID } from '@typegoose/auto-increment'
import { prop, index, plugin, Ref, modelOptions } from '@typegoose/typegoose'
import { IsString, IsNotEmpty, IsArray, IsDefined, IsIn, IsInt, ArrayNotEmpty, ArrayUnique } from 'class-validator'
import { mongoosePaginate } from '@app/transformers/mongoose.transformer'
import { generalAutoIncrementIDConfig } from '@app/constants/increment.constant'
import { getProviderByTypegooseClass } from '@app/transformers/model.transformer'
import { mongoosePaginate } from '@app/utils/paginate'
import { PublishState, PublicState, OriginState } from '@app/interfaces/biz.interface'
import { Category } from '@app/modules/category/category.model'
import { Extend } from '@app/models/extend.model'
Expand Down Expand Up @@ -39,7 +40,7 @@ export class Meta {
}

@plugin(mongoosePaginate)
@plugin(AutoIncrementID, { field: 'id', startAt: 1 })
@plugin(AutoIncrementID, generalAutoIncrementIDConfig)
@modelOptions({
schemaOptions: {
toObject: { getters: true },
Expand Down
17 changes: 9 additions & 8 deletions src/modules/article/article.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
*/

import lodash from 'lodash'
import { Types } from 'mongoose'
import { DocumentType } from '@typegoose/typegoose'
import { PaginateResult, Types } from 'mongoose'
import { Injectable } from '@nestjs/common'
import { InjectModel } from '@app/transformers/model.transformer'
import { getArticleUrl } from '@app/transformers/urlmap.transformer'
Expand All @@ -15,10 +15,10 @@ import { CacheService, CacheIntervalResult } from '@app/processors/cache/cache.s
import { ArchiveService } from '@app/modules/archive/archive.service'
import { TagService } from '@app/modules/tag/tag.service'
import { MongooseModel } from '@app/interfaces/mongoose.interface'
import { PaginateResult, PaginateOptions } from '@app/utils/paginate'
import { SortType, PublicState, PublishState } from '@app/interfaces/biz.interface'
import { Article, getDefaultMeta } from './article.model'
import * as CACHE_KEY from '@app/constants/cache.constant'
import logger from '@app/utils/logger'

export const COMMON_USER_QUERY_PARAMS = Object.freeze({
state: PublishState.Published,
Expand All @@ -45,7 +45,7 @@ export class ArticleService {
key: CACHE_KEY.HOT_ARTICLES,
promise: () => {
return this.getList.bind(this)(COMMON_USER_QUERY_PARAMS, {
limit: 10,
perPage: 10,
sort: this.getHotSortOption(),
})
},
Expand Down Expand Up @@ -80,10 +80,12 @@ export class ArticleService {
}

// 请求文章列表
public getList(querys, options): Promise<PaginateResult<Article>> {
options.populate = ['category', 'tag']
options.select = '-password -content'
return this.articleModel.paginate(querys, options)
public getList(querys, options: PaginateOptions): Promise<PaginateResult<Article>> {
return this.articleModel.paginate(querys, {
populate: ['category', 'tag'],
select: '-password -content',
...options,
})
}

// 获取文章详情(使用 ObjectId)
Expand Down Expand Up @@ -149,7 +151,6 @@ export class ArticleService {
Reflect.deleteProperty(newArticle, 'update_at')

const article = await this.articleModel.findByIdAndUpdate(articleID, newArticle as any, { new: true }).exec()
logger.info('----修改文章后', article)
this.seoService.update(getArticleUrl(article.id))
this.archiveService.updateCache()
this.tagService.updateListCache()
Expand Down
2 changes: 1 addition & 1 deletion src/modules/category/category.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
* @author Surmon <https://github.com/surmon-china>
*/

import { PaginateResult } from 'mongoose'
import { Controller, UseGuards, Get, Put, Post, Delete, Body, Param } from '@nestjs/common'
import { JwtAuthGuard } from '@app/guards/auth.guard'
import { HumanizedJwtAuthGuard } from '@app/guards/humanized-auth.guard'
import { HttpProcessor } from '@app/decorators/http.decorator'
import { QueryParams } from '@app/decorators/query-params.decorator'
import { PaginateResult } from '@app/utils/paginate'
import { Category, CategoriesPayload } from './category.model'
import { CategoryService } from './category.service'

Expand Down
5 changes: 3 additions & 2 deletions src/modules/category/category.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import { Types } from 'mongoose'
import { AutoIncrementID } from '@typegoose/auto-increment'
import { prop, plugin, modelOptions } from '@typegoose/typegoose'
import { IsString, MaxLength, IsAlphanumeric, IsNotEmpty, IsArray, ArrayNotEmpty, ArrayUnique } from 'class-validator'
import { mongoosePaginate } from '@app/transformers/mongoose.transformer'
import { generalAutoIncrementIDConfig } from '@app/constants/increment.constant'
import { getProviderByTypegooseClass } from '@app/transformers/model.transformer'
import { mongoosePaginate } from '@app/utils/paginate'
import { Extend } from '@app/models/extend.model'

@plugin(mongoosePaginate)
@plugin(AutoIncrementID, { field: 'id', startAt: 1 })
@plugin(AutoIncrementID, generalAutoIncrementIDConfig)
@modelOptions({
schemaOptions: {
timestamps: {
Expand Down
5 changes: 3 additions & 2 deletions src/modules/category/category.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
* @author Surmon <https://github.com/surmon-china>
*/

import { PaginateResult, Types } from 'mongoose'
import { Types } from 'mongoose'
import { Injectable } from '@nestjs/common'
import { InjectModel } from '@app/transformers/model.transformer'
import { getCategoryUrl } from '@app/transformers/urlmap.transformer'
import { MongooseModel } from '@app/interfaces/mongoose.interface'
import { PaginateResult, PaginateOptions } from '@app/utils/paginate'
import { PublicState, PublishState } from '@app/interfaces/biz.interface'
import { ArchiveService } from '@app/modules/archive/archive.service'
import { SeoService } from '@app/processors/helper/helper.service.seo'
Expand All @@ -26,7 +27,7 @@ export class CategoryService {
) {}

// 请求分类列表(及聚和数据)
public async getList(querys, options, isAuthenticated): Promise<PaginateResult<Category>> {
public async getList(querys, options: PaginateOptions, isAuthenticated): Promise<PaginateResult<Category>> {
const matchState = {
state: PublishState.Published,
public: PublicState.Public,
Expand Down
2 changes: 1 addition & 1 deletion src/modules/comment/comment.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
*/

import lodash from 'lodash'
import { PaginateResult } from 'mongoose'
import { Controller, Get, Put, Post, Patch, Delete, Body, UseGuards } from '@nestjs/common'
import { JwtAuthGuard } from '@app/guards/auth.guard'
import { HumanizedJwtAuthGuard } from '@app/guards/humanized-auth.guard'
import { HttpProcessor } from '@app/decorators/http.decorator'
import { PaginateResult } from '@app/utils/paginate'
import { QueryParams, QueryParamsField } from '@app/decorators/query-params.decorator'
import { SortType } from '@app/interfaces/biz.interface'
import { Comment, CreateCommentBase, CommentsPayload, CommentsStatePayload } from './comment.model'
Expand Down
Loading

0 comments on commit 287edf0

Please sign in to comment.