Nestjs

Nestjs for TypeScript

https://docs.nestjs.com/

CLI

# 全局安装CLI
npm i -g @nestjs/cli

# 创建项目
nest new project-name

# 运行(watch模式)
npm run start:dev


# 创建子项目
nest g app xxx
# nest g app admin 会生成一个apps文件夹,下面有admin和server文件夹

# 创建公共模块
nest g lib db

# 启动子项目路
nest start -w admin


# 创建子模块(一个空的文件夹)
nest g mo child-module 
nest g mo -p admin users

# 创建生成XxController
nest g co xx
nest g co -p admin users

npm i --save @nestjs/swagger swagger-ui-express
npm i mongoose @types/mongoose nestjs-typegoose @typegoose/typegoose

Swagger

npm i --save @nestjs/swagger swagger-ui-express
...
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  // -------------------------------------------------------------------swagger
  const options = new DocumentBuilder()
    .setTitle('标题')
    .setDescription('描述')
    .setVersion('1.0')
    .addTag('添加标签')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('docs', app, document);
  // ------------------------------------------------------------------------
  await app.listen(5000, () => console.log('---> http://localhost:5000/docs');
}
bootstrap();

Mongo

npm i mongoose @types/mongoose nestjs-typegoose @typegoose/typegoose

xxx.model.ts

纯粹定义模型

import { prop } from '@typegoose/typegoose';
import { ApiProperty } from '@nestjs/swagger';

export class Posts {

    @ApiProperty({description: '标题1', example: '标题1'})
    @prop()
    title: string;

    @ApiProperty({description: '内容1', example: '内容1'})
    @prop()
    content: string;
}

xxx.module.ts

import { Module } from '@nestjs/common';
import { PostsController } from './posts.controller';
import { TypegooseModule } from 'nestjs-typegoose';
import { Posts } from './posts.model';

@Module({
  imports: [TypegooseModule.forFeature([Posts])],
  controllers: [PostsController]
})
export class PostsModule {}

mongo.ts

/**
 * mongodb数据库连接字符串
 */
const srv = 'mongodb srv://xxx:test@cluster0-umpkc.mongodb.net/testdb?retryWrites=true&w=majority';
const local= 'mongodb://wlh:root@localhost:27017';
export {srv, atlas, local}

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PostsModule } from './posts/posts.module';
import { TypegooseModule } from 'nestjs-typegoose';
import { srv } from './mongo'

@Module({
  imports: [TypegooseModule.forRoot(srv, {
    useNewUrlParser : true,
    useUnifiedTopology : true,
    useCreateIndex : true,
    useFindAndModify : false,
  }) , PostsModule],
  controllers: [AppController],
  providers: [AppService]
})
export class AppModule {}

xxx.controller.ts CRUD

npm i nestjs-mongoose-crud
import { Controller } from '@nestjs/common';
import { Crud } from 'nestjs-mongoose-crud'
import { Posts } from './posts.model';
import { InjectModel } from 'nestjs-typegoose';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { ApiTags, ApiOperation, ApiPropertyOptional, ApiProperty, ApiResponseProperty } from '@nestjs/swagger'

// users?query={"where":{"username":"user1","age":{"$gt":18}},"sort":"-_id","limit":10,"page":2,"populate":"friends"}
@Crud({
    model: Posts,
    routes: {
        find: {
            decorators: [ApiOperation({summary:'帖子列表', description: 'API描述'})],
            // where: {'title': 'Java02'},
            paginate: {data: 'rows'},
            limit: 1,
            sort: "content",
        },
        create: {
            dto: Posts,
            decorators: [ApiOperation({summary:'新建帖子', description: 'API描述'})]
        },
        update: {
            decorators: [ApiOperation({summary:'更新帖子', description: 'API描述'})]
        }
    }
})
@ApiTags('帖子')
@Controller('posts')
export class PostsController {
    constructor(@InjectModel(Posts) private readonly model:ModelType<Posts>){}
}

MySQL

npm i --save mysql @nestjs/typeorm typeorm 

ormconfig.json

放置在根目录下

{
    "type": "mariadb",
    "host": "localhost",
    "port": 3306,
    "username": "root",
    "password": "root",
    "database": "wlh",
    "entities": ["dist/**/*.entity{.ts,.js}"],
    "synchronize": true
}

xxx.model.ts

纯粹定义模型

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Photo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 500 })
  name: string;

  @Column('text')
  description: string;

  @Column()
  filename: string;

  @Column('int')
  views: number;

  @Column()
  isPublished: boolean;
}

xxx.module.ts

import { Module } from '@nestjs/common';
import { PhotoController } from './photo.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Photo } from './photo.entity';

@Module({
  imports: [TypeOrmModule.forFeature([Photo])],
  controllers: [PhotoController]
})
export class PhotoModule {}

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PhotoModule } from './photo/photo.module';

@Module({
  imports: [TypeOrmModule.forRoot(), PhotoModule, ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

xxx.controller.ts

import { Controller, Get } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Photo } from './photo.entity';
import { Repository } from 'typeorm';

@Controller('photo')
export class PhotoController {
    constructor(
        @InjectRepository(Photo) private readonly repos: Repository<Photo>
    ){}


    @Get()
    findAll(): Promise<Photo[]> {
      return this.repos.find();
    }
}

本文由博客一文多发平台 OpenWrite 发布!

发布了1 篇原创文章 · 获赞 0 · 访问量 25
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览