master
expressgy 2 years ago
commit 4cc541f50c
  1. 25
      .eslintrc.js
  2. 35
      .gitignore
  3. 5
      .prettierrc
  4. 73
      README.md
  5. 8
      nest-cli.json
  6. 74
      package.json
  7. 5683
      pnpm-lock.yaml
  8. 22
      src/app.controller.spec.ts
  9. 48
      src/app.controller.ts
  10. 11
      src/app.module.ts
  11. 10
      src/app.service.ts
  12. 48
      src/main.ts
  13. 25
      src/xiaoman/dto/create-xiaoman.dto.ts
  14. 4
      src/xiaoman/dto/update-xiaoman.dto.ts
  15. 1
      src/xiaoman/entities/xiaoman.entity.ts
  16. 20
      src/xiaoman/xiaoman.controller.spec.ts
  17. 50
      src/xiaoman/xiaoman.controller.ts
  18. 7
      src/xiaoman/xiaoman.guard.spec.ts
  19. 27
      src/xiaoman/xiaoman.guard.ts
  20. 9
      src/xiaoman/xiaoman.module.ts
  21. 18
      src/xiaoman/xiaoman.service.spec.ts
  22. 26
      src/xiaoman/xiaoman.service.ts
  23. 24
      test/app.e2e-spec.ts
  24. 9
      test/jest-e2e.json
  25. 4
      tsconfig.build.json
  26. 21
      tsconfig.json

@ -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',
},
};

35
.gitignore vendored

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# 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

@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 4
}

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/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.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><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.
## Installation
```bash
$ pnpm install
```
## Running the app
```bash
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod
```
## Test
```bash
# unit tests
$ pnpm run test
# e2e tests
$ pnpm run test:e2e
# test coverage
$ pnpm 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).

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

@ -0,0 +1,74 @@
{
"name": "nest-learn",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"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"
},
"dependencies": {
"@fastify/multipart": "^7.4.2",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/platform-fastify": "^9.3.9",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"nacos": "^2.5.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "29.2.4",
"@types/node": "18.11.18",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "29.3.1",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "29.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.1",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

File diff suppressed because it is too large Load Diff

@ -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!');
});
});
});

@ -0,0 +1,48 @@
import {
Body,
Controller,
Get,
Param,
Post,
Query,
Req,
Session,
} from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(
@Req() request: Request,
@Body() body: Body,
@Session() session: any,
@Param() param: any,
@Query() query: any,
): string {
console.log('BODY', body);
console.log('SESSION', session);
console.log('PARAM', param);
console.log('QUERY', query);
return 'hello World';
}
@Post()
async readBody(@Body() body: Body, @Req() request: any): Promise<string> {
const files = await request.saveRequestFiles();
console.log('FILE', files);
console.log(
'FILE:filepath',
files[0].filepath,
files[0].fieldname,
files[0].filename,
files[0].encoding,
files[0].mimetype,
// files[0].fields,
files[0].file.bytesRead,
);
// console.log(body);
return 'hello World';
}
}

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { XiaomanModule } from './xiaoman/xiaoman.module';
@Module({
imports: [XiaomanModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

@ -0,0 +1,10 @@
import { Injectable } from '@nestjs/common';
import { Request } from 'express';
@Injectable()
export class AppService {
getHello(request: Request): string {
console.log(request);
return 'Hello World!';
}
}

@ -0,0 +1,48 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import fastifyM from '@fastify/multipart';
import { NacosNamingClient } from 'nacos';
import { ValidationPipe } from '@nestjs/common';
//
// async function bootstrap() {
// const app = await NestFactory.create(AppModule);
// await app.listen(3000);
// }
// bootstrap();
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({
logger: true,
}),
);
app.useGlobalPipes(new ValidationPipe());
await app.register(fastifyM);
await app.listen(3000, '0.0.0.0');
}
async function microServer() {
const logger = console;
const client = new NacosNamingClient({
logger,
serverList: '192.168.1.200:8848', // replace to real nacos serverList
namespace: 'public',
});
await client.ready();
const serviceName = 'node-nestjs'; //服务名
await client.registerInstance(serviceName, {
ip: '192.168.1.128',
port: 3000,
});
}
// microServer();
bootstrap();

@ -0,0 +1,25 @@
import { IsEmail, IsNotEmpty, IsPhoneNumber, IsString } from 'class-validator';
// 此文件为验证演示
// https://github.com/typestack/class-validator#usage
// 这里有更多的验证方法
export class CreateXiaomanDto {
@IsNotEmpty({
message: 'name 不能为空',
})
@IsString()
name: string;
@IsPhoneNumber('CN', {
message: 'phone 不是一个电话号码',
})
phone: string;
@IsEmail(
{},
{
message: 'email 不是一个合法邮箱',
},
)
email: string;
}

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateXiaomanDto } from './create-xiaoman.dto';
export class UpdateXiaomanDto extends PartialType(CreateXiaomanDto) {}

@ -0,0 +1 @@
export class Xiaoman {}

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { XiaomanController } from './xiaoman.controller';
import { XiaomanService } from './xiaoman.service';
describe('XiaomanController', () => {
let controller: XiaomanController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [XiaomanController],
providers: [XiaomanService],
}).compile();
controller = module.get<XiaomanController>(XiaomanController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

@ -0,0 +1,50 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
ValidationPipe,
ParseIntPipe,
UseGuards,
} from '@nestjs/common';
import { XiaomanService } from './xiaoman.service';
import { CreateXiaomanDto } from './dto/create-xiaoman.dto';
import { UpdateXiaomanDto } from './dto/update-xiaoman.dto';
import { XiaomanGuard } from './xiaoman.guard';
@Controller('xiaoman')
export class XiaomanController {
constructor(private readonly xiaomanService: XiaomanService) {}
@Post()
create(@Body(new ValidationPipe()) createXiaomanDto: CreateXiaomanDto) {
return this.xiaomanService.create(createXiaomanDto);
}
@Get()
@UseGuards(XiaomanGuard)
findAll() {
return this.xiaomanService.findAll();
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.xiaomanService.findOne(+id);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() updateXiaomanDto: UpdateXiaomanDto,
) {
return this.xiaomanService.update(+id, updateXiaomanDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.xiaomanService.remove(+id);
}
}

@ -0,0 +1,7 @@
import { XiaomanGuard } from './xiaoman.guard';
describe('XiaomanGuard', () => {
it('should be defined', () => {
expect(new XiaomanGuard()).toBeDefined();
});
});

@ -0,0 +1,27 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class XiaomanGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
console.log(context);
const request = context.switchToHttp().getRequest();
// console.log(request);
console.log(request.url);
console.log(request.headers);
// 自定义返回消息
throw new UnauthorizedException({
statusCode: 403,
message: '你没有访问权限',
error: 'Forbidden',
});
return false;
}
}

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { XiaomanService } from './xiaoman.service';
import { XiaomanController } from './xiaoman.controller';
@Module({
controllers: [XiaomanController],
providers: [XiaomanService],
})
export class XiaomanModule {}

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { XiaomanService } from './xiaoman.service';
describe('XiaomanService', () => {
let service: XiaomanService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [XiaomanService],
}).compile();
service = module.get<XiaomanService>(XiaomanService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateXiaomanDto } from './dto/create-xiaoman.dto';
import { UpdateXiaomanDto } from './dto/update-xiaoman.dto';
@Injectable()
export class XiaomanService {
create(createXiaomanDto: CreateXiaomanDto) {
return 'This action adds a new xiaoman';
}
findAll() {
return `This action returns all xiaoman`;
}
findOne(id: number) {
return `This action returns a #${id} xiaoman`;
}
update(id: number, updateXiaomanDto: UpdateXiaomanDto) {
return `This action updates a #${id} xiaoman`;
}
remove(id: number) {
return `This action removes a #${id} xiaoman`;
}
}

@ -0,0 +1,24 @@
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!');
});
});

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}
Loading…
Cancel
Save