第四篇 控制器與服務(wù)
controller在nest應(yīng)用中扮演的是路由分配的功能,并且通過(guò)調(diào)用service來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的增刪改查功能。而服務(wù)是通過(guò)依賴注入的方式注入的控制器的屬性中。
項(xiàng)目目錄
src
│ app.module.ts
│ main.ts
│
├─auth
│ auth.controller.ts
│ auth.module.ts
│ auth.service.ts
│
├─dbs
│ dbs.module.ts
│ dbs.service.ts
│
└─user
user.controller.ts
user.module.ts
user.service.ts
分析項(xiàng)目的目錄我們知道了該項(xiàng)目中有User與Auth兩個(gè)業(yè)務(wù)模塊,一個(gè)數(shù)據(jù)庫(kù)模塊Dbs,和一個(gè)根模塊App。
我們將在auth.service中實(shí)現(xiàn)登錄認(rèn)證的功能,然后在依賴到auth.controller模塊中,這樣我們就可以實(shí)現(xiàn)用戶登錄的功能。
代碼解析
// src/auth/auth.controller.ts
import { AuthService } from './auth.service';
import { Controller, Post, Body } from '@nestjs/common';
interface LoginDto {
username: string;
password: string;
}
@Controller('auth') // 這里的 auth 表示的路由 /atuh
export class AuthController {
@Inject() private authService: AuthService;
// 將AuthService注入到authService,屬性中
// 其實(shí)不用太在意注入到底是什么,這里你可以理解為AuthController留了個(gè)口叫authService,然后nest
// 在內(nèi)部自動(dòng)將new AuthService()然后填到authService里
@Post('login') // Post /atuh/login 可以測(cè)試api
login (@Body() dto: LoginDto) {
return this.authService.login(dto.username, dto.password);
}
}
import { Injectable, NotFoundException } from '@nestjs/common';
import { DbsService } from 'src/dbs/dbs.service';
@Injectable()
export class AuthService {
// @Inject() private dbs: DbsService;
constructor(private dbs: DbsService) { }
// 兩種注入方式,效果一樣
login (username: string, password: string) {
const user = this.dbs.findOneByLogin(username, password);
if (user.length === 0) {
throw new NotFoundException('賬號(hào)或密碼錯(cuò)誤');
}
return user;
}
}
測(cè)試


看著感覺很麻煩吧,沒辦法企業(yè)級(jí)開發(fā)就是這樣,因?yàn)橹挥羞@樣才能將業(yè)務(wù)與數(shù)據(jù)分離,為了以后更好的維護(hù)擴(kuò)展,今天就到這里吧,明天為了讓代碼變得更加有維護(hù)性和拓展性,明天開始學(xué)習(xí)一個(gè)神奇的東西Guard,并且對(duì)自己寫的Guard用修飾器進(jìn)行封裝。
該項(xiàng)目的所有代碼我已經(jīng)發(fā)布到Git上了,地址:https://github.com/holleworldabc/nest-helloworld
最后關(guān)注、點(diǎn)贊、收藏,每天都會(huì)更新新的文章。
ByBy咱們明天見。
咱們明天見。
本站作品的版權(quán)皆為作品作者所有。
本站文字和內(nèi)容為本站編輯或翻譯,部分內(nèi)容屬本站原創(chuàng),所以轉(zhuǎn)載前務(wù)必通知本站并以超鏈接形式注明內(nèi)容來(lái)自本站,否則以免帶來(lái)不必要的麻煩。
本站內(nèi)容歡迎分享,但拒絕有商業(yè)目的的轉(zhuǎn)載!