我按照https://docs.nestjs.com/techniques/mongodb 中的示例进行操作
问题是出现猫鼬验证错误时(例如,我有一个带有必填字段的架构,但未提供):
来自 games.service.ts:
async create(createGameDto: CreateGameDto): Promise<IGame> {
const createdGame = new this.gameModel(createGameDto);
return await createdGame.save();
}
Run Code Online (Sandbox Code Playgroud)
save() 函数返回一个 Promise。
现在我在 game.controller.ts 中有这个
@Post()
async create(@Body() createGameDto: CreateGameDto) {
this.gamesService.create(createGameDto);
}
Run Code Online (Sandbox Code Playgroud)
处理错误然后返回具有不同 http 状态和 json 文本的响应的最佳方法是什么?你通常会抛出一个HttpException但从哪里?如果我在承诺中使用 .catch() 处理错误,我就不能这样做。
(刚开始使用nestjs框架)
创建新用户将忽略来自 create-user.dto.ts
但是,当我更新用户时,它会添加不需要的字段,如下所示:
// update-user.dto.ts
import { IsEmail } from 'class-validator';
import { Address } from '../model/address';
export class UpdateUserDto {
firstName: string;
lastName: string;
@IsEmail(undefined, { message: 'Not a valid e-mail' })
email: string;
username: string;
password: string;
addresses: Address[];
}
Run Code Online (Sandbox Code Playgroud)
这是来自用户服务的更新操作
// user.service.ts
async update(data: UpdateUserDto) {
try {
this.logger.log(data);
const id = '5c6dd9852d4f441638c2df86';
const user = await this.userRepository.update(id, data);
return { message: 'Updated your information' };
} catch (error) {
this.logger.log(error);
throw new HttpException('', HttpStatus.INTERNAL_SERVER_ERROR);
}
} …Run Code Online (Sandbox Code Playgroud) 我想知道是否可以HttpService使用HttpModule.
我曾经使用 AXIOS 的拦截器,HttpService包装了 axios 但我似乎无法在这里添加任何拦截器,似乎没有地方
HttpModule.register(...)
Run Code Online (Sandbox Code Playgroud)
然后我想到NestJS自带拦截器,想知道是否可以使用NestJS拦截器。
我不想将拦截器应用于控制器、服务,而是将其应用于HttpService?
任何想法,有点迷失如何以 Nestjs 的方式做到这一点。
提前致谢
我想对请求有效负载应用验证,例如有字符串类型的字段名称。但名称不是必填字段,但如果存在,则必须执行@IsNotEmpty()
我试过这样的事情
@IsNotEmpty() name?: string//它不考虑?可选约束
在下面的代码中,我的测试用例按预期通过,但我使用 stryker 进行突变测试,handleError 函数在突变测试中幸存下来,所以我想通过测试是否调用 handleError 函数来杀死突变体。需要帮忙测试私有函数。
我试过 spyOn 但没有用
const orderBuilderSpy = jest.spyOn(orderBuilder, 'build')
const handleError = jest.fn()
expect(rderBuilderSpy).toHaveBeenCalledWith(handleError)
Run Code Online (Sandbox Code Playgroud)
const orderBuilderSpy = jest.spyOn(orderBuilder, 'build')
const handleError = jest.fn()
expect(rderBuilderSpy).toHaveBeenCalledWith(handleError)
Run Code Online (Sandbox Code Playgroud)
我尝试用对象数组映射一个键字符串。
我可以创建一个简单的对象,但我想在这些数组中轻松添加一个对象。地图对象非常适合执行此操作。
问题:我不知道如何为 GraphQL 定义类型映射 :'(
@ObjectType()
export class Inventaire
@Field()
_id: string;
@Field()
stocks: Map<string, Article[]>;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试对使用弹性搜索的服务进行单元测试。我想确保我使用了正确的技术。
我是这个问题许多领域的新用户,所以我的大部分尝试都是通过阅读与此类似的其他问题并尝试在我的用例中有意义的问题。我相信我缺少 createTestingModule 中的一个字段。也有时我看到providers: [Service]和其他人components: [Service]。
const module: TestingModule = await Test.createTestingModule({
providers: [PoolJobService],
}).compile()
Run Code Online (Sandbox Code Playgroud)
这是我当前的错误:
Nest can't resolve dependencies of the PoolJobService (?).
Please make sure that the argument at index [0]
is available in the _RootTestModule context.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
池作业服务
Nest can't resolve dependencies of the PoolJobService (?).
Please make sure that the argument at index [0]
is available in the _RootTestModule context.
Run Code Online (Sandbox Code Playgroud)
PoolJobService.spec.ts
import { Injectable } from '@nestjs/common'
import { ElasticSearchService } from …Run Code Online (Sandbox Code Playgroud) 如何转换数据库实体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) 我正在尝试学习 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"
nestjs ×10
typescript ×6
node.js ×5
javascript ×3
graphql ×2
axios ×1
jestjs ×1
mongodb ×1
typegraphql ×1
typeorm ×1
validation ×1