阅读 Nestjs 官方文档,我发现了以下实现ValidationPipe:
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, { metatype }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype: Function): boolean {
const types: Function[] …Run Code Online (Sandbox Code Playgroud) 所以我是Nestjs新手,我发现所有教程都是使用TypeORM连接数据库并执行CRUD操作。
所以我想知道是否有其他方法将 postgreSQL 连接到 Nestjs 并用 SQL 而不是 TypeORM 编写我的 CRUD 操作。
我怎样才能这样做呢?
这样做有什么好处呢?
这样做对性能更好吗?
我想知道当我在构造函数中注入某些东西时是否需要设置只读?例如 :
constructor(readonly private userService: UserService) { }
Run Code Online (Sandbox Code Playgroud)
您能解释一下这种做法的用处(或没有用处)吗?
我试图通过使用 TypeORM 和 crud 库创建一个简单的 REST Api 来进入 Nestjs。到目前为止,我已经创建了一个基于工作角色的身份验证,但我遇到了一个奇怪的问题。我使用 crud 库为 User 实体创建一个简单的控制器。GET 请求运行正常,没有任何问题。但我无法 POST 来创建新用户,也无法使用 PATCH 来更新用户。我认为这可能只是我的一个非常愚蠢的错误,但由于我没有编写太多代码,所以我找不到与文档中的示例有任何差异。
当我尝试修补属性时,它只是用原始用户对象响应我,没有进行任何更改(就像我发送了一个空请求)。当我尝试发布新用户时,响应是以下错误消息:
{
"statusCode": 400,
"error": "Bad Request",
"message": "Empty data. Nothing to save."
}
Run Code Online (Sandbox Code Playgroud)
这可能与验证有关..
这是我的用户控制器:
import { Controller, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
import { AuthGuard } from '@nestjs/passport';
import { ApiTags, ApiSecurity } from '@nestjs/swagger';
import { RolesGuard } from 'src/auth/role.guard';
import { Roles } from './roles.decorator';
import { …Run Code Online (Sandbox Code Playgroud) 我是 NestJ 的新手。我在 Body 中有一个传入字段,在 DTO 中验证它之前我需要对其进行 JSON.parse。
控制器
@Post('test')
@UsePipes(new ValidationPipe({transform: true}))
@UseInterceptors(
FileInterceptor('image', {
storage: diskStorage({
destination: './uploads/users',
filename: editFileName,
}),
fileFilter: imageFileFilter,
}),
)
testapi(
@UploadedFile() file,
// @Body('role', CustomUserPipe) role: string[],
@Body() data: CreateUserDto,
)
{
//
}
Run Code Online (Sandbox Code Playgroud)
数据传输组织
@Transform(role => {JSON.parse(role)}, {toPlainOnly: true})
@IsNotEmpty({message: "Role can't be empty"})
@IsArray({message: "Role must be in array"})
@IsEnum(UserRole, {each: true, message: "Enter valid role"})
role: UserRole[];
Run Code Online (Sandbox Code Playgroud) 我有一个 NestJS 后端,由 JWT 保护。我想知道存储实际用户或将其传递给我的服务的最佳方式是什么?
我有一个 JwtAuthGuard
@Injectable()
export class JwtAuthGuard extends AuthGuard( 'jwt' ) {
canActivate(context: ExecutionContext) {
return super.canActivate( context );
}
handleRequest(err, user, info) {
if ( err || !user ) {
throw err || new UnauthorizedException();
}
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
我的实际用户 ID 位于 handleRequest 中的 user var 中,但我不知道在哪里“存储”它以便能够在某些模块中访问它。有人可以帮助我吗?
谢谢
我正在尝试使用 Joi 验证具有多个查询的 Nest.js 上的 GET 请求。我了解如何UsePipes在单个参数上使用和验证单个对象。但是我现在有一个具有多个查询的端点,这是我的控制器:
@Get(':cpId/search')
@UsePipes(new JoiValidationPipe(queryDTOSchema))
async getSomethingByFilters(
@Param('cpId') cpId: string,
@Query('startDate') startDate?: number,
@Query('endDate') endDate?: number,
@Query('el') el?: string,
@Query('fields') fields?: string,
@Query('keyword') keyword?: string,
@Query('page') page?: number,
@Query('limit') limit?: number,
)...Run Code Online (Sandbox Code Playgroud)
现在UsePipes正在针对每个查询验证相同的架构,但我不明白如何单独验证每个查询。
有没有办法分别验证每个查询?我找不到任何引用,我能想到的唯一解决方案是将所有这些查询转换为单个对象,在这种情况下这是不可取的。
我对 NestJs 很陌生,但是我最近要详细说明的问题更多的是异步异常处理问题。我有一个 http post 函数,负责在 mongodb 中插入用户,以防找不到具有该 id 的任何其他用户。由于 findOne 函数是异步的,因此当存在重复用户时我不能抛出异常。这是我的控制器:
@Post('/register')
async register(@Body() createUserDto: User): Promise<String> {
return await this.sejamService.registerUser(createUserDto);
}
Run Code Online (Sandbox Code Playgroud)
我的用户服务:
try {
this.findOne(userProfile.nationalCode).then(res => {
if (res === undefined) {
var user = new User(userProfile.nationalCode, userProfile.email, userProfile.password, userProfile.firstName,
userProfile.surname, userProfile.fatherName, userProfile.birthCertNumber, userProfile.phoneNumber);
//const createdUser = new this.userModel(userProfile);
this.usersRepository.save(user);
} else {
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: 'some error',
}, HttpStatus.CONFLICT);
}
});
} catch (e) {
console.log('error');
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: 'some error', …Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的 Nest JS 应用程序中进行第三方 API 调用。由于 Nest JS 在底层使用 Axios,并且在其文档中拥有专门的页面https://docs.nestjs.com/techniques/http-module,因此我确保遵循文档中提供的实现,但我保留当我尝试通过 Nestjs 的 httpModule 发出 HTTP 请求时,遇到httpService undefined错误。我不确定我错过了什么,我尝试在这里搜索相关问题,但没有成功。请帮忙看一下,下面是我的代码示例。
银行验证.service.ts
import { HttpService } from '@nestjs/common';
import { Observable } from 'rxjs';
import { config } from 'dotenv';
import { AxiosResponse } from 'axios';
config();
export class BankVerificationService {
constructor(private httpService: HttpService){}
getBanks(countryCode): Observable<AxiosResponse<any>> {
console.log(this.httpService, '===============')
return this.httpService.get(`https://api.flutterwave.com/v3/banks/${countryCode}`, {
headers: {
Authorization: `Bearer ${process.env.FLUTTERWAVE_TEST_SECRET}`
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的 Axios HTTP 模块配置
import { Module, HttpModule } …Run Code Online (Sandbox Code Playgroud) 我有 Nestjs 应用程序,它使用 TypeORM 包与 Postgres SQL 交互。
我里面有以下代码,
import {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index} from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
public id: number;
@Index()
@Column({nullable: true})
public userId: number;
@Index()
@Column()
public appId: string;
@Column({nullable: true})
public keyId: number;
}
import {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index} from 'typeorm';
@Entity()
export class Key {
@PrimaryGeneratedColumn()
public id: number;
@Index()
@Column()
public userId: number;
@Index()
@Column()
public key: string;
}
import {Injectable} from '@nestjs/common';
import {InjectRepository} from …Run Code Online (Sandbox Code Playgroud) nestjs ×10
typescript ×6
node.js ×3
typeorm ×3
postgresql ×2
angular ×1
axios ×1
crud ×1
javascript ×1
joi ×1
jwt ×1
passport-jwt ×1