From 2732e2039786575a37be340b6b98c4229a52ff59 Mon Sep 17 00:00:00 2001 From: SunnyQjm Date: Sun, 27 Oct 2019 22:56:10 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=9F=BA=E7=A1=80=E7=9A=84?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E6=B3=A8=E5=86=8C=E5=8A=9F=E8=83=BD=EF=BC=88?= =?UTF-8?q?=E5=B9=B6=E6=94=AF=E6=8C=81jwt=E9=AA=8C=E8=AF=81=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 34 +++++++++++++++ .prettierrc | 4 ++ README.md | 75 ++++++++++++++++++++++++++++++++ nest-cli.json | 4 ++ package.json | 74 +++++++++++++++++++++++++++++++ src/app.controller.spec.ts | 22 ++++++++++ src/app.controller.ts | 15 +++++++ src/app.module.ts | 24 ++++++++++ src/app.service.ts | 8 ++++ src/auth/auth.controller.spec.ts | 18 ++++++++ src/auth/auth.controller.ts | 24 ++++++++++ src/auth/auth.module.ts | 29 ++++++++++++ src/auth/auth.service.spec.ts | 18 ++++++++ src/auth/auth.service.ts | 56 ++++++++++++++++++++++++ src/auth/constants.ts | 3 ++ src/auth/dto/create-user.dto.ts | 9 ++++ src/auth/jwt.strategy.ts | 19 ++++++++ src/auth/local.strategy.ts | 27 ++++++++++++ src/cats/cats.controller.spec.ts | 18 ++++++++ src/cats/cats.controller.ts | 20 +++++++++ src/cats/cats.interface.ts | 5 +++ src/cats/cats.service.spec.ts | 18 ++++++++ src/cats/cats.service.ts | 15 +++++++ src/main.ts | 11 +++++ src/model/BaseResponse.ts | 25 +++++++++++ src/user/user.controller.spec.ts | 18 ++++++++ src/user/user.controller.ts | 14 ++++++ src/user/user.entity.ts | 29 ++++++++++++ src/user/user.module.ts | 13 ++++++ src/user/user.service.spec.ts | 18 ++++++++ src/user/user.service.ts | 27 ++++++++++++ test/app.e2e-spec.ts | 23 ++++++++++ test/jest-e2e.json | 9 ++++ tsconfig.build.json | 4 ++ tsconfig.json | 15 +++++++ tslint.json | 18 ++++++++ 36 files changed, 763 insertions(+) create mode 100644 .gitignore create mode 100644 .prettierrc create mode 100644 README.md create mode 100644 nest-cli.json create mode 100644 package.json create mode 100644 src/app.controller.spec.ts create mode 100644 src/app.controller.ts create mode 100644 src/app.module.ts create mode 100644 src/app.service.ts create mode 100644 src/auth/auth.controller.spec.ts create mode 100644 src/auth/auth.controller.ts create mode 100644 src/auth/auth.module.ts create mode 100644 src/auth/auth.service.spec.ts create mode 100644 src/auth/auth.service.ts create mode 100644 src/auth/constants.ts create mode 100644 src/auth/dto/create-user.dto.ts create mode 100644 src/auth/jwt.strategy.ts create mode 100644 src/auth/local.strategy.ts create mode 100644 src/cats/cats.controller.spec.ts create mode 100644 src/cats/cats.controller.ts create mode 100644 src/cats/cats.interface.ts create mode 100644 src/cats/cats.service.spec.ts create mode 100644 src/cats/cats.service.ts create mode 100644 src/main.ts create mode 100644 src/model/BaseResponse.ts create mode 100644 src/user/user.controller.spec.ts create mode 100644 src/user/user.controller.ts create mode 100644 src/user/user.entity.ts create mode 100644 src/user/user.module.ts create mode 100644 src/user/user.service.spec.ts create mode 100644 src/user/user.service.ts create mode 100644 test/app.e2e-spec.ts create mode 100644 test/jest-e2e.json create mode 100644 tsconfig.build.json create mode 100644 tsconfig.json create mode 100644 tslint.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c16ef02 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# 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 diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..dcb7279 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,4 @@ +{ + "singleQuote": true, + "trailingComma": "all" +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a59ef92 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +

+ Nest Logo +

+ +[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 + +

A progressive Node.js framework for building efficient and scalable server-side applications, heavily inspired by Angular.

+

+NPM Version +Package License +NPM Downloads +Travis +Linux +Coverage +Gitter +Backers on Open Collective +Sponsors on Open Collective + + +

+ + +## Description + +[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. + +## 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 +``` + +## Support + +Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). + +## Stay in touch + +- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) +- Website - [https://nestjs.com](https://nestjs.com/) +- Twitter - [@nestframework](https://twitter.com/nestframework) + +## License + + Nest is [MIT licensed](LICENSE). diff --git a/nest-cli.json b/nest-cli.json new file mode 100644 index 0000000..56167b3 --- /dev/null +++ b/nest-cli.json @@ -0,0 +1,4 @@ +{ + "collection": "@nestjs/schematics", + "sourceRoot": "src" +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..d600c9d --- /dev/null +++ b/package.json @@ -0,0 +1,74 @@ +{ + "name": "nest-demo", + "version": "0.0.1", + "description": "", + "author": "", + "license": "MIT", + "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": "tslint -p tsconfig.json -c tslint.json", + "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/common": "^6.7.2", + "@nestjs/core": "^6.7.2", + "@nestjs/jwt": "^6.1.1", + "@nestjs/passport": "^6.1.0", + "@nestjs/platform-express": "^6.7.2", + "@nestjs/typeorm": "^6.2.0", + "@types/passport": "^1.0.1", + "@types/passport-jwt": "^3.0.2", + "@types/passport-local": "^1.0.33", + "class-validator": "^0.10.2", + "mysql": "^2.17.1", + "passport": "^0.4.0", + "passport-jwt": "^4.0.0", + "passport-local": "^1.0.0", + "reflect-metadata": "^0.1.13", + "rimraf": "^3.0.0", + "rxjs": "^6.5.3", + "typeorm": "^0.2.20" + }, + "devDependencies": { + "@nestjs/cli": "^6.9.0", + "@nestjs/schematics": "^6.7.0", + "@nestjs/testing": "^6.7.1", + "@types/express": "^4.17.1", + "@types/jest": "^24.0.18", + "@types/node": "^12.7.5", + "@types/supertest": "^2.0.8", + "jest": "^24.9.0", + "prettier": "^1.18.2", + "supertest": "^4.0.2", + "ts-jest": "^24.1.0", + "ts-loader": "^6.2.1", + "ts-node": "^8.4.1", + "tsconfig-paths": "^3.9.0", + "tslint": "^5.20.0", + "typescript": "^3.6.3" + }, + "jest": { + "moduleFileExtensions": [ + "js", + "json", + "ts" + ], + "rootDir": "src", + "testRegex": ".spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + }, + "coverageDirectory": "./coverage", + "testEnvironment": "node" + } +} diff --git a/src/app.controller.spec.ts b/src/app.controller.spec.ts new file mode 100644 index 0000000..d22f389 --- /dev/null +++ b/src/app.controller.spec.ts @@ -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); + }); + + describe('root', () => { + it('should return "Hello World!"', () => { + expect(appController.getHello()).toBe('Hello World!'); + }); + }); +}); diff --git a/src/app.controller.ts b/src/app.controller.ts new file mode 100644 index 0000000..1c267cd --- /dev/null +++ b/src/app.controller.ts @@ -0,0 +1,15 @@ +import { Body, Controller, Get, Post, Request, UseGuards } from '@nestjs/common'; +import { AppService } from './app.service'; + +@Controller() +export class AppController { + constructor( + private readonly appService: AppService, + ) { + } + + @Get() + getHello(): string { + return this.appService.getHello(); + } +} diff --git a/src/app.module.ts b/src/app.module.ts new file mode 100644 index 0000000..0112331 --- /dev/null +++ b/src/app.module.ts @@ -0,0 +1,24 @@ +import { Module } from '@nestjs/common'; +import { AppController } from './app.controller'; +import { AppService } from './app.service'; +import { CatsController } from './cats/cats.controller'; +import { CatsService } from './cats/cats.service'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { UserModule } from './user/user.module'; +import { AuthModule } from './auth/auth.module'; + +@Module({ + imports: [TypeOrmModule.forRoot({ + type: 'mysql', + host: 'localhost', + port: 3306, + username: 'sunny-blog', + password: 'XkczhsZc3F5ZDhsi', + database: 'sunny-blog', + entities: [__dirname + '/**/*.entity{.ts,.js}'], + synchronize: true, + }), UserModule, AuthModule], + controllers: [AppController, CatsController], + providers: [AppService, CatsService], +}) +export class AppModule {} diff --git a/src/app.service.ts b/src/app.service.ts new file mode 100644 index 0000000..927d7cc --- /dev/null +++ b/src/app.service.ts @@ -0,0 +1,8 @@ +import { Injectable } from '@nestjs/common'; + +@Injectable() +export class AppService { + getHello(): string { + return 'Hello World!'; + } +} diff --git a/src/auth/auth.controller.spec.ts b/src/auth/auth.controller.spec.ts new file mode 100644 index 0000000..5695209 --- /dev/null +++ b/src/auth/auth.controller.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { AuthController } from './auth.controller'; + +describe('Auth Controller', () => { + let controller: AuthController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [AuthController], + }).compile(); + + controller = module.get(AuthController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts new file mode 100644 index 0000000..9e78343 --- /dev/null +++ b/src/auth/auth.controller.ts @@ -0,0 +1,24 @@ +import { Body, Controller, Post, Req, UseGuards } from '@nestjs/common'; +import { AuthService } from './auth.service'; +import { AuthGuard } from '@nestjs/passport'; +import { CreateUserDto } from './dto/create-user.dto'; + +@Controller('auth') +export class AuthController { + constructor( + private readonly authService: AuthService, + ) { + } + + @UseGuards(AuthGuard('local')) + @Post('login') + async login(@Req() req) { + return this.authService.login(req.user); + } + + @Post('register') + async register(@Body() user: CreateUserDto) { + return this.authService.register(user); + } + +} diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts new file mode 100644 index 0000000..44eb349 --- /dev/null +++ b/src/auth/auth.module.ts @@ -0,0 +1,29 @@ +import { Module } from '@nestjs/common'; +import { AuthService } from './auth.service'; +import { PassportModule } from '@nestjs/passport'; +import { JwtModule } from '@nestjs/jwt'; +import { jwtConstants } from './constants'; +import { UserModule } from '../user/user.module'; +import { LocalStrategy } from './local.strategy'; +import { JwtStrategy } from './jwt.strategy'; +import { AuthController } from './auth.controller'; + +@Module({ + imports: [ + UserModule, + PassportModule, + JwtModule.register({ + secret: jwtConstants.secret, + signOptions: { expiresIn: '60s' }, + }), + ], + providers: [ + AuthService, + LocalStrategy, + JwtStrategy, + ], + exports: [AuthService], + controllers: [AuthController], +}) +export class AuthModule { +} diff --git a/src/auth/auth.service.spec.ts b/src/auth/auth.service.spec.ts new file mode 100644 index 0000000..800ab66 --- /dev/null +++ b/src/auth/auth.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { AuthService } from './auth.service'; + +describe('AuthService', () => { + let service: AuthService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [AuthService], + }).compile(); + + service = module.get(AuthService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts new file mode 100644 index 0000000..7d87dd9 --- /dev/null +++ b/src/auth/auth.service.ts @@ -0,0 +1,56 @@ +import { Injectable } from '@nestjs/common'; +import { UserService } from '../user/user.service'; +import { JwtService } from '@nestjs/jwt'; +import { CreateUserDto } from './dto/create-user.dto'; +import { BaseResponse } from '../model/BaseResponse'; +import { User } from '../user/user.entity'; + +@Injectable() +export class AuthService { + constructor( + private readonly userService: UserService, + private readonly jwtService: JwtService, + ) { + } + + async validateUser(username: string, pass: string): Promise { + // 通过比对用户传递的和数据库中的用户名密码,判断是否用户验证通过 + const user = await this.userService.findOne(username); + if (user && user.password === pass) { + const { password, ...result } = user; + return result; + } + return null; + } + + async login(user: any) { + const payload = { username: user.username, sub: user.id }; + return { + access_token: this.jwtService.sign(payload), + ...user, + }; + } + + async register(userDto: CreateUserDto) { + // 判断用户是否已经存在 + const user = await this.userService.findOne(userDto.username); + if (!user) { + const newUser: User = { + ...userDto, + }; + // 创建新用户,插入数据库 + await this.userService.insertUser(newUser); + const payload = { username: newUser.username, sub: newUser.id }; + + const {password, ...result} = newUser; + // 返回创建成功 + return BaseResponse.success({ + access_token: this.jwtService.sign(payload), + ...result, + }); + } + + // 返回用户已存在 + return BaseResponse.fail('user already exit'); + } +} diff --git a/src/auth/constants.ts b/src/auth/constants.ts new file mode 100644 index 0000000..c172fd2 --- /dev/null +++ b/src/auth/constants.ts @@ -0,0 +1,3 @@ +export const jwtConstants = { + secret: 'SunnyQjm-Rein', +}; diff --git a/src/auth/dto/create-user.dto.ts b/src/auth/dto/create-user.dto.ts new file mode 100644 index 0000000..2c76e65 --- /dev/null +++ b/src/auth/dto/create-user.dto.ts @@ -0,0 +1,9 @@ +import {IsInt, IsString} from 'class-validator'; + +export class CreateUserDto { + @IsString() + readonly username: string; + + @IsString() + readonly password: string; +} diff --git a/src/auth/jwt.strategy.ts b/src/auth/jwt.strategy.ts new file mode 100644 index 0000000..973777b --- /dev/null +++ b/src/auth/jwt.strategy.ts @@ -0,0 +1,19 @@ +import { PassportStrategy } from '@nestjs/passport'; +import { ExtractJwt, Strategy } from 'passport-jwt'; +import { Injectable } from '@nestjs/common'; +import { jwtConstants } from './constants'; + +@Injectable() +export class JwtStrategy extends PassportStrategy(Strategy) { + constructor() { + super({ + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + ignoreExpiration: false, + secretOrKey: jwtConstants.secret, + }); + } + + async validate(payload: any) { + return { id: payload.sub, username: payload.username }; + } +} diff --git a/src/auth/local.strategy.ts b/src/auth/local.strategy.ts new file mode 100644 index 0000000..c1e098c --- /dev/null +++ b/src/auth/local.strategy.ts @@ -0,0 +1,27 @@ +// import {} from '@nest' +import { Strategy } from 'passport-local'; + +import { PassportStrategy } from '@nestjs/passport'; +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { AuthService } from './auth.service'; + +@Injectable() +export class LocalStrategy extends PassportStrategy(Strategy) { + constructor(private readonly authService: AuthService) { + + // passport-local 通过用户名和密码两个字段验证,下面的参数可以指定两个字段的名字 + super({ + usernameField: 'username', + passwordField: 'password', + }); + } + + async validate(username: string, password: string): Promise { + // 验证用户名和密码是否有效,有效则local验证通过 + const user = await this.authService.validateUser(username, password); + if (!user) { + throw new UnauthorizedException('验证未通过'); + } + return user; + } +} diff --git a/src/cats/cats.controller.spec.ts b/src/cats/cats.controller.spec.ts new file mode 100644 index 0000000..2f5bc2c --- /dev/null +++ b/src/cats/cats.controller.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { CatsController } from './cats.controller'; + +describe('Cats Controller', () => { + let controller: CatsController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [CatsController], + }).compile(); + + controller = module.get(CatsController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/cats/cats.controller.ts b/src/cats/cats.controller.ts new file mode 100644 index 0000000..fcaf518 --- /dev/null +++ b/src/cats/cats.controller.ts @@ -0,0 +1,20 @@ +import { Controller, Get, Post, Req } from '@nestjs/common'; +import { Request } from 'express'; +import { CatsService } from './cats.service'; +import { Cat } from './cats.interface'; + +@Controller('cats') +export class CatsController { + constructor(private readonly catsService: CatsService) { + } + + @Get() + async findAll(@Req() request: Request): Promise { + return this.catsService.findAll(); + } + + @Post() + create(): string { + return 'This action adds a new cat'; + } +} diff --git a/src/cats/cats.interface.ts b/src/cats/cats.interface.ts new file mode 100644 index 0000000..961c973 --- /dev/null +++ b/src/cats/cats.interface.ts @@ -0,0 +1,5 @@ +export interface Cat { + name: string; + age: number; + breed: string; +} diff --git a/src/cats/cats.service.spec.ts b/src/cats/cats.service.spec.ts new file mode 100644 index 0000000..0e9bf2b --- /dev/null +++ b/src/cats/cats.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { CatsService } from './cats.service'; + +describe('CatsService', () => { + let service: CatsService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [CatsService], + }).compile(); + + service = module.get(CatsService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/cats/cats.service.ts b/src/cats/cats.service.ts new file mode 100644 index 0000000..f952d0e --- /dev/null +++ b/src/cats/cats.service.ts @@ -0,0 +1,15 @@ +import { Injectable } from '@nestjs/common'; +import { Cat } from './cats.interface'; + +@Injectable() +export class CatsService { + private readonly cats: Cat[] = []; + + create(cat: Cat) { + this.cats.push(cat); + } + + findAll(): Cat[] { + return this.cats; + } +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..55c02f8 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,11 @@ +import { NestFactory } from '@nestjs/core'; +import { NestExpressApplication } from '@nestjs/platform-express'; +import { AppModule } from './app.module'; + +async function bootstrap() { + const app = await NestFactory.create(AppModule); + await app.listen(3000); + +} + +bootstrap(); diff --git a/src/model/BaseResponse.ts b/src/model/BaseResponse.ts new file mode 100644 index 0000000..672e500 --- /dev/null +++ b/src/model/BaseResponse.ts @@ -0,0 +1,25 @@ +interface BaseResponseData { + statusCode: number; + error: string; + message: string; + data: any | any[]; +} + +export class BaseResponse { + static success(data: any | any[]) { + return { + statusCode: 0, + error: '', + message: '', + data, + }; + } + + static fail(message) { + return { + statusCode: -1, + error: '', + message, + }; + } +} diff --git a/src/user/user.controller.spec.ts b/src/user/user.controller.spec.ts new file mode 100644 index 0000000..95e4e62 --- /dev/null +++ b/src/user/user.controller.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { UserController } from './user.controller'; + +describe('User Controller', () => { + let controller: UserController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [UserController], + }).compile(); + + controller = module.get(UserController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts new file mode 100644 index 0000000..3e71cfc --- /dev/null +++ b/src/user/user.controller.ts @@ -0,0 +1,14 @@ +import { Controller, Get } from '@nestjs/common'; +import { User } from './user.entity'; +import { UserService } from './user.service'; + +@Controller('user') +export class UserController { + constructor( + private readonly userService: UserService, + ) {} + @Get('list') + async findAll(): Promise { + return this.userService.findAll(); + } +} diff --git a/src/user/user.entity.ts b/src/user/user.entity.ts new file mode 100644 index 0000000..697ded2 --- /dev/null +++ b/src/user/user.entity.ts @@ -0,0 +1,29 @@ +import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; + +@Entity() +export class User { + @PrimaryGeneratedColumn() + id?: number; + + @Column({ length: 500 }) + username: string; + + @Column() + password: string; + + @Column({ + default: '', + }) + avatar?: string; + + @Column({ + default: '', + }) + nickName?: string; + + @Column({ + type: 'int', + default: 18, + }) + age?: number; +} diff --git a/src/user/user.module.ts b/src/user/user.module.ts new file mode 100644 index 0000000..d6db1f3 --- /dev/null +++ b/src/user/user.module.ts @@ -0,0 +1,13 @@ +import { Module } from '@nestjs/common'; +import { UserService } from './user.service'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { User } from './user.entity'; +import { UserController } from './user.controller'; + +@Module({ + imports: [TypeOrmModule.forFeature([User])], + providers: [UserService], + controllers: [UserController], + exports: [UserService], +}) +export class UserModule {} diff --git a/src/user/user.service.spec.ts b/src/user/user.service.spec.ts new file mode 100644 index 0000000..873de8a --- /dev/null +++ b/src/user/user.service.spec.ts @@ -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); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/user/user.service.ts b/src/user/user.service.ts new file mode 100644 index 0000000..449e721 --- /dev/null +++ b/src/user/user.service.ts @@ -0,0 +1,27 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { User } from './user.entity'; + +@Injectable() +export class UserService { + constructor( + @InjectRepository(User) + private readonly userRepository: Repository, + ) { + } + + async insertUser(user: User) { + return await this.userRepository.insert(user); + } + + async findOne(username: string): Promise { + return await this.userRepository.findOne({ + username, + }); + } + + async findAll(): Promise { + return await this.userRepository.find(); + } +} diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.ts new file mode 100644 index 0000000..61920f1 --- /dev/null +++ b/test/app.e2e-spec.ts @@ -0,0 +1,23 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import * as request from 'supertest'; +import { AppModule } from './../src/app.module'; + +describe('AppController (e2e)', () => { + let app; + + 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!'); + }); +}); diff --git a/test/jest-e2e.json b/test/jest-e2e.json new file mode 100644 index 0000000..e9d912f --- /dev/null +++ b/test/jest-e2e.json @@ -0,0 +1,9 @@ +{ + "moduleFileExtensions": ["js", "json", "ts"], + "rootDir": ".", + "testEnvironment": "node", + "testRegex": ".e2e-spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + } +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..64f86c6 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..69f185f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "commonjs", + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es2017", + "sourceMap": true, + "outDir": "./dist", + "baseUrl": "./", + "incremental": true + }, + "exclude": ["node_modules", "dist"] +} diff --git a/tslint.json b/tslint.json new file mode 100644 index 0000000..5651b2f --- /dev/null +++ b/tslint.json @@ -0,0 +1,18 @@ +{ + "defaultSeverity": "error", + "extends": ["tslint:recommended"], + "jsRules": { + "no-unused-expression": true + }, + "rules": { + "quotemark": [true, "single"], + "member-access": [false], + "ordered-imports": [false], + "max-line-length": [true, 150], + "member-ordering": [false], + "interface-name": [false], + "arrow-parens": false, + "object-literal-sort-keys": false + }, + "rulesDirectory": [] +}