NestJS build blog system (2) – write static article CURD

preface

Now that we have the basic NestJS framework ready and are familiar with some of the basic concepts, it’s time to start filling in our first feature.

Introduction to the

This article will familiarize you with the basic usage of Controller and Service in NestJS through a simple example.

Write the code

Create a module

Using Nest CLI can quickly help us to create the corresponding file in the terminal type nest-h

name alias description
application application Generate a new application workspace
class cl Generate a new class
configuration config Generate a CLI configuration file
controller co Generate a controller declaration
decorator d Generate a custom decorator
filter f Generate a filter declaration
gateway ga Generate a gateway declaration
guard gu Generate a guard declaration
interceptor in Generate an interceptor declaration
interface interface Generate an interface
middleware mi Generate a middleware declaration
module mo Generate a module declaration
pipe pi Generate a pipe declaration
provider pr Generate a provider declaration
resolver r Generate a GraphQL resolver declaration
service s Generate a service declaration
library lib Generate a new library within a monorepo
sub-app app Generate a new application within a monorepo
resource res Generate a new CRUD resource

Create a new article module and type in sequence on the command line

Nest G co modules/article # Nest G co modules/article #Copy the code

At this point our code structure is

. ├ ─ ─ the README. Md ├ ─ ─ nest - cli. Json ├ ─ ─ package. The json ├ ─ ─ the SRC │ ├ ─ ─ app. The controller. The spec. The ts │ ├ ─ ─ app. The controller. The ts │ ├ ─ ─ App. The module. Ts │ ├ ─ ─ app. Service. The ts │ ├ ─ ─ filters │ ├ ─ ─ main. Ts │ └ ─ ─ modules # new │ └ ─ ─ article │ ├ ─ ─ Article. Controller. Spec. Ts │ ├ ─ ─ the article. The controller. The ts │ ├ ─ ─ the article. The module. The ts │ ├ ─ ─ the article. The service. The spec. The ts │ └ ─ ─ Article. Service. Ts ├ ─ ─ the test │ ├ ─ ─ app. E2e - spec. Ts │ └ ─ ─ jest - e2e. Json ├ ─ ─ tsconfig. Build. The json ├ ─ ─ tsconfig. Json └ ─ ─ yarn.lockCopy the code

Nest CLI will automatically introduce article. Controller and article. Service in article. Module and article

It looks something like this

main: {
  app.module: {
    app.controller
    app.service

    article.module: {
      article.controller
      article.service
    }

  }
}

Copy the code

Write the routing

Write the route in article. Controller

// src/modules/article/article.controller.ts

import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { ArticleService } from './article.service';
import { Article } from './interface/article.interace';

@Controller('article')
export class ArticleController {
  constructor(
    private articleService: ArticleService
  ) {}

  @Get('list')
  getMore() {
    return 'Article List'
  }

  @Get('info')
  getOne(
    @Query() id:string
  ) {
    return 'Article Details'
  }

  @Post('create')
  create(
    @Body() article: Article
  ) {
    return 'Create article'
  }

  @Post('edit')
  update(
    @Body() article: Article
  ) {
    return 'Edit article'
  }

  @Post('remove')
  delete(
    @Body() id: number
  ) {
    return 'Delete article'}}Copy the code

Of course, NestJS provides decorators for standard Http methods, and you can do the same

// src/modules/article/article.controller.ts

import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { ArticleService } from './article.service';
import { Article } from './interface/article.interace';

@Controller('article')
export class ArticleController {
  constructor(
    private articleService: ArticleService
  ) {}

  @Get(a)getMore() {
    return 'Article List'
  }

  @Get(':id')
  getOne(
    @Query() id:string
  ) {
    return 'Article Details'
  }

  @Post(':id')
  create(
    @Body() article: Article
  ) {
    return 'Create article'
  }

  @Put(':id')
  update(
    @Body() article: Article
  ) {
    return 'Edit article'
  }

  @Delete(':id')
  delete() {
    return 'Delete article'}}Copy the code

Nest offers a pretty rich array of decorators to work with, including the controller for details

For the sake of simplicity, I only choose Get and Post

Write the service

Routing, now we only request localhost: 3000 / article/list will only return to the simple list of articles a few strings. So we need to write the service, which is controller (route) -> provider (service)

Before writing services, we first define the field structure of the article, here USES to create the SRC/modules/article/interface/article. The interface. The ts

export interfaceArticle { id? :' '.// id
  title: ' './ / title
  description: ' './ / description
  content: ' '.// contentcreateTime? :' '.// Create timeupdateTime? :' '.// Update timeisDelete? :' '.// Whether to delete
}
Copy the code

Once you have defined the field structure of the article, you can start writing the service

// src/modules/article/article.service.ts

import { Injectable } from '@nestjs/common';
import { Article } from './interface/article.interace';

@Injectable(a)export class ArticleService {
  list: any[]; // Store temporary data
  constructor() {
    this.list = []
  }

  // Get the list
  getMore() {
    return this.list.filter(item= >! item.isDelete) }// Get a single bar
  getOne({ id }) {
    const item = this.list.filter(item= > {
      return item.id === id
    })[0]
    if (item) {
      return item
    }
    return 'Unable to find article'
  }

  // Create the article
  create(
    article: Article
  ) {
    const id = this.list.length
    constitem = { id, ... article }this.list.push(item)
  }

  // Update the article
  update(
    article: Article
  ) {
    let idx = 0
    const item = this.list.filter((item, i) = > {
      if (item.id === article.id) {
        idx = i
      }
      return item.id === article.id
    })
    if(! item) {return 'Unable to find article'
    }
    constnItem = { ... item, ... article, }this.list.splice(idx, 1, nItem)
  }
  
  // Delete the article
  delete({ id }) {
    let idx = 0
    const item = this.list.filter((item, i) = > {
      if (item.id === id) {
        idx = i
      }
      return item.id === id
    })
    if(! item) {return 'Unable to find article'
    }
    constnItem = { ... item,isDelete: true,}this.list.splice(idx, 1, nItem)
  }
}
Copy the code

Rewrite our controller to match the route to the service

import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { ArticleService } from './article.service';
import { Article } from './interface/article.interace';

@Controller('article')
export class ArticleController {
  constructor(
    private articleService: ArticleService
  ) {}

  @Get('list')
  getMore() {
    return this.articleService.getMore()
  }

  @Get('info')
  getOne(
    @Query() id:string
  ) {
    return this.articleService.getOne({ id })
  }

  @Post('create')
  create(
    @Body() article: Article
  ) {
    return this.articleService.create(article)
  }

  @Post('edit')
  update(
    @Body() article: Article
  ) {
    return this.articleService.update(article)
  }

  @Post('remove')
  delete(
    @Body() id: number
  ) {
    return this.articleService.delete({ id })
  }
}
Copy the code

Then we can add, delete, change and check the article.

At this point, we’ve learned about nest’s basic requests, but the data is stored in a list of variables, which means that when we restart the service, the data will be lost.

In the next section, we use TypeORM and mysql for data persistence

reference

  • NestJS
  • NestJS Chinese website
  • Code for this section

A series of

  • NestJS build blog system (a) – build a framework