快速入门nest.js(2/10)--Service

简介: 意味着对象之间可以创建各种关系,并且对象实例连接在一起的逻辑都可以由Nest运行时系统处理,而不是尝试自己创建和管理这种类型的依赖注入。

准备


帮助我们将业务逻辑与控制器分开,将我们的业务逻辑分离为服务

// 使用nest g s


可以看到app.module.ts中多出了providers: [AppService, CoffeesService],其中的CoffeesService为新建的。

意味着对象之间可以创建各种关系,并且对象实例连接在一起的逻辑都可以由Nest运行时系统处理,而不是尝试自己创建和管理这种类型的依赖注入。

模拟假数据源:


// ./entities/coffee.entity
export class Coffee {
  id: number;
  name: string;
  brand: string;
  flavors: string[];
}


// coffees.service中
import { Coffee } from './entities/coffee.entity';


CRUD


// coffees.service中
@Injectable()
export class CoffeesService {
  // 模拟一个假数据源进行CRUD
  private coffees: Coffee[] = [
    {
      id: 1,
      name: 'Shipwreck Roast',
      brand: 'Buddy Brew',
      flavors: ['chocolate', 'vanilla'],
    },
  ];
  // CRUD
  findAll() {
    return this.coffees;
  }
  findOne(id: string) {
    return this.coffees.find((item) => item.id === +id);
  }
  create(createCoffeeDto: any) {
    this.coffees.push(createCoffeeDto);
  }
  update(id: string, updateCoffeeDto: any) {
    const existingCoffee = this.findOne(id);
    if (existingCoffee) {
      // update the existing entity
    }
  }
  remove(id: string) {
    const coffeeIndex = this.coffees.findIndex((item) => item.id === +id);
    if(coffeeIndex >= 0){
      this.coffees.splice(coffeeIndex, 1);
    }
  }
}


我们之前在controller里面没有做任何操作,这里将CRUD操作加入其中:

// coffees.controller中
@Get(':id')
findOne(@Param('id') id: string) {
    // 选择传入某个字符串
    return this.coffeeService.findOne(id);  // 使用service中的方法替换之前写的空方法
    // return `this action return ${id} coffee`;
}


其他的类似......

处理错误


为常见的场景抛出不同的状态码


    
findOne(id: string) {
    const coffee = this.coffees.find((item) => item.id === +id);
    if(!coffee){
        throw new HttpException(`Coffee ${id} not found`, HttpStatus.NOT_FOUND);
    }
    return coffee;
}


// fa
{
    "statusCode": 404,
    "message": "Coffee 2 not found",
    "error": "Not Found"
}


简化:

throw new NotFoundException(`Coffee ${id} not found`);  // 简化类


当你出现其他异常时,nest会帮助你返回500

throw 'A random error';


// 返回
{
    "statusCode": 500,
    "message": "Internal server error"
}


目录
相关文章
|
8天前
|
SQL 存储 前端开发
React&Nest.js全栈社区平台(五)——👋封装通用分页Service实现文章流与详情
React&Nest.js全栈社区平台(五)——👋封装通用分页Service实现文章流与详情
React&Nest.js全栈社区平台(五)——👋封装通用分页Service实现文章流与详情
|
移动开发 JSON JavaScript
AngularJs异步上传图片,并获取图片地址(JS service层)
anjularjs对于post和get请求默认的Content-Type header 是application/json。通过设置‘Content-Type’: undefined,这样浏览器会把Content-Type 设置为 multipart/form-data.
97 0
AngularJs异步上传图片,并获取图片地址(JS service层)
|
存储 缓存 JSON
[译] JS 中 service workers 的简介
Service workers是Progressive Web Apps的核心部分,允许缓存资源和Web推送通知等,以创建良好的离线体验。它们充当Web应用程序,浏览器和网络之间的代理,允许开发人员拦截和缓存网络请求,并基于网络的可用性采取适当的操作。
|
前端开发 JavaScript API
如何使用Javascript 访问local部署的YAAS service
Created by Jerry Wang, last modified on May 08, 2015 启动你本地Eclipse里的YAAS service: 为了方便起见,新建一个批处理文件,内容如下,双击即可执行:
90 0
如何使用Javascript 访问local部署的YAAS service
how is service url defined in configuration.js consumed
Created by Wang, Jerry, last modified on Mar 26, 2015
92 0
how is service url defined in configuration.js consumed
|
Web App开发 JavaScript 前端开发
|
JavaScript 前端开发 .NET
用JavaScript调用WCF Service
原文:用JavaScript调用WCF Service   原创地址:http://www.cnblogs.com/jfzhu/p/4039604.html 转载请注明出处   前面介绍过《Step by Step 创建一个WCF Service》和《使用WCF的Trace与Message Log功能》,本文介绍一下如何用JavaScript来调用WCF Service。
721 0
|
JavaScript 前端开发 数据格式
javascript如何访问WebService
原理:异步提交POST数据到Web Services的方法上,分析返回的xml数据,获得结果。下面是用比较流行的Ajax框架JQuery来实现刚才的操作。 var calc = function() { var a = parseInt($('#numberA').
667 0