我在我的应用程序后端使用nestjs。我使用cqrs模块https://github.com/nestjs/cqrs,我读到cqrs有一个命令来写入操作和查询来读取操作,但是nestjs文档(https://docs .nestjs.com/recipes/cqrs)只有一个命令示例,那么如何在nestjs中实现查询?
我有一个控制器
//imports etc
...
@Get('me')
async get(@Req res): Promise<UserVm> {
// extract auth user from request object
// return auth user
}
@Get(':id') // uuid
async get(@Param('id') id: string): Promise<UserSummaryVm> {
// return a summary user profile
}
...
Run Code Online (Sandbox Code Playgroud)
然而,/:id是压倒性的/me。我尝试重新排序路线但无济于事。我总是收到以下错误:
[Nest] 94764 - 8/23/2018, 7:45:50 PM [ExceptionsHandler] Could not find
any entity of type "User" matching: "me"
EntityNotFound: Could not find any entity of type "User" matching: "me"
at new EntityNotFoundError
([PROJECT_ROOT]\src\error\EntityNotFoundError.ts:11:9)
at [PROJECT_ROOT]\src\entity-manager\EntityManager.ts:622:39
at process._tickCallback …Run Code Online (Sandbox Code Playgroud) 我尝试为我的小型应用程序创建单元测试。我想测试使用注入配置和其他服务的服务。
@Injectable()
export class AuthService {
private readonly localUri: string;
constructor(
@Inject(CORE_CONFIG_TOKEN) private readonly coreConfig: ICoreConfig,
@Inject(PROVIDER_CONFIG_TOKEN) private readonly providerConfig: IProviderConfig,
private readonly _httpService: HttpService,
private readonly _usersService: UsersService,
) {
this.localUri = `http://${this.coreConfig.domain}:${this.coreConfig.port}`;
}
...
/**
* Checks if a given email is already taken
* @param email
*/
async isEmailTaken(email: string): Promise<boolean> {
return (await this._usersService.findUserByEmail(email)) !== undefined;
}
...
Run Code Online (Sandbox Code Playgroud)
我不明白如何测试这项服务。我不知道如何为注入的配置提供正确的 TestModule 提供程序@Inject(CORE_CONFIG_TOKEN) private readonly coreConfig: ICoreConfig
const testCoreConfig = '{...}'
const module = await Test.createTestingModule({
providers: …Run Code Online (Sandbox Code Playgroud) 我正在尝试对具有来自 Nestjs 护照模块的 AuthGuard 的路由进行 e2e 测试,但我真的不知道如何处理它。当我运行测试时它说:
[ExceptionHandler] 未知的身份验证策略“承载者”
我还没有嘲笑它,所以我想这是因为这个,但我不知道该怎么做。
这是我到目前为止所拥有的:
播放器.e2e-规格.ts
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { PlayerModule } from '../src/modules/player.module';
import { PlayerService } from '../src/services/player.service';
import { Repository } from 'typeorm';
describe('/player', () => {
let app: INestApplication;
const playerService = { updatePasswordById: (id, password) => undefined };
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [PlayerModule],
})
.overrideProvider(PlayerService)
.useValue(playerService)
.overrideProvider('PlayerRepository') …Run Code Online (Sandbox Code Playgroud) 这个例子有什么好的解决办法吗?
好像我有很多模块,就像photo.module.ts我需要DatabaseModule在每个功能模块中导入一样。
尝试将其放入app.module.ts但没有帮助。也许有一些forRoot静态导入的解决方案?
我在这个项目中使用 TypeScript 和 NestJS:
https://github.com/EricKit/nest-user-auth
我正在尝试将 _id 属性添加到 GraphQL 架构中:
type User {
username: String!
email: String!
permissions: [String!]!
createdAt: Date!
updatedAt: Date!
enabled: Boolean!
_id: String!
}
Run Code Online (Sandbox Code Playgroud)
现在,NestJS 从此模式为用户生成一个类型文件
export abstract class User {
username: string;
email: string;
permissions: string[];
createdAt: Date;
updatedAt: Date;
enabled: boolean;
_id: string;
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我想为 UserDocument 创建一个接口,添加 mongoDB 特定字段并定义一个文档
export interface UserDocument extends User, Document {
// Declaring everything that is not in the GraphQL Schema for a User
_id: string; // TODO: This …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Nestjs 后端实现 RS256 JWT 令牌。我按照Nestjs 文档中提供的示例进行操作。
在我的模块中,我JwtModule使用我的私钥注册:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.key`),
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, HttpStrategy],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)
我能够调用 auth/token 端点并获取令牌,但是当我尝试访问受保护的端点时,我总是收到 401。
您可以在下面找到我的定制JwtStrategy:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: extractKey(`${process.cwd()}/keys/jwt.public.key`),
});
}
async validate(payload: JwtPayload) {
console.log('JwtStrategy');
const user = await this.authService.validateUser(payload);
if (!user) {
throw …Run Code Online (Sandbox Code Playgroud) 此处提供了Repo来突出显示该问题。
我遇到了竞争条件问题。我创建了一个ConfigModule- 这有一个forRoot和一个forChild。
设置文件forRoot的加载.env并forChild在另一个模块中使用它。
问题是forChild之前调用过forRoot。由于尚未首先执行,因此将ConfigService注入缺少的配置。forRoot
> AppModule > ConfigModule.forRoot InstanceModule >
> ConfigModule.forChild
Run Code Online (Sandbox Code Playgroud)
我放置了一些简单的console.log命令来输出这个
I am in Config Module FOR CHILD
I am in Config Module FOR ROOT
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,forChild首先执行的是,我尝试使用forwardRef,但没有成功。
如果你让应用程序运行你会看到
[2019-03-24T11:49:33.602] [ERROR] ConfigService - There are missing mandatory configuration: Missing PORT
[2019-03-24T11:49:33.602] [FATAL] ConfigService - Missing mandatory configuration, cannot continue!, exiting
Run Code Online (Sandbox Code Playgroud)
这是因为我检查了一些process.env可用的文件,这些文件是在 …
尝试在 CreateUserAction.ts 中使用 ICommandBusAdapter.ts,但出现以下错误:
[ExceptionHandler] Nest can't resolve dependencies of the ICommandBusAdapter (?). Please make sure that the argument at index [0] is available in the AdapterModule context
我创建了一个AdapterModule将所有提供程序共享给其他模块的模块,但它似乎不起作用。
任何想法 ?
AppModule.ts
import { UserModule } from './User/UserModule';
import { AdapterModule } from './Common/AdapterModule';
@Module({
imports: [AdapterModule, UserModule, // ...],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
适配器模块.ts
import { CommandBusAdapter } from 'src/Infrastructure/Adapter/Bus/CommandBusAdapter';
const providers = [
{ provide: 'ICommandBusAdapter', useClass: CommandBusAdapter },
// ...
];
@Module({
providers: [...providers], …Run Code Online (Sandbox Code Playgroud) 如何从 ApplicationContext 获取实体的存储库
const ctx = await NestFactory.createApplicationContext(AppModule)
const repository = ctx.get<Repository<UserEntity>>(Repository);
// Error: Nest cannot find given element (it does not exist in current context)
Run Code Online (Sandbox Code Playgroud) nestjs ×10
node.js ×4
typescript ×4
javascript ×3
cqrs ×1
graphql ×1
jwt ×1
mongodb ×1
mongoose ×1
passport-jwt ×1
passport.js ×1
typeorm ×1
unit-testing ×1