第四篇 控制器與服務
controller
在nest應用中扮演的是路由分配的功能,并且通過調用service
來實現對數據庫的增刪改查功能。而服務是通過依賴注入
的方式注入的控制器的屬性中。
項目目錄
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
分析項目的目錄我們知道了該項目中有User與Auth兩個業務模塊,一個數據庫模塊Dbs
,和一個根模塊App
。
我們將在auth.service
中實現登錄認證的功能,然后在依賴到auth.controller
模塊中,這樣我們就可以實現用戶登錄的功能。
代碼解析
// 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,屬性中
// 其實不用太在意注入到底是什么,這里你可以理解為AuthController留了個口叫authService,然后nest
// 在內部自動將new AuthService()然后填到authService里
@Post('login') // Post /atuh/login 可以測試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('賬號或密碼錯誤');
}
return user;
}
}
測試
看著感覺很麻煩吧,沒辦法企業級開發就是這樣,因為只有這樣才能將業務與數據分離,為了以后更好的維護擴展,今天就到這里吧,明天為了讓代碼變得更加有維護性和拓展性,明天開始學習一個神奇的東西Guard
,并且對自己寫的Guard
用修飾器進行封裝。
該項目的所有代碼我已經發布到Git上了,地址:https://github.com/holleworldabc/nest-helloworld
最后關注
、點贊
、收藏
,每天都會更新新的文章。
ByBy咱們明天見。
咱們明天見。
本站作品的版權皆為作品作者所有。
本站文字和內容為本站編輯或翻譯,部分內容屬本站原創,所以轉載前務必通知本站并以超鏈接形式注明內容來自本站,否則以免帶來不必要的麻煩。
本站內容歡迎分享,但拒絕有商業目的的轉載!