├── src ├── core │ ├── lib │ │ └── passport-weixin │ │ │ ├── index.ts │ │ │ ├── weixin.constants.ts │ │ │ ├── weixin.providers.ts │ │ │ └── weixin.service.ts │ ├── filter │ │ ├── http-exception.filter.spec.ts │ │ └── http-exception.filter.ts │ ├── interceptor │ │ ├── transform.interceptor.spec.ts │ │ └── transform.interceptor.ts │ └── middleware │ │ └── md.middleware.ts ├── user │ ├── dto │ │ ├── update-user.dto.ts │ │ ├── create-user.dto.ts │ │ └── user-info.dto.ts │ ├── user.module.ts │ ├── user.service.spec.ts │ ├── user.controller.spec.ts │ ├── entities │ │ └── user.entity.ts │ ├── user.controller.ts │ └── user.service.ts ├── app.service.ts ├── tag │ ├── dto │ │ └── create-tag.dto.ts │ ├── tag.module.ts │ ├── tag.service.spec.ts │ ├── tag.controller.ts │ ├── tag.controller.spec.ts │ ├── tag.service.ts │ └── entities │ │ └── tag.entity.ts ├── auth │ ├── dto │ │ ├── wechat-login.dto.ts │ │ └── login.dto.ts │ ├── auth.service.spec.ts │ ├── auth.controller.spec.ts │ ├── jwt-auth.guard.ts │ ├── auth.interface.ts │ ├── role.guard.ts │ ├── jwt.strategy.ts │ ├── local.strategy.ts │ ├── auth.module.ts │ ├── auth.controller.ts │ └── auth.service.ts ├── category │ ├── dto │ │ └── create-category.dto.ts │ ├── category.module.ts │ ├── category.service.spec.ts │ ├── category.controller.spec.ts │ ├── category.controller.ts │ ├── category.service.ts │ └── entities │ │ └── category.entity.ts ├── posts │ ├── posts.service.spec.ts │ ├── posts.controller.spec.ts │ ├── posts.module.ts │ ├── dto │ │ └── post.dto.ts │ ├── posts.controller.ts │ ├── posts.entity.ts │ └── posts.service.ts ├── app.controller.spec.ts ├── main.ts ├── app.controller.ts └── app.module.ts ├── .prettierrc ├── nest-cli.json ├── .env.prod ├── tsconfig.build.json ├── .env ├── test ├── jest-e2e.json └── app.e2e-spec.ts ├── .gitignore ├── tsconfig.json ├── config └── env.ts ├── .eslintrc.js ├── README.md └── package.json /src/core/lib/passport-weixin/index.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/core/lib/passport-weixin/weixin.constants.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/core/lib/passport-weixin/weixin.providers.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/core/lib/passport-weixin/weixin.service.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /.env.prod: -------------------------------------------------------------------------------- 1 | DB_HOST=localhost 2 | DB_PORT=3306 3 | DB_USER=root 4 | DB_PASSWD=root 5 | DB_DATABASE=blog -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | DB_HOST=192.168.1.115 2 | DB_PORT=3306 3 | DB_USER=root 4 | DB_PASSWORD=111111 5 | DB_DATABASE=blog 6 | 7 | SALT= NestProject 8 | SECRET=test123456 9 | 10 | APPID=sssss 11 | APPSECRET= xxxx -------------------------------------------------------------------------------- /src/user/dto/update-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { PartialType } from '@nestjs/swagger'; 2 | import { CreateUserDto } from './create-user.dto'; 3 | 4 | export class UpdateUserDto extends PartialType(CreateUserDto) {} 5 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | console.log("哈哈哈") 7 | return 'Hello World!'; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/tag/dto/create-tag.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class CreateTagDto { 5 | @ApiProperty({ description: '标签名称' }) 6 | @IsNotEmpty() 7 | name: string; 8 | } 9 | -------------------------------------------------------------------------------- /src/core/filter/http-exception.filter.spec.ts: -------------------------------------------------------------------------------- 1 | import { HttpExceptionFilter } from './http-exception.filter'; 2 | 3 | describe('HttpExceptionFilter', () => { 4 | it('should be defined', () => { 5 | expect(new HttpExceptionFilter()).toBeDefined(); 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /src/core/interceptor/transform.interceptor.spec.ts: -------------------------------------------------------------------------------- 1 | import { TransformInterceptor } from './transform.interceptor'; 2 | 3 | describe('TransformInterceptor', () => { 4 | it('should be defined', () => { 5 | expect(new TransformInterceptor()).toBeDefined(); 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /src/auth/dto/wechat-login.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class WechatLoginDto { 5 | @ApiProperty({ description: '授权码' }) 6 | @IsNotEmpty({ message: '请输入授权码' }) 7 | code: string; 8 | } 9 | -------------------------------------------------------------------------------- /src/category/dto/create-category.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty, IsString } from 'class-validator'; 3 | 4 | export class CreateCategoryDto { 5 | @ApiProperty({ description: '分类名称' }) 6 | @IsNotEmpty({ message: '请输入分类名称' }) 7 | @IsString() 8 | name: string; 9 | } 10 | -------------------------------------------------------------------------------- /src/auth/dto/login.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class LoginDto { 5 | @ApiProperty({ description: '用户名' }) 6 | @IsNotEmpty({ message: '请输入用户名' }) 7 | username: string; 8 | 9 | @ApiProperty({ description: '密码' }) 10 | @IsNotEmpty({ message: '请输入密码' }) 11 | password: string; 12 | } 13 | -------------------------------------------------------------------------------- /src/user/dto/create-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class CreateUserDto { 5 | @ApiProperty({ description: '用户名' }) 6 | @IsNotEmpty({message:"请输入用户名"}) 7 | username: string; 8 | 9 | @ApiProperty({ description: '密码' }) 10 | @IsNotEmpty({message:"请输入密码"}) 11 | password: string; 12 | 13 | @ApiProperty({ description: '用户角色' }) 14 | role: string; 15 | } 16 | -------------------------------------------------------------------------------- /src/tag/tag.module.ts: -------------------------------------------------------------------------------- 1 | import { TagService } from './tag.service'; 2 | import { TagEntity } from './entities/tag.entity'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { Module } from '@nestjs/common'; 5 | import { TagController } from './tag.controller'; 6 | 7 | @Module({ 8 | imports: [TypeOrmModule.forFeature([TagEntity])], 9 | controllers: [TagController], 10 | providers: [TagService], 11 | exports:[TagService] 12 | }) 13 | export class TagModule {} 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /src/category/category.module.ts: -------------------------------------------------------------------------------- 1 | import { CategoryEntity } from './entities/category.entity'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { Module } from '@nestjs/common'; 4 | import { CategoryController } from './category.controller'; 5 | import { CategoryService } from './category.service'; 6 | 7 | @Module({ 8 | imports: [TypeOrmModule.forFeature([CategoryEntity])], 9 | controllers: [CategoryController], 10 | providers: [CategoryService], 11 | exports:[CategoryService] 12 | }) 13 | export class CategoryModule {} 14 | -------------------------------------------------------------------------------- /src/posts/posts.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PostsService } from './posts.service'; 3 | 4 | describe('PostsService', () => { 5 | let service: PostsService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [PostsService], 10 | }).compile(); 11 | 12 | service = module.get(PostsService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/tag/tag.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TagService } from './tag.service'; 3 | 4 | describe('TagService', () => { 5 | let service: TagService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [TagService], 10 | }).compile(); 11 | 12 | service = module.get(TagService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { AuthModule } from './../auth/auth.module'; 2 | import { User } from './entities/user.entity'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { Module, forwardRef } from '@nestjs/common'; 5 | import { UserService } from './user.service'; 6 | import { UserController } from './user.controller'; 7 | 8 | @Module({ 9 | imports: [TypeOrmModule.forFeature([User])], 10 | controllers: [UserController], 11 | providers: [UserService,], 12 | exports: [UserService], 13 | }) 14 | export class UserModule {} 15 | -------------------------------------------------------------------------------- /src/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | 4 | describe('AuthService', () => { 5 | let service: AuthService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [AuthService], 10 | }).compile(); 11 | 12 | service = module.get(AuthService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/user/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserService } from './user.service'; 3 | 4 | describe('UserService', () => { 5 | let service: UserService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UserService], 10 | }).compile(); 11 | 12 | service = module.get(UserService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/tag/tag.controller.ts: -------------------------------------------------------------------------------- 1 | import { TagService } from './tag.service'; 2 | import { ApiOperation, ApiTags } from '@nestjs/swagger'; 3 | import { Body, Controller, Post } from '@nestjs/common'; 4 | import { CreateTagDto } from './dto/create-tag.dto'; 5 | 6 | @ApiTags('标签') 7 | @Controller('tag') 8 | export class TagController { 9 | constructor(private readonly tagService: TagService) {} 10 | 11 | @ApiOperation({ summary: '创建标签' }) 12 | @Post() 13 | create(@Body() body: CreateTagDto) { 14 | return this.tagService.create(body.name); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/posts/posts.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PostsController } from './posts.controller'; 3 | 4 | describe('PostsController', () => { 5 | let controller: PostsController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [PostsController], 10 | }).compile(); 11 | 12 | controller = module.get(PostsController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/tag/tag.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TagController } from './tag.controller'; 3 | 4 | describe('TagController', () => { 5 | let controller: TagController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [TagController], 10 | }).compile(); 11 | 12 | controller = module.get(TagController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/auth/auth.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthController } from './auth.controller'; 3 | 4 | describe('AuthController', () => { 5 | let controller: AuthController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [AuthController], 10 | }).compile(); 11 | 12 | controller = module.get(AuthController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/category/category.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CategoryService } from './category.service'; 3 | 4 | describe('CategoryService', () => { 5 | let service: CategoryService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [CategoryService], 10 | }).compile(); 11 | 12 | service = module.get(CategoryService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/category/category.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CategoryController } from './category.controller'; 3 | 4 | describe('CategoryController', () => { 5 | let controller: CategoryController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [CategoryController], 10 | }).compile(); 11 | 12 | controller = module.get(CategoryController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/category/category.controller.ts: -------------------------------------------------------------------------------- 1 | import { CategoryService } from './category.service'; 2 | import { ApiOperation, ApiTags } from '@nestjs/swagger'; 3 | import { Body, Controller, Post } from '@nestjs/common'; 4 | import { CreateCategoryDto } from './dto/create-category.dto'; 5 | 6 | @ApiTags('文章分类') 7 | @Controller('category') 8 | export class CategoryController { 9 | constructor(private readonly categoryService: CategoryService) {} 10 | @ApiOperation({ summary: '创建分类' }) 11 | @Post() 12 | async create(@Body() body: CreateCategoryDto) { 13 | return await this.categoryService.create(body.name); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/user/dto/user-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class UserInfoDto { 5 | @ApiProperty({ description: '用户名' }) 6 | @IsNotEmpty() 7 | username: string; 8 | 9 | @ApiProperty({ description: '用户昵称' }) 10 | nickname: string; 11 | 12 | @ApiProperty({ description: '用户头像' }) 13 | avatar: string; 14 | 15 | @ApiProperty({ description: '用户邮箱' }) 16 | email: string; 17 | 18 | @ApiProperty({ description: '角色' }) 19 | role: string; 20 | 21 | @ApiProperty({ description: '创建时间' }) 22 | createTime: Date; 23 | } 24 | -------------------------------------------------------------------------------- /src/auth/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Injectable, 3 | ExecutionContext, 4 | UnauthorizedException, 5 | } from '@nestjs/common'; 6 | import { AuthGuard } from '@nestjs/passport'; 7 | 8 | @Injectable() 9 | export class JwtAuthGuard extends AuthGuard('jwt') { 10 | getRequest(context: ExecutionContext) { 11 | 12 | const ctx = context.switchToHttp(); 13 | const request = ctx.getRequest(); 14 | return request; 15 | } 16 | 17 | handleRequest(err, user: User): User { 18 | if (err || !user) { 19 | throw new UnauthorizedException('身份验证失败'); 20 | } 21 | return user; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/tag/tag.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Repository } from 'typeorm'; 4 | import { TagEntity } from './entities/tag.entity'; 5 | 6 | @Injectable() 7 | export class TagService { 8 | constructor( 9 | @InjectRepository(TagEntity) 10 | private readonly tagRepository: Repository, 11 | ) {} 12 | 13 | async create(name) { 14 | return await this.tagRepository.save({ name }); 15 | } 16 | 17 | findByName() {} 18 | 19 | async findByIds(ids: string[]) { 20 | return this.tagRepository.findByIds(ids); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/core/interceptor/transform.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CallHandler, 3 | ExecutionContext, 4 | Injectable, 5 | NestInterceptor, 6 | } from '@nestjs/common'; 7 | import { map, Observable } from 'rxjs'; 8 | 9 | interface Response { 10 | data: T 11 | } 12 | @Injectable() 13 | export class TransformInterceptor implements NestInterceptor > { 14 | intercept(context: ExecutionContext, next: CallHandler): Observable { 15 | return next.handle().pipe( 16 | map((data) => { 17 | return { 18 | data, 19 | code: 0, 20 | msg: '请求成功', 21 | }; 22 | }), 23 | ); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /config/env.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import * as path from 'path'; 3 | // const dotenv = require('dotenv'); 4 | const isProd = process.env.NODE_ENV === 'production'; 5 | 6 | function parseEnv() { 7 | const localEnv = path.resolve('.env'); 8 | const prodEnv = path.resolve('.env.prod'); 9 | 10 | if (!fs.existsSync(localEnv) && !fs.existsSync(prodEnv)) { 11 | throw new Error('缺少环境配置文件'); 12 | } 13 | 14 | const filePath = isProd && fs.existsSync(prodEnv) ? prodEnv : localEnv; 15 | 16 | // const config = dotenv.parse(fs.readFileSync(filePath)); 17 | 18 | return { path:filePath }; 19 | } 20 | 21 | export default parseEnv(); 22 | -------------------------------------------------------------------------------- /src/category/category.service.ts: -------------------------------------------------------------------------------- 1 | import { CategoryEntity } from './entities/category.entity'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Injectable } from '@nestjs/common'; 4 | import { Repository } from 'typeorm'; 5 | 6 | @Injectable() 7 | export class CategoryService { 8 | constructor( 9 | @InjectRepository(CategoryEntity) 10 | private readonly categoryRepository: Repository, 11 | ) {} 12 | 13 | async create(name: string) { 14 | return await this.categoryRepository.save({ name }); 15 | } 16 | 17 | async findById(id) { 18 | return await this.categoryRepository.findOne(id); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/user/user.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserController } from './user.controller'; 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserController', () => { 6 | let controller: UserController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [UserController], 11 | providers: [UserService], 12 | }).compile(); 13 | 14 | controller = module.get(UserController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/recommended', 10 | 'plugin:prettier/recommended', 11 | ], 12 | root: true, 13 | env: { 14 | node: true, 15 | jest: true, 16 | }, 17 | ignorePatterns: ['.eslintrc.js'], 18 | rules: { 19 | '@typescript-eslint/interface-name-prefix': 'off', 20 | '@typescript-eslint/explicit-function-return-type': 'off', 21 | '@typescript-eslint/explicit-module-boundary-types': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /src/auth/auth.interface.ts: -------------------------------------------------------------------------------- 1 | export interface AccessTokenInfo { 2 | accessToken: string; 3 | expiresIn: number; 4 | getTime: number; 5 | openid: string; 6 | } 7 | 8 | export interface AccessConfig { 9 | access_token: string; 10 | refresh_token: string; 11 | openid: string; 12 | scope: string; 13 | unionid?: string; 14 | expires_in: number; 15 | } 16 | 17 | export interface WechatError { 18 | errcode: number; 19 | errmsg: string; 20 | } 21 | 22 | export interface WechatUserInfo { 23 | openid: string; 24 | nickname: string; 25 | sex: number; 26 | language: string; 27 | city: string; 28 | province: string; 29 | country: string; 30 | headimgurl: string; 31 | privilege: string[]; 32 | unionid: string; 33 | } 34 | -------------------------------------------------------------------------------- /src/tag/entities/tag.entity.ts: -------------------------------------------------------------------------------- 1 | import { PostsEntity } from 'src/posts/posts.entity'; 2 | import { 3 | Column, 4 | CreateDateColumn, 5 | Entity, 6 | ManyToMany, 7 | PrimaryGeneratedColumn, 8 | UpdateDateColumn, 9 | } from 'typeorm'; 10 | 11 | @Entity('tag') 12 | export class TagEntity { 13 | @PrimaryGeneratedColumn() 14 | id: number; 15 | 16 | // 标签名 17 | @Column() 18 | name: string; 19 | 20 | @ManyToMany(() => PostsEntity, (post) => post.tags) 21 | posts: Array; 22 | 23 | @CreateDateColumn({ 24 | type: 'timestamp', 25 | comment: '创建时间', 26 | name: 'create_time', 27 | }) 28 | createTime: Date; 29 | 30 | @UpdateDateColumn({ 31 | type: 'timestamp', 32 | comment: '更新时间', 33 | name: 'update_time', 34 | }) 35 | updateTime: Date; 36 | } 37 | -------------------------------------------------------------------------------- /src/category/entities/category.entity.ts: -------------------------------------------------------------------------------- 1 | import { PostsEntity } from 'src/posts/posts.entity'; 2 | import { 3 | Column, 4 | CreateDateColumn, 5 | Entity, 6 | OneToMany, 7 | PrimaryGeneratedColumn, 8 | UpdateDateColumn, 9 | } from 'typeorm'; 10 | 11 | @Entity('category') 12 | export class CategoryEntity { 13 | @PrimaryGeneratedColumn() 14 | id: number; 15 | 16 | @Column() 17 | name: string; 18 | 19 | @OneToMany(() => PostsEntity, (post) => post.category) 20 | posts: Array; 21 | 22 | @CreateDateColumn({ 23 | type: 'timestamp', 24 | comment: '创建时间', 25 | name: 'create_time', 26 | }) 27 | createTime: Date; 28 | 29 | @UpdateDateColumn({ 30 | type: 'timestamp', 31 | comment: '更新时间', 32 | name: 'update_time', 33 | }) 34 | updateTime: Date; 35 | } 36 | -------------------------------------------------------------------------------- /src/posts/posts.module.ts: -------------------------------------------------------------------------------- 1 | import { AuthModule } from './../auth/auth.module'; 2 | import { MDMiddleware } from './../core/middleware/md.middleware'; 3 | import { TagModule } from './../tag/tag.module'; 4 | import { CategoryModule } from './../category/category.module'; 5 | import { PostsEntity } from './posts.entity'; 6 | import { TypeOrmModule } from '@nestjs/typeorm'; 7 | import { 8 | MiddlewareConsumer, 9 | Module, 10 | NestModule, 11 | RequestMethod, 12 | } from '@nestjs/common'; 13 | import { PostsController } from './posts.controller'; 14 | import { PostsService } from './posts.service'; 15 | 16 | @Module({ 17 | imports: [ 18 | TypeOrmModule.forFeature([PostsEntity]), 19 | CategoryModule, 20 | TagModule, 21 | AuthModule, 22 | ], 23 | controllers: [PostsController], 24 | providers: [PostsService], 25 | }) 26 | export class PostsModule implements NestModule { 27 | configure(consumer: MiddlewareConsumer) { 28 | consumer 29 | .apply(MDMiddleware) 30 | .forRoutes({ path: 'post', method: RequestMethod.POST }); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/auth/role.guard.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CanActivate, 3 | ExecutionContext, 4 | Injectable, 5 | SetMetadata, 6 | UnauthorizedException, 7 | } from '@nestjs/common'; 8 | import { JwtService } from '@nestjs/jwt'; 9 | import { Reflector } from '@nestjs/core'; 10 | 11 | export const Roles = (...roles: string[]) => SetMetadata('roles', roles); 12 | 13 | @Injectable() 14 | export class RolesGuard implements CanActivate { 15 | constructor( 16 | private readonly reflector: Reflector, 17 | private readonly jwtService: JwtService, 18 | ) {} 19 | 20 | canActivate(context: ExecutionContext): boolean { 21 | const roles = this.reflector.get('roles', context.getHandler()); 22 | if (!roles) { 23 | return true; 24 | } 25 | 26 | const req = context.switchToHttp().getRequest(); 27 | const user = req.user; 28 | if (!user) { 29 | return false; 30 | } 31 | const hasRoles = roles.some((role) => role === user.role); 32 | if (!hasRoles) { 33 | throw new UnauthorizedException('您没有权限'); 34 | } 35 | return hasRoles; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { TransformInterceptor } from './core/interceptor/transform.interceptor'; 2 | import { HttpExceptionFilter } from './core/filter/http-exception.filter'; 3 | import { ValidationPipe } from '@nestjs/common'; 4 | import { NestFactory } from '@nestjs/core'; 5 | import { NestExpressApplication } from '@nestjs/platform-express'; 6 | import { AppModule } from './app.module'; 7 | import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; 8 | 9 | async function bootstrap() { 10 | const app = await NestFactory.create(AppModule); 11 | app.setGlobalPrefix('api'); // 全局路由前缀 12 | app.useGlobalFilters(new HttpExceptionFilter()); 13 | app.useGlobalInterceptors(new TransformInterceptor()); 14 | 15 | app.useGlobalPipes(new ValidationPipe()); 16 | 17 | const config = new DocumentBuilder() 18 | .setTitle('管理后台') 19 | .setDescription('管理后台接口文档') 20 | .setVersion('1.0') 21 | .addBearerAuth() 22 | .build(); 23 | const document = SwaggerModule.createDocument(app, config); 24 | SwaggerModule.setup('docs', app, document); 25 | await app.listen(9080); 26 | } 27 | bootstrap(); 28 | -------------------------------------------------------------------------------- /src/auth/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { AuthService } from './auth.service'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { UnauthorizedException } from '@nestjs/common'; 4 | import { PassportStrategy } from '@nestjs/passport'; 5 | import { InjectRepository } from '@nestjs/typeorm'; 6 | import { StrategyOptions, Strategy, ExtractJwt } from 'passport-jwt'; 7 | import { Repository } from 'typeorm'; 8 | import { User } from 'src/user/entities/user.entity'; 9 | 10 | export class JwtStorage extends PassportStrategy(Strategy) { 11 | constructor( 12 | @InjectRepository(User) 13 | private readonly userRepository: Repository, 14 | private readonly authService: AuthService, 15 | private readonly configService: ConfigService, 16 | ) { 17 | super({ 18 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 19 | secretOrKey: configService.get('SECRET'), 20 | } as StrategyOptions); 21 | } 22 | 23 | async validate(user: User) { 24 | const existUser = await this.authService.getUser(user); 25 | if (!existUser) { 26 | throw new UnauthorizedException('token不正确'); 27 | } 28 | return existUser; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Post, Put ,UploadedFile,UseInterceptors} from '@nestjs/common'; 2 | import { ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger'; 3 | import { AppService } from './app.service'; 4 | import { FileInterceptor } from '@nestjs/platform-express'; 5 | 6 | 7 | export const ApiFile = 8 | (fileName: string = 'file'): MethodDecorator => 9 | (target: any, propertyKey: string, descriptor: PropertyDescriptor) => { 10 | ApiBody({ 11 | schema: { 12 | type: 'object', 13 | properties: { 14 | [fileName]: { 15 | type: 'string', 16 | format: 'binary', 17 | }, 18 | }, 19 | }, 20 | })(target, propertyKey, descriptor); 21 | }; 22 | @ApiTags("公共接口") 23 | @Controller('app') 24 | 25 | export class AppController { 26 | constructor(private readonly appService: AppService) {} 27 | 28 | @Get() 29 | getHello() { 30 | return this.appService.getHello(); 31 | } 32 | 33 | 34 | @Post('upload') 35 | @ApiOperation({ summary: '上传文件' }) 36 | @ApiConsumes('multipart/form-data') 37 | @ApiFile() 38 | @UseInterceptors( FileInterceptor('file')) 39 | async uploadFile(@UploadedFile('file') file: any): Promise { 40 | console.log("0000", file) 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 考拉的 Nest 实战学习系列 2 | 3 | readme 中有很多要说的,今天刚开源还没来及更新,晚些慢慢写,其实本人最近半年多没怎么写后端代码,主要在做低代码和中台么内容,操作的也不是原生数据库而是元数据Meta,文中的原生数据库操作也当作复习下,数据库的操作为了同时适合前端和Node开发小伙伴,所以并不是很复杂,但是该有的部分都会讲解,比如多表关联查询,文件存储等等。 4 | 5 | ## 项目目的 6 | 1. 希望帮助 Node开发者们熟练掌握 Nest.js 框架, 7 | 2. 帮助想要学习 Node.js 的前端小伙伴们更好的入门一个优秀 Node 框架 8 | 9 | ### Nest.js 实战系列一 学完这篇 Nest.js 实战,还没入门的来锤我!(长文预警) 10 | 文章地址: https://juejin.cn/post/7032079740982788132 11 | 12 | ![https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/69d294713fb048a2bfe43b1e6cac7f4f~tplv-k3u1fbpfcp-zoom-in-crop-mark:1304:0:0:0.awebp?](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/69d294713fb048a2bfe43b1e6cac7f4f~tplv-k3u1fbpfcp-zoom-in-crop-mark:1304:0:0:0.awebp?) 13 | 14 | ### Nest.js 实战系列二-手把手带你-实现注册、扫码登录、jwt认证等 15 | 文章地址: https://juejin.cn/post/7032079740982788132 16 | 17 | ![https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b21bddede0dc4ef29fd97c4e40522211~tplv-k3u1fbpfcp-zoom-in-crop-mark:1304:0:0:0.awebp?](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b21bddede0dc4ef29fd97c4e40522211~tplv-k3u1fbpfcp-zoom-in-crop-mark:1304:0:0:0.awebp?) 18 | 19 | ### Nest.js 实战系列三-手把手带你-实现注册、扫码登录、jwt认证等 20 | 文章地址: 首发公众号(后面更新github和掘金) 21 | ![https://user-images.githubusercontent.com/52817889/158059624-06c76d8a-118f-41e0-9d66-c87b59b0a162.png](https://user-images.githubusercontent.com/52817889/158059624-06c76d8a-118f-41e0-9d66-c87b59b0a162.png) 22 | -------------------------------------------------------------------------------- /src/auth/local.strategy.ts: -------------------------------------------------------------------------------- 1 | import { compareSync } from 'bcryptjs'; 2 | import { BadRequestException, HttpException, HttpStatus } from '@nestjs/common'; 3 | import { PassportStrategy } from '@nestjs/passport'; 4 | import { InjectRepository } from '@nestjs/typeorm'; 5 | import { IStrategyOptions, Strategy } from 'passport-local'; 6 | import { Repository } from 'typeorm'; 7 | import { User } from 'src/user/entities/user.entity'; 8 | 9 | export class LocalStorage extends PassportStrategy(Strategy) { 10 | constructor( 11 | @InjectRepository(User) 12 | private readonly userRepository: Repository, 13 | ) { 14 | // 如果不是username、password, 在constructor中配置 15 | super({ 16 | usernameField: 'username', 17 | passwordField: 'password', 18 | } as IStrategyOptions); 19 | } 20 | 21 | async validate(username: string, password: string) { 22 | // 因为密码是加密后的,没办法直接对比用户名密码,只能先根据用户名查出用户,再比对密码 23 | const user = await this.userRepository 24 | .createQueryBuilder('user') 25 | .addSelect('user.password') 26 | .where('user.username=:username', { username }) 27 | .getOne(); 28 | 29 | if (!user) { 30 | throw new BadRequestException('用户名不正确!'); 31 | } 32 | 33 | if (!compareSync(password, user.password)) { 34 | throw new BadRequestException('密码错误!'); 35 | } 36 | 37 | return user; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/core/filter/http-exception.filter.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ArgumentsHost, 3 | Catch, 4 | ExceptionFilter, 5 | HttpException, 6 | } from '@nestjs/common'; 7 | 8 | @Catch(HttpException) 9 | export class HttpExceptionFilter implements ExceptionFilter { 10 | catch(exception: HttpException, host: ArgumentsHost) { 11 | const ctx = host.switchToHttp(); // 获取请求上下文 12 | const response = ctx.getResponse(); // 获取请求上下文中的 response对象 13 | const status = exception.getStatus(); // 获取异常状态码 14 | const exceptionResponse: any = exception.getResponse(); 15 | let validMessage = ''; 16 | 17 | for (let key in exception) { 18 | console.log(key, exception[key]); 19 | } 20 | if (typeof exceptionResponse === 'object') { 21 | validMessage = 22 | typeof exceptionResponse.message === 'string' 23 | ? exceptionResponse.message 24 | : exceptionResponse.message[0]; 25 | } 26 | const message = exception.message 27 | ? exception.message 28 | : `${status >= 500 ? 'Service Error' : 'Client Error'}`; 29 | const errorResponse = { 30 | data: {}, 31 | message: validMessage || message, 32 | code: -1, 33 | }; 34 | 35 | // 设置返回的状态码, 请求头,发送错误信息 36 | response.status(status); 37 | response.header('Content-Type', 'application/json; charset=utf-8'); 38 | response.send(errorResponse); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { JwtStorage } from './jwt.strategy'; 2 | import { Module, forwardRef, Global } from '@nestjs/common'; 3 | import { PassportModule } from '@nestjs/passport'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { User } from 'src/user/entities/user.entity'; 6 | import { AuthController } from './auth.controller'; 7 | import { AuthService } from './auth.service'; 8 | import { LocalStorage } from './local.strategy'; 9 | import { JwtModule } from '@nestjs/jwt'; 10 | import { ConfigService } from '@nestjs/config'; 11 | import { UserModule } from 'src/user/user.module'; 12 | import { HttpModule } from '@nestjs/axios'; 13 | 14 | // const jwtModule = JwtModule.register({ 15 | // secret:"xxx" 16 | // }) 17 | // 这里不建议将秘钥写死在代码也, 它应该和数据库配置的数据一样,从环境变量中来 18 | const jwtModule = JwtModule.registerAsync({ 19 | inject: [ConfigService], 20 | useFactory: async (configService: ConfigService) => { 21 | return { 22 | secret: configService.get('SECRET', 'test123456'), 23 | signOptions: { expiresIn: '4h' }, 24 | }; 25 | }, 26 | }); 27 | 28 | @Module({ 29 | imports: [ 30 | TypeOrmModule.forFeature([User]), 31 | HttpModule, 32 | PassportModule, 33 | jwtModule, 34 | UserModule, 35 | ], 36 | controllers: [AuthController], 37 | providers: [AuthService, LocalStorage, JwtStorage], 38 | exports: [jwtModule], 39 | }) 40 | export class AuthModule {} 41 | -------------------------------------------------------------------------------- /src/posts/dto/post.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; 2 | import { IsNotEmpty, IsNumber } from 'class-validator'; 3 | 4 | export class CreatePostDto { 5 | @ApiProperty({ description: '文章标题' }) 6 | @IsNotEmpty({ message: '文章标题必填' }) 7 | readonly title: string; 8 | 9 | @ApiPropertyOptional({ description: '内容' }) 10 | readonly content: string; 11 | 12 | @ApiPropertyOptional({ description: '文章封面' }) 13 | readonly coverUrl: string; 14 | 15 | @ApiPropertyOptional({ description: '文章状态' }) 16 | readonly status: string; 17 | 18 | @IsNumber() 19 | @ApiProperty({ description: '文章分类' }) 20 | readonly category: number; 21 | 22 | @ApiPropertyOptional({ description: '是否推荐' }) 23 | readonly isRecommend: boolean; 24 | 25 | @ApiPropertyOptional({ description: '文章标签' }) 26 | readonly tag: string; 27 | } 28 | 29 | export class PostInfoDto { 30 | public id: number; 31 | public title: string; 32 | public content: string; 33 | public contentHtml: string; 34 | public summary: string; 35 | public toc: string; 36 | public coverUrl: string; 37 | public isRecommend: boolean; 38 | public status: string; 39 | public userId: string; 40 | public author: string; 41 | public category: string; 42 | public tags: string[]; 43 | public count: number; 44 | public likeCount: number; 45 | } 46 | 47 | export interface PostsRo { 48 | list: PostInfoDto[]; 49 | count: number; 50 | } 51 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { PostsModule } from './posts/posts.module'; 5 | import { TypeOrmModule } from '@nestjs/typeorm'; 6 | import { ConfigService, ConfigModule } from '@nestjs/config'; 7 | import envConfig from '../config/env'; 8 | import { UserModule } from './user/user.module'; 9 | import { AuthModule } from './auth/auth.module'; 10 | import { CategoryModule } from './category/category.module'; 11 | import { TagModule } from './tag/tag.module'; 12 | @Module({ 13 | imports: [ 14 | ConfigModule.forRoot({ isGlobal: true, envFilePath: [envConfig.path] }), 15 | ConfigModule.forRoot({isGlobal: true}), 16 | TypeOrmModule.forRootAsync({ 17 | inject: [ConfigService], 18 | useFactory: async (configService: ConfigService) => ({ 19 | type: 'mysql', 20 | host: configService.get('DB_HOST', '127.0.0.0'), 21 | port: configService.get('DB_PORT', 3306), 22 | username: configService.get('DB_USER', 'root'), 23 | password: configService.get('DB_PASSWORD', 'root'), 24 | database: configService.get('DB_DATABASE', 'blog'), 25 | // charset: 'utf8mb4', 26 | timezone: '+08:00', 27 | synchronize: true, 28 | autoLoadEntities: true 29 | }), 30 | }), 31 | PostsModule, 32 | UserModule, 33 | AuthModule, 34 | CategoryModule, 35 | TagModule, 36 | ], 37 | controllers: [AppController], 38 | providers: [AppService], 39 | }) 40 | export class AppModule {} 41 | -------------------------------------------------------------------------------- /src/user/entities/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { Exclude } from 'class-transformer'; 2 | import { 3 | BeforeInsert, 4 | Column, 5 | Entity, 6 | OneToMany, 7 | PrimaryGeneratedColumn, 8 | } from 'typeorm'; 9 | import * as bcrypt from 'bcryptjs'; 10 | import { ApiProperty } from '@nestjs/swagger'; 11 | import { PostsEntity } from 'src/posts/posts.entity'; 12 | @Entity('user') 13 | export class User { 14 | @ApiProperty({ description: '用户id' }) 15 | @PrimaryGeneratedColumn('uuid') 16 | id: string; 17 | 18 | @Column({ length: 100, nullable: true }) 19 | username: string; 20 | 21 | @Column({ length: 100, nullable: true }) 22 | nickname: string; 23 | 24 | @Exclude() 25 | @Column({ select: false, nullable: true }) 26 | password: string; 27 | 28 | @Column({ default: null }) 29 | avatar: string; 30 | 31 | @Column({ default: null }) 32 | email: string; 33 | 34 | @Column({ default: null }) 35 | openid: string; 36 | 37 | @Column('enum', { enum: ['root', 'author', 'visitor'], default: 'visitor' }) 38 | role: string; 39 | 40 | @OneToMany(() => PostsEntity, (post) => post.author) 41 | posts: PostsEntity[]; 42 | 43 | @Column({ 44 | name: 'create_time', 45 | type: 'timestamp', 46 | default: () => 'CURRENT_TIMESTAMP', 47 | }) 48 | createTime: Date; 49 | 50 | @Exclude() 51 | @Column({ 52 | name: 'update_time', 53 | type: 'timestamp', 54 | default: () => 'CURRENT_TIMESTAMP', 55 | }) 56 | updateTime: Date; 57 | 58 | @BeforeInsert() 59 | async encryptPwd() { 60 | if (!this.password) return; 61 | this.password = await bcrypt.hashSync(this.password, 10); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Controller, 3 | Get, 4 | Post, 5 | Body, 6 | Patch, 7 | Param, 8 | Delete, 9 | UseInterceptors, 10 | ClassSerializerInterceptor, 11 | UseGuards, 12 | Request, 13 | Req, 14 | } from '@nestjs/common'; 15 | import { UserService } from './user.service'; 16 | import { CreateUserDto } from './dto/create-user.dto'; 17 | import { UpdateUserDto } from './dto/update-user.dto'; 18 | import { 19 | ApiBearerAuth, 20 | ApiOperation, 21 | ApiResponse, 22 | ApiTags, 23 | } from '@nestjs/swagger'; 24 | import { UserInfoDto } from './dto/user-info.dto'; 25 | import { AuthGuard } from '@nestjs/passport'; 26 | 27 | @ApiTags('用户') 28 | @Controller('user') 29 | export class UserController { 30 | constructor(private readonly userService: UserService) {} 31 | 32 | @ApiOperation({ summary: '注册用户' }) 33 | @ApiResponse({ status: 201, type: UserInfoDto }) 34 | @UseInterceptors(ClassSerializerInterceptor) 35 | @Post('register') 36 | register(@Body() createUser: CreateUserDto) { 37 | return this.userService.register(createUser); 38 | } 39 | 40 | @ApiOperation({ summary: '获取用户信息' }) 41 | @ApiBearerAuth() 42 | @UseGuards(AuthGuard('jwt')) 43 | @Get() 44 | async getUserInfo(@Req() req) { 45 | return req.user; 46 | } 47 | 48 | @Get(':id') 49 | findOne(@Param('id') id: string) { 50 | return this.userService.findOne(id); 51 | } 52 | 53 | @Patch(':id') 54 | update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { 55 | return this.userService.update(+id, updateUserDto); 56 | } 57 | 58 | @Delete(':id') 59 | remove(@Param('id') id: string) { 60 | return this.userService.remove(+id); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { AuthService } from './auth.service'; 2 | import { LoginDto } from './dto/login.dto'; 3 | import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger'; 4 | import { 5 | Body, 6 | ClassSerializerInterceptor, 7 | Controller, 8 | Get, 9 | Headers, 10 | Post, 11 | Req, 12 | Res, 13 | UseGuards, 14 | UseInterceptors, 15 | } from '@nestjs/common'; 16 | import { AuthGuard } from '@nestjs/passport'; 17 | import { urlencoded } from 'express'; 18 | import * as urlencode from 'urlencode'; 19 | import { WechatLoginDto } from './dto/wechat-login.dto'; 20 | 21 | @ApiTags('验证') 22 | @Controller('auth') 23 | export class AuthController { 24 | constructor(private readonly authService: AuthService) {} 25 | 26 | @ApiOperation({ summary: '登录' }) 27 | @UseGuards(AuthGuard('local')) 28 | @UseInterceptors(ClassSerializerInterceptor) 29 | @Post('login') 30 | async login(@Body() user: LoginDto, @Req() req) { 31 | return await this.authService.login(req.user); 32 | } 33 | 34 | @ApiOperation({ summary: '微信登录跳转' }) 35 | @Get('wechatLogin') 36 | async wechatLogin(@Headers() header, @Res() res) { 37 | 38 | const APPID = process.env.APPID; 39 | const redirectUri = urlencode( 40 | 'http://www.inode.club' 41 | ); 42 | res.redirect( 43 | `https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`, 44 | ); 45 | } 46 | 47 | @ApiOperation({ summary: '微信登录' }) 48 | @ApiBody({ type: WechatLoginDto, required: true }) 49 | @Post('wechat') 50 | async loginWithWechat(@Body('code') code: string) { 51 | return this.authService.loginWithWechat(code); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/core/middleware/md.middleware.ts: -------------------------------------------------------------------------------- 1 | import { BadRequestException } from '@nestjs/common'; 2 | /*** 3 | * md 文件转为html, 依赖于showdown来处理 4 | */ 5 | 6 | import { Injectable, NestMiddleware } from '@nestjs/common'; 7 | import * as showdown from 'showdown'; 8 | import * as cheerio from 'cheerio'; 9 | const converter = new showdown.Converter(); 10 | 11 | @Injectable() 12 | export class MDMiddleware implements NestMiddleware { 13 | // 参数是固定的Request/Response/nest 14 | use(req: any, res: Response, next: Function) { 15 | const { content } = req.body; 16 | if (content) { 17 | try { 18 | const html = converter.makeHtml(content); 19 | req.body.contentHtml = html; 20 | req.body.summary = toText(html); 21 | } catch (error) { 22 | throw new BadRequestException('markdown 格式错误'); 23 | } 24 | } 25 | next(); 26 | } 27 | } 28 | 29 | function toText(html, len = 30) { 30 | if (html != null) { 31 | const substr = html.replace(/<[^>]+>|&[^>]+;/g, '').trim(); 32 | console.log('substr', substr); 33 | return substr.length < len ? substr : substr.substring(0, len) + '...'; 34 | } 35 | } 36 | function getToc(html: string) { 37 | // 这个功能能前端做还是前端做 38 | // decodeEntities防止中文转化为unicdoe 39 | const $ = cheerio.load(html, { decodeEntities: false }); 40 | 41 | // 用count生成自定义id 42 | let hArr = [], 43 | highestLvl, 44 | count = 0; 45 | $('h1, h2, h3, h4, h5, h6').each(function () { 46 | let id = `h${count}`; 47 | count++; 48 | $(this).attr('id', id); 49 | let lvl: number = Number($(this).get(0).tagName.substr(1)); 50 | if (!highestLvl) highestLvl = lvl; 51 | console.log('lvl:', lvl, highestLvl); 52 | hArr.push({ 53 | hLevel: lvl - highestLvl + 1, 54 | content: $(this).html(), 55 | id: id, 56 | }); 57 | }); 58 | console.log('hArr:', hArr); 59 | } 60 | 61 | function toTree(flatArr) { 62 | let result = []; 63 | let stack = []; // 栈数组 64 | let collector = result; // 收集器 65 | 66 | flatArr.forEach((item, index) => { 67 | if (stack.length === 0) { 68 | // 第一次循环 69 | stack.push(item); 70 | collector.push(item); 71 | 72 | item.children = []; 73 | item.parentCollector = result; 74 | 75 | // 改变收集器为当前级别的子集 76 | collector = item.children; 77 | } else { 78 | let topStack = stack[stack.length - 1]; 79 | 80 | if (topStack.hLevel >= item.hLevel) { 81 | // 说明不能作为其子集 82 | let outTrack = stack.pop(); // 移除栈顶元素 83 | stack.push(item); 84 | 85 | // 当前 86 | } 87 | } 88 | }); 89 | } 90 | -------------------------------------------------------------------------------- /src/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { compareSync } from 'bcryptjs'; 2 | import { User } from './entities/user.entity'; 3 | import { 4 | Injectable, 5 | HttpException, 6 | HttpStatus, 7 | BadRequestException, 8 | } from '@nestjs/common'; 9 | import { InjectRepository } from '@nestjs/typeorm'; 10 | import { CreateUserDto } from './dto/create-user.dto'; 11 | import { UpdateUserDto } from './dto/update-user.dto'; 12 | import { Repository } from 'typeorm'; 13 | import { WechatUserInfo } from '../auth/auth.interface'; 14 | 15 | @Injectable() 16 | export class UserService { 17 | constructor( 18 | @InjectRepository(User) 19 | private userRepository: Repository, 20 | ) {} 21 | 22 | /** 23 | * 账号密码注册 24 | * @param createUser 25 | */ 26 | async register(createUser: CreateUserDto) { 27 | const { username } = createUser; 28 | 29 | const user = await this.userRepository.findOne({ 30 | where: { username }, 31 | }); 32 | if (user) { 33 | throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST); 34 | } 35 | 36 | const newUser = await this.userRepository.create(createUser); 37 | return await this.userRepository.save(newUser); 38 | } 39 | 40 | async registerByWechat(userInfo: WechatUserInfo) { 41 | const { nickname, openid, headimgurl } = userInfo; 42 | const newUser = await this.userRepository.create({ 43 | nickname, 44 | openid, 45 | avatar: headimgurl, 46 | }); 47 | return await this.userRepository.save(newUser); 48 | } 49 | 50 | // async login(user: Partial) { 51 | // const { username, password } = user; 52 | 53 | // const existUser = await this.userRepository 54 | // .createQueryBuilder('user') 55 | // .addSelect('user.password') 56 | // .where('user.username=:username', { username }) 57 | // .getOne(); 58 | 59 | // console.log('existUser', existUser); 60 | // if ( 61 | // !existUser || 62 | // !(await this.comparePassword(password, existUser.password)) 63 | // ) { 64 | // throw new BadRequestException('用户名或者密码错误'); 65 | // } 66 | // return existUser; 67 | // } 68 | 69 | findAll() { 70 | return `This action returns all user`; 71 | } 72 | 73 | async findOne(id: string) { 74 | return await this.userRepository.findOne(id); 75 | } 76 | 77 | async findByOpenid(openid: string) { 78 | return await this.userRepository.findOne({ where: { openid } }); 79 | } 80 | 81 | update(id: number, updateUserDto: UpdateUserDto) { 82 | return `This action updates a #${id} user`; 83 | } 84 | 85 | remove(id: number) { 86 | return `This action removes a #${id} user`; 87 | } 88 | 89 | comparePassword(password, libPassword) { 90 | return compareSync(password, libPassword); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/posts/posts.controller.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * @Descripttion: 3 | * @version: 4 | * @Author: koala 5 | * @Date: 2021-12-11 15:48:24 6 | * @LastEditors: koala 7 | * @LastEditTime: 2022-01-21 10:50:48 8 | */ 9 | import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'; 10 | import { PostsService } from './posts.service'; 11 | import { 12 | Body, 13 | Controller, 14 | Delete, 15 | Get, 16 | Param, 17 | Post, 18 | Put, 19 | Query, 20 | Req, 21 | UseGuards, 22 | } from '@nestjs/common'; 23 | import { CreatePostDto, PostsRo } from './dto/post.dto'; 24 | import { AuthGuard } from '@nestjs/passport'; 25 | import { RolesGuard, Roles } from './../auth/role.guard'; 26 | 27 | @ApiTags('文章') 28 | @Controller('post') 29 | export class PostsController { 30 | constructor(private readonly postsService: PostsService) {} 31 | 32 | /** 33 | * 创建文章 34 | */ 35 | @ApiOperation({ summary: '创建文章' }) 36 | @ApiBearerAuth() 37 | @Post() 38 | @Roles('admin', 'root') 39 | @UseGuards(AuthGuard('jwt'), RolesGuard) 40 | async create(@Body() post: CreatePostDto, @Req() req) { 41 | return await this.postsService.create(req.user, post); 42 | } 43 | 44 | /** 45 | * 获取所有文章 46 | */ 47 | @ApiOperation({ summary: '获取文章列表' }) 48 | @Get('/list') 49 | async findAll( 50 | @Query() query, 51 | @Query('pageSize') pageSize: number, 52 | @Query('pageNum') pageNum: number, 53 | ): Promise { 54 | return await this.postsService.findAll(query); 55 | } 56 | /** 57 | * 获取归档列表 58 | */ 59 | @ApiOperation({ summary: '归档日期列表' }) 60 | @Get('/archives') 61 | getArchives() { 62 | return this.postsService.getArchives(); 63 | } 64 | 65 | /** 66 | * 获取文章归档 67 | */ 68 | @ApiOperation({ summary: '文章归档' }) 69 | @Get('/archives/list') 70 | getArchiveList(@Query("time") time: string) { 71 | return this.postsService.getArchiveList(time); 72 | } 73 | 74 | /** 75 | * 获取指定文章 76 | * @param id 77 | */ 78 | @ApiOperation({ summary: '获取指定文章' }) 79 | @Get(':id') 80 | async findById(@Param('id') id: string) { 81 | return await this.postsService.findById(id); 82 | } 83 | 84 | /** 85 | * 更新文章 86 | * @param id 87 | * @param post 88 | */ 89 | @ApiOperation({ summary: '更新指定文章' }) 90 | @ApiBearerAuth() 91 | @Put(':id') 92 | @UseGuards(AuthGuard('jwt')) 93 | async update(@Param('id') id: number, @Body() post: CreatePostDto) { 94 | return await this.postsService.updateById(id, post); 95 | } 96 | 97 | /** 98 | * 删除 99 | * @param id 100 | */ 101 | @ApiOperation({ summary: '删除文章' }) 102 | @Delete(':id') 103 | async remove(@Param('id') id) { 104 | return await this.postsService.remove(id); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/posts/posts.entity.ts: -------------------------------------------------------------------------------- 1 | import { TagEntity } from './../tag/entities/tag.entity'; 2 | import { CategoryEntity } from './../category/entities/category.entity'; 3 | import { User } from 'src/user/entities/user.entity'; 4 | import { 5 | Column, 6 | Entity, 7 | JoinColumn, 8 | JoinTable, 9 | ManyToMany, 10 | ManyToOne, 11 | PrimaryGeneratedColumn, 12 | RelationId, 13 | } from 'typeorm'; 14 | import { Exclude, Expose } from 'class-transformer'; 15 | import { PostInfoDto } from './dto/post.dto'; 16 | 17 | @Entity('post') 18 | export class PostsEntity { 19 | @PrimaryGeneratedColumn() 20 | id: number; // 标记为主列,值自动生成 21 | 22 | // 文章标题 23 | @Column({ length: 50 }) 24 | title: string; 25 | 26 | // markdown内容 27 | @Column({ type: 'mediumtext', default: null }) 28 | content: string; 29 | 30 | // markdown 转 html 31 | @Column({ type: 'mediumtext', default: null, name: 'content_html' }) 32 | contentHtml: string; 33 | 34 | // 摘要,自动生成 35 | @Column({ type: 'text', default: null }) 36 | summary: string; 37 | 38 | // 封面图 39 | @Column({ default: null, name: 'cover_url' }) 40 | coverUrl: string; 41 | 42 | // 阅读量 43 | @Column({ type: 'int', default: 0 }) 44 | count: number; 45 | 46 | // 点赞量 47 | @Column({ type: 'int', default: 0, name: 'like_count' }) 48 | likeCount: number; 49 | 50 | // 推荐显示 51 | @Column({ type: 'tinyint', default: 0, name: 'is_recommend' }) 52 | isRecommend: number; 53 | 54 | // 文章状态 55 | @Column('simple-enum', { enum: ['draft', 'publish'] }) 56 | status: string; 57 | 58 | // 作者 59 | @ManyToOne((type) => User, (user) => user.nickname) 60 | author: User; 61 | 62 | // @RelationId( (user:User) => user.posts) 63 | // userId:User 64 | 65 | // 分类 66 | @Exclude() 67 | @ManyToOne(() => CategoryEntity, (category) => category.posts, { 68 | // cascade: true, 69 | }) 70 | @JoinColumn({ 71 | name: 'category_id', 72 | }) 73 | category: CategoryEntity; 74 | 75 | // 标签 76 | @ManyToMany(() => TagEntity, (tag) => tag.posts) 77 | @JoinTable({ 78 | name: 'post_tag', 79 | joinColumns: [{ name: 'post_id' }], 80 | inverseJoinColumns: [{ name: 'tag_id' }], 81 | }) 82 | tags: TagEntity[]; 83 | 84 | @Column({ type: 'timestamp', name: 'publish_time', default: null }) 85 | publishTime: Date; 86 | 87 | @Column({ type: 'timestamp', name: 'create_time', default: () => 'CURRENT_TIMESTAMP' }) 88 | createTime: Date; 89 | 90 | @Column({ type: 'timestamp',name: 'update_time', default: () => 'CURRENT_TIMESTAMP' }) 91 | updateTime: Date; 92 | 93 | toResponseObject(): PostInfoDto { 94 | let responseObj: PostInfoDto = { 95 | ...this, 96 | isRecommend: this.isRecommend ? true : false, 97 | }; 98 | if (this.category) { 99 | responseObj.category = this.category.name; 100 | } 101 | if (this.tags && this.tags.length) { 102 | responseObj.tags = this.tags.map((item) => item.name); 103 | } 104 | if (this.author && this.author.id) { 105 | responseObj.userId = this.author.id; 106 | responseObj.author = this.author.nickname || this.author.username; 107 | } 108 | return responseObj; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nest-blog", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json" 22 | }, 23 | "dependencies": { 24 | "@nestjs/axios": "0.0.3", 25 | "@nestjs/common": "^8.0.0", 26 | "@nestjs/config": "^1.1.0", 27 | "@nestjs/core": "^8.0.0", 28 | "@nestjs/jwt": "^8.0.0", 29 | "@nestjs/mapped-types": "*", 30 | "@nestjs/passport": "^8.0.1", 31 | "@nestjs/platform-express": "^8.0.0", 32 | "@nestjs/swagger": "^5.1.4", 33 | "@nestjs/typeorm": "^8.0.2", 34 | "@types/passport-jwt": "^3.0.6", 35 | "@types/urlencode": "^1.1.2", 36 | "bcryptjs": "^2.4.3", 37 | "cheerio": "^1.0.0-rc.10", 38 | "class-transformer": "^0.4.0", 39 | "class-validator": "^0.13.1", 40 | "dotenv": "^10.0.0", 41 | "mysql2": "^2.3.3-rc.0", 42 | "passport": "^0.5.0", 43 | "passport-jwt": "^4.0.0", 44 | "passport-local": "^1.0.0", 45 | "passport-weixin": "^0.2.0", 46 | "reflect-metadata": "^0.1.13", 47 | "rimraf": "^3.0.2", 48 | "rxjs": "^7.2.0", 49 | "showdown": "^1.9.1", 50 | "swagger-ui-express": "^4.1.6", 51 | "typeorm": "^0.2.39", 52 | "urlencode": "^1.1.0" 53 | }, 54 | "devDependencies": { 55 | "@nestjs/cli": "^8.0.0", 56 | "@nestjs/schematics": "^8.0.0", 57 | "@nestjs/testing": "^8.0.0", 58 | "@types/bcryptjs": "^2.4.2", 59 | "@types/express": "^4.17.13", 60 | "@types/jest": "^27.0.1", 61 | "@types/multer": "^1.4.7", 62 | "@types/node": "^16.0.0", 63 | "@types/passport": "^1.0.7", 64 | "@types/passport-local": "^1.0.34", 65 | "@types/showdown": "^1.9.4", 66 | "@types/supertest": "^2.0.11", 67 | "@typescript-eslint/eslint-plugin": "^5.0.0", 68 | "@typescript-eslint/parser": "^5.0.0", 69 | "eslint": "^8.0.1", 70 | "eslint-config-prettier": "^8.3.0", 71 | "eslint-plugin-prettier": "^4.0.0", 72 | "jest": "^27.2.5", 73 | "prettier": "^2.3.2", 74 | "source-map-support": "^0.5.20", 75 | "supertest": "^6.1.3", 76 | "ts-jest": "^27.0.3", 77 | "ts-loader": "^9.2.3", 78 | "ts-node": "^10.0.0", 79 | "tsconfig-paths": "^3.10.1", 80 | "typescript": "^4.3.5" 81 | }, 82 | "jest": { 83 | "moduleFileExtensions": [ 84 | "js", 85 | "json", 86 | "ts" 87 | ], 88 | "rootDir": "src", 89 | "testRegex": ".*\\.spec\\.ts$", 90 | "transform": { 91 | "^.+\\.(t|j)s$": "ts-jest" 92 | }, 93 | "collectCoverageFrom": [ 94 | "**/*.(t|j)s" 95 | ], 96 | "coverageDirectory": "../coverage", 97 | "testEnvironment": "node" 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { UserService } from './../user/user.service'; 2 | import { Injectable, BadRequestException, HttpException } from '@nestjs/common'; 3 | import { HttpService } from '@nestjs/axios'; 4 | import { JwtService } from '@nestjs/jwt'; 5 | import { User } from '../user/entities/user.entity'; 6 | import { 7 | AccessTokenInfo, 8 | AccessConfig, 9 | WechatError, 10 | WechatUserInfo, 11 | } from './auth.interface'; 12 | import { lastValueFrom, map, Observable } from 'rxjs'; 13 | import { AxiosResponse } from 'axios'; 14 | @Injectable() 15 | export class AuthService { 16 | constructor( 17 | private jwtService: JwtService, 18 | private userService: UserService, 19 | private httpService: HttpService, 20 | ) {} 21 | private accessTokenInfo: AccessTokenInfo; 22 | public apiServer = 'https://api.weixin.qq.com'; 23 | 24 | createToken(user: Partial) { 25 | return this.jwtService.sign(user); 26 | } 27 | 28 | async login(user: Partial) { 29 | const token = this.createToken({ 30 | id: user.id, 31 | username: user.username, 32 | role: user.role, 33 | }); 34 | 35 | return { token }; 36 | } 37 | 38 | async loginWithWechat(code) { 39 | if (!code) { 40 | throw new BadRequestException('请输入微信授权码'); 41 | } 42 | await this.getAccessToken(code); 43 | 44 | const user = await this.getUserByOpenid(); 45 | if (!user) { 46 | // 获取用户信息,注册新用户 47 | const userInfo: WechatUserInfo = await this.getUserInfo(); 48 | return this.userService.registerByWechat(userInfo); 49 | } 50 | return this.login(user); 51 | } 52 | 53 | async getUser(user) { 54 | return await this.userService.findOne(user.id); 55 | } 56 | 57 | async getUserByOpenid() { 58 | return await this.userService.findByOpenid(this.accessTokenInfo.openid); 59 | } 60 | async getUserInfo() { 61 | const result: AxiosResponse = 62 | await lastValueFrom( 63 | this.httpService.get( 64 | `${this.apiServer}/sns/userinfo?access_token=${this.accessTokenInfo.accessToken}&openid=${this.accessTokenInfo.openid}`, 65 | ), 66 | ); 67 | if (result.data.errcode) { 68 | throw new BadRequestException( 69 | `[getUserInfo] errcode:${result.data.errcode}, errmsg:${result.data.errmsg}`, 70 | ); 71 | } 72 | console.log('result', result.data); 73 | 74 | return result.data; 75 | } 76 | 77 | async getAccessToken(code) { 78 | const { APPID, APPSECRET } = process.env; 79 | if (!APPSECRET) { 80 | throw new BadRequestException('[getAccessToken]必须有appSecret'); 81 | } 82 | if ( 83 | !this.accessTokenInfo || 84 | (this.accessTokenInfo && this.isExpires(this.accessTokenInfo)) 85 | ) { 86 | // 请求accessToken数据 87 | const res: AxiosResponse = 88 | await lastValueFrom( 89 | this.httpService.get( 90 | `${this.apiServer}/sns/oauth2/access_token?appid=${APPID}&secret=${APPSECRET}&code=${code}&grant_type=authorization_code`, 91 | ), 92 | ); 93 | 94 | if (res.data.errcode) { 95 | throw new BadRequestException( 96 | `[getAccessToken] errcode:${res.data.errcode}, errmsg:${res.data.errmsg}`, 97 | ); 98 | } 99 | this.accessTokenInfo = { 100 | accessToken: res.data.access_token, 101 | expiresIn: res.data.expires_in, 102 | getTime: Date.now(), 103 | openid: res.data.openid, 104 | }; 105 | } 106 | 107 | return this.accessTokenInfo.accessToken; 108 | } 109 | 110 | isExpires(access) { 111 | return Date.now() - access.getTime > access.expiresIn * 1000; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/posts/posts.service.ts: -------------------------------------------------------------------------------- 1 | import { CategoryService } from './../category/category.service'; 2 | import { CreatePostDto, PostInfoDto, PostsRo } from './dto/post.dto'; 3 | import { HttpException, Injectable, HttpStatus } from '@nestjs/common'; 4 | import { InjectRepository } from '@nestjs/typeorm'; 5 | import { getRepository, Repository } from 'typeorm'; 6 | import { PostsEntity } from './posts.entity'; 7 | import { TagService } from './../tag/tag.service'; 8 | import { count } from 'console'; 9 | 10 | @Injectable() 11 | export class PostsService { 12 | constructor( 13 | @InjectRepository(PostsEntity) 14 | private readonly postsRepository: Repository, 15 | private readonly categoryService: CategoryService, 16 | private readonly tagService: TagService, 17 | ) {} 18 | 19 | async create(user, post: CreatePostDto): Promise { 20 | const { title } = post; 21 | if (!title) { 22 | throw new HttpException('缺少文章标题', HttpStatus.BAD_REQUEST); 23 | } 24 | 25 | const doc = await this.postsRepository.findOne({ 26 | where: { title }, 27 | }); 28 | if (doc) { 29 | throw new HttpException('文章已存在', HttpStatus.BAD_REQUEST); 30 | } 31 | 32 | let { tag, category = 0, status, isRecommend, coverUrl } = post; 33 | 34 | const categoryDoc = await this.categoryService.findById(category); 35 | 36 | const tags = await this.tagService.findByIds(('' + tag).split(',')); 37 | const postParam: Partial = { 38 | ...post, 39 | isRecommend: isRecommend ? 1 : 0, 40 | category: categoryDoc, 41 | tags: tags, 42 | author: user, 43 | }; 44 | if (status === 'publish') { 45 | Object.assign(postParam, { 46 | publishTime: new Date(), 47 | }); 48 | } 49 | 50 | const newPost: PostsEntity = await this.postsRepository.create({ 51 | ...postParam, 52 | }); 53 | const created = await this.postsRepository.save(newPost); 54 | return created.id; 55 | } 56 | 57 | async findAll(query): Promise { 58 | const qb = await this.postsRepository 59 | .createQueryBuilder('post') 60 | .leftJoinAndSelect('post.category', 'category') 61 | .leftJoinAndSelect('post.tags', 'tag') 62 | .leftJoinAndSelect('post.author', 'user') 63 | .orderBy('post.updateTime', 'DESC'); 64 | qb.where('1 = 1'); 65 | qb.orderBy('post.create_time', 'DESC'); 66 | 67 | const count = await qb.getCount(); 68 | const { pageNum = 1, pageSize = 10, ...params } = query; 69 | qb.limit(pageSize); 70 | qb.offset(pageSize * (pageNum - 1)); 71 | 72 | let posts = await qb.getMany(); 73 | const result: PostInfoDto[] = posts.map((item) => item.toResponseObject()); 74 | return { list: result, count: count }; 75 | 76 | // 使用find 方式实现 77 | /** 78 | const { pageNum = 1, pageSize = 10, ...params } = query; 79 | const result = await this.postsRepository.findAndCount({ 80 | relations: ['category', 'author', "tags"], 81 | order: { 82 | id: 'DESC', 83 | }, 84 | skip: (pageNum - 1) * pageSize, 85 | take: pageSize, 86 | }); 87 | const list = result[0].map((item) => item.toResponseObject()); 88 | return { list, count: result[1] }; 89 | */ 90 | } 91 | 92 | async findById(id): Promise { 93 | const qb = this.postsRepository 94 | .createQueryBuilder('post') 95 | .leftJoinAndSelect('post.category', 'category') 96 | .leftJoinAndSelect('post.tags', 'tag') 97 | .leftJoinAndSelect('post.author', 'user') 98 | .where('post.id=:id') 99 | .setParameter('id', id); 100 | 101 | const result = await qb.getOne(); 102 | if (!result) 103 | throw new HttpException(`id为${id}的文章不存在`, HttpStatus.BAD_REQUEST); 104 | await this.postsRepository.update(id, { count: result.count + 1 }); 105 | 106 | return result.toResponseObject(); 107 | } 108 | 109 | async updateById(id, post): Promise { 110 | const existPost = await this.postsRepository.findOne(id); 111 | if (!existPost) { 112 | throw new HttpException(`id为${id}的文章不存在`, HttpStatus.BAD_REQUEST); 113 | } 114 | 115 | const { category, tag, status } = post; 116 | const tags = await this.tagService.findByIds(('' + tag).split(',')); 117 | const categoryDoc = await this.categoryService.findById(category); 118 | const newPost = { 119 | ...post, 120 | isRecommend: post.isRecommend ? 1 : 0, 121 | category: categoryDoc, 122 | tags, 123 | publishTime: status === 'publish' ? new Date() : existPost.publishTime, 124 | }; 125 | 126 | const updatePost = this.postsRepository.merge(existPost, newPost); 127 | return (await this.postsRepository.save(updatePost)).id; 128 | } 129 | 130 | async updateViewById(id) { 131 | const post = await this.postsRepository.findOne(id); 132 | const updatePost = await this.postsRepository.merge(post, { 133 | count: post.count + 1, 134 | }); 135 | this.postsRepository.save(updatePost); 136 | } 137 | 138 | async getArchives() { 139 | const data = await this.postsRepository 140 | .createQueryBuilder('post') 141 | .select([`DATE_FORMAT(update_time, '%Y年%m') time`, `COUNT(*) count`]) 142 | .where('status=:status', { status: 'publish' }) 143 | .groupBy('time') 144 | .orderBy('update_time', 'DESC') 145 | .getRawMany(); 146 | return data; 147 | } 148 | 149 | async getArchiveList(time) { 150 | const data = await this.postsRepository 151 | .createQueryBuilder('post') 152 | .where('status=:status', { status: 'publish' }) 153 | .andWhere(`DATE_FORMAT(update_time, '%Y年%m')=:time`, { time: time }) 154 | .orderBy('update_time', 'DESC') 155 | .getRawMany(); 156 | return data; 157 | } 158 | 159 | async remove(id) { 160 | const existPost = await this.postsRepository.findOne(id); 161 | if (!existPost) { 162 | throw new HttpException(`id为${id}的文章不存在`, HttpStatus.BAD_REQUEST); 163 | } 164 | return await this.postsRepository.remove(existPost); 165 | } 166 | } 167 | --------------------------------------------------------------------------------