AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[nestjs](coding)

Martin Hope
albertfdp
Asked: 2024-11-24 02:05:40 +0800 CST

加载实体之前检查 CASL 能力

  • 5

我有以下定义的能力CaslAbilityFactory:

    if (auth.isAdmin) {
      can(Action.Create, User);
      can(Action.Read, "all");
      can(Action.Manage, User);
      can(Action.Update, User, ["email", "firstName", "lastName", "role"]);

      can(Action.Delete, User);
      cannot(Action.Delete, User, isOwner);
    }

    if (auth.isUser) {
      can([Action.Read, Action.Update], User, isOwner);
    }

然后,我定义了以下解析器:

  @Mutation(() => User)
  @UseGuards(PoliciesGuard)
  @CheckPolicies(ability => ability.can(Action.Update, User))
  async updateUser(
    @Args("input") input: UpdateUserInput,
    @CurrentAuth() auth,
  ): Promise<User> {
    const ability = this.caslAbilityFactory.createForAuth(auth);

    if (ability.cannot(Action.Update, { id: input.id }) {
      throw new ForbiddenException();
    }

    return this.usersService.update(input.id, input);
  }

装饰器@CheckPolicies正确地确保只有具有用户操作的用户Update才能调用它,但我需要断言,对于这个特定的用户,我可以更新它吗?如果请求者是所有者,则可以。但在加载用户之前如何检查这一点?

一个显而易见的解决方案是加载用户,运行检查,然后执行更新。另一个更棘手的解决方案是以某种方式将其转换为new User({ id })并运行检查。

有没有更好的解决办法?

谢谢,

nestjs
  • 1 个回答
  • 12 Views
Martin Hope
thxmike
Asked: 2024-10-15 22:50:23 +0800 CST

NESTJS - 使用 HEAD Http 请求类型和 GET 进行相同路由

  • 5

根据设计,在我们的 RESTful api 中,我们使用 HEAD 来检查实体是否存在。我最近在使用 NestJS 和使用相同路由的 Http 请求类型 HEAD 和 GET 时遇到了一个问题。出于某种原因,当客户端向 API 发出 http HEAD 请求(例如 HEAD - /api/test)时,它会路由到代码的 GET 部分控制器。经过一些故障排除后,它似乎与方法在控制器中的位置有关。如果将控制器代码的 HEAD 部分放在 GET 之后,请求将拦截到 GET 请求。如果你把它放在后面,它将按预期工作。不知道为什么,但知道这一点是件好事

代码片段:

// HEAD must be before GET for NestJS controller with the same route
@Head(':id')  // check for the existence of an entity
  async hasOne(@Res() response, @Param('id') id): Promise<any> {

   // do something
  }

  @Get(':id') // Get a single entity
  getOne(@Param('id') id): Promise<any> {

   // do something
  }

我们正在使用 NestJS 10.4.4

nestjs
  • 1 个回答
  • 26 Views
Martin Hope
Pongsan
Asked: 2024-07-23 21:04:39 +0800 CST

Nestjs无法生成

  • 4

在此处输入图片描述 我在 github codespaces 和我的本地机器(windows 11)上遇到了这个错误。Node 版本是 20 Package.json 作为 nest 的新默认版本。除了 elsinore 文件之外,所有默认版本都来自 nestcli。我添加了更漂亮的规则。

我想生成nestjs模块。

nestjs
  • 1 个回答
  • 111 Views
Martin Hope
Marcus Junius Brutus
Asked: 2024-06-04 23:20:51 +0800 CST

如何在NestJS中很好地记录请求对象?

  • 4

我正在尝试记录请求对象(用于调试目的)。我的 NestJS 应用程序使用express(默认选项)。

我在控制器和服务提供者中都获取了请求对象(在后一种情况下注入后)。控制器中的相关部分是:

  // this is the Logger from @nestjs/common
  private readonly logger = new Logger(MessagesController.name);
  
  @Get()
  findAll(@Req() request: Request): string
  {
    this.logger.log(request);
    return this.messagesService.findAll();
  }

服务提供者中的相关部分是:

// the service is request-scoped since it's injected with a request-scoped provider
@Injectable({scope: Scope.REQUEST})
export class MessagesService {

  constructor(@Inject(REQUEST) private request: Request) {
    this.request = request;
  }

  findAll(): string {
    this.logger.log(this.request);
    return "all messages";
  }

}

在两种发生日志记录的情况下(即在控制器和服务中),对象都会简单地记录在控制台上,因为[object Object]这根本没有帮助。如果对的调用this.logger.log(request)被替换为普通的,则console.log(request)该对象会很好地打印在控制台上。

我如何才能Logger很好@nestjs/common地打印这些请求对象?

nestjs
  • 1 个回答
  • 19 Views
Martin Hope
Victor Shelepen
Asked: 2023-09-19 19:06:43 +0800 CST

在 NestJS 中共享动态模块 - 当动态模块注册几次时会发生什么?

  • 5

我需要共享一个动态模块。在文档中我发现我们可以在全球范围内共享服务。是的,这是一个解决方案。但是,我想知道在模块级别是否可行。这就是为什么我对动态模块注册几次时会发生什么感兴趣。从实践中,我发现它在 NestJS 中创建了不同的模块实例。该模块的行为与 Angular 中的不同,但 NestJS 喜欢提及 Angular 的相似性。属性模块带我走了。现在我明白它仅用于控制模块行为。但是,我在文档中没有看到任何解释。我看到类似的问题。但我还没有找到我感兴趣的细节。

以下代码只是想法。尚未对其进行检查。

import { DynamicModule, Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({})
export class ConfigModule {
  static register(options: Record<string, any>): DynamicModule {
    return {
      module: ConfigModule,
      providers: [
        {
          provide: 'CONFIG_OPTIONS',
          useValue: options,
        },
        ConfigService,
      ],
      exports: [ConfigService],
    };
  }
}

export const ConfiguredConfigModule = ConfigModule.register({key: 'flower'});
... 

@Module({
  imports: [ConfiguredConfigModule]
})
export class AppModule {}

问候。

nestjs
  • 1 个回答
  • 10 Views
Martin Hope
Tomek Buszewski
Asked: 2023-08-28 21:45:34 +0800 CST

NestJS 无法解决自动生成文件的依赖关系

  • 5

我的 Nest 应用程序遇到了最奇怪的问题(生活在 Nx 中,无论它的价值如何)。我生成了一个新资源:

nx g resource --project testing
✔ Which generator would you like to use? · @nx/nest:resource
✔ What name would you like to use for this resource (plural, e.g., `users`)? · items
✔ What transport layer do you use? · graphql-code-first
✔ Would you like to generate CRUD entry points? (Y/n) · false

它被添加到Imports主 app.module 中:

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      playground: false,
      plugins: [ApolloServerPluginLandingPageLocalDefault()],
      autoSchemaFile: "schema.gql",
    }),
    ItemsModule,
  ],
})
export class AppModule {}

然后,我添加了简单的解析器以使 GraphQL 满意:

// ./items/items.resolver.ts
import { Int, Query, Resolver } from "@nestjs/graphql";

import type { ItemsService } from "./items.service";

@Resolver()
export class ItemsResolver {
  constructor(private readonly service: ItemsService) {}

  @Query(() => [Int])
  getAll() {
    return [1, 2, 3];
  }
}

所以我的 items.module 看起来像这样:


import { ItemsResolver } from "./items.resolver";
import { ItemsService } from "./items.service";

@Module({
  providers: [ItemsResolver, ItemsService],
})
export class ItemsModule {}

这对我来说非常有效。但尽管如此,我仍然得到 Error: Nest can't resolve dependencies of the ItemsResolver (?). Please make sure that the argument Object at index [0] is available in the ItemsModule context.

如果我从班级中删除该服务ItemsResolver,一切都会正常。

nestjs
  • 1 个回答
  • 17 Views
Martin Hope
Cookie
Asked: 2023-08-20 20:46:08 +0800 CST

解决 NestJS 依赖

  • 5

我在尝试执行npm install @nestjs/microservices时遇到此错误:

# npm resolution error report

While resolving: [appName]
Found: @nestjs/[email protected]
node_modules/@nestjs/common
  @nestjs/common@"^9.4.3" from the root project

Could not resolve dependency:
peer @nestjs/common@"^10.0.0" from @nestjs/[email protected]
node_modules/@nestjs/microservices
  @nestjs/microservices@"*" from the root project

Fix the upstream dependency conflict, or retry
this command with --force or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

这些是我在 package.json 中的依赖项:

"dependencies": {
    "@nestjs/cache-manager": "^2.1.0",
    "@nestjs/common": "^9.4.3",
    "@nestjs/config": "^3.0.0",
    "@nestjs/core": "^9.0.0",
    "@nestjs/passport": "^10.0.0",
    "@nestjs/platform-express": "^9.4.3",
    "@nestjs/swagger": "^7.0.12",
    "@nestjs/typeorm": "^10.0.0",
    "bcryptjs": "^2.4.3",
    "cache-manager": "^5.2.3",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.0",
    "dotenv": "^16.3.1",
    "express-session": "^1.17.3",
    "jsonwebtoken": "^9.0.0",
    "passport": "^0.6.0",
    "passport-google-oauth20": "^2.0.0",
    "pg": "^8.11.1",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.2.0",
    "typeorm": "^0.3.17"
  },

我尝试使用--legacy-peer-deps但它不会编译,我不想使用--force。如果有人知道要解决什么问题,我将非常感激。

nestjs
  • 1 个回答
  • 12 Views
Martin Hope
Herlin
Asked: 2023-08-17 19:32:04 +0800 CST

全局防护/过滤器/拦截器在 e2e 测试、GRPC 期间不会触发

  • 5

我遇到了全局防护、拦截器和过滤器的问题,它们在运行时有效,但在 e2e 测试期间不起作用。

这是守卫设置的示例。对于所有中间件(如项目)来说,问题都是相同的,除非我在本地为每个控制器等指定它们,否则它们不会触发。

我的顶级模块:

@Module({
  imports: [
    JwtModule.register({
      secret: JWT_PASS,
      global: true,
    }),
    BoothModule,
    SessionTypeModule,
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: AuthenticationGuard,
    },
  ],
})
export class AppModule {}

一名警卫:

@Injectable()
export class AuthenticationGuard implements CanActivate {
  private readonly log = new Logger('AuthenticationGuard');

  constructor(private readonly jwtService: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
     console.log('triggered?!');
     ....
     return true;
  }

控制台日志有效,测试因保护逻辑失败而失败。

beforeAll(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [
        AppModule,
        ClientsModule.register([
          {
            name: '<name>',
            transport: Transport.GRPC,
            options: {
              url: 'localhost:5001',
              package: '<package>',
              protoPath: '<path>',
              credentials: GRPC.ChannelCredentials.createInsecure(),
            },
          },
        ]),
      ],
    }).compile();

    app = moduleFixture.createNestApplication();

    app.useGlobalInterceptors(new ExceptionInterceptor());
    app.connectMicroservice<MicroserviceOptions>({
      transport: Transport.GRPC,
      options: {
        url: 'localhost:5001',
        package: SPEEDPHOTO_PACKAGE_NAME,
        protoPath: BOOTH_PROTO,
      },
    });

    await app.startAllMicroservices();

    await app.init();

    const clientGrpc: ClientGrpc = app
      .getMicroservices()[0]
      .get(BOOTH_SERVICE_NAME);
    client = clientGrpc.getService<BoothServiceClient>(BOOTH_SERVICE_NAME);
  });

它仅在测试期间失败。

nestjs
  • 1 个回答
  • 14 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve