标签: nestjs

NestJS:使用 JWT 向 AuthGuard 添加验证选项

我正在尝试AuthGuard按照文档使用装饰器和通行证 JWT 策略。

文档中的所有内容都很好用。但是我现在想保护具有包含在 JWT 中的范围的路由。所以这是我的应用程序生成的基本 jwt 负载:

{
  "user": {
    "id": "20189c4f-1183-4216-8b48-333ddb825de8",
    "username": "user.test@gmail.com"
  },
  "scope": [
    "manage_server"
  ],
  "iat": 1534766258,
  "exp": 1534771258,
  "iss": "15f2463d-8810-44f9-a908-801872ded159",
  "sub": "20189c4f-1183-4216-8b48-333ddb825de8",
  "jti": "078047bc-fc1f-4c35-8abe-72834f7bcc44"
}
Run Code Online (Sandbox Code Playgroud)

这是AuthGuard装饰器保护的基本受保护路由:

@Get('protected')
@UseGuards(AuthGuard('jwt'))
async protected(): Promise<string> {
    return 'Hello Protected World';
}
Run Code Online (Sandbox Code Playgroud)

我想添加选项并将该路由的访问权限限制为具有manager_serverJWT 范围的人员。所以在阅读了一些AuthGuard代码之后,我认为我可以写出类似的东西:

@Get('protected')
@UseGuards(AuthGuard('jwt', {
    scope: 'manage_server'
}))
async protected(): Promise<string> {
    return 'Hello Protected World';
}
Run Code Online (Sandbox Code Playgroud)

但是,我在文档中看不到可以使用此选项的地方。

我认为向 the 的validate函数添加一个选项参数JWTStrategy可以解决问题,但事实并非如此。这是我的validate函数(包含在 …

javascript node.js nestjs

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

在NestJS HTTP服务器中使用子进程时,CPU绑定的进程会阻止工作池

节点版本: v10.13.0

我正在尝试对NodeJS请求并发性进行非常简单的测试,包括繁重的CPU计算.我理解NodeJS不是CPU绑定进程的最佳工具,并且不应系统地生成子进程,但此代码是为了测试子进程的工作原理.这也是使用NestJS用TypeScript编写的.

SRC/app.controller.ts

import { Get, Param, Controller } from '@nestjs/common';
import fork = require('child_process');

@Controller()
export class AppController {
  @Get()
  async root(): Promise<string> {
    let promise = new Promise<string>(
        (resolve, reject) => {
          // spawn new child process
          const process = fork.fork('./src/cpu-intensive.ts');
          process.on('message', (message) => {
            // when process finished, resolve
            resolve( message.result);
          });
          process.send({});    
        }
    );    
    return await promise;
  }
}
Run Code Online (Sandbox Code Playgroud)

SRC/CPU-intensive.ts

process.on('message', async (message) => {
  // simulates a 10s-long process
  let now = …
Run Code Online (Sandbox Code Playgroud)

child-process httpserver node.js nestjs

13
推荐指数
1
解决办法
448
查看次数

Nest 无法解析 ItemsService (?) 的依赖项。请确保索引 [0] 处的参数在 AppModule 上下文中可用

我遵循了Nest JS Crash 教程,Youtube Link,我遵循了这个,但是当我在服务中导入接口时,它显示错误

Nest 无法解析 ItemsService (?) 的依赖项。请确保索引 [0] 处的参数在 AppModule 上下文中可用。

我克隆了教程中给出的存储库,它工作正常,但是当我将该存储库的 src 文件夹复制到我的项目时,它会引发错误。这是我的服务文件

import { Injectable } from '@nestjs/common';
import { Item } from './interfaces/item.interface';
import { Model } from 'mongoose';

import { ItemsModule } from './items.module'

import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class ItemsService {
  constructor(@InjectModel('Item') private readonly itemModel: Model<Item>) {}
});

}
Run Code Online (Sandbox Code Playgroud)

当我评论构造函数行时,它工作正常,我认为问题出在这一行上,

从'猫鼬'导入{模型};

因为当我将鼠标悬停在这一行时,它显示找不到此模块的声明。我什至尝试复制工作代码的 package.json 文件进行测试,但仍然错误保持不变

我的模块项目包含控制器文件、服务文件、模块文件、dto 文件、接口文件、架构文件、

typescript nestjs

13
推荐指数
5
解决办法
3万
查看次数

Nestjs 返回 404 not found 1 条路线对其他人来说工作正常

我正在使用 Nestjs 创建一个 API,这对它来说相当新。我创建了 4 个模块,所有 4 个模块似乎都工作正常。我创建了另一个模块名称steps,但我在其中访问的所有路由都返回404 not found。

nestjs

13
推荐指数
4
解决办法
2万
查看次数

如何在不同的NestJS模块中引用Mongoose模型

我是 NestJS 的新手。我确信这是一个简单的问题,但我就是找不到答案。

Nest 文档中,建议每个模型有一个模块。这涉及使用以下方法创建模型MongooseModule.forFeature

imports: [MongooseModule.forFeature([{ name: 'Cat', schema: CatSchema }])]
Run Code Online (Sandbox Code Playgroud)

文档说:

如果您还想在另一个模块中使用模型,请将 MongooseModule 添加到其他模块的exports部分CatsModule并导入CatsModule

我的问题是如何在新模块中引用模型。

我可以看到:

  1. 如果使用以下命令创建模型,将如何完成此操作mongoose.model('Name', MySchema)
  2. 需要什么出口
  3. 一个暗示这将使用 完成的问题import { Model } from 'mongoose'; @InjectModel('name') myModel: Model<MyInterface>),但感觉它重复了由 完成的模型创建MongooseModule.forFeature,因为它再次将 mongoose 模型与模式结合起来

任何帮助表示赞赏!

mongoose node.js nestjs

13
推荐指数
1
解决办法
1万
查看次数

如何使用 typeorm 在 Nest js 中存储大整数

某个.entity.ts

amount:number
Run Code Online (Sandbox Code Playgroud)

但是当我在 postgres 中存储非常大的数据时,它会抛出错误“整数超出范围”

我的问题是如何使用 typeorm 将Big Int存储为 psql 中的类型

typeorm nestjs

13
推荐指数
3
解决办法
2万
查看次数

使用 Supertest 时 request.cookies 未定义

我通过 NestJS API 中的 HTTP-Only cookie 传递身份验证令牌。

因此,在为我的 Auth 端点编写一些 E2E 测试时,我遇到了 cookie 不在我期望的位置的问题。

这是我精简的测试代码:

describe('auth/logout', () => {
  it('should log out a user', async (done) => {
    // ... code to create user account

    const loginResponse: Response = await request(app.getHttpServer())
                                              .post('/auth/login')
                                              .send({ username: newUser.email, password });

    // get cookie manually from response.headers['set-cookie']
    const cookie = getCookieFromHeaders(loginResponse);

    // Log out the new user
    const logoutResponse: Response = await request(app.getHttpServer())
                                            .get('/auth/logout')
                                            .set('Cookie', [cookie]);

  });
});
Run Code Online (Sandbox Code Playgroud)

在我的 JWT 策略中,我使用自定义 cookie 解析器。我遇到的问题是request.cookies …

cookies supertest nestjs

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

如何在nestjs graphql中实现用户防护

我试图获取当前用户,但在解析器中我未定义,在 jwt 策略中我使用令牌获取用户对象,但在解析器中用户未定义

授权卫士

import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthenticationError } from 'apollo-server-core';
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {

    canActivate(context: ExecutionContext) {
        const ctx = GqlExecutionContext.create(context);
        const { req } = ctx.getContext();

        return super.canActivate(
            new ExecutionContextHost([req]),
        );
    }

    handleRequest(err: any, user: any) {
        if (err || !user) {
            throw err || new AuthenticationError('GqlAuthGuard');
        }
        return user;
    } …
Run Code Online (Sandbox Code Playgroud)

javascript jwt graphql graphql-js nestjs

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

Nestjs 依赖注入 - 将服务注入服务

我有一项服务,可以毫无问题地注入其他组件。

当我尝试将该服务注入另一个服务时,我得到

Error: Nest can't resolve dependencies of the AService (?). 
Please make sure that the argument BService at index [0] is available in the AService context.
Run Code Online (Sandbox Code Playgroud)

我找不到任何方法来相互注入服务。这是否不受支持,有点反模式......?

如果是这样,如何处理具有我希望在多个组件和服务中的所有应用程序中可用的功能的服务?

代码如下:

b.模块.ts

import { Module } from '@nestjs/common';
import { BService } from './b.service';

@Module({
  imports: [],
  exports: [bService],
  providers: [bService]
})
export class bModule { }
Run Code Online (Sandbox Code Playgroud)

b.服务.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class BService {
  someFunc();
}
Run Code Online (Sandbox Code Playgroud)

a.module.ts

import { Module } from '@nestjs/common';
import { SensorsService …
Run Code Online (Sandbox Code Playgroud)

dependency-injection typescript nestjs

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

有没有一种方法可以使用 Group By 和 Count with Type Orm Repository

我是新来的,最近加入了 ORM 我正在​​尝试的代码

第一个查询:我想使用这种方法,但不确定如何按列进行分组,然后在该列上按 desc 排序

 const result = await this.jobViewsRepository.find({
        relations: ["jobs"],
        loadEagerRelations: true,  
        order: { id: "DESC" },
        skip: offset,
        take: limit,
    }
    );
Run Code Online (Sandbox Code Playgroud)

我正在尝试是否可以在上面的查询中使用它

第二个问题:它对我来说完美无缺,我正在寻找的结果

    const res = await this.jobViewsRepository.createQueryBuilder('jobViews')           
    .addSelect("COUNT(jobViews.user_id) AS jobViews_total_count" )
    .leftJoinAndSelect(Jobs, "jobs", "jobs.id = jobViews.job_id")
    .where("jobs.user_id != :id", { id: user_id })        
    .groupBy("jobViews.job_id")**
    .orderBy('jobViews_total_count', 'DESC')**
    .limit(limit)
    .offset(offset)           
    .getRawMany();
Run Code Online (Sandbox Code Playgroud)

如果有人能帮我解决这个问题,我将不胜感激

谢谢

typeorm nestjs

13
推荐指数
1
解决办法
6920
查看次数