如何转换数据库实体User:
class User {
public firstName: string;
public lastName: string;
public phone?: string;
public email: string;
public status: EUserState;
public tokens: Token[];
public password: string;
}
Run Code Online (Sandbox Code Playgroud)
进入 DTO 实体GetUserDTO:
class GetUserDTO {
public id: number;
public firstName: string;
public lastName: string;
public phone?: string;
public email: string;
}
Run Code Online (Sandbox Code Playgroud)
在打字稿中?我正在使用@nestjs,class-validator和class-transformer包,但我没有找到任何方法来使用它们来实现这一目标。
有人可能会说,拥有 DTO 对此毫无意义,但我们在服务器和客户端之间共享 DTO 以维护 API 结构。
有任何想法吗?
我遵循了文档,并且能够为响应映射添加一个拦截器。
我想要一个一致的 json 格式输出用于响应。
我如何使用拦截器或其他比这种方法更好的方法来实现这一点。
{
"statusCode": 201,
"message": "Custom Dynamic Message"
"data": {
// properties
meta: {}
}
}
Run Code Online (Sandbox Code Playgroud)
transform.interceptor.ts
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Response<T> {
statusCode: number;
data: T;
}
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, Response<T>> {
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<Response<T>> {
return next
.handle()
.pipe(
map((data) => ({
statusCode: context.switchToHttp().getResponse().statusCode,
data,
})),
);
} …Run Code Online (Sandbox Code Playgroud) 我想测试我的AuthModule控制器HTTP层与supertest作为官方描述Nestjs文档。此模块使用EmailService从EmailModule.
我知道您可以按如下方式覆盖提供程序:
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
AuthModule,
],
})
.overrideProvider(EmailService)
.useValue(buildMock(EmailService))
Run Code Online (Sandbox Code Playgroud)
但是,这并不工作,我假设,因为EmailModule在进口AuthModule。一种解决方法是.overrideProvider(...).useValue(...)在每一个供应商EmailModule,但这种非意义,因为我接下来要由进口也模拟模块EmailModule。
当我进行 e2e 测试时AuthModule,老实说,我并不关心它的EmailModule工作原理。我需要模拟的是EmailService并确保我的身份验证模块与该服务正确交互。
不幸的Test.createTestingModule({})是,没有.overrideModule()方法。
我试着EmailModule用开玩笑的方式嘲笑:
jest.mock('../../src/email/email.module.ts', () => {
@Module({})
class EmailModule {
}
return EmailModule;
});
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
Error: Nest cannot create the module instance. Often, this is because of …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习 NestJS,只是按照简单的教程来创建 Nestjs 应用程序。
执行 cli 命令时出现以下错误nest new test-project
NestJS cli 版本:7.1.5 NodeJS 版本:v10.18.1
错误:
Error: Collection "@nestjs/schematics" cannot be resolved.
at NodeModulesEngineHost.resolve (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/node-module-engine-host.js:74:19)
at NodeModulesEngineHost._resolveCollectionPath (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/node-module-engine-host.js:79:37)
at NodeModulesEngineHost.createCollectionDescription (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/file-system-engine-host-base.js:109:27)
at SchematicEngine._createCollectionDescription (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/engine/engine.js:147:40)
at SchematicEngine.createCollection (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/engine/engine.js:140:43)
at NodeWorkflow.execute (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/workflow/base.js:100:41)
at main (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:224:24)
at Object.<anonymous> (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:315:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
Run Code Online (Sandbox Code Playgroud)
无法执行命令:“/Users/tsuthar/.config/yarn/global/node_modules/@nestjs/cli/node_modules/.bin/schematics”@nestjs/schematics:application --name=nestjs-task-management --directory =undefined --no-dry-run --no-skip-git --package-manager=undefined --language="ts" --collection="@nestjs/schematics"
我有一个使用 typescript 的节点应用程序,我正在尝试按照 TypeORM 的文档创建一个新的迁移。
首先,我安装了CLI,像这样设置我的连接选项,当我尝试运行此命令时:
npm run typeorm migration:create -- -n migrationNameHere
我收到以下错误:
迁移创建过程中出错:类型错误:无法读取对象中未定义的属性“startsWith”。(...\src\commands\MigrationCreateCommand.ts:62:37) 在步骤 (...\node_modules\typeorm\node_modules\tslib\tslib.js:141:27) 在 Object.throw (...\node_modules \typeorm\node_modules\tslib\tslib.js:122:57) 在被拒绝 (...\node_modules\typeorm\node_modules\tslib\tslib.js:113:69) npm ERR!代码 ELIFECYCLE npm ERR!错误号 1 npm 错误号!backend@0.0.1 typeorm: node --require ts-node/register ./node_modules/typeorm/cli.js "migration:create" "-n" "migrationNameHere"` npm ERR!退出状态 1
这些是我在 package.json 中的嵌套依赖项:
我的节点版本是v12.14.1,nestjs 是7.0.0和 nestjs/typeorm 是7.1.3
我的 app.module.ts 是这样的:
TypeOrmModule.forRoot({
type: 'mysql',
host: database().host,
port: parseInt(database().port),
username: database().username,
password: database().password,
database: database().schema,
entities: [Question, QuestionOption],
migrations: ['migration/*.js'],
cli: …Run Code Online (Sandbox Code Playgroud) 我有 KeysModule,可用于添加或删除 API 密钥。我需要这些密钥来保护某些路由免遭未经授权的访问。为了保护这些路由,我创建了 ApiGuard:
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class ApiGuard implements CanActivate {
async canActivate(
context: ExecutionContext,
): Promise<boolean> {
const request = context.switchToHttp().getRequest();
return request.headers.api_key;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在路由中使用它:
@Get('/protected')
@UseGuards(ApiGuard)
async protected(@Headers() headers: Api) {
const key = await this.ks.findKey({ key: headers.api_key });
if (!key || !key.active) return 'Invalid Key';
return 'Your API key works';
}
Run Code Online (Sandbox Code Playgroud)
其中 ks 是 KeyService 用于检查密钥是否正确。此解决方案有效,但很愚蠢。我必须在我想使用这个守卫的任何地方复制和粘贴一些代码行(我的意思是路线中的行)。
我试图将所有逻辑移至 ApiGuard,但出现错误,即 KeyService 无法注入 ApiGuard 类。解释一下,我在 KeysModule 的提供者中有 KeyService,但 ApiGuard 是全局使用的。 …
假设我们有 2 个服务,A 和 B。服务 A 具有执行以下操作的功能:
现在,让我们假设以下步骤 3 或 4 之一失败。由于服务 B 在数据库中进行了更改,因此这些更改仍然存在。
在这种情况下,有没有办法回滚数据库?我虽然是关于数据库事务的,但是我在 nest js 中找不到任何方法来做到这一点,尽管 TypeOrm 支持它,但嵌套看起来并不自然。如果没有,我现在“卡住”了服务 B 发生的更改,但没有更改应该由 A 发生。
非常感谢。
我正在尝试使用 aValidationPipe但无论我如何编写代码,在发送请求时都会收到以下警告:No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.
我的路线看起来像这样:
@Get()
@UsePipes(new ValidationPipe({ transform: true }))
async findAll(@Query() queryDto: QueryDto) {
return await this.myService.findAll(queryDto);
}
Run Code Online (Sandbox Code Playgroud)
我的 DTO 看起来像这样:
export class queryDto
{
@ApiModelProperty({
description: 'Maximum number of results',
type: Number,
example: 50,
default: 50,
required: false
})
readonly limit: number = 50;
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用ValidationPipe多种方法,遵循doc,但没有任何效果对我有用。我知道这是行不通的,因为虽然请求得到响应,默认值,我在我的DTO写的财产limit,这是50,是不是当查询是空的使用。因此,当limit查询中提供no 时,limit …
I want to achieve something like this using nest.js: (something very similar with Spring framework)
@Controller('/test')
class TestController {
@Get()
get(@Principal() principal: Principal) {
}
}
Run Code Online (Sandbox Code Playgroud)
After hours of reading documentation, I found that nest.js supports creating custom decorator. So I decided to implement my own @Principal decorator. The decorator is responsible for retrieving access token from http header and get principal of user from my own auth service using the token.
import { createParamDecorator } from '@nestjs/common';
export const …Run Code Online (Sandbox Code Playgroud) 目前,我在控制器中找到了他:
@Crud({
model: {
type: Broker
},
query: {
join: {
user: {
eager: true,
exclude: ['password']
}
}
}
})
@Controller('broker')
@UseGuards(AuthGuard('jwt'))
export class BrokerController {
constructor(public service: BrokerService) {}
}
Run Code Online (Sandbox Code Playgroud)
one to many用户和代理之间存在关系。我正在通过jwt令牌对用户进行身份验证,并且需要根据用户ID过滤数据。有什么办法可以通过Crud配置做到这一点?
nestjs ×10
node.js ×5
typescript ×5
javascript ×3
typeorm ×3
decorator ×1
express ×1
jestjs ×1
npm ×1
testing ×1