前言
搭建后台服务需要那些准备工作呢~
JWT
对接口进行权限验证,保障数据安全~
@Module({
imports: [
UserModule,
JwtModule.register({
global: true,
secret: jwtConstants.secret,
signOptions: { expiresIn: '3600s' },
}),
],
providers: [AuthService, {
provide: APP_GUARD,
useClass: AuthGuard,
},],
controllers: [AuthController],
exports: [AuthService],
})
然后配置权限守卫,自定义权限装饰器~
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: jwtConstants.secret,
});
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
就可以使用@public装饰器去开放权限
@Public()
@HttpCode(HttpStatus.OK)
@Post('login')
signIn(@Body() signInDto: Record<string, any>) {
return this.authService.signIn(signInDto.username, signInDto.password);
}
SQL
配置typeorm mysql数据库~
@Module({
imports: [
AuthModule,
UserModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '',
database: '',
entities: [],
synchronize: true,
}),
LoggerModule,
],
controllers: [AppController],
providers: [AppService,
],
})
注入依赖
@Module({
imports:[TypeOrmModule.forFeature([User]),LoggerModule],
providers: [UserService],
exports:[UserService,TypeOrmModule],
controllers:[UserController]
})
然后就可以使用typeorm的api进行数据增删改查~
@Get()
queryAllUsers() {
this.myLoggerService.customLog(UserController.name,'查询成功')
return this.userService.findAll();
}
@Post('/create')
createUser(@Body() user: Partial<User>) {
return this.userService.createUser(user)
}
拦截器
对响应式数据进行格式化~
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, Response<T>>
{
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<Response<T>> {
return next.handle().pipe(
map((data) => {
return { ...data };
}),
);
}
}
在providers中配置格式转化拦截器~
@Module({
imports: [
AuthModule,
UserModule
],
controllers: [AppController],
providers: [AppService,
{
provide:APP_INTERCEPTOR,
useClass:TransformInterceptor
}
],
})
日志
自定义日志
@Injectable({ scope: Scope.TRANSIENT })
export class MyLoggerService extends ConsoleLogger {
customLog(name,msg) {
this.log(`${name} - ${msg}`);
}
}
配置全局日志~
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
bufferLogs: true,
});
app.useLogger(new MyLoggerService())
await app.listen(3000);
}
bootstrap();
最后
后台服务就搭建起来啦~