我试图在我的项目中巧妙地使用 DTO 和实体,但它似乎比它应该的更复杂。我正在构建一个用于管理库存的后端,我使用 NestJs 和 TypeOrm。
我的客户正在向我发送一组数据并抛出一个 POST 请求,比方说:
{
"length": 25,
"quantity": 100,
"connector_A": {
"id": "9244e41c-9da7-45b4-a1e4-4498bb9de6de"
},
"connector_B": {
"id": "48426cf0-de41-499b-9c02-94c224392448"
},
"category": {
"id": "f961d67f-aea0-48a3-b298-b2f78be18f1f"
}
}
Run Code Online (Sandbox Code Playgroud)
我的控制器有责任使用自定义 ValidationPipe 来检查该字段:
@Post()
@UsePipes(new ValidationPipe())
create(@Body() data: CableDto) {
return this.cablesService.create(data);
}
Run Code Online (Sandbox Code Playgroud)
我在很多地方都读到过,在最佳实践中,RAW 数据应该转换为 DTO,而在插入数据时,我应该将我的 DTO 转换为 typeOrm 实体。
我对这个方法没问题,但我发现它非常复杂,当我的表和前缀名词之间存在关系时,它会更复杂。
这是我的实体电缆
@Entity('t_cable')
export class Cable {
@PrimaryGeneratedColumn('uuid')
CAB_Id: string;
@Column({
type: "double"
})
CAB_Length: number;
@Column({
type: "int"
})
CAB_Quantity: number;
@Column()
CON_Id_A: string
@Column()
CON_Id_B: string
@Column()
CAT_Id: …Run Code Online (Sandbox Code Playgroud) 我有多种身份验证策略,例如其中之一:
@Injectable()
export class EmployeeStrategy extends PassportStrategy(Strategy, 'employee') {
constructor(
private authService: AuthService,
@Inject(appConfig.KEY)
configService: ConfigType<typeof appConfig>,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.EMPLOYEE_KEY,
});
}
async validate({ phone }: JwtPayload) {
const employee = await this.authService.authByRole(phone, Role.Employee);
if (!employee) {
throw new UnauthorizedException('insufficient scope');
}
return employee;
}
Run Code Online (Sandbox Code Playgroud)
还有一些人大多喜欢这个。但是因为我在其中抛出了未经授权的异常,所以我不能在同一个路由/控制器上使用多个异常。例如
@UseGuards(AuthGuard(['employee', 'admin']))
Run Code Online (Sandbox Code Playgroud)
第一个崩溃导致错误的。如何解决这个问题?
我有一个已经可以正常工作的用户身份验证。用户认证的令牌在一小时内过期。
我想实现另一个单独的身份验证策略,即使用我的 Nestjs API 的第三个 API。第三方 API 有单独的端点,令牌应在 24 小时后过期。API 必须与我的应用保持连接 24 小时。
我不介意使用额外的包来实现这一点。
我还需要创建一个名为thirdParty Guard 的保护,以便仅第三部分API 就可以访问该端点。
这是我的 jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.SECRETKEY
});
}
async validate(payload: any, done: VerifiedCallback) {
const user = await this.authService.validateUser(payload);
if (!user) {
return done(
new HttpException('Unauthorised access', HttpStatus.UNAUTHORIZED),
false,
);
}
//return user;
return done(null, user, payload.iat)
}
}
Run Code Online (Sandbox Code Playgroud)
ApiKey.strategy.ts
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {
constructor(private …Run Code Online (Sandbox Code Playgroud) 我是 Nestjs 的新手。如何设置接受日期格式和日期时间格式的列?
不是在这两种情况下,列是两个不同的列,一个接受日期,另一个接受日期时间。
我有一个新的 Web 应用程序,并且编写了一个迁移器来创建用户表。但是,无论我尝试什么,typeorm 似乎都找不到此迁移器,因此也不会运行它。
我的文件结构(未显示其他文件/文件夹):
??? Server
? ??? dist
| | ??? Migrations
| | | ??? 1234567891234567890-AddUserTable.js
| | | ??? 1234567891234567890-AddUserTable.js.map
| | | ??? 1234567891234567890-AddUserTable.d.ts
? ??? src
| | ??? Migrations
| | | ??? 1234567891234567890-AddUserTable.ts
| | ??? app.module.ts
Run Code Online (Sandbox Code Playgroud)
app.module.ts
@Module({
imports: [
ConfigModule.forRoot({ envFilePath: '.env' }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get('TYPEORM_HOST'),
port: +configService.get<number>('TYPEORM_PORT'),
username: configService.get('TYPEORM_USERNAME'),
password: configService.get('TYPEORM_PASSWORD'),
database: configService.get('TYPEORM_DATABASE'),
synchronize: configService.get('TYPEORM_SYNCHRONIZE'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
migrations: …Run Code Online (Sandbox Code Playgroud) 我尝试使用 mailgun 发送电子邮件。我使用 node.js (nest.js),这是我的邮件服务。我应该改变什么?当我尝试发送第一封电子邮件(mailgun 官方网站中的描述)时,我收到了相同的错误消息。
import { Injectable } from '@nestjs/common';
import * as Mailgun from 'mailgun-js';
import { IMailGunData } from './interfaces/mail.interface';
import { ConfigService } from '../config/config.service';
@Injectable()
export class MailService {
private mg: Mailgun.Mailgun;
constructor(private readonly configService: ConfigService) {
this.mg = Mailgun({
apiKey: this.configService.get('MAILGUN_API_KEY'),
domain: this.configService.get('MAILGUN_API_DOMAIN'),
});
}
send(data: IMailGunData): Promise<Mailgun.messages.SendResponse> {
console.log(data);
console.log(this.mg);
return new Promise((res, rej) => {
this.mg.messages().send(data, function (error, body) {
if (error) {
console.log(error);
rej(error);
}
res(body);
});
});
}
} …Run Code Online (Sandbox Code Playgroud) 我在为 nestjs-typeorm-mongo 项目创建初始迁移时遇到问题。
我从 nestjs克隆了这个示例项目,它使用 typeorm 和 mongodb。该项目确实有效,当我在将“照片”文档放入我的本地 mongo 并使用名为“test”和集合“photos”的数据库后在本地运行它时,我可以调用 localhost:3000/photo 并接收照片文档。
现在我正在尝试使用以下命令使用 typeorm cli 创建迁移:
./node_modules/.bin/ts-node ./node_modules/typeorm/cli.js migration:generate -n initial
Run Code Online (Sandbox Code Playgroud)
...但它不起作用。我无法创建初始提交 - 即使在我的app.module.ts文件中设置“同步:false”后,我总是收到错误消息:
未发现数据库架构更改 - 无法生成迁移。要创建新的空迁移,请在尝试生成迁移时使用“typeorm migration:create”命令...
除了将同步更改为 false 之外,我所做的唯一其他更改是ormconfig.json通过运行在项目根目录中添加一个文件typeorm init --database mongodb:
{
"type": "mongodb",
"database": "test",
"synchronize": true,
"logging": false,
"entities": [
"src/**/*.entity.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
Run Code Online (Sandbox Code Playgroud) 我需要 nestjs 和 jest 测试方面的帮助。我是 NestJS 的新手,在运行测试时遇到了无法找到模块错误的问题。
我正在尝试测试我的服务,当我运行测试时,我收到了错误消息:
src/article/article.service.spec.ts ? 测试套件无法运行
Cannot find module 'src/article/article.entity' from 'comment/comment.entity.ts'
Require stack:
comment/comment.entity.ts
article/article.entity.ts
article/article.service.spec.ts
6 | ManyToOne,
7 | } from 'typeorm';
> 8 | import { Article } from 'src/article/article.entity';
| ^
9 |
10 | @Entity()
11 | export class Comment {
at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:307:11)
at Object.<anonymous> (comment/comment.entity.ts:8:1)
Run Code Online (Sandbox Code Playgroud)
这种类似的错误通过不同控制器、服务等的所有其他测试出现。
这是我要测试的代码。
article.service.ts
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Article } from "./article.entity";
import …Run Code Online (Sandbox Code Playgroud) 我当前的实体如下所示:
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Landmark extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
longitude: number
@Column()
latitude: number
}
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有更好的方法来做到这一点,使用一种特殊的 postgres 类型,它适用于 typeorm。
nestjs ×10
typeorm ×5
node.js ×3
typescript ×3
mysql ×2
date ×1
dto ×1
jestjs ×1
mailgun ×1
mongodb ×1
next.js ×1
orm ×1
passport.js ×1
postgresql ×1
reactjs ×1
testing ×1
unit-testing ×1