标签: nestjs

在 NestJS graphQL 模型中使用 prisma 的枚举

我应该返回的对象:

@ObjectType()
export class User {
  @Field(() => String)
  email: string

  @Field(() => [Level])
  level: Level[]
}
Run Code Online (Sandbox Code Playgroud)

Level 是 prisma 生成的枚举,在 schema.prisma 中定义:

enum Level {
  EASY
  MEDIUM
  HARD
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试在 GraphQL Mutation 中返回此 User 对象:

enum Level {
  EASY
  MEDIUM
  HARD
}
Run Code Online (Sandbox Code Playgroud)

运行此代码时,我收到以下错误:

UnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the "Level". Make sure your class is decorated with an appropriate decorator.
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?prisma 的枚举不能用作字段吗?

enums graphql nestjs prisma

2
推荐指数
1
解决办法
4146
查看次数

我可以使用 Nestjs 注入接口而不是类吗?

我想用这样的东西:

猫接口.ts

export interface ICats {
  meow(): void
}
Run Code Online (Sandbox Code Playgroud)

猫服务.ts

@Injectable()
export class CatsService implements ICats {
  constructor()

  meow(): void {
    return;
  }
}
Run Code Online (Sandbox Code Playgroud)

猫模块.ts

@Module({
  providers: [CatsService]
  exports: [CatsService]
})
export class CatsModule {}
Run Code Online (Sandbox Code Playgroud)

动物.service.ts

@Injectable()
export class AnimalsService {
  constructor(@Inject('ICats') private readonly cats: ICats)

  test(): void {
    return this.cats.meow();
  }
}
Run Code Online (Sandbox Code Playgroud)

动物模块.ts

@Module({
  imports: [CatsModule],
  providers: [AnimalsService],
  exports: [AnimalsService]
Run Code Online (Sandbox Code Playgroud)

但收到 Nest can't resolve dependencies of the

dependency-injection typescript nestjs

2
推荐指数
1
解决办法
1955
查看次数

Nestjs - 在服务中使用多个模型

我有一个 Nestjs 和 MongoDB 应用程序。

auth.module.ts-

@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)

auth.service.ts-

@Injectable()
export class AuthService {
  // Inject User model into AuthService
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  getUser(username: string) {
    const user = this.userModel.find({ name: username });
    return user;
  }

  
}
Run Code Online (Sandbox Code Playgroud)

@nestjs/mongoose我使用和创建了一个 UserSchema mongoose

根据文档,当我导入MongooseModule模块中使用的架构时,该架构只能在该特定模块中使用。

如果我想访问我的模块和服务中的多个模型怎么办?有办法吗?

如何将多个模型注入到服务中?

mongoose nestjs nestjs-mongoose

2
推荐指数
1
解决办法
3661
查看次数

生成新的 Nestjs 模块会导致错误:无法执行命令

我使用带有 M1 芯片的 MacOS monterey 作为操作系统。使用以下命令安装 NestJS cli:sudo npm install -g @nestjs/cli

当使用nest new message一切正常创建新的嵌套项目时,但是当我尝试使用此命令创建新模块时,nest generate module messages我遇到错误。

为什么会发生这种情况?我尝试使用安装原理图npm i -g @nestjs/schematics,我不知道是否应该安装它,但这无论如何都没有帮助。

我面临的错误是:

/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:338
            throw new Error(`Unknown argument ${key}. Did you mean ${(0, yargs_parser_1.decamelize)(key)}?`);
                  ^

Error: Unknown argument skipImport. Did you mean skip-import?
    at parseArgs (/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:338:19)
    at main (/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:122:49)
    at Object.<anonymous> (/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:367:5)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981: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

Failed to …
Run Code Online (Sandbox Code Playgroud)

node.js npm typescript nestjs

2
推荐指数
2
解决办法
7773
查看次数

Unale 从 TypeORM 连接到 postgres

我使用 NestJS 连接到数据库,并使用 TypeORM 作为 db 包。我的 postgres 正在 docker 中运行,ip 172.17.0.3: 5432

sudo docker run --name postgre -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=密码 -p 5432:5432 -v /data/postgres:/var/lib/postgresql/data -d postgres

这是我的存储模块文件:

import { Module } from '@nestjs/common';
import { storageConfig, StorageService } from './storage.service';
import { TypeOrmModule} from '@nestjs/typeorm'
import { User } from './entities/user.entity';

@Module({
  providers: [StorageService],
  imports: [
    TypeOrmModule.forRoot({
      driver: 'pg',
      type: 'postgres',
      host: '172.17.0.3',
      port: 5432,
    
      username: 'admin',
      password: 'password',
      database: 'user_storage',
      schema: 'public',    
      entities: [User]    
    })
  ]
}) …
Run Code Online (Sandbox Code Playgroud)

postgresql typeorm nestjs

2
推荐指数
1
解决办法
7862
查看次数

如何使用 @nestjs/swagger 和 @UseGuards 授权多个 api 密钥?

我正在使用 @UseGuards 来验证标头中的两个 api 密钥。

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
  // check two api keys('some' and 'thing') in header at once
}

Run Code Online (Sandbox Code Playgroud)

另外,我在控制器中使用 @ApiHeader 来大肆展示。

  @ApiOperation({ summary: 'blah blah' })
  @ApiHeader({ name: 'some'}, {name: 'thing'})
  @UseGuards(AuthGuard)
  @Get('/hello')
  async adminableCollections() {
    // do something
  }

Run Code Online (Sandbox Code Playgroud)

我想使用 @ApiSecurity 或其他东西代替 @ApiHeader 使用授权按钮(如图中)一次性授权,而不是为每个方法输入值。 swagger 授权按钮,可以授权我想要的所有方法

我尝试使用文档生成器添加自定义安全性,但它似乎根本不起作用。

  const swaggerConfig = new DocumentBuilder()
    .setTitle('My API')
    .setDescription('Document for my api.')
    .setVersion('0.0.1')
    .addApiKey('some', { type: 'apiKey', in: 'header', name: 'some' })
    .addApikey('thing', { type: …
Run Code Online (Sandbox Code Playgroud)

swagger typescript swagger-ui nestjs nestjs-swagger

2
推荐指数
1
解决办法
4430
查看次数

如何在 Express 中启用信任代理。Nestjs应用程序

我正在学习nestjs,并构建一个应用程序,但我的ip位于代理后面,

Nestjs 文档说启用快速信任代理,

https://docs.nestjs.com/security/rate-limiting

我在如何做到这一点以及如何找到 IP 方面遇到了麻烦。

ip proxy nestjs

2
推荐指数
1
解决办法
4705
查看次数

在 NestJS 上将 DTO 与 multipart/form-data 一起使用时出现空对象

在我的后端,我有这个端点:

@Post()
@UseInterceptors(FilesInterceptor('files'))
create(
  @UploadedFiles() files: Array<Express.Multer.File>,
  @Body() body: MyDto,
  ) {
  console.log(body);
  console.log(files);
}
Run Code Online (Sandbox Code Playgroud)

MyDto很简单:

export class MyDto {

  year: string
}
Run Code Online (Sandbox Code Playgroud)

当我multipart/form-data仅使用字段或与一个或多个文件一起发送请求(在 Firefox、Chrome 和 Postman 上尝试使用代码)时year,我从第一个console.log(打印 的那个body)中得到:

MyDto {}
Run Code Online (Sandbox Code Playgroud)

当我从正文中删除输入时,端点变为:

@Post()
@UseInterceptors(FilesInterceptor('files'))
create(
  @UploadedFiles() files: Array<Express.Multer.File>,
  @Body() body,
  ) {
  console.log(body);
  console.log(files);
}
Run Code Online (Sandbox Code Playgroud)

本体如图所示:

[Object: null prototype] { year: '2022' }
Run Code Online (Sandbox Code Playgroud)

变量files总是正确的。
如何设置正文的类型?

main.ts的如下:

const app = await NestFactory.create(AppModule, {
    logger: ['log', 'error'],
  });
  app.enableCors(); …
Run Code Online (Sandbox Code Playgroud)

multipartform-data dto multer nestjs

2
推荐指数
1
解决办法
4887
查看次数

REST 模块中的 Nest JS Throttler Guard 正在破坏 GraphQL 模块

我有一个带有 REST 模块和 GraphQL 模块的Nest.js应用程序。两者都导入到App.module.ts. 我正在使用 Nest 的Throttler Guard来保护整个应用程序。众所周知,GraphQL 不能与普通的 一起使用ThrottlerGuard,因此我创建了一个GqlThrottlerGuard并将其导入到 GraphQL 模块上,同时将原始的导入ThrottlerGuard到 REST 模块上。

所以,我的 graphQL 模块如下所示:

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: true
    }),
    ThrottlerModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        ttl: config.get('security.throttle.ttl'),
        limit: config.get('security.throttle.limit'),
      }),
    }),
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: GqlThrottlerGuard,
    },
  ],
})
export class GraphModule { }
Run Code Online (Sandbox Code Playgroud)

还有 REST 模块,如下所示:

@Module({
  imports: [
    ThrottlerModule.forRootAsync({
      imports: …
Run Code Online (Sandbox Code Playgroud)

rest node.js typescript graphql nestjs

2
推荐指数
1
解决办法
1583
查看次数

语法错误:运行 Nestjs 时出现无效或意外的标记

当我运行此nestjs代码时,遇到错误:

SyntaxError: Invalid or unexpected token
Run Code Online (Sandbox Code Playgroud)

是什么原因?

import {Controller, Get, Bind, Req, Post} from '@nestjs/common';

@Controller('cats')
export class catsController {
    @Post()
    create() {
        return "this is a action 1ss"
    }
    @Get()
    @Bind(Req())
    findAll(request) {
        return "this is a action";
    }
}
Run Code Online (Sandbox Code Playgroud)

javascript syntax-error node.js nestjs

2
推荐指数
1
解决办法
5442
查看次数