feat: first commit
This commit is contained in:
parent
3c78380f94
commit
b492be63bb
13
.env.development
Normal file
13
.env.development
Normal file
@ -0,0 +1,13 @@
|
||||
NODE_ENV=development
|
||||
|
||||
# 优先Sqlite3
|
||||
|
||||
# MYSQL 配置
|
||||
MYSQL_HOST='117.73.12.97'
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER='xcszny'
|
||||
MYSQL_PASSWD='Y123456a?'
|
||||
MYSQL_DATABASE='nest'
|
||||
|
||||
# JWT SALT
|
||||
JWT_SALT=.even_jwt_@@__
|
13
.env.production
Normal file
13
.env.production
Normal file
@ -0,0 +1,13 @@
|
||||
NODE_ENV=development
|
||||
|
||||
# 优先Sqlite3
|
||||
|
||||
# MYSQL 配置
|
||||
MYSQL_HOST='117.73.12.97'
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER='xcszny'
|
||||
MYSQL_PASSWD='Y123456a?'
|
||||
MYSQL_DATABASE='nest'
|
||||
|
||||
# JWT SALT
|
||||
JWT_SALT=.even_jwt_@@__
|
25
.eslintrc.js
Normal file
25
.eslintrc.js
Normal file
@ -0,0 +1,25 @@
|
||||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: 'tsconfig.json',
|
||||
tsconfigRootDir: __dirname,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
jest: true,
|
||||
},
|
||||
ignorePatterns: ['.eslintrc.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
};
|
56
.gitignore
vendored
Normal file
56
.gitignore
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
4
.prettierrc
Normal file
4
.prettierrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@ -0,0 +1,16 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
# 构建参数,在Jenkinsfile中构建镜像时定义
|
||||
ARG PROFILE
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 将dist文件夹中的内容复制出来
|
||||
COPY dist/ /app/
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 3000
|
||||
|
||||
# 启动应用
|
||||
CMD ["node", "main.js"]
|
60
Jenkinsfile
vendored
Normal file
60
Jenkinsfile
vendored
Normal file
@ -0,0 +1,60 @@
|
||||
pipeline {
|
||||
agent any
|
||||
environment {
|
||||
// 镜像名称
|
||||
IMAGE_NAME = "node-service"
|
||||
|
||||
// 工作目录
|
||||
WS = "${WORKSPACE}"
|
||||
|
||||
// 自定义构建参数
|
||||
PROFILE = "prod"
|
||||
|
||||
// docker网络
|
||||
DOCKER_NETWORK = "inspur"
|
||||
}
|
||||
|
||||
// 定义流水线的加工流程
|
||||
stages {
|
||||
// 流水线的所有阶段
|
||||
stage('1.环境检查与初始化') {
|
||||
steps {
|
||||
sh 'pwd && ls -alh'
|
||||
sh 'printenv'
|
||||
sh 'docker version'
|
||||
sh 'git --version'
|
||||
}
|
||||
}
|
||||
|
||||
stage('2.编译') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-slim'
|
||||
}
|
||||
}
|
||||
steps {
|
||||
sh 'pwd && ls -alh'
|
||||
sh 'node -v'
|
||||
sh 'cd ${WS} && npm config set registry https://registry.npmmirror.com && npm install -g yarn'
|
||||
sh 'yarn config set registry https://registry.npmmirror.com && yarn'
|
||||
}
|
||||
}
|
||||
|
||||
stage('3.打包') {
|
||||
steps {
|
||||
sh 'pwd && ls -alh'
|
||||
sh 'yarn build:webpack'
|
||||
}
|
||||
}
|
||||
|
||||
stage('4.部署') {
|
||||
// 删除容器和虚悬镜像
|
||||
steps {
|
||||
sh 'pwd && ls -alh'
|
||||
sh 'docker rm -f ${IMAGE_NAME} || true && docker rmi $(docker images -q -f dangling=true) || true'
|
||||
sh 'docker network list | grep "${DOCKER_NETWORK}" && echo "docker network ${DOCKER_NETWORK} is exist" || docker network create ${DOCKER_NETWORK}'
|
||||
sh 'docker run -d --name ${IMAGE_NAME} --network ${DOCKER_NETWORK} ${IMAGE_NAME}'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
87
package.json
Normal file
87
package.json
Normal file
@ -0,0 +1,87 @@
|
||||
{
|
||||
"name": "node-service",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"build:webpack": "nest build --webpack --webpackPath=./webpack.config.js",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "cross-env NODE_ENV=development nest start",
|
||||
"start:dev": "cross-env NODE_ENV=development nest start --watch",
|
||||
"start:debug": "cross-env NODE_ENV=development nest start --debug --watch",
|
||||
"start:prod": "cross-env NODE_ENV=production node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/cache-manager": "^2.2.2",
|
||||
"@nestjs/common": "^10.0.0",
|
||||
"@nestjs/core": "^10.0.0",
|
||||
"@nestjs/jwt": "^10.2.0",
|
||||
"@nestjs/passport": "^10.0.3",
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/swagger": "^7.3.1",
|
||||
"@nestjs/typeorm": "^10.0.2",
|
||||
"better-sqlite3": "^11.0.0",
|
||||
"cache-manager": "^5.5.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"fork-ts-checker-webpack-plugin": "^9.0.2",
|
||||
"mysql2": "^3.10.0",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"reflect-metadata": "^0.2.0",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.20"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.0.0",
|
||||
"@nestjs/schematics": "^10.0.0",
|
||||
"@nestjs/testing": "^10.0.0",
|
||||
"@types/express": "^4.17.17",
|
||||
"@types/jest": "^29.5.2",
|
||||
"@types/node": "^20.3.1",
|
||||
"@types/supertest": "^6.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^6.0.0",
|
||||
"@typescript-eslint/parser": "^6.0.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"dotenv": "^16.4.5",
|
||||
"eslint": "^8.42.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jest": "^29.5.0",
|
||||
"prettier": "^3.0.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^6.3.3",
|
||||
"ts-jest": "^29.1.0",
|
||||
"ts-loader": "^9.4.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.1.3"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
22
src/app.controller.spec.ts
Normal file
22
src/app.controller.spec.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
// expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
77
src/app.controller.ts
Normal file
77
src/app.controller.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import { Body, Controller, Get, HttpException, Post, Query, Req, Res, Sse } from '@nestjs/common';
|
||||
import { Public } from './common/public.guard';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UserService } from './user/user.service';
|
||||
import { CreateUserDto } from './user/dto/create-user.dto';
|
||||
import { IsString, MaxLength, MinLength } from "class-validator";
|
||||
import { Observable } from 'rxjs';
|
||||
import { Response } from 'express'
|
||||
import * as EventEmitter from 'events'
|
||||
|
||||
const emitter = new EventEmitter();
|
||||
interface SSEUser {
|
||||
id: string
|
||||
}
|
||||
|
||||
export class LoginUserDto {
|
||||
@IsString()
|
||||
@MinLength(5)
|
||||
@MaxLength(20)
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
@MaxLength(20)
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly userService: UserService
|
||||
) {}
|
||||
|
||||
@Public()
|
||||
@Post('/login')
|
||||
async login(@Body() loginUserDto: LoginUserDto): Promise<any> {
|
||||
const user = await this.userService.findByUserNameAndPass(
|
||||
loginUserDto.username, loginUserDto.password
|
||||
)
|
||||
|
||||
if (user) return { token: this.jwtService.sign({ ...user }) }
|
||||
return new HttpException('用户名或密码错误', 500)
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('/registry')
|
||||
registry(@Body() createUserDto: CreateUserDto): any {
|
||||
return this.userService.create(createUserDto);
|
||||
}
|
||||
|
||||
public activeUserList: Map<number, SSEUser> = new Map()
|
||||
|
||||
@Sse('sse')
|
||||
sse(@Req() req: Request, @Res() res: Response): Observable<MessageEvent> {
|
||||
const SSEID:number = (req["user"] && req["user"]["id"]) || -1;
|
||||
if (req["user"] instanceof Object) this.activeUserList.set(SSEID, { ...req["user"] })
|
||||
|
||||
return new Observable<any>((observer) => {
|
||||
observer.next({ data: { message: "Message!" } })
|
||||
const emitterHandler = (data) => observer.next({ data })
|
||||
res.on('close', () => {
|
||||
this.activeUserList.delete(SSEID)
|
||||
emitter.removeListener('message_' + SSEID, emitterHandler)
|
||||
})
|
||||
emitter.on('message_' + SSEID, emitterHandler)
|
||||
})
|
||||
}
|
||||
|
||||
@Post("/sse-message")
|
||||
async SSEMessage(@Query() query:any, @Body() body:any) {
|
||||
emitter.emit('message_' + query.id, body)
|
||||
const onlineUser = this.activeUserList.has(parseInt(query.id))
|
||||
if (onlineUser) return { message: '请求成功!' }
|
||||
return { message: '用户不在线!' }
|
||||
}
|
||||
}
|
70
src/app.module.ts
Normal file
70
src/app.module.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import {
|
||||
IS_PROD,
|
||||
JWT_SALT,
|
||||
MYSQL_DATABASE,
|
||||
MYSQL_HOST,
|
||||
MYSQL_PASSWD,
|
||||
MYSQL_PORT,
|
||||
MYSQL_USER
|
||||
} from './config';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { JwtStrategy } from './common/jwt.strategy';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { JwtPublicGuard } from './common/public.guard';
|
||||
import { RolesGuard } from './common/role.guard';
|
||||
import { UserModule } from './user/user.module';
|
||||
import { User } from './user/entities/user.entity';
|
||||
|
||||
// 使用sqlite和程序内缓存时,全部程序不依赖外部组件
|
||||
// 注意:Webpack打包不适用Sqlite!
|
||||
const enableSqlite:boolean = false
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
enableSqlite ? TypeOrmModule.forRoot({
|
||||
type: 'better-sqlite3',
|
||||
database: 'db.sql',
|
||||
entities: [User],
|
||||
synchronize: !IS_PROD
|
||||
}) : TypeOrmModule.forRoot({
|
||||
type: 'mysql',
|
||||
host: MYSQL_HOST,
|
||||
port: MYSQL_PORT,
|
||||
username: MYSQL_USER,
|
||||
password: MYSQL_PASSWD,
|
||||
database: MYSQL_DATABASE,
|
||||
entities: [User],
|
||||
synchronize: !IS_PROD
|
||||
}),
|
||||
CacheModule.register({
|
||||
ttl: 100,
|
||||
max: 30,
|
||||
isGlobal: true
|
||||
}),
|
||||
JwtModule.register({
|
||||
secret: JWT_SALT,
|
||||
signOptions: { expiresIn: '24h' }
|
||||
}),
|
||||
UserModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
AppService,
|
||||
JwtStrategy,
|
||||
// 挂载,登录权限控制器, 注意顺序,先经过jwt
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: JwtPublicGuard
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: RolesGuard
|
||||
}
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
1
src/common/cacheKey.contants.ts
Normal file
1
src/common/cacheKey.contants.ts
Normal file
@ -0,0 +1 @@
|
||||
export const USER_CACHE_KEY = 'user_cache_key'
|
20
src/common/jwt.strategy.ts
Normal file
20
src/common/jwt.strategy.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { ExtractJwt, Strategy } from "passport-jwt";
|
||||
import { JWT_SALT } from "../config";
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor() {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: JWT_SALT
|
||||
});
|
||||
}
|
||||
|
||||
// jwt验证
|
||||
async validate(payload:object) {
|
||||
return { ...payload };
|
||||
}
|
||||
}
|
34
src/common/public.guard.ts
Normal file
34
src/common/public.guard.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 登录权限装饰器
|
||||
* 基于 AuthGuard('jwt') 进行了二次处理
|
||||
* 正常用法是在控制器中对需要登录才能使用的接口用 @UseGuards(AuthGuard('jwt')) 进行装饰
|
||||
* 因为大多数接口都需要鉴权,所以进行了一层包装,只有不需要登录的接口才进行鉴权
|
||||
* 使用方法 控制器中 @Public() 进行装饰
|
||||
*/
|
||||
|
||||
import { SetMetadata, ExecutionContext, Injectable } from '@nestjs/common'
|
||||
import { Reflector } from '@nestjs/core'
|
||||
import { AuthGuard } from '@nestjs/passport'
|
||||
import { Observable } from 'rxjs'
|
||||
|
||||
@Injectable()
|
||||
export class JwtPublicGuard extends AuthGuard('jwt') {
|
||||
constructor(private reflector: Reflector) {
|
||||
super()
|
||||
}
|
||||
|
||||
canActivate(
|
||||
context: ExecutionContext
|
||||
): boolean | Promise<boolean> | Observable<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride('isPublic', [
|
||||
context.getHandler(),
|
||||
context.getClass()
|
||||
])
|
||||
|
||||
if (isPublic) return true
|
||||
|
||||
return super.canActivate(context)
|
||||
}
|
||||
}
|
||||
|
||||
export const Public = () => SetMetadata('isPublic', true)
|
53
src/common/role.guard.ts
Normal file
53
src/common/role.guard.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import {
|
||||
SetMetadata,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* 角色鉴权
|
||||
* @param role 接口要求权限
|
||||
* @param userRole 用户权限
|
||||
* @returns boolean
|
||||
*/
|
||||
const matchRole: (role: string, userRole: string) => boolean = (
|
||||
role,
|
||||
userRole,
|
||||
) => {
|
||||
// 如果没有使用装饰器,则返回 true
|
||||
if (!role) return true;
|
||||
|
||||
// 如果是超级管理员或者管理员,则返回 true
|
||||
if (userRole === 'admin') return;
|
||||
return false;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) { }
|
||||
|
||||
canActivate(
|
||||
context: ExecutionContext,
|
||||
): boolean | Promise<boolean> | Observable<boolean> {
|
||||
|
||||
const isPublic = this.reflector.getAllAndOverride('isPublic', [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) return;
|
||||
|
||||
const role = this.reflector.get<string>('role', context.getHandler());
|
||||
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const user_role = req.user.role;
|
||||
|
||||
// 根据接口规定进行判断是否满足返回 boolean 。。。
|
||||
return matchRole(role, user_role);
|
||||
}
|
||||
}
|
||||
|
||||
export const Role = (role: string) => SetMetadata('role', role);
|
15
src/config.ts
Normal file
15
src/config.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import * as path from 'path'
|
||||
require("dotenv").config({
|
||||
path: path.resolve(__dirname, '../.env.' + process.env.NODE_ENV)
|
||||
})
|
||||
|
||||
// 打包出的dist仍然依赖.env配置文件,所以如果要单独部署,默认配置仍需要认真填写
|
||||
//(或者把.env.prod文件拿到dist同级目录)
|
||||
export const IS_PROD: boolean = process.env.NODE_ENV === 'production'
|
||||
export const MYSQL_HOST: string = process.env.MYSQL_HOST || '117.73.12.97'
|
||||
export const MYSQL_PORT: number = parseInt(process.env.MYSQL_PORT) || 3306
|
||||
export const MYSQL_USER: string = process.env.MYSQL_USER || 'xcszny'
|
||||
export const MYSQL_PASSWD: string = process.env.MYSQL_PASSWD || 'Y123456a?'
|
||||
export const MYSQL_DATABASE: string = process.env.MYSQL_DATABASE || 'nest'
|
||||
|
||||
export const JWT_SALT: string = process.env.JWT_SALT || '.even_jwt_@@__'
|
20
src/main.ts
Normal file
20
src/main.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.setGlobalPrefix('api'); // 全局前缀
|
||||
app.useGlobalPipes(new ValidationPipe())
|
||||
const swag_config = new DocumentBuilder()
|
||||
.setTitle('管理后台')
|
||||
.setDescription('管理后台接口文档')
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, swag_config);
|
||||
SwaggerModule.setup('docs', app, document);
|
||||
await app.listen(3000);
|
||||
}
|
||||
bootstrap();
|
18
src/user/dto/create-user.dto.ts
Normal file
18
src/user/dto/create-user.dto.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { IsString, MaxLength, MinLength } from "class-validator";
|
||||
|
||||
export class CreateUserDto {
|
||||
@IsString({ message: 'username 必须为字符串!' })
|
||||
@MinLength(5, { message: '最小长度不少于5' })
|
||||
@MaxLength(20, { message: '最大长度不超过20' })
|
||||
username: string;
|
||||
|
||||
@IsString({ message: 'username 必须为字符串!' })
|
||||
@MinLength(5, { message: '最小长度不少于5' })
|
||||
@MaxLength(20, { message: '最大长度不超过20' })
|
||||
nickname: string;
|
||||
|
||||
@IsString({ message: 'username 必须为字符串!' })
|
||||
@MinLength(5, { message: '最小长度不少于5' })
|
||||
@MaxLength(20, { message: '最大长度不超过20' })
|
||||
password: string;
|
||||
}
|
4
src/user/dto/update-user.dto.ts
Normal file
4
src/user/dto/update-user.dto.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateUserDto } from './create-user.dto';
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
23
src/user/entities/user.entity.ts
Normal file
23
src/user/entities/user.entity.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
|
||||
|
||||
@Entity("system_user")
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
// 使用sqlite时候用text和integer, Mysql时候用varchar和timestamp
|
||||
@Column({ type: 'varchar', length: 30, nullable: false })
|
||||
username: string;
|
||||
|
||||
@Column({ type: "varchar", length: 30, nullable: false })
|
||||
nickname: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100, nullable: false })
|
||||
password: string;
|
||||
|
||||
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
||||
create_time: Date;
|
||||
|
||||
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
||||
update_time: Date;
|
||||
}
|
20
src/user/user.controller.spec.ts
Normal file
20
src/user/user.controller.spec.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
describe('UserController', () => {
|
||||
let controller: UserController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UserController>(UserController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
50
src/user/user.controller.ts
Normal file
50
src/user/user.controller.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import {
|
||||
Controller,
|
||||
Get, Post, Body, Patch,
|
||||
Param, Delete, HttpException,
|
||||
Inject, Query, UseInterceptors
|
||||
} from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { CACHE_MANAGER, CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';
|
||||
import { USER_CACHE_KEY } from '../common/cacheKey.contants';
|
||||
import { Cache } from 'cache-manager';
|
||||
|
||||
|
||||
@Controller('user')
|
||||
@CacheTTL(1000 * 3)
|
||||
@CacheKey(USER_CACHE_KEY)
|
||||
@UseInterceptors(CacheInterceptor)
|
||||
export class UserController {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
async create(@Body() createUserDto: CreateUserDto) {
|
||||
return this.userService.create(createUserDto);
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
async list(@Query('pageSize') pageSize: number, @Query('pageNo') pageNo: number) {
|
||||
if (!pageSize || !pageNo) return new HttpException('请求参数不全', 500)
|
||||
return await this.userService.findByPaginate(pageSize, pageNo)
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.userService.findOne(+id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
|
||||
return this.userService.update(+id, updateUserDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.userService.remove(+id);
|
||||
}
|
||||
}
|
17
src/user/user.module.ts
Normal file
17
src/user/user.module.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { UserController } from './user.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([User])
|
||||
],
|
||||
controllers: [
|
||||
UserController
|
||||
],
|
||||
providers: [UserService],
|
||||
exports: [UserService]
|
||||
})
|
||||
export class UserModule {}
|
18
src/user/user.service.spec.ts
Normal file
18
src/user/user.service.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
describe('UserService', () => {
|
||||
let service: UserService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<UserService>(UserService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
57
src/user/user.service.ts
Normal file
57
src/user/user.service.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { HttpException, Injectable, Logger } from '@nestjs/common';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { Repository } from 'typeorm/repository/Repository';
|
||||
import { User } from './entities/user.entity';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { MD5 } from 'crypto-js'
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
@InjectRepository(User)
|
||||
private readonly userRepository: Repository<User>
|
||||
) {}
|
||||
|
||||
private readonly logger = new Logger(UserService.name)
|
||||
|
||||
async create(createUserDto: CreateUserDto) {
|
||||
const existedUser = await this.userRepository.findOneBy({
|
||||
nickname: createUserDto.nickname,
|
||||
username: createUserDto.username
|
||||
});
|
||||
if (!!existedUser) return new HttpException('user existed!', 400);
|
||||
createUserDto.password = MD5(createUserDto.password).toString().toUpperCase()
|
||||
this.logger.log('new user created! user:' + createUserDto.username)
|
||||
return await this.userRepository.save(createUserDto);
|
||||
}
|
||||
|
||||
async findByPaginate(limit: number, page: number) {
|
||||
const skip = (page - 1) * limit
|
||||
const userList = await this.userRepository.findAndCount({
|
||||
take: limit, skip,
|
||||
});
|
||||
return [userList[0].map(_user => {
|
||||
const { password, ...sanitizedUser } = _user
|
||||
return sanitizedUser
|
||||
}), userList[1]]
|
||||
}
|
||||
|
||||
findOne(id: number) {
|
||||
return this.userRepository.findOne({ where: { id } });
|
||||
}
|
||||
|
||||
update(id: number, updateUserDto: UpdateUserDto) {
|
||||
return this.userRepository.update(id, updateUserDto);
|
||||
}
|
||||
|
||||
remove(id: number) {
|
||||
return this.userRepository.delete(id);
|
||||
}
|
||||
|
||||
async findByUserNameAndPass(username: string, password: string) {
|
||||
return await this.userRepository.findOneBy({
|
||||
username, password: MD5(password).toString().toUpperCase()
|
||||
})
|
||||
}
|
||||
}
|
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
21
tsconfig.json
Normal file
21
tsconfig.json
Normal file
@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false
|
||||
}
|
||||
}
|
57
webpack.config.js
Normal file
57
webpack.config.js
Normal file
@ -0,0 +1,57 @@
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
|
||||
|
||||
console.log('start build');
|
||||
module.exports = {
|
||||
mode: 'production',
|
||||
entry: './src/main',
|
||||
target: 'node',
|
||||
externals: {},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /.ts?$/,
|
||||
use: {
|
||||
loader: 'ts-loader',
|
||||
options: { transpileOnly: true },
|
||||
},
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
],
|
||||
},
|
||||
output: {
|
||||
filename: '[name].js',
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.js', '.ts', '.json'],
|
||||
},
|
||||
plugins: [
|
||||
new webpack.IgnorePlugin({
|
||||
checkResource(resource) {
|
||||
const lazyImports = [
|
||||
'@nestjs/microservices',
|
||||
'@nestjs/microservices/microservices-module',
|
||||
'cache-manager',
|
||||
'class-validator',
|
||||
'class-transformer',
|
||||
"class-transformer/storage",
|
||||
"@nestjs/websockets/socket-module"
|
||||
];
|
||||
if (!lazyImports.includes(resource)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
require.resolve(resource, {
|
||||
paths: [process.cwd()],
|
||||
});
|
||||
} catch (err) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
new ForkTsCheckerWebpackPlugin(),
|
||||
],
|
||||
};
|
Loading…
Reference in New Issue
Block a user