nest基础学习流程图

部署

1.

2.

3.

4.

使用的库
Pipe


service




依赖注入原因
控制反转

3个module 连接在一起


TypeORM 连接数据库


建立数据库表




路由,请求

插入数据库后编辑的


登录



最简单的开发流程增删改查
controller
import { Controller, Get, Post, Param, Body, Put, Delete } from '@nestjs/common';
import { AddressService } from './address.service';
import { Address } from './address.entity';
@Controller('address')
export class AddressController {
constructor(private readonly addressService: AddressService) { }
// 获取所有地址
@Get()
findAll(): Promise<Address[]> {
return this.addressService.findAll();
}
// 根据ID获取单个地址
@Get(':id')
findOne(@Param('id') id: number): Promise<Address> {
return this.addressService.findOne(id);
}
// 新增地址
@Post()
create(@Body() address: Address): Promise<Address> {
return this.addressService.create(address);
}
// 更新地址
@Put(':id')
update(@Param('id') id: number, @Body() address: Address): Promise<Address> {
return this.addressService.update(id, address);
}
// 删除地址
@Delete(':id')
remove(@Param('id') id: number): Promise<void> {
return this.addressService.remove(id);
}
}
entity
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class Address {
@PrimaryGeneratedColumn()
id: number;
@Column()
street: string;
@Column()
city: string;
@Column()
postalCode: string;
@Column()
country: string;
// 日期时间类型(包含日期和时间)
@Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
// 时间戳类型(通常用于记录最后更新时间)
@Column({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP',
onUpdate: 'CURRENT_TIMESTAMP'
})
updatedAt: Date;
}
module
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Address } from './address.entity';
import { AddressController } from './address.controller';
import { AddressService } from './address.service';
@Module({
imports: [TypeOrmModule.forFeature([Address])],
controllers: [AddressController],
providers: [AddressService]
})
export class AddressModule {}
service
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Address } from './address.entity';
@Injectable()
export class AddressService {
constructor(
@InjectRepository(Address)
private readonly addressRepository: Repository<Address>,
) {}
// 增加地址
async create(address: Address): Promise<Address> {
return await this.addressRepository.save(address);
}
// 查找所有地址
async findAll(): Promise<Address[]> {
return await this.addressRepository.find();
}
// 查找单个地址
async findOne(id: number): Promise<Address> {
return await this.addressRepository.findOneBy({id});
}
// 更新地址
async update(id: number, address: Address): Promise<Address> {
await this.addressRepository.update(id, address);
return this.findOne(id); // 返回更新后的地址
}
// 删除地址
async remove(id: number): Promise<void> {
await this.addressRepository.delete(id);
}
}
app.module
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { User } from './user/user.entity';
import { Address } from './address/address.entity';
import { AddressModule } from './address/address.module';
@Module({
imports: [TypeOrmModule.forRoot({
type: 'mysql', // 使用 mysql 数据库
host: 'localhost', // 数据库地址
port: 3306, // MySQL 默认端口
username: 'root', // 数据库用户名
password: '123456', // 数据库密码
database: 'testdb', // 数据库名称
entities: [User,Address] , // 定义要映射的实体
synchronize: true, // 自动同步实体(开发环境可以开启)
}), UserModule, AddressModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
jwt参考
user.controller.ts
import {BadRequestException, Body, Controller, Get, Post, Req, Res, UnauthorizedException, UseGuards} from '@nestjs/common';
import {UserService} from './user.service';
import * as bcrypt from 'bcrypt';
import {JwtService} from '@nestjs/jwt';
import {Response, Request} from 'express';
import {AuthGuard} from 'src/auth/auth.guard';
@Controller('api')
export class UserController {
constructor(
private readonly userService: UserService,
private readonly jwtService: JwtService
) {}
@Get('user123')
@UseGuards(AuthGuard)
getAllUser() {
return this.userService.findAll();
}
// 注册
@Post('register')
async register(@Body('username') username: string, @Body('email') email: string, @Body('password') password: string) {
const hashedPassword = await bcrypt.hash(password, 12);
return this.userService.register({
username,
email,
password: hashedPassword
});
}
// 登录
@Post('login')
async login(@Body('email') email: string, @Body('password') password: string, @Res({passthrough: true}) response: Response) {
const user = await this.userService.findOne(email);
if (!user) {
throw new BadRequestException('invalid credentials');
}
if (!(await bcrypt.compare(password, user.password))) {
throw new BadRequestException('invalid creadentials');
}
// return user;
const jwt = await this.jwtService.signAsync({id: user.id});
response.cookie('jwt', jwt, {httpOnly: true});
return {
message: 'success'
};
}
@Post('logout')
async logout(@Res({passthrough: true}) response: Response) {
response.clearCookie('jwt');
return {
message: 'success'
};
}
@Get('user')
async user(@Req() request: Request) {
try {
const cookie = request.cookies['jwt'];
const data = await this.jwtService.verifyAsync(cookie);
if (!data) {
throw new UnauthorizedException();
}
const user = await this.userService.findOneId(data['id']);
const {password, ...result} = user;
return result;
} catch (e) {
throw new UnauthorizedException();
}
}
}
auth.guard.ts
import {Injectable} from '@nestjs/common';
import {CanActivate, ExecutionContext, UnauthorizedException} from '@nestjs/common';
import {JwtService} from '@nestjs/jwt';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const cookie = request.cookies['jwt'];
if (!cookie) {
throw new UnauthorizedException('Missing token');
}
try {
// 验证 JWT
const decoded = await this.jwtService.verifyAsync(cookie);
request.user = decoded; // 将解码后的用户信息添加到请求中
return true;
} catch (error) {
throw new UnauthorizedException('Invalid or expired token');
}
}
}
auth.module.ts
import {Module} from '@nestjs/common';
import {AuthController} from './auth.controller';
import {AuthService} from './auth.service';
import {JwtModule} from '@nestjs/jwt';
import {TypeOrmModule} from '@nestjs/typeorm';
@Module({
imports: [
JwtModule.register({
secret: 'secret',
signOptions: {expiresIn: '60s'}
})
],
controllers: [AuthController],
providers: [AuthService],
exports: [JwtModule]
})
export class AuthModule {}

浙公网安备 33010602011771号