feat: 迁移最新代码

master
luoer 2023-08-01 17:27:37 +08:00
parent 6327960a60
commit 7e7b6152f7
82 changed files with 890 additions and 6676 deletions

36
.env
View File

@ -1,20 +1,26 @@
# ========================================================================================
# 应用配置
# ========================================================================================
# 应用名称
APP_TITLE = 绝弹应用
# 应用副标题
APP_SUBTITLE = 快速构建NestJS应用的模板工具
# 服务端口
SERVER_PORT = 3030
# 服务地址
SERVER_HOST = 0.0.0.0
# 服务域名
SERVER_URL = http://127.0.0.1
# 接口地址
SERVER_OPENAPI_URL = /openapi
APP_TITLE = 绝弹应用
APP_SUBTITLE = 快速构建NestJS应用的模板工具
# ========================================================================================
# 数据库配置
# ========================================================================================
# 数据库类型
DB_TYPE = sqlite
# sqlite数据库地址
DB_SQLITE_PATH = content/database/database.sqlite
DB_SQLITE_PATH = ./database/db.sqlite
# mysql数据库地址
DB_MYSQL_HOST = 127.0.0.1
# mysql数据库端口
@ -26,4 +32,18 @@ DB_MYSQL_PASSWORD = test1
# mysql数据库名称
DB_MYSQL_DATABASE = test1
UPLOAD_FOLDER = content/upload
# ========================================================================================
# 上传和静态文件配置
# ========================================================================================
# 上传文件目录
UPLOAD_DIR = ./uploads
# 静态文件目录
STATIC_DIR = ./public
# ========================================================================================
# 分页配置
# ========================================================================================
# 默认页码
DEFAULT_PAGE = 1
# 默认每页数量
DEFAULT_SIZE = 10

View File

@ -39,6 +39,15 @@ SwaggerModule.setup('openapi', app, document);
}
```
## 权限认证
1. 依赖
```bash
pnpm i @nestjs/passport passport passport-local passport-jwt
```
路径:/auth/login - localguard - localService.validate - jwtService.sign
## 配置文件
1. 安装依赖

Binary file not shown.

BIN
database/db.sqlite Normal file

Binary file not shown.

View File

@ -20,7 +20,7 @@
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"orm": "typeorm-ts-node-esm -d ./src/features/typeorm/config/index.ts"
"orm": "typeorm-ts-node-esm -d ./src/features/typeorm/datasource/index.ts"
},
"prettier": {
"printWidth": 120,

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +1,21 @@
import { ClassSerializerInterceptor, Global, Module } from '@nestjs/common';
import { APP_FILTER, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import {
AllExecptionFilter,
BaseModule,
ConfigModule,
HttpExecptionFilter,
LoggerInterceptor,
LoggerModule,
MulterModule,
ResponseInterceptor,
ServeStaticModule,
TypeormModule,
ValidationExecptionFilter,
validationPipeFactory,
} from './features';
import { AuthModule, UserModule } from './modules';
import { PostModule } from './modules/post/post.module';
import { RoleModule } from './modules/role/role.module';
import { UploadModule } from './modules/upload/upload.module';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { PostModule } from '@/modules/post';
import { RoleModule } from '@/modules/role';
import { UploadModule } from '@/modules/upload';
import { PermissionModule } from '@/modules/permission';
import { PermissionGuard } from '@/features/permission/permission.guard';
import { ConfigModule } from '@/config';
import { LoggerInterceptor, LoggerModule } from '@/features/logger';
import { ServeStaticModule } from '@/features/static';
import { BaseModule } from '@/features/base';
import { AllExecptionFilter, HttpExecptionFilter } from '@/features/exception';
import { ResponseInterceptor } from '@/features/response';
import { TypeormModule } from '@/features/typeorm';
import { validationPipeFactory, ValidationExecptionFilter } from '@/features/validation';
import { JwtModule } from '@nestjs/jwt';
import { AuthModule, JwtGuard } from '@/modules/auth';
import { UserModule } from '@/modules/user';
@Global()
@Module({
@ -38,10 +36,6 @@ import { UploadModule } from './modules/upload/upload.module';
* ()
*/
BaseModule,
/**
* ()
*/
MulterModule,
/**
* ORM
*/
@ -54,6 +48,10 @@ import { UploadModule } from './modules/upload/upload.module';
*
*/
AuthModule,
/**
* JWT
*/
JwtModule,
/**
*
*/
@ -66,6 +64,10 @@ import { UploadModule } from './modules/upload/upload.module';
*
*/
PostModule,
/**
*
*/
PermissionModule,
],
providers: [
/**
@ -124,6 +126,20 @@ import { UploadModule } from './modules/upload/upload.module';
provide: APP_FILTER,
useClass: ValidationExecptionFilter,
},
/**
* JWT()
*/
{
provide: APP_GUARD,
useClass: JwtGuard,
},
/**
* ()
*/
{
provide: APP_GUARD,
useClass: PermissionGuard,
},
],
})
export class AppModule {}

View File

@ -0,0 +1,54 @@
export interface Config {
/**
*
*/
SERVER_PORT: number;
/**
*
*/
SERVER_HOST: string;
/**
* OPENAPI
*/
SERVER_OPENAPI_URL: string;
/**
*
*/
APP_TITLE: string;
/**
*
*/
APP_SUBTITLE: string;
/**
*
*/
DB_TYPE: string;
/**
* SQLite
*/
DB_SQLITE_PATH: string;
/**
*
*/
UPLOAD_DIR: string;
/**
* URL
*/
UPLOAD_URL: string;
/**
*
*/
STATIC_DIR: string;
/**
*
*/
DEFAULT_PAGE: number;
/**
*
*/
DEFAULT_SIZE: number;
/**
* JWT
*/
JWT_SECRET: string;
}

View File

@ -0,0 +1,6 @@
import { ConfigModule as _ConfigModule } from '@nestjs/config';
export const ConfigModule = _ConfigModule.forRoot({
envFilePath: ['.env.development', '.env.local', '.env'],
isGlobal: true,
});

2
src/config/index.ts Normal file
View File

@ -0,0 +1,2 @@
export * from './config.module';
export * from './config.interface';

View File

@ -1,5 +1,17 @@
/**
*
*/
export enum envKeys {
/**
*
*/
SERVER_HOST = 'SERVER_HOST',
/**
*
*/
SERVER_PORT = 'SERVER_PORT',
UPLOAD_FOLDER = 'UPLOAD_FOLDER',
/**
*
*/
UPLOAD_DIR = 'UPLOAD_DIR',
}

View File

@ -1,5 +1,20 @@
import { LoggerService } from '../logger';
import { Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Config } from '@/config';
export class BaseService {
constructor(protected readonly loogerService: LoggerService) {}
@Inject(ConfigService)
protected readonly configService: ConfigService<Config>;
/**
*
*/
formatPagination(page?: number, size?: number) {
const _page = page || this.configService.get('DEFAULT_PAGE', 1);
const _size = size || this.configService.get('DEFAULT_SIZE', 10);
return {
skip: (_page - 1) * _size,
take: _size,
};
}
}

View File

@ -1,5 +0,0 @@
export enum configEnum {
SERVER_HOST = 'SERVER_HOST',
SERVER_PORT = 'SERVER_PORT',
UPLOAD_FOLDER = 'UPLOAD_FOLDER',
}

View File

@ -1,6 +0,0 @@
import { ConfigModule as configModule } from '@nestjs/config';
export const ConfigModule = configModule.forRoot({
envFilePath: ['.env.local', '.env'],
isGlobal: true,
});

View File

@ -1,6 +0,0 @@
import { ConfigModule as configModule } from '@nestjs/config';
export const ConfigModule = configModule.forRoot({
envFilePath: ['.env.local', '.env'],
isGlobal: true,
});

View File

@ -9,7 +9,7 @@ export class AllExecptionFilter implements ExceptionFilter {
const response = ctx.getResponse<_Response>();
const message = exception.message;
const code = ResponseCode.UNKNOWN_ERROR;
console.log(exception);
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json(Response.create({ code, message, data: null }));
}
}

View File

@ -9,7 +9,6 @@ export class HttpExecptionFilter implements ExceptionFilter {
const response = ctx.getResponse<_Response>();
const code = exception.getStatus();
const message = exception.message;
response.status(code).json(Response.error(null, message));
}
}

View File

@ -1,12 +0,0 @@
export * from './base';
export * from './config';
export * from './exception';
export * from './logger';
export * from './multer';
export * from './pagination';
export * from './response';
export * from './static';
export * from './swagger';
export * from './typeorm';
export * from './validation';

View File

@ -1,6 +1,6 @@
import { CallHandler, ExecutionContext, Inject, NestInterceptor } from '@nestjs/common';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { Observable, tap } from 'rxjs';
import { LoggerService } from './logger.service';
export class LoggerInterceptor implements NestInterceptor {
@ -8,10 +8,14 @@ export class LoggerInterceptor implements NestInterceptor {
logger: LoggerService;
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
const controller = context.getClass();
const handler = context.getHandler();
const { method, url } = context.switchToHttp().getRequest<Request>();
this.logger.log(`${method} ${url} +1`, `${controller.name}.${handler.name}`);
return next.handle();
const now = Date.now();
return next.handle().pipe(
tap(() => {
const ms = Date.now() - now;
const scope = [context.getClass().name, context.getHandler().name].join('.');
this.logger.log(`${method} ${url}(${ms} ms) +1`, scope);
}),
);
}
}

View File

@ -1,5 +1,5 @@
import { ConsoleLogger, Injectable } from '@nestjs/common';
import { dayjs } from 'src/common';
import { dayjs } from '@/libs';
@Injectable()
export class LoggerService extends ConsoleLogger {

View File

@ -1,34 +0,0 @@
import { Global, Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MulterModule as _MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { join, parse } from 'path';
import { dayjs } from 'src/common';
@Global()
@Module({
imports: [
_MulterModule.registerAsync({
useFactory: async (configService) => {
const dest = configService.get('UPLOAD_FOLDER', './content/upload');
return {
storage: diskStorage({
destination: join(dest),
filename: (req, file, cb) => {
const yearMonth = dayjs().format('YYYY-MM');
const { name, ext } = parse(file.originalname);
const randomName = Array(32)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join('');
cb(null, `${yearMonth}/${name}-${randomName}${ext}`);
},
}),
};
},
inject: [ConfigService],
}),
],
exports: [_MulterModule],
})
export class MulterModule {}

View File

@ -1,7 +1,7 @@
import { Transform } from 'class-transformer';
import { IsNumber, IsOptional, Min } from 'class-validator';
export class paginationDto {
export class PaginationDto {
/**
*
*/
@ -11,6 +11,7 @@ export class paginationDto {
@Min(1)
@Transform(({ value }) => Number(value))
page: number;
/**
*
*/

View File

@ -0,0 +1,34 @@
import { SetMetadata } from '@nestjs/common';
export const PERMISSION_KEY = 'permission';
/**
*
*/
export const enum PermissionEnum {
/**
*
*/
CREATE = 'create',
/**
*
*/
READ = 'read',
/**
*
*/
UPDATE = 'update',
/**
*
*/
DELETE = 'delete',
}
/**
*
* @param permissions
* @returns
*/
export function Permission(...permissions: PermissionEnum[]) {
return SetMetadata(PERMISSION_KEY, permissions);
}

View File

@ -0,0 +1,29 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PERMISSION_KEY } from './permission.decorator';
import { UserService } from '@/modules/user';
@Injectable()
export class PermissionGuard implements CanActivate {
constructor(private reflector: Reflector, private userService: UserService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const controller = context.getClass();
const handler = context.getHandler();
const permissions = this.reflector.getAllAndMerge(PERMISSION_KEY, [controller, handler]);
if (!permissions || !permissions.length) {
return true;
}
const user = context.switchToHttp().getRequest().user;
if (!user) {
throw new UnauthorizedException('用户未登录');
}
const userPermissions = await this.userService.findUserPermissions(user.id);
const hasPermission = permissions.every((permission) => userPermissions.includes(permission));
if (!hasPermission) {
console.log(userPermissions, permissions);
throw new UnauthorizedException('权限不足');
}
return true;
}
}

View File

@ -1,5 +1,5 @@
/**
* HTTP
* HTTP
*/
export enum ResponseCode {
/**

View File

@ -3,41 +3,33 @@ import { SetMetadata } from '@nestjs/common';
/**
* KEY
*/
export const RESPONSE_KEY = 'resultor';
export const RESPONSE_KEY = 'APP:RESPONSE';
/**
*
*/
export enum ResponseType {
type RespondFn = {
(type: 'raw' | 'wrap' | 'pagination'): any;
/**
*
*
*/
WRAP = 'wrap',
RAW: 'raw';
/**
*
*
*/
RAW = 'raw',
WRAP: 'wrap';
/**
*
* `[data, total]`
*/
PAGINATION = 'pagination',
}
/**
*
*/
export class ResponseOptions {
/**
* wrap
*/
type?: ResponseType = ResponseType.WRAP;
}
PAGINATION: 'pagination';
};
/**
*
* @param options
* @param type
* @returns
*/
export const Responsing = (options: ResponseOptions) => {
return SetMetadata(RESPONSE_KEY, { ...ResponseOptions, ...options });
};
export const Respond = <RespondFn>((type = 'wrap') => {
return SetMetadata(RESPONSE_KEY, type);
});
Respond.RAW = 'raw';
Respond.WRAP = 'wrap';
Respond.PAGINATION = 'pagination';

View File

@ -2,27 +2,46 @@ import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nes
import { Reflector } from '@nestjs/core';
import { Observable, map } from 'rxjs';
import { Response } from './response';
import { RESPONSE_KEY, ResponseType } from './response.decorator';
import { RESPONSE_KEY, Respond } from './response.decorator';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';
import { Config } from '@/config';
@Injectable()
export class ResponseInterceptor implements NestInterceptor {
constructor(private reflector: Reflector) {}
constructor(private reflector: Reflector, private configService: ConfigService<Config>) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const controller = context.getClass();
const handler = context.getHandler();
const metadata = this.reflector.getAllAndOverride(RESPONSE_KEY, [controller, handler]);
const maper = (data: any) => {
if (metadata?.type === ResponseType.RAW) {
return data;
}
if (data instanceof Response) {
return data;
}
return Response.success(data);
};
return next.handle().pipe(map(maper));
const type = this.reflector.getAllAndOverride(RESPONSE_KEY, [controller, handler]);
return next.handle().pipe(
map((data: any) => {
if (type === Respond.RAW) {
return data;
}
if (type === Respond.PAGINATION) {
const request = context.switchToHttp().getRequest<Request>();
const [list, total] = data;
if (request.query.meta) {
const page = Number(request.query.page || this.configService.get('DEFAULT_PAGE', 1));
const size = Number(request.query.size || this.configService.get('DEFAULT_SIZE', 10));
return Response.success({
data: list,
meta: {
page,
size,
total,
},
});
}
return Response.success({ data: list, total });
}
if (data instanceof Response) {
return data;
}
return Response.success({ data });
}),
);
}
}

View File

@ -14,6 +14,7 @@ export class Response<T = any> {
example: 2000,
})
code?: ResponseCode;
/**
*
* @example '请求成功'
@ -23,29 +24,39 @@ export class Response<T = any> {
example: '请求成功',
})
message?: string;
/**
*
* @example 1
*/
@ApiProperty({})
data: T;
/**
*
* @example { total: 100 }
*/
meta?: any;
/**
*
*/
total?: number;
/**
*
*/
static success(data: any, message = '请求成功') {
return this.create({ code: ResponseCode.SUCESS, message, data });
static success({ code = ResponseCode.SUCESS, message = '请求成功', ...rest }: Response = {} as any) {
return this.create({ code, message, ...rest });
}
/**
*
*/
static error(data = null, message = '请求失败') {
return this.create({ code: ResponseCode.ERROR, message, data });
}
/**
*
*/

View File

@ -1,12 +1,18 @@
import { ServeStaticModule as module } from '@nestjs/serve-static';
import { join } from 'path';
import { ConfigService } from '@nestjs/config';
import { ServeStaticModule as _ServeStaticModule } from '@nestjs/serve-static';
import { Config } from '@/config';
export const ServeStaticModule = module.forRoot(
{
rootPath: join(process.cwd(), 'content/upload'),
serveRoot: '/upload',
export const ServeStaticModule = _ServeStaticModule.forRootAsync({
useFactory: (configService: ConfigService<Config>) => {
return [
{
rootPath: configService.get<string>('UPLOAD_DIR', 'uploads'),
serveRoot: configService.get<string>('UPLOAD_URL', '/uploads'),
},
{
rootPath: configService.get<string>('STATIC_DIR', 'public'),
},
];
},
{
rootPath: join(process.cwd(), 'public'),
},
);
inject: [ConfigService],
});

View File

@ -1,9 +1,10 @@
import { INestApplication } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Config } from '@/config';
export const initSwagger = (app: INestApplication) => {
const configService = app.get(ConfigService);
const configService = app.get(ConfigService<Config>);
const openapiUrl = configService.get<string>('SERVER_OPENAPI_URL', 'openapi');
const appTitle = configService.get<string>('APP_TITLE', 'Apptify');
const appSubtitle = configService.get<string>('APP_SUBTITLE', 'Apptify');
@ -13,6 +14,11 @@ export const initSwagger = (app: INestApplication) => {
.setDescription('Openapi 3.0文档')
.setExternalDoc('JSON数据', `${openapiUrl}.json`)
.addTag('user', '用户管理')
.addTag('auth', '认证管理')
.addTag('role', '角色管理')
.addTag('permission', '权限管理')
.addTag('post', '文章管理')
.addTag('upload', '文件上传')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup(openapiUrl, app, document, {

View File

@ -9,7 +9,7 @@ import { MockPosts1685026010848 } from '../migrations/1685026010848-MockPosts';
*/
export const baseConfig: DataSourceOptions = {
type: 'sqlite',
database: 'content/database/database.sqlite',
database: 'database/db.sqlite',
logging: false,
namingStrategy: new SnakeNamingStrategy(),
};
@ -21,7 +21,7 @@ export const ormConfig: TypeOrmModuleOptions = {
...baseConfig,
synchronize: true,
autoLoadEntities: true,
logging: true,
logging: false,
};
/**

View File

@ -2,7 +2,7 @@ import { Exclude } from 'class-transformer';
import { Column, CreateDateColumn, DeleteDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
/**
* , id
* , id
*/
@Entity({ orderBy: { id: 'DESC' } })
export class BaseEntity {
@ -12,35 +12,30 @@ export class BaseEntity {
*/
@PrimaryGeneratedColumn({ comment: '自增ID' })
id: number;
/**
*
* @example "2022-01-01 10:10:10"
*/
@CreateDateColumn({ comment: '创建时间' })
createdAt: Date;
/**
* ID
* @example 1
*/
@Column({ comment: '创建人' })
@Column({ comment: '创建人', nullable: true })
createdBy: number;
/**
*
* @example "2022-01-02 11:11:11"
*/
@UpdateDateColumn({ comment: '更新时间' })
updatedAt: Date;
/**
* ID
* @example 1
*/
@Column({ comment: '更新人' })
@Column({ comment: '更新人', nullable: true })
updatedBy: number;
/**
*
* @example "2022-01-03 12:12:12"
@ -48,12 +43,11 @@ export class BaseEntity {
@Exclude()
@DeleteDateColumn({ comment: '删除时间' })
deleteddAt: Date;
/**
* ID
* @example 1
*/
@Exclude()
@Column({ comment: '删除人' })
@Column({ comment: '删除人', nullable: true })
deletedBy: number;
}

View File

@ -1,9 +1,30 @@
import { TypeOrmModule } from '@nestjs/typeorm';
import { ormConfig } from './config';
export * from './config';
import { ormConfig } from './datasource';
import { ConfigService } from '@nestjs/config';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import { Config } from '@/config';
export * from './datasource';
export * from './entities/base';
/**
*
*/
export const TypeormModule = TypeOrmModule.forRoot(ormConfig);
export const TypeormModule = TypeOrmModule.forRootAsync({
useFactory: (configService: ConfigService<Config>) => {
const type = configService.get<string>('DB_TYPE', 'sqlite');
if (type === 'sqlite') {
const database = configService.get<string>('DB_SQLITE_PATH', 'database/db.sqlite');
return {
type,
database,
synchronize: true,
autoLoadEntities: true,
namingStrategy: new SnakeNamingStrategy(),
};
}
if (type === 'mysql') {
}
return ormConfig;
},
inject: [ConfigService],
});

View File

@ -1,20 +1,19 @@
import mock from 'mockjs';
import { MigrationInterface, QueryRunner } from 'typeorm';
import { v4 } from 'uuid';
export class CreateUsersTable1682693329275 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const numbers = Array(20).fill(0);
const users = numbers.map(() => {
const guid = `"${v4()}"`;
const username = `"${mock.Random.name()}"`;
const nickname = `"${mock.Random.cname()}"`;
const description = `"${mock.Random.csentence(100, 120)}"`;
const avatar = `"https://picsum.photos/400/300"`;
const password = `"123456"`;
return [guid, username, nickname, description, avatar, password];
const createdAt = `"${mock.Random.datetime()}"`;
return [username, nickname, description, avatar, password, createdAt];
});
const fields = ['guid', 'username', 'nickname', 'description', 'avatar', 'password'].join(',');
const fields = ['username', 'nickname', 'description', 'avatar', 'password', 'created_at'].join(',');
const values = users.map((user) => `(${user.join(',')})`).join(',');
await queryRunner.query(`INSERT INTO user (${fields}) VALUES ${values}`);
}

View File

@ -1,18 +1,16 @@
import mock from 'mockjs';
import { MigrationInterface, QueryRunner } from 'typeorm';
import { v4 } from 'uuid';
export class MockPosts1685026010848 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const numbers = Array(20).fill(0);
const users = numbers.map(() => {
const guid = `"${v4()}"`;
const title = `"${mock.Random.csentence(10, 30)}"`;
const description = `"${mock.Random.csentence(100, 120)}"`;
const content = `"${mock.Random.csentence(200, 220)}"`;
return [guid, title, description, content];
return [title, description, content];
});
const fields = ['guid', 'title', 'description', 'content'].join(',');
const fields = ['title', 'description', 'content'].join(',');
const values = users.map((user) => `(${user.join(',')})`).join(',');
await queryRunner.query(`INSERT INTO post (${fields}) VALUES ${values}`);
}

View File

@ -2,48 +2,42 @@ import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import relativeTime from 'dayjs/plugin/relativeTime';
export const DATETIME = 'YYYY-MM-DD HH:mm:ss';
export const DATE = 'YYYY-MM-DD';
export const TIME = 'HH:mm:ss';
/**
*
* 使
*/
dayjs.locale('zh-cn');
/**
*
* 使
* @see https://dayjs.gitee.io/docs/zh-CN/plugin/relative-time
*/
dayjs.extend(relativeTime);
/**
*
*
*/
dayjs.DATETIME = DATETIME;
dayjs.DATETIME = 'YYYY-MM-DD HH:mm:ss';
/**
*
*/
dayjs.DATE = DATE;
dayjs.DATE = 'YYYY-MM-DD';
/**
*
*/
dayjs.TIME = TIME;
dayjs.TIME = 'HH:mm:ss';
/**
* format
*/
dayjs.prototype._format = dayjs.prototype.format;
/**
* formatformat使
*/
dayjs.prototype._format = dayjs.prototype.format;
dayjs.prototype.format = function (format?: string) {
if (format) {
return this._format(format);
}
return this._format(dayjs.DATETIME);
dayjs.prototype.format = function (format = dayjs.DATETIME) {
return this._format(format);
};
export { dayjs };

View File

@ -16,6 +16,9 @@ declare module 'dayjs' {
*/
export let TIME: 'HH:mm:ss';
/**
* format
*/
interface Dayjs {
_format: (format?: string) => string;
}

View File

@ -1,6 +1,7 @@
import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { initSwagger, LoggerService } from 'src/features';
import { initSwagger } from '@/features/swagger';
import { LoggerService } from '@/features/logger';
import { AppModule } from './app.module';
async function bootstrap() {

View File

@ -1,21 +1,21 @@
import { Body, Controller, HttpStatus, Post, Request, UseGuards } from '@nestjs/common';
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { Public } from './jwt';
import { LocalAuthDto, LocalAuthGuard } from './local';
import { AuthUserDto } from './dto/auth-user.dto';
@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private accountService: AuthService) {}
constructor(private authService: AuthService) {}
@Public()
@UseGuards(LocalAuthGuard)
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiResponse({ status: HttpStatus.UNAUTHORIZED, description: '账号或密码错误' })
@ApiResponse({ status: HttpStatus.OK, description: '登录成功' })
@ApiResponse({ description: '登录成功' })
@ApiOperation({ summary: '账号登录', operationId: 'login' })
login(@Request() req: any, @Body() user: LocalAuthDto) {
this.accountService.sign(req.user);
login(@Body() user: AuthUserDto) {
return this.authService.signIn(user);
}
}

View File

@ -2,13 +2,12 @@ import { Module } from '@nestjs/common';
import { UserModule } from '../user';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtAuthService, JwtModule } from './jwt';
import { LocalAuthService } from './local';
import { JwtModule } from './jwt';
@Module({
imports: [UserModule, JwtModule],
providers: [AuthService, LocalAuthService, JwtAuthService],
exports: [AuthService],
controllers: [AuthController],
imports: [UserModule, JwtModule],
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}

View File

@ -1,22 +1,21 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user';
import { AuthUserDto } from './dto/auth-user.dto';
@Injectable()
export class AuthService {
constructor(private userService: UserService, private jwtService: JwtService) {}
// 验证用户
async auth(username: string, password: string): Promise<any> {
const user = await this.userService.findOne({ username });
if (!user) return null;
if (user.password !== password) return null;
return user;
}
// 令牌签名
async sign(user: any) {
const payload = { id: user.id, username: user.username };
return this.jwtService.sign(payload);
async signIn(authUserDto: AuthUserDto) {
const user = await this.userService.findByUsername(authUserDto.username);
const { password, ...result } = user;
if (!user) {
throw new UnauthorizedException('用户名不存在');
}
if (password !== authUserDto.password) {
throw new UnauthorizedException('密码错误');
}
return this.jwtService.signAsync(result);
}
}

View File

@ -1,6 +1,6 @@
import { IsString } from 'class-validator';
export class LocalAuthDto {
export class AuthUserDto {
/**
*
* @example admin
@ -11,5 +11,6 @@ export class LocalAuthDto {
*
* @example 123456
*/
@IsString()
password: string;
}

View File

@ -2,3 +2,4 @@ export * from './auth.controller';
export * from './auth.module';
export * from './auth.service';
export * from './jwt';
export * from './dto/auth-user.dto';

View File

@ -1,4 +1,3 @@
export * from './jwt-decorator';
export * from './jwt-guard';
export * from './jwt-module';
export * from './jwt-service';

View File

@ -6,6 +6,8 @@ import { SetMetadata } from '@nestjs/common';
export const PUBLICK_KEY = 'isPublic';
/**
*
* 访
*/
export const Public = (idPublic = true) => SetMetadata(PUBLICK_KEY, idPublic);
export function Public(isPublic = true) {
return SetMetadata(PUBLICK_KEY, isPublic);
}

View File

@ -1,30 +1,41 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { APP_GUARD, Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { PUBLICK_KEY } from './jwt-decorator';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
export class JwtGuard implements CanActivate {
constructor(private reflector: Reflector, private jwtService: JwtService, private configService: ConfigService) {}
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);
if (token) {
const secret = this.configService.get('JWT_SECRET');
const user = await this.jwtService.verifyAsync(token, { secret });
request['user'] = user;
}
const metadata = [context.getClass(), context.getHandler()];
const isPublic = this.reflector.getAllAndOverride(PUBLICK_KEY, metadata);
if (isPublic === undefined || isPublic) {
return true;
}
if (isPublic !== false && request.method.toLowerCase() === 'GET') {
return true;
}
if (!token) {
throw new UnauthorizedException('请先登录');
}
return true;
}
const routeMethod = context.switchToHttp().getRequest<Request>().method;
if (routeMethod === 'GET' && isPublic !== false) return true;
if (isPublic) return true;
return super.canActivate(context);
extractTokenFromHeader(request: Request): string {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
if (type === 'Bearer') {
return token;
}
return undefined;
}
}
export const AppJwtGuard = {
provide: APP_GUARD,
useClass: JwtAuthGuard,
};

View File

@ -1,8 +1,15 @@
import { JwtModule as Jwt } from '@nestjs/jwt';
import { Config } from '@/config';
import { ConfigService } from '@nestjs/config';
import { JwtModule as _JwtModule } from '@nestjs/jwt';
export const JwtModule = Jwt.register({
secret: 'secret',
signOptions: {
expiresIn: '60000s',
export const JwtModule = _JwtModule.registerAsync({
useFactory: (configService: ConfigService<Config>) => {
return {
secret: configService.get('JWT_SECRET', 'todo'),
signOptions: {
expiresIn: '60000s',
},
};
},
inject: [ConfigService],
});

View File

@ -1,18 +0,0 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtAuthService extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'dsfsfs',
});
}
async validate({ id, username }) {
return { id, username };
}
}

View File

@ -1,3 +0,0 @@
export * from './local-guard';
export * from './local-service';
export * from './local.dto';

View File

@ -1,5 +0,0 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

View File

@ -1,22 +0,0 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { UserService } from 'src/modules/user/user.service';
@Injectable()
export class LocalAuthService extends PassportStrategy(Strategy) {
constructor(private readonly userService: UserService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.userService.findOne({ username });
if (!user) {
throw new UnauthorizedException('用户名不存在');
}
if (user.password !== password) {
throw new UnauthorizedException('密码错误');
}
return true;
}
}

View File

@ -1,2 +0,0 @@
export * from './auth';
export * from './user';

View File

@ -0,0 +1,13 @@
import { IsOptional, IsString } from 'class-validator';
export class CreatePermissionDto {
@IsString()
name: string;
@IsString()
slug: string;
@IsOptional()
@IsString()
description: string;
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreatePermissionDto } from './create-permission.dto';
export class UpdatePermissionDto extends PartialType(CreatePermissionDto) {}

View File

@ -0,0 +1,31 @@
import { BaseEntity } from '@/features/typeorm';
import { Role } from '@/modules/role/entities/role.entity';
import { Column, Entity, ManyToMany } from 'typeorm';
@Entity()
export class Permission extends BaseEntity {
/**
*
* @example '文章列表'
*/
@Column({ comment: '权限名称' })
name: string;
/**
*
* @example 'post:list'
*/
@Column({ comment: '权限标识' })
slug: string;
/**
*
* @example '文章列表'
*/
@Column({ comment: '权限描述', nullable: true })
description: string;
/**
*
* @example '文章列表'
*/
@ManyToMany(() => Role, (role) => role.permissions)
roles: Role[];
}

View File

@ -0,0 +1,6 @@
export * from './dto/create-permission.dto';
export * from './dto/update-permission.dto';
export * from './entities/permission.entity';
export * from './permission.controller';
export * from './permission.module';
export * from './permission.service';

View File

@ -0,0 +1,43 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { PermissionService } from './permission.service';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Respond } from '@/features/response';
@ApiTags('permission')
@Controller('permissions')
export class PermissionController {
constructor(private readonly permissionService: PermissionService) {}
@Post()
@ApiOperation({ summary: '创建权限', operationId: 'addPermission' })
create(@Body() createPermissionDto: CreatePermissionDto) {
return this.permissionService.create(createPermissionDto);
}
@Get()
@Respond(Respond.PAGINATION)
@ApiOperation({ summary: '批量查询权限', operationId: 'getPermissions' })
findAll() {
return this.permissionService.findAll();
}
@Get(':id')
@ApiOperation({ summary: '查询权限', operationId: 'getPermission' })
findOne(@Param('id') id: string) {
return this.permissionService.findOne(+id);
}
@Patch(':id')
@ApiOperation({ summary: '更新权限', operationId: 'updatePermission' })
update(@Param('id') id: string, @Body() updatePermissionDto: UpdatePermissionDto) {
return this.permissionService.update(+id, updatePermissionDto);
}
@Delete(':id')
@ApiOperation({ summary: '删除权限', operationId: 'delPermission' })
remove(@Param('id') id: string) {
return this.permissionService.remove(+id);
}
}

View File

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { PermissionService } from './permission.service';
import { PermissionController } from './permission.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Permission } from './entities/permission.entity';
@Module({
imports: [TypeOrmModule.forFeature([Permission])],
controllers: [PermissionController],
providers: [PermissionService],
})
export class PermissionModule {}

View File

@ -0,0 +1,33 @@
import { Injectable } from '@nestjs/common';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Permission } from './entities/permission.entity';
import { Repository } from 'typeorm';
@Injectable()
export class PermissionService {
constructor(@InjectRepository(Permission) private readonly permissionRepository: Repository<Permission>) {}
async create(createPermissionDto: CreatePermissionDto) {
const permission = this.permissionRepository.create(createPermissionDto);
await this.permissionRepository.save(permission);
return permission.id;
}
findAll() {
return this.permissionRepository.findAndCount();
}
findOne(id: number) {
return `This action returns a #${id} permission`;
}
update(id: number, updatePermissionDto: UpdatePermissionDto) {
return `This action updates a #${id} permission`;
}
remove(id: number) {
return `This action removes a #${id} permission`;
}
}

View File

@ -1,4 +1,4 @@
import { BaseEntity } from 'src/features';
import { BaseEntity } from '@/features/typeorm';
import { User } from 'src/modules/user';
import { Column, Entity, ManyToMany } from 'typeorm';

View File

@ -0,0 +1,6 @@
export * from './dto/create-post.dto';
export * from './dto/update-post.dto';
export * from './entities/post.entity';
export * from './post.controller';
export * from './post.module';
export * from './post.service';

View File

@ -2,32 +2,39 @@ import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/commo
import { PostService } from './post.service';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
@Controller('post')
@ApiTags('post')
export class PostController {
constructor(private readonly postService: PostService) {}
@Post()
@ApiOperation({ summary: '创建文章', operationId: 'addPost' })
create(@Body() createPostDto: CreatePostDto) {
return this.postService.create(createPostDto);
}
@Get()
@ApiOperation({ summary: '批量查询文章', operationId: 'getPosts' })
findAll() {
return this.postService.findAll();
}
@Get(':id')
@ApiOperation({ summary: '查询文章', operationId: 'getPost' })
findOne(@Param('id') id: string) {
return this.postService.findOne(+id);
}
@Patch(':id')
@ApiOperation({ summary: '更新文章', operationId: 'updatePost' })
update(@Param('id') id: string, @Body() updatePostDto: UpdatePostDto) {
return this.postService.update(+id, updatePostDto);
}
@Delete(':id')
@ApiOperation({ summary: '删除文章', operationId: 'delPost' })
remove(@Param('id') id: string) {
return this.postService.remove(+id);
}

View File

@ -1 +1,18 @@
export class CreateRoleDto {}
import { Permission } from '@/modules/permission/entities/permission.entity';
import { IsInt, IsOptional, IsString } from 'class-validator';
export class CreateRoleDto {
@IsString()
name: string;
@IsString()
slug: string;
@IsString()
@IsOptional()
description?: string;
@IsOptional()
@IsInt({ each: true })
permissions?: Permission[];
}

View File

@ -1,11 +1,39 @@
import { BaseEntity } from '@/features/typeorm';
import { Permission } from '@/modules/permission/entities/permission.entity';
import { User } from 'src/modules/user';
import { Entity, ManyToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Column, Entity, JoinTable, ManyToMany } from 'typeorm';
@Entity()
export class Role {
@PrimaryGeneratedColumn()
id: number;
export class Role extends BaseEntity {
/**
*
* @example '管理员'
*/
@Column({ comment: '角色名称' })
name: string;
/**
*
* @example 'admin'
*/
@Column({ comment: '角色标识' })
slug: string;
/**
*
* @example '拥有所有权限'
*/
@Column({ comment: '角色描述', nullable: true })
description: string;
/**
*
* @example [1, 2, 3]
*/
@JoinTable()
@ManyToMany(() => Permission, (permission) => permission.roles)
permissions: Permission[];
/**
*
* @example [1, 2, 3]
*/
@ManyToMany(() => User, (user) => user.roles)
user: User;
}

View File

@ -0,0 +1,6 @@
export * from './dto/create-role.dto';
export * from './dto/update-role.dto';
export * from './entities/role.entity';
export * from './role.controller';
export * from './role.module';
export * from './role.service';

View File

@ -1,35 +1,42 @@
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { RoleService } from './role.service';
import { Respond } from '@/features/response';
@ApiTags('role')
@Controller('role')
@Controller('roles')
export class RoleController {
constructor(private readonly roleService: RoleService) {}
@Post()
@ApiOperation({ summary: '创建角色', operationId: 'addRole' })
create(@Body() createRoleDto: CreateRoleDto) {
return this.roleService.create(createRoleDto);
}
@Get()
@Respond(Respond.PAGINATION)
@ApiOperation({ summary: '批量查询角色', operationId: 'getRoles' })
findAll() {
return this.roleService.findAll();
}
@Get(':id')
@ApiOperation({ summary: '查询角色', operationId: 'getRole' })
findOne(@Param('id') id: string) {
return this.roleService.findOne(+id);
}
@Patch(':id')
@ApiOperation({ summary: '更新角色', operationId: 'updateRole' })
update(@Param('id') id: string, @Body() updateRoleDto: UpdateRoleDto) {
return this.roleService.update(+id, updateRoleDto);
}
@Delete(':id')
@ApiOperation({ summary: '删除角色', operationId: 'delRole' })
remove(@Param('id') id: string) {
return this.roleService.remove(+id);
}

View File

@ -1,15 +1,27 @@
import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';
@Injectable()
export class RoleService {
create(createRoleDto: CreateRoleDto) {
return 'This action adds a new role';
constructor(@InjectRepository(Role) private readonly roleRepository: Repository<Role>) {}
async create(createRoleDto: CreateRoleDto) {
const role = this.roleRepository.create(createRoleDto);
if (createRoleDto.permissions) {
role.permissions = createRoleDto.permissions.map((id) => ({ id })) as any;
}
await this.roleRepository.save(role);
return role.id;
}
findAll() {
return `This action returns all role`;
return this.roleRepository.findAndCount({
relations: ['permissions'],
});
}
findOne(id: number) {

View File

@ -1,46 +1,42 @@
import { BaseEntity, Column, Entity } from 'typeorm';
import { BaseEntity } from '@/features/typeorm';
import { Column, Entity } from 'typeorm';
@Entity()
export class Upload extends BaseEntity {
/**
*
* @example 1024
*/
@Column({ comment: '文件大小' })
size: number;
/**
*
* @example "xxx.jpg"
*/
@Column({ comment: '文件名' })
name: string;
/**
*
* @example 1024
*/
@Column({ comment: '文件大小' })
size: number;
/**
*
* @example "image/jpeg"
*/
@Column({ comment: '文件类型' })
mimetype: string;
/**
*
* @example "upload/2021/10/01/xxx.jpg"
* @example "/upload/2021/10/01/xxx.jpg"
*/
@Column({ comment: '文件路径' })
path: string;
/**
*
* @example "xxx"
*/
@Column({ comment: '文件哈希' })
hash: string;
/**
*
* @example ".jpg"
*/
@Column({ comment: '文件后缀' })
ext: string;
extension: string;
}

View File

@ -0,0 +1,6 @@
export * from './dto/create-upload.dto';
export * from './dto/update-upload.dto';
export * from './entities/upload.entity';
export * from './upload.controller';
export * from './upload.module';
export * from './upload.service';

View File

@ -1,9 +1,8 @@
import { Body, Controller, Delete, Get, Param, Patch, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { Controller, Delete, Get, Param, Patch, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Respond } from '@/features/response';
@ApiTags('upload')
@Controller('upload')
@ -13,27 +12,31 @@ export class UploadController {
@Post()
@UseInterceptors(FileInterceptor('file'))
@ApiOperation({ summary: '上传文件', operationId: 'upload' })
create(@Body() createUploadDto: CreateUploadDto, @UploadedFile() file: Express.Multer.File) {
file.filename;
return this.uploadService.create(createUploadDto);
create(@UploadedFile() file: Express.Multer.File) {
return this.uploadService.create(file);
}
@Get()
@Respond(Respond.PAGINATION)
@ApiOperation({ summary: '批量查询', operationId: 'getUploads' })
findAll() {
return this.uploadService.findAll();
}
@Get(':id')
@ApiOperation({ summary: '查询', operationId: 'getUpload' })
findOne(@Param('id') id: string) {
return this.uploadService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateUploadDto: UpdateUploadDto) {
return this.uploadService.update(+id, updateUploadDto);
@ApiOperation({ summary: '更新', operationId: 'updateUpload' })
update() {
return this.uploadService.update();
}
@Delete(':id')
@ApiOperation({ summary: '删除', operationId: 'delUpload' })
remove(@Param('id') id: string) {
return this.uploadService.remove(+id);
}

View File

@ -1,9 +1,37 @@
import { Module } from '@nestjs/common';
import { UploadController } from './upload.controller';
import { UploadService } from './upload.service';
import { MulterModule } from '@nestjs/platform-express';
import { ConfigService } from '@nestjs/config';
import dayjs from 'dayjs';
import { join, parse } from 'path';
import { diskStorage } from 'multer';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Upload } from './entities/upload.entity';
@Module({
imports: [],
imports: [
TypeOrmModule.forFeature([Upload]),
MulterModule.registerAsync({
useFactory: async (configService) => {
const dest = configService.get('UPLOAD_FOLDER', './public/upload');
const storage = diskStorage({
destination: join(dest),
filename: (req, file, cb) => {
const yearMonth = dayjs().format('YYYY-MM');
const { name, ext } = parse(file.originalname);
const randomName = Array(32)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join('');
cb(null, `${yearMonth}/${name}-${randomName}${ext}`);
},
});
return { storage };
},
inject: [ConfigService],
}),
],
controllers: [UploadController],
providers: [UploadService],
})

View File

@ -1,27 +1,34 @@
import { Injectable } from '@nestjs/common';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { Upload } from './entities/upload.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class UploadService {
constructor() {
console;
}
constructor(@InjectRepository(Upload) private readonly uploadRepository: Repository<Upload>) {}
create(createUploadDto: CreateUploadDto) {
return 'This action adds a new upload';
async create(file: Express.Multer.File) {
const upload = this.uploadRepository.create({
name: file.originalname,
mimetype: file.mimetype,
size: file.size,
hash: file.filename,
path: file.path,
});
await this.uploadRepository.save(upload);
return upload.id;
}
findAll() {
return `This action returns all upload`;
return this.uploadRepository.findAndCount();
}
findOne(id: number) {
return `This action returns a #${id} upload`;
}
update(id: number, updateUploadDto: UpdateUploadDto) {
return `This action updates a #${id} upload`;
update() {
return `This action updates a #${1} upload`;
}
remove(id: number) {

View File

@ -1,16 +1,37 @@
import { IsOptional, IsString } from 'class-validator';
import { Role } from '@/modules/role/entities/role.entity';
import { IsInt, IsOptional, IsString } from 'class-validator';
export class CreateUserDto {
@IsString({ message: '用户名不能为空' })
/**
*
* @example 'juetan'
*/
@IsString()
username: string;
/**
*
* @example 'password'
*/
@IsString()
password: string;
/**
*
* @example '绝弹'
*/
@IsString()
nickname: string;
@IsString()
/**
*
* @example './assets/222421415123.png '
*/
@IsOptional()
@IsString()
avatar: string;
/**
*
* @example [1, 2, 3]
*/
@IsOptional()
@IsInt({ each: true })
roles: Role[];
}

View File

@ -1,8 +1,9 @@
import { IntersectionType } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { paginationDto } from 'src/features';
import { IsOptional, IsString } from 'class-validator';
import { PaginationDto } from '@/features/pagination';
export class FindUserDto extends IntersectionType(paginationDto) {
export class FindUserDto extends IntersectionType(PaginationDto) {
@IsOptional()
@IsString()
name: string;
nickname: string;
}

View File

@ -1,25 +1,12 @@
import { ApiHideProperty } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';
import { BaseEntity } from 'src/features';
import { Post } from 'src/modules/post/entities/post.entity';
import { Role } from 'src/modules/role/entities/role.entity';
import { Column, Entity, ManyToMany } from 'typeorm';
import { BaseEntity } from '@/features/typeorm';
import { Post } from '@/modules/post';
import { Role } from '@/modules/role';
import { Column, Entity, JoinTable, ManyToMany } from 'typeorm';
@Entity()
@Entity({ orderBy: { id: 'DESC' } })
export class User extends BaseEntity {
/**
*
*/
@ApiHideProperty()
@ManyToMany(() => Post, (post) => post.author)
posts: Post[];
/**
*
*/
@ManyToMany(() => Role, (role) => role.user)
roles: Role[];
/**
*
* @example 'juetan'
@ -55,4 +42,26 @@ export class User extends BaseEntity {
@Exclude()
@Column({ length: 64 })
password: string;
/**
*
* @example 'example@mail.com'
*/
@Column({ length: 64, nullable: true })
email: string;
/**
*
*/
@ApiHideProperty()
@ManyToMany(() => Post, (post) => post.author)
@JoinTable()
posts: Post[];
/**
*
*/
@ManyToMany(() => Role, (role) => role.user)
@JoinTable()
roles: Role[];
}

View File

@ -1,24 +1,13 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UploadedFile,
UseInterceptors,
Version,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Version } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { BaseController, Pagination } from 'src/features';
import { Public } from '../auth/jwt';
import { Respond } from '@/features/response';
import { BaseController } from '@/features/base';
import { CreateUserDto, UpdateUserDto } from './dto';
import { FindUserDto } from './dto/find-user.dto';
import { User } from './entities';
import { UserService } from './user.service';
import { Permission, PermissionEnum } from '@/features/permission/permission.decorator';
import { Public } from '@/modules/auth/jwt/jwt-decorator';
@ApiTags('user')
@Controller('users')
@ -27,40 +16,37 @@ export class UserController extends BaseController {
super();
}
@UseInterceptors(FileInterceptor('avatar'))
@Post()
@ApiOperation({ summary: '创建用户', operationId: 'createUser' })
create(@Body() createUserDto: CreateUserDto, @UploadedFile() file: Express.Multer.File) {
createUserDto.avatar = `upload/${file.filename}`;
console.log(createUserDto, file);
@ApiOperation({ summary: '创建用户', operationId: 'addUser' })
create(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
}
@Public()
@Get()
@Public(false)
@Respond(Respond.PAGINATION)
@Permission(PermissionEnum.READ)
@ApiOkResponse({ isArray: true, type: User })
@ApiOperation({ summary: '批量查询', operationId: 'selectUsers' })
@ApiOperation({ summary: '批量查询', operationId: 'getUsers' })
async findMany(@Query() query: FindUserDto) {
const [data, total] = await this.userService.findAll(query);
const { page, size } = query;
return Pagination.wrap({ page, size, total, data });
return this.userService.findMany(query);
}
@Version('2')
@Get(':id')
@ApiOperation({ summary: '查询用户', operationId: 'selectUserv2' })
@ApiOperation({ summary: '查询用户', operationId: 'getUserv2' })
findOne(@Param('id') id: number) {
return this.userService.findOne(+id);
}
@Patch(':id')
@ApiOperation({ summary: '更新用户', operationId: 'updateUser' })
@ApiOperation({ summary: '更新用户', operationId: 'setUser' })
update(@Param('id') id: number, @Body() updateUserDto: UpdateUserDto) {
return this.userService.update(+id, updateUserDto);
}
@Delete(':id')
@ApiOperation({ summary: '删除用户', operationId: 'deleteUser' })
@ApiOperation({ summary: '删除用户', operationId: 'delUser' })
remove(@Param('id') id: number) {
return this.userService.remove(+id);
}

View File

@ -1,21 +1,25 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Pagination } from 'src/features';
import { Repository } from 'typeorm';
import { Like, Repository } from 'typeorm';
import { CreateUserDto, UpdateUserDto } from './dto';
import { FindUserDto } from './dto/find-user.dto';
import { User } from './entities';
import { BaseService } from '@/features/base';
@Injectable()
export class UserService {
constructor(@InjectRepository(User) private userRepository: Repository<User>) {}
export class UserService extends BaseService {
constructor(@InjectRepository(User) private userRepository: Repository<User>) {
super();
}
/**
*
*/
async create(createUserDto: CreateUserDto) {
console.log(createUserDto);
const user = this.userRepository.create(createUserDto);
if (createUserDto.roles) {
user.roles = createUserDto.roles.map((id) => ({ id })) as any;
}
await this.userRepository.save(user);
return user.id;
}
@ -23,9 +27,17 @@ export class UserService {
/**
*
*/
async findAll(dto: FindUserDto) {
const options = Pagination.optionize(dto);
return this.userRepository.findAndCount({ ...options, order: { createdAt: 'DESC' } });
async findMany(findUserdto: FindUserDto) {
const { nickname, page, size } = findUserdto;
const { skip, take } = this.formatPagination(page, size);
return this.userRepository.findAndCount({
skip,
take,
where: {
nickname: nickname && Like(`%${nickname}%`),
},
relations: ['roles'],
});
}
/**
@ -53,7 +65,22 @@ export class UserService {
/**
*
*/
find(username: string) {
return this.userRepository.findOne({ where: { username } });
findByUsername(username: string) {
return this.userRepository.findOneOrFail({ where: { username } });
}
/**
* id
*/
async findUserPermissions(id: number) {
const user = await this.userRepository.findOne({
where: { id },
relations: ['roles', 'roles.permissions'],
});
if (user) {
const permissions = user.roles.flatMap((role) => role.permissions);
return [...new Set(permissions.map((i) => i.slug))];
}
return [];
}
}

4
src/types/env.d.ts vendored
View File

@ -16,5 +16,9 @@ declare namespace NodeJS {
*
*/
NODE_ENV: 'development' | 'production' | 'test';
/**
*
*/
UPLOAD_DIR: string;
}
}

View File

@ -19,7 +19,7 @@
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"paths": {
"modules": ["./src/modules"]
"@/*": ["src/*"]
}
}
}

View File

@ -1,3 +1,8 @@
/**
* 使用 Webpack 时的配置文件
* @param {import('webpack').Configuration} config
* @returns
*/
module.exports = (config) => {
return config;
};