我有以下 mongoDb 类:
@Schema()
export class Poker {
@Transform(({ value }) => value.toString())
_id: ObjectId;
@Prop()
title: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
@Type(() => User)
author: User;
}
Run Code Online (Sandbox Code Playgroud)
我返回它,并class-transform在 NestJs 服务器中进行转换。
它被拦截器转换:
@Get()
@UseGuards(JwtAuthenticationGuard)
@UseInterceptors(MongooseClassSerializerInterceptor(Poker))
async findAll(@Req() req: RequestWithUser) {
return this.pokersService.findAll(req.user);
}
Run Code Online (Sandbox Code Playgroud)
我不是拦截器的作者,但它的实现方式如下:
function MongooseClassSerializerInterceptor(
classToIntercept: Type,
): typeof ClassSerializerInterceptor {
return class Interceptor extends ClassSerializerInterceptor {
private changePlainObjectToClass(document: PlainLiteralObject) {
if (!(document instanceof Document)) {
return document;
}
return plainToClass(classToIntercept, document.toJSON());
}
private prepareResponse( …Run Code Online (Sandbox Code Playgroud) 我是 Nest js 的新手,我正在尝试使用 JWT 令牌对 Nest js 进行身份验证。我通过这篇文章来实现我的身份验证代码。
当我运行代码时,我收到这样的错误。
**
[Nest] 16236 - 01/29/2022, 7:16:06 PM 错误 [ExceptionHandler] Nest 无法解析 AuthenticationService(?、JwtService、ConfigService)的依赖项。请确保索引 [0] 处的参数 UsersService 在 AuthenticationModule 上下文中可用。潜在的解决方案:
- 如果 UsersService 是提供者,它是当前 AuthenticationModule 的一部分吗?
- 如果 UsersService 是从单独的 @Module 导出的,那么该模块是否在 AuthenticationModule 中导入?@Module({ import: [ /* 包含 UsersService 的模块 */ ] })
**
而且我不知道我的代码有什么问题。
这是我的用户模块:
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}
Run Code Online (Sandbox Code Playgroud)
这是我的身份验证模块:
@Module({
imports: [
UsersModule,
PassportModule,
ConfigModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async …Run Code Online (Sandbox Code Playgroud) 我正在开发 NestJs 应用程序,并为我的authenticateUser函数编写了单元测试user.service.ts。它已在我的本地计算机中通过。但是当我将其部署到服务器并运行单元测试时,我收到错误Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED。似乎 redis 模拟不起作用。我应该如何模拟 redis 并解决这个工作问题?
用户服务.ts
async authenticateUser(authDto: AuthDTO): Promise<AuthResponse> {
try {
const userData = await this.userRepository.findOne({msisdn});
if(userData){
await this.redisCacheService.setCache(msisdn, userData);
}
} catch (error) {
console.log(error)
}
}
Run Code Online (Sandbox Code Playgroud)
redisCache.service.ts
export class RedisCacheService {
constructor(
@Inject(CACHE_MANAGER) private readonly cache: Cache,
) {}
async setCache(key, value) {
await this.cache.set(key, value);
}
}
Run Code Online (Sandbox Code Playgroud)
用户.服务.规格.ts
describe('Test User Service', () => {
let userRepository: Repository<UserEntity>;
let userService: UserService; …Run Code Online (Sandbox Code Playgroud) 我需要读取控制器中的 CSV 文件,以将 CSV 文件数据添加到我的数据库中。但我不知道该怎么做。我多次寻找答案,但找不到与我的问题相关的答案。我真的需要你的帮助。谢谢。
我的控制器方法:-
@Post()
@UseInterceptors(FileInterceptor('filename', { dest: './uploads' }))
async upload(@UploadedFile() files: Express.Multer.File) {
console.log(files);
}
Run Code Online (Sandbox Code Playgroud)
我的控制台日志输出:-
我正在从 Nest 文档中学习课程主题反思和元数据。他们使用了@setmetadata('roles'),但我不知道元数据来自何处以及何时使用?
在nestjs中,需要将http模块导入到每个功能模块中。有没有办法在整个应用程序中仅导入一次 http 模块?
虽然所有功能模块的http配置都是一样的,为什么我们需要在每个功能模块中导入并配置呢?
谢谢。
我正在尝试部署支持 Heroku 的 Nestjs,每当它运行命令时prebuild: rimraf dist都会package.json遇到此错误。我不知道 glob 是什么,但我假设我不需要它......disableGlob = true在 cli/scripts 中设置的语法是什么?
当前错误:
/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:42
throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')
^
Error: glob dependency not found, set `options.disableGlob = true` if intentional
at defaults (/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:42:11)
at rimraf (/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:60:3)
at go (/tmp/build_ceb6e44a/node_modules/rimraf/bin.js:44:3)
at Object.<anonymous> (/tmp/build_ceb6e44a/node_modules/rimraf/bin.js:68:3)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Node.js v17.9.0
Run Code Online (Sandbox Code Playgroud)
注意:Heroku 正在node 17.9.0 …
我有一个 NestJs 应用程序,它使用 HttpOnly cookie 进行身份验证。在开发过程中一切都很完美。我的 NextJs 客户端 (http://localhost:4200) 使用 Graphql 向我的 NestJs 服务器 (http://localhost:3333) 发送登录请求,该服务器在响应中设置 httpOnly cookie,然后客户端成功将 cookie 添加到浏览器存储。
但是,当我将这两个应用程序部署到 Render.com 时,除了最后一步之外,一切都正常。响应中已成功接收 cookie,但未将其添加到浏览器存储中。有趣的是,如果我使用已部署生产服务器的 GraphQL 游乐场来发出登录请求,则一切正常。因此,显然,问题似乎是请求来自子域。
我的生产配置:
客户端:https://swingapple-web-staging.onrender.com
服务器: https: //swingapple-api-staging.onrender.com
Cookie 设置(服务器):
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
secure: process.env.NODE_ENV === 'production',
domain: process.env.NODE_ENV === 'production' ? '.onrender.com' : undefined
Run Code Online (Sandbox Code Playgroud)
Nestjs的GraphQLModule设置(服务器):
playground: true,
introspection: true,
autoSchemaFile: true,
sortSchema: true,
context: ({ req, res }) => ({ req, res }),
cors: {
credentials: true,
origin: [process.env.CLIENT_URL, 'http://localhost:4200'] …Run Code Online (Sandbox Code Playgroud) I try to implement nestjs backend and redis as caching. I can do it according to the official document https://docs.nestjs.com/techniques/caching#in-memory-cache.
I use the package cache-manager-redis-store and the code in app.module.ts is as shown below.
import { Module, CacheModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import * as Joi from 'joi';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
CacheModule.registerAsync({
imports: [
ConfigModule.forRoot({ …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Nest 的文档设置一个简单的混合应用程序,但该应用程序卡住了而没有抛出。
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
const logger = new Logger('Main');
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const redisConfig = configService.get('database.redis');
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.REDIS,
options: {
url: `redis://${redisConfig.host}:${redisConfig.port}`,
},
});
await app.startAllMicroservices();
await app.listen(configService.get('app.port'));
}
bootstrap()
.then(() => logger.log('App running'))
.catch((e) => logger.error(e));
Run Code Online (Sandbox Code Playgroud)
当我注释掉 …