Commit ca0d3ca9 by yixinjj

first commit

0 parents
Showing 85 changed files with 1963 additions and 0 deletions
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="mysql://user_limin:LmotGSOY@192.168.3.113:3306/app_admin"
\ No newline at end of file \ No newline at end of file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-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
\ No newline at end of file \ No newline at end of file
{
"printWidth": 800,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "none",
"semi": false,
"wrap_line_length": 820,
"wrap_attributes": "auto",
"proseWrap": "always",
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "ignore",
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"jsxBracketSameLine": true,
"files.insertFinalNewline": true,
"prettier.ignorePath": ".prettierignore",
"useTabs": false,
"eslintIntegration": false,
"overrides": [
{
"files": ".prettierrc",
"options": {
"parser": "json"
}
}
],
"endOfLine": "auto"
}
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>
[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
[travis-url]: https://travis-ci.org/nestjs/nest
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec"><img src="https://img.shields.io/badge/Donate-PayPal-dc3d53.svg"/></a>
<a href="https://twitter.com/nestframework"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## 学前准备
- vscode 编辑器
- chrome 浏览器
- iterm2 命令行工具
- [postman](https://www.postman.com/) 接口调试工具
- [Sourcetree](https://www.sourcetreeapp.com/) git 可视化工具
## 序言
在这次学习过程中, 您将了解 Nest 的核心基础知识。主要是了解基本的 nest 应用程序构建模块。
### 2020-5-17 更新
代码中15次commit,包含以下模块:
#### 1.初始化项目
#### 2.添加控制器
#### 3.添加swagger文档支持
#### 4.添加日志
#### 5.添加错误处理
#### 6.添加pipe
#### 7.添加权限控制
#### 8.邮件服务
#### 9.config配置
#### 10.监控
#### 11.jwt的token令牌支持以及鉴权
#### 12.基于mysql的讲解
#### 13.任务队列
#### 14.文件上传文件下载
如果有同学学习之后有心得,欢迎提PR书写以上对应模块的心得分享。
## TODO-list
- 微服务
- 消息系统(Kafka)日志系统
- MongoDB + Mongoose
- TCP + redis
## 环境依赖
请确保您的操作系统上安装了 Node.js(> = 6.11.0)。
## 建立
使用Nest CLI 建立项目非常简单。只要确保你已经安装了npm,然后在你的 OS 终端中使用以下命令:
```bash
$ npm i -g @nestjs/cli
$ nest new project
```
project 目录将在 src 目录中包含几个核心文件。
- src
- app.controller.ts
- app.module.ts
- main.ts
按照约定,新创建的模块应该有一个专用目录。
| 文件 | 描述 |
| ------------- |-------------|
| main.ts | 应用程序入口文件。它使用 NestFactory 用来创建 Nest 应用实例。 |
| app.module.ts | 定义 AppModule 应用程序的根模块。 |
| app.controller.ts | 带有单个路由的基本控制器示例。 |
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## 自动生成实体类
```bash
"scripts": {
"db": "rimraf ./src/modules/entities & npx typeorm-model-generator -h 121.36.70.68 -d chat -p 3306 -u root -x 123456 -e mysql -o ./src/modules/entities --noConfig true --ce pascal --cp camel"
}
#### rm -rf entities表示先删除文件夹entities(window下使用 rimraf entities )
#### npx typeorm-model-generator如果全局安装了就不需要加npx没有全局安装就加上去
#### -h localhost -d 数据库名字 -p 端口 -u 用户名 -x 密码 -e 数据库类型
#### -o entities表示输出到指定的文件夹
#### --noConfig true表示不生成ormconfig.json和tsconfig.json文件
#### --ce pascal表示将类名转换首字母是大写的驼峰命名
#### --cp camel表示将数据库中的字段比如create_at转换为createAt
#### -a表示会继承一个BaseEntity的类,根据自己需求加
```
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": ["templates/**/*"]
}
}
{
"name": "app-admin",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "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",
"prisma:pull": "npx prisma db pull",
"prisma:studio": "npx prisma studio",
"prisma:generate": "npx prisma generate",
"prisma:generate:watch": "npx prisma generate --watch",
"migrate:dev": "prisma migrate dev --preview-feature",
"migrate:dev:create": "prisma migrate dev --create-only --preview-feature",
"migrate:reset": "prisma migrate reset --preview-feature",
"migrate:deploy": "npx prisma migrate deploy --preview-feature",
"migrate:status": "npx prisma migrate status --preview-feature",
"migrate:resolve": "npx prisma migrate resolve --preview-feature",
"db": "rimraf ./src/modules/entities & typeorm-model-generator -h 192.168.3.113 -d app_admin -p 3306 -u user_limin -x LmotGSOY -e mysql -o ./src/modules/entities --noConfig true --ce pascal --cp camel"
},
"dependencies": {
"@nest-modules/mailer": "^1.3.22",
"@nestjs-modules/mailer": "^1.6.0",
"@nestjs/bull": "^0.1.1",
"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0",
"@nestjs/jwt": "^7.0.0",
"@nestjs/passport": "^7.0.0",
"@nestjs/platform-express": "^7.0.0",
"@nestjs/platform-socket.io": "^7.0.11",
"@nestjs/schedule": "^0.3.1",
"@nestjs/swagger": "^4.5.5",
"@nestjs/typeorm": "^7.0.0",
"@prisma/client": "^5.19.1",
"bull": "^3.14.0",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"compressing": "^1.5.1",
"global": "^4.4.0",
"mysql": "^2.18.1",
"nest-status-monitor": "^0.1.3",
"nestjs-config": "^1.4.6",
"nestjs-prisma": "^0.23.0",
"nodemailer": "^6.4.16",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4",
"swagger-ui-express": "^4.1.4",
"typeorm": "^0.2.25"
},
"devDependencies": {
"@nestjs/cli": "^7.0.0",
"@nestjs/schematics": "^7.0.0",
"@nestjs/testing": "^7.0.0",
"@types/bull": "^3.13.0",
"@types/express": "^4.17.6",
"@types/jest": "25.1.4",
"@types/node": "^13.9.1",
"@types/supertest": "^2.0.8",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "^25.1.0",
"prettier": "^1.19.1",
"prisma": "^5.19.1",
"prisma-dbml-generator": "^0.12.0",
"supertest": "^4.0.2",
"ts-jest": "25.2.1",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^5.6.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model device {
id Int @id @default(autoincrement())
create_time DateTime @db.DateTime(0)
sn String @unique @db.VarChar(20)
// device_info device_info?
// log_config log_config?
}
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model device_info {
id Int @id @default(autoincrement())
device_sn String @unique @db.VarChar(20)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time DateTime? @db.DateTime(0)
last_log_remove_time DateTime? @db.Date
// device device? @relation(fields: [device_sn], references: [sn])
// log_config log_config?
}
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model log_config {
id Int @id @default(autoincrement())
device_sn String @unique @db.VarChar(50)
log_saved_days Int? @default(7) @db.TinyInt
log_user_field log_user_field[]
// device device @relation(fields: [device_sn], references: [sn])
// device_info device_info @relation(fields: [device_sn], references: [device_sn], onDelete: NoAction, onUpdate: NoAction, map: "FK_303042b366f2ba3d54f4ddaf6ab")
}
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model log_user_field {
id Int @id @default(autoincrement())
name String @db.VarChar(20)
config_id Int?
log_config log_config? @relation(fields: [config_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_303042b366f2ba3d54f4ddaf6ac")
@@index([config_id], map: "FK_log_user_field_log_config")
}
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!');
});
});
});
import { resolve } from 'path'
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { ScheduleModule } from '@nestjs/schedule'
import { ConfigModule, ConfigService } from 'nestjs-config'
import { MailerModule } from '@nest-modules/mailer'
import { StatusMonitorModule } from 'nest-status-monitor'
import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware'
import { TasksModule } from './tasks/tasks.module'
import { AudioModule } from './jobs/audio/audio.module'
import { AuthModule } from './modules/auth/auth.module'
import { HelloModule } from './modules/hello/hello.module'
import { DeviceModule } from './modules/device/device.module'
import { ExceptionModule } from './modules/exception/exception.module'
import { RoleGuardModule } from './modules/role-guard/role-guard.module'
import { EmailModule } from './modules/email/email.module'
import { UsersModule } from './modules/users/users.module'
import { AlbumModule } from './modules/album/album.module'
@Module({
imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('database'),
inject: [ConfigService]
}),
// TODO @nestjs/terminus almost the same
StatusMonitorModule.setUp(statusMonitorConfig),
MailerModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('email'),
inject: [ConfigService]
}),
ScheduleModule.forRoot(),
// TasksModule,
// AudioModule,
AuthModule,
HelloModule,
DeviceModule,
ExceptionModule,
RoleGuardModule,
EmailModule,
// UsersModule,
AlbumModule
]
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
// 为 hello 路由添加中间件
consumer
.apply(LoggerMiddleware)
.exclude({ path: 'hello', method: RequestMethod.POST })
.forRoutes('hello')
}
}
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
/**
* @description: 响应码
*/
export enum RESPONSE_CODE {
NOSUCCESS = -1, // 表示请求成功,但操作未成功
SUCCESS = 200, // 请求成功
BAD_REQUEST = 400, // 请求错误
UNAUTHORIZED = 401, // 未授权
FORBIDDEN = 403, // 禁止访问
NOT_FOUND = 404, // 资源未找到
INTERNAL_SERVER_ERROR = 500, // 服务器错误
}
/**
* @description: 请求提示语
*/
export enum RESPONSE_MSG {
SUCCESS = '请求成功',
FAILURE = '请求失败',
}
\ No newline at end of file \ No newline at end of file
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'
import { Response, Request } from 'express'
import { BodyResponse } from '../utils'
// @Catch() 装饰器绑定所需的元数据到异常过滤器上。它告诉 Nest这个特定的过滤器正在寻找
@Catch()
export class ExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// 获取上下文
const ctx = host.switchToHttp()
// 获取响应体
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
// 获取状态码,判断是HTTP异常还是服务器异常
const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
// 自定义异常返回体
response.status(statusCode).json(BodyResponse(null, '服务器内部错误!', statusCode, request.url))
}
}
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'
import { Request, Response } from 'express'
import { BodyResponse } from '../utils'
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp()
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
const status = exception.getStatus()
console.log(exception)
const exceptionRes: any = exception.getResponse()
const { message } = exceptionRes
// response.status(status).json({
// status,
// timestamp: new Date().toISOString(),
// path: request.url,
// error,
// message,
// });
// 自定义异常返回体
response.status(status).json(BodyResponse(null, message, status, request.url))
}
}
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const { user } = request.query;
// const hasRole = () =>
// user.roles.some(role => !!roles.find(item => item === role));
// return user && user.roles && hasRole();
return !!roles.find(role => role === user);
}
}
export * as enums from './enums'
export * as utils from './utils'
import { CallHandler, ExecutionContext, HttpException, HttpStatus, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'
@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(catchError(err => throwError(new HttpException('New message', HttpStatus.BAD_GATEWAY))))
}
}
export * from './transform.interceptor'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { tap } from 'rxjs/operators'
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...')
const now = Date.now()
return next.handle().pipe(tap(() => console.log(`After... ${Date.now() - now}ms`)))
}
}
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { timeout } from 'rxjs/operators'
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(timeout(5000))
}
}
import { map } from 'rxjs/operators'
import { Observable } from 'rxjs'
import { BodyResponse, Response } from '../../common/utils'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<Response<T>> {
return next.handle().pipe(map(data => BodyResponse(data)))
}
}
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void) {
const { method, path } = req;
console.log(`${method} ${path}`);
next();
}
}
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform<string> {
async transform(value: string, metadata: ArgumentMetadata) {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
}
return val;
}
}
import {
ArgumentMetadata,
HttpException,
HttpStatus,
Injectable,
PipeTransform,
Type,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
// tslint:disable-next-line
console.log(value);
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
const errObj = {};
errors.forEach(err => {
const {
property,
constraints,
} = err;
errObj[property] = Object.values(constraints);
});
throw new HttpException(
{ message: 'Request params validation failed', error: errObj },
HttpStatus.BAD_REQUEST,
);
}
return value;
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}
import { RESPONSE_CODE, RESPONSE_MSG } from '../enums';
import type { Response } from './types';
export const getCurrentTimestamp = (): number=> {
return Date.parse(new Date().toString()) / 1000;
}
/**
* @description: 统一返回体
*/
export const BodyResponse = <T = any>(
data,
msg?: string ,
code?: number,
url?: string
): Response<T> => {
return {
code:code || RESPONSE_CODE.SUCCESS,
msg:msg || RESPONSE_MSG.SUCCESS,
data,
timestamp: getCurrentTimestamp(),
url,
};
};
export * from './types';
\ No newline at end of file \ No newline at end of file
/**
* @description: 全局响应体
*/
export type Response<T = any> = {
code: number // 状态码
data?: T // 业务数据
msg: string // 响应信息
url: string // 请求接口路径
timestamp: number // 时间戳
}
/**
* @description: 分页数据
*/
export type PageResponse<T = any> = {
current?: number // 页码
size?: number // 当前页条数
total?: number // 总条数
records: T[] // 业务数据
}
import { join } from 'path';
export default {
type: 'mysql',
host: '192.168.3.113',
// socketPath: '/tmp/mysql.sock',
port: 3306,
username: 'user_limin',
password: 'LmotGSOY',
database: 'app_admin',
// entities: [join(__dirname, '../', '**/**.entity{.ts,.js}')],
entities: [join(__dirname, '../', 'modules/entities/**{.ts,.js}')],
synchronize: true,
};
import { join } from 'path';
import { PugAdapter } from '@nestjs-modules/mailer/dist/adapters/pug.adapter';
export default {
transport: 'smtps://1255968521@qq.com:tsjjzmqcmhmoheje@smtp.qq.com',
defaults: {
from: '"nest-modules" <modules@nestjs.com>',
},
template: {
dir: join(__dirname, '../templates/email/'),
adapter: new PugAdapter(),
options: {
strict: true,
},
},
};
import { join } from 'path';
import { diskStorage } from 'multer';
export default {
root: join(__dirname, '../uploads'),
storage: diskStorage({
destination: join(__dirname, `../uploads/${new Date().toLocaleDateString()}`),
filename: (req, file, cb) => {
const filename = `${new Date().getTime()}.${file.mimetype.split('/')[1]}`;
return cb(null, filename);
},
}),
};
export default {
host: 'localhost',
port: 6379,
}
\ No newline at end of file \ No newline at end of file
export default {
pageTitle: 'Nest.js Monitoring Page',
port: 3000,
path: '/status',
ignoreStartsWith: '/healt/alive',
spans: [
{
interval: 1, // Every second
retention: 60, // Keep 60 datapoints in memory
},
{
interval: 5, // Every 5 seconds
retention: 60,
},
{
interval: 15, // Every 15 seconds
retention: 60,
},
],
chartVisibility: {
cpu: true,
mem: true,
load: true,
responseTime: true,
rps: true,
statusCodes: true,
},
healthChecks: [],
};
import { ApiProperty } from '@nestjs/swagger';
import { RESPONSE_CODE, RESPONSE_MSG } from '../common/enums';
export class ResponseDto {
@ApiProperty({
type: Number,
description: '业务状态码',
default: RESPONSE_CODE.SUCCESS,
})
code: number;
@ApiProperty({
type: String,
description: '业务信息',
default: RESPONSE_MSG.SUCCESS,
})
msg: string;
@ApiProperty({ description: '请求接口路径' })
url: string;
@ApiProperty({ description: '业务数据' })
data?: any;
@ApiProperty({ type: Number, description: '时间戳', default: 1720685424078 })
timestamp: number;
}
import { InjectQueue } from '@nestjs/bull';
import { Controller, Post } from '@nestjs/common';
import { Queue } from 'bull';
@Controller('audio')
export class AudioController {
constructor(@InjectQueue('audio') private readonly audioQueue: Queue) {}
@Post('transcode')
async transcode() {
await this.audioQueue.add(
'transcode',
{
file: 'audio.mp3',
},
{ delay: 1000 },
);
}
}
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { ConfigService } from 'nestjs-config';
import { AudioController } from './audio.controller';
import { AudioProcessor } from './audio.processor';
@Module({
imports: [
BullModule.registerQueueAsync({
name: 'audio',
useFactory: (config: ConfigService) => ({
redis: config.get('redis')
}),
inject: [ConfigService]
}),
],
controllers: [AudioController],
providers: [AudioProcessor],
})
export class AudioModule {}
import { Process, Processor, OnQueueActive } from '@nestjs/bull';
import { Logger } from '@nestjs/common';
import { Job } from 'bull';
@Processor('audio')
export class AudioProcessor {
private readonly logger = new Logger(AudioProcessor.name);
@OnQueueActive()
onActive(job: Job) {
this.logger.debug(`Processing job ${job.id} of type ${job.name} with data ${job.data}...`)
}
@Process('transcode')
handleTranscode(job: Job) {
this.logger.debug('Start transcoding...');
this.logger.debug(job.data);
this.logger.debug('Transcoding completed');
}
}
import { NestFactory } from '@nestjs/core'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { HttpExceptionFilter } from './common/filters/http-exception.filter'
import { ExceptionsFilter } from './common/filters/exception.filter'
import { ValidationPipe } from './common/pipes/validation.pipe'
import { LoggingInterceptor } from './common/interceptors/logging.interceptor'
import { AppModule } from './app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
// 全局使用中间件
// app.use(logger)
// 全局过滤器
app.useGlobalFilters(new HttpExceptionFilter())
app.useGlobalFilters(new ExceptionsFilter())
// 全局管道
// app.useGlobalPipes(new ValidationPipe());
// 全局拦截器
// app.useGlobalInterceptors(new LoggingInterceptor());
// 设置swagger文档相关配置
const swaggerOptions = new DocumentBuilder()
.setTitle('app-admin api document')
.setDescription('nest starter project api document')
.setVersion('1.0')
.addBearerAuth()
.build()
const document = SwaggerModule.createDocument(app, swaggerOptions)
SwaggerModule.setup('doc', app, document)
await app.listen(3000)
}
bootstrap()
import {
Controller,
Post,
UploadedFile,
UseInterceptors,
Get,
Res,
} from '@nestjs/common';
import { Response } from 'express';
import { FileInterceptor } from '@nestjs/platform-express';
import { AlbumService } from './album.service';
@Controller('album')
export class AlbumController {
constructor(private readonly albumService: AlbumService) {}
@Post()
@UseInterceptors(FileInterceptor('file'))
upload(@UploadedFile() file) {
this.albumService.upload(file);
return true;
}
@Get('export')
async downloadAll(@Res() res: Response) {
const { filename, tarStream } = await this.albumService.downloadAll();
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader(
'Content-Disposition',
`attachment; filename=${filename}`,
);
tarStream.pipe(res);
}
}
import { Module } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { ConfigService } from 'nestjs-config';
import { AlbumController } from './album.controller';
import { AlbumService } from './album.service';
@Module({
imports: [
MulterModule.registerAsync({
useFactory: (config: ConfigService) => config.get('file'),
inject: [ConfigService],
}),
],
controllers: [AlbumController],
providers: [AlbumService],
})
export class AlbumModule {}
import { Injectable } from '@nestjs/common';
import { tar } from 'compressing';
import { ConfigService } from 'nestjs-config';
@Injectable()
export class AlbumService {
constructor(private readonly configService: ConfigService) {}
upload(file) {
console.log(file);
}
async downloadAll() {
const uploadDir = this.configService.get('file').root;
const tarStream = new tar.Stream();
await tarStream.addEntry(uploadDir);
return { filename: 'hello-world.tar', tarStream };
}
}
import { Controller, Get, Post, Request, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
@Controller()
export class AuthController {
constructor(private readonly authService: AuthService) {}
// 登录测试
@UseGuards(AuthGuard('local'))
@Post('/auth/login')
async login(@Request() req) {
return this.authService.login(req.user);
}
// 测试登录后才可访问的接口,在需要的地方使用守卫,可保证必须携带token才能访问
@UseGuards(AuthGuard('jwt'))
@Get('me')
getProfile(@Request() req) {
return req.user;
}
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
// import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { jwtConstants } from './constants';
@Module({
imports: [
// UsersModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '60s' },
}),
],
controllers: [AuthController],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(
// private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
async validateUser(username: string, pass: string): Promise<any> {
// const user = await this.usersService.find(username);
const user = { name: 'walker123', password: '123321' };
if (user && user.password) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any): Promise<any> {
const payload = {username: user.username, sub: user.userId};
return {
access_token: this.jwtService.sign(payload),
};
}
}
export const jwtConstants = {
secret: 'secretKey',
};
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { jwtConstants } from './constants';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromHeader('token'),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
}
async validate(payload: any) {
return {userId: payload.sub, username: payload.username};
}
}
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
// tslint:disable-next-line
console.log(username, password)
return {username, password};
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new HttpException(
{ message: 'authorized failed', error: 'please try again later.' },
HttpStatus.BAD_REQUEST);
}
return user;
}
}
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { DeviceInfoService } from './device-info.service';
@ApiBearerAuth()
@ApiTags('device-info')
@Controller('/device-info')
export class DeviceInfoController {
constructor(private readonly deviceInfoService: DeviceInfoService) {}
// 查询
@Get()
fetch(@Query() { id }): string {
return this.deviceInfoService.fetch(id);
}
}
import { Module } from '@nestjs/common';
import { DeviceInfoController } from './device-info.controller';
import { DeviceInfoService } from './device-info.service';
@Module({
imports: [],
controllers: [DeviceInfoController],
providers: [DeviceInfoService],
})
export class DeviceInfoModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class DeviceInfoService {
fetch(id): string {
return `Hello World! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Controller, Get, Post, Body, UseInterceptors } from '@nestjs/common'
import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors'
@Controller('device')
export class DeviceController {
constructor(private readonly deviceService: DeviceService) {}
@Get()
@UseInterceptors(TransformInterceptor)
findAll() {
return this.deviceService.findAll()
}
@Post()
async create(@Body() param) {
const newParam = { ...param, status: true }
await this.deviceService.create(newParam)
return true
}
@Post('/many')
async createMany(@Body() users) {
const newUsers = users.map(user => ({ ...user, status: true }))
await this.deviceService.createMany(newUsers)
return true
}
}
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { DeviceController } from './device.controller';
import { DeviceService } from './device.service';
import { Device as DeviceEntity } from '../entities/Device';
import { PrismaService } from 'nestjs-prisma';
@Module({
imports: [TypeOrmModule.forFeature([DeviceEntity])],
controllers: [DeviceController],
providers: [DeviceService,PrismaService],
})
export class DeviceModule {}
import { Inject,Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository, Connection, getRepository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma';
import { Prisma } from '@prisma/client';
@Injectable()
export class DeviceService {
constructor(
@InjectRepository(DeviceEntity)
private readonly deviceRepository: Repository<DeviceEntity>,
@Inject(PrismaService)
private readonly prisma: PrismaService,
private connection: Connection,
) {}
async findAll(): Promise<any> {
// relations: ['photos'], 联合查询
return await this.prisma.device.findMany();
// 或者使用queryBuilder
// return await getRepository(UsersEntity)
// .createQueryBuilder("user")
// .leftJoinAndSelect("user.photos", "photo")
// .getMany()
}
async create(user): Promise<DeviceEntity[]> {
const { name } = user;
const u = await getRepository(DeviceEntity).findOne({ where: { name } });
// .createQueryBuilder('users')
// .where('users.name = :name', { name });
// const u = await qb.getOne();
if (u) {
throw new HttpException(
{
message: 'Input data validation failed',
error: 'name must be unique.',
},
HttpStatus.BAD_REQUEST,
);
}
return await this.deviceRepository.save(user);
}
async createMany(users: DeviceEntity[]) {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
users.forEach(async user => {
await queryRunner.manager.getRepository(DeviceEntity).save(user);
});
await queryRunner.commitTransaction();
} catch (err) {
// since we have errors lets rollback the changes we made
await queryRunner.rollbackTransaction();
} finally {
// you need to release a queryRunner which was manually instantiated
await queryRunner.release();
}
}
}
import { Controller, Get } from '@nestjs/common';
import { EmailService } from './email.service';
@Controller('email')
export class EmailController {
constructor(private readonly emailService: EmailService) {}
@Get()
sendEmail(): string {
this.emailService.sendEmail();
return 'Message sent';
}
}
import { Module } from '@nestjs/common';
import { EmailController } from './email.controller';
import { EmailService } from './email.service';
@Module({
imports: [],
controllers: [EmailController],
providers: [EmailService],
})
export class EmailModule {}
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nest-modules/mailer';
@Injectable()
export class EmailService {
constructor(private readonly mailerService: MailerService) {}
sendEmail() {
this.mailerService.sendMail({
to: 'flana_zhong@163.com',
from: '1255968521@qq.com',
// subject: 'Testing Nest MailerModule ✔',
subject: 'Walker Lee Love You ✔',
// html: '<b>Welcome Frost!</b>',
template: './welcome',
context: {
// Data to be sent to template engine.
code: 'cf1a3f828287',
username: 'walker lee',
},
});
}
}
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity("device", { schema: "app_admin" })
export class Device {
@PrimaryGeneratedColumn({ type: "int", name: "id" })
id: number;
@Column("datetime", { name: "create_time" })
createTime: Date;
@Column("varchar", { name: "sn", length: 20 })
sn: string;
}
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity("device_info", { schema: "app_admin" })
export class DeviceInfo {
@PrimaryGeneratedColumn({ type: "int", name: "id", comment: "主键,自增" })
id: number;
@Column("varchar", { name: "device_sn", length: 20 })
deviceSn: string;
@Column("varchar", {
name: "user",
nullable: true,
comment: "使用者(员工)",
length: 20,
})
user: string | null;
@Column("tinyint", {
name: "status",
nullable: true,
comment: "0:废弃;1:离线;2:在线",
})
status: number | null;
@Column("datetime", {
name: "last_log_upload_time",
nullable: true,
comment: "最后一次日志上传时间",
})
lastLogUploadTime: Date | null;
@Column("date", {
name: "last_log_remove_time",
nullable: true,
comment: "最后一次清除日志日期",
})
lastLogRemoveTime: string | null;
}
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { LogUserField } from "./LogUserField";
@Entity("log_config", { schema: "app_admin" })
export class LogConfig {
@PrimaryGeneratedColumn({ type: "int", name: "id" })
id: number;
@Column("varchar", {
name: "device_sn",
comment: "设备ID,device表sn",
length: 50,
})
deviceSn: string;
@Column("tinyint", {
name: "log_saved_days",
nullable: true,
comment: "日志保留天数",
default: () => "'7'",
})
logSavedDays: number | null;
@OneToMany(() => LogUserField, (logUserField) => logUserField.config)
logUserFields: LogUserField[];
}
import {
Column,
Entity,
Index,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { LogConfig } from "./LogConfig";
@Index("FK_log_user_field_log_config", ["configId"], {})
@Entity("log_user_field", { schema: "app_admin" })
export class LogUserField {
@PrimaryGeneratedColumn({ type: "int", name: "id", comment: "主键,自增" })
id: number;
@Column("varchar", { name: "name", comment: "字段名", length: 20 })
name: string;
@Column("int", { name: "config_id", nullable: true })
configId: number | null;
@ManyToOne(() => LogConfig, (logConfig) => logConfig.logUserFields, {
onDelete: "NO ACTION",
onUpdate: "NO ACTION",
})
@JoinColumn([{ name: "config_id", referencedColumnName: "id" }])
config: LogConfig;
}
import {
Controller,
Get,
Post,
Patch,
Query,
Delete,
Body,
Param,
Headers,
UseFilters,
HttpException,
HttpStatus,
ParseIntPipe,
} from '@nestjs/common';
import {
ApiTags,
ApiBearerAuth,
ApiBody,
ApiParam,
} from '@nestjs/swagger';
import { ExceptionService } from './exception.service';
import { HttpExceptionFilter } from '../../common/filters/http-exception.filter';
@ApiBearerAuth()
@ApiTags('exception')
// @UseFilters(new HttpExceptionFilter())
@Controller('/exception')
export class ExceptionController {
constructor(private readonly exceptionService: ExceptionService) {}
// 查询
@Get()
fetch(@Query() { id }, @Headers('token') token): string {
if (!id) {
throw new HttpException(
{ status: HttpStatus.BAD_REQUEST, message: '请求参数id 必传', error: 'id is required' },
HttpStatus.BAD_REQUEST,
);
}
return this.exceptionService.fetch(id);
}
// 创建
@Post()
@ApiBody({ description: '填写更新内容' })
save(@Body() { message, id }): string {
return this.exceptionService.save(message);
}
// 更新
@Patch(':id')
@ApiParam({ name: 'id' })
@ApiBody({ description: '请输入message' })
// 有时,我们希望参数的类型为数字,则可以通过管道进行转换
// !现nest自带部分管道
update(@Param('id', new ParseIntPipe()) id, @Body() { message }): string {
console.log(typeof id)
return this.exceptionService.update(id, message);
}
// 删除
@Delete()
remove(@Query() { id }): string {
return this.exceptionService.remove(id);
}
}
import { Module } from '@nestjs/common';
import { ExceptionController } from './exception.controller';
import { ExceptionService } from './exception.service';
@Module({
imports: [],
controllers: [ExceptionController],
providers: [ExceptionService],
})
export class ExceptionModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class ExceptionService {
fetch(id): string {
return `Hello World! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { ApiProperty } from '@nestjs/swagger';
export enum UserRole {
Admin = 'Admin',
User = 'User',
}
export class Hello {
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;
@ApiProperty({ example: 1, description: 'The age of the Cat' })
age: number;
@ApiProperty({
example: 'Maine Coon',
description: 'The breed of the Cat',
})
breed: string;
@ApiProperty({ enum: UserRole })
role: UserRole;
}
import { IsInt, IsString } from 'class-validator';
export class CreateCatDto {
@IsString()
readonly name: string;
@IsInt()
readonly age: number;
@IsString()
readonly breed: string;
}
import { Test, TestingModule } from '@nestjs/testing';
import { HelloController } from './hello.controller';
import { HelloService } from './hello.service';
describe('AppController', () => {
let appController: HelloService;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [HelloController],
providers: [HelloService],
}).compile();
appController = app.get<HelloController>(HelloController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
import {
Controller,
Get,
Post,
Patch,
Query,
Delete,
Body,
Param,
Headers,
} from '@nestjs/common';
import {
ApiResponse,
ApiTags,
ApiQuery,
ApiBearerAuth,
ApiBody,
ApiParam,
} from '@nestjs/swagger';
import { HelloService } from './hello.service';
import { Hello, UserRole } from './classes/hello';
@ApiBearerAuth()
@ApiTags('hello')
@Controller('/hello')
export class HelloController {
constructor(private readonly helloService: HelloService) {}
// 查询
@Get()
@ApiQuery({ name: 'name', required: false })
@ApiQuery({ name: 'role', enum: UserRole })
@ApiResponse({
status: 200,
description: 'get ...',
type: Hello,
})
fetch(@Query() { id }, @Headers('token') token): string {
// console.log(url);
return this.helloService.fetch(id);
}
// 创建
@Post()
@ApiBody({ description: '填写更新内容' })
save(@Body() { message }): string {
return this.helloService.save(message);
}
// 更新
@Patch(':id')
@ApiParam({ name: 'id' })
@ApiBody({ description: '请输入message' })
update(@Param() { id }, @Body() { message }): string {
return this.helloService.update(id, message);
}
// 删除
@Delete()
remove(@Query() { id }): string {
return this.helloService.remove(id);
}
}
import { Module } from '@nestjs/common';
import { HelloController } from './hello.controller';
import { HelloService } from './hello.service';
@Module({
imports: [],
controllers: [HelloController],
providers: [HelloService],
})
export class HelloModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
fetch(id): string {
return `Hello World!! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Entity, PrimaryGeneratedColumn, ManyToOne, Column } from 'typeorm';
import { UsersEntity } from '../users/users.entity';
@Entity({ name: 'photo' })
export class PhotoEntity {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(
() => UsersEntity,
user => user.photos,
)
user: UsersEntity;
@Column({ type: 'varchar', length: 80 })
url: string;
}
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { RoleGuardService } from './role-guard.service';
@ApiBearerAuth()
@ApiTags('role-guard')
@UseGuards(RolesGuard)
@Controller('/role-guard')
export class RoleGuardController {
constructor(private readonly roleGuardService: RoleGuardService) {}
// 查询
@Get()
@Roles('admin')
fetch(@Query() { id }): string {
return this.roleGuardService.fetch(id);
}
}
import { Module } from '@nestjs/common';
import { RoleGuardController } from './role-guard.controller';
import { RoleGuardService } from './role-guard.service';
@Module({
imports: [],
controllers: [RoleGuardController],
providers: [RoleGuardService],
})
export class RoleGuardModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class RoleGuardService {
fetch(id): string {
return `Hello World! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Controller, Get, Post, Body } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
findAll() {
return this.usersService.findAll();
}
@Post()
async create(@Body() param) {
const newParam = { ...param, status: true };
await this.usersService.create(newParam);
return true;
}
@Post('/many')
async createMany(@Body() users) {
const newUsers = users.map(user => ({ ...user, status: true }));
await this.usersService.createMany(newUsers);
return true
}
}
import { Column, Entity, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { PhotoEntity } from '../photo/photo.entity';
@Entity({ name: 'users' })
export class UsersEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 20 })
name: string;
@Column('varchar')
password: string;
@Column()
status: boolean;
@OneToMany(
() => PhotoEntity,
photo => photo.user,
)
photos: [];
}
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { UsersEntity } from './users.entity';
@Module({
imports: [TypeOrmModule.forFeature([UsersEntity])],
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository, Connection, getRepository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { UsersEntity } from './users.entity';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(UsersEntity)
private readonly usersRepository: Repository<UsersEntity>,
private connection: Connection,
) {}
async findAll(): Promise<UsersEntity[]> {
// relations: ['photos'], 联合查询
return await this.usersRepository.find({ relations: ['photos'] });
// 或者使用queryBuilder
// return await getRepository(UsersEntity)
// .createQueryBuilder("user")
// .leftJoinAndSelect("user.photos", "photo")
// .getMany()
}
async create(user): Promise<UsersEntity[]> {
const { name } = user;
const u = await getRepository(UsersEntity).findOne({ where: { name } });
// .createQueryBuilder('users')
// .where('users.name = :name', { name });
// const u = await qb.getOne();
if (u) {
throw new HttpException(
{
message: 'Input data validation failed',
error: 'name must be unique.',
},
HttpStatus.BAD_REQUEST,
);
}
return await this.usersRepository.save(user);
}
async createMany(users: UsersEntity[]) {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
users.forEach(async user => {
await queryRunner.manager.getRepository(UsersEntity).save(user);
});
await queryRunner.commitTransaction();
} catch (err) {
// since we have errors lets rollback the changes we made
await queryRunner.rollbackTransaction();
} finally {
// you need to release a queryRunner which was manually instantiated
await queryRunner.release();
}
}
}
import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
@Module({
providers: [TasksService],
})
export class TasksModule {}
import { Injectable, Logger } from '@nestjs/common';
import { Cron, Interval, Timeout } from '@nestjs/schedule';
@Injectable()
export class TasksService {
private readonly logger = new Logger(TasksService.name);
@Cron('45 * * * * *')
handleCron() {
this.logger.debug('Called when the second is 45');
}
@Interval(10000)
handleInterval() {
this.logger.debug('Called every 10 seconds');
}
@Timeout(5000)
handleTimeout() {
this.logger.debug('Called once after 5 seconds');
}
}
doctype html
html(lang='en')
head
title Pug
body
h1 Welcome.
#container.col
p You are amazing
p
| Pug is a terse and simple
| templating language with a
| strong focus on performance
| and powerful features.
ul
li #{code}
li #{username}
li Jack
li Androw
declare namespace Api {
namespace Common {
/**
* @description: 全局响应体
*/
type Response<T = any> = {
code: number // 状态码
data?: T // 业务数据
msg: string // 响应信息
timestamp: number // 时间戳
}
/**
* @description: 分页数据
*/
type PageResponse<T = any> = {
current?: number // 页码
size?: number // 当前页条数
total?: number // 总条数
records: T[] // 业务数据
}
}
}
http://localhost:3000/device
\ No newline at end of file \ No newline at end of file
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
},
"exclude": ["node_modules", "dist"]
}
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!