标签: nestjs

Nest JS GraphQL“不能为不可为空返回空值”

我试图解决研究代码中的一个错误,但失败了。然后我只是尝试启动此代码...

https://github.com/nestjs/nest/tree/master/sample/23-type-graphql

和同样的情况...

错误看起来像

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Recipe.id.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "recipe",
        "id"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "Error: Cannot return null for non-nullable field Recipe.id.",
            "    at completeValue (/home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:560:13)",
            "    at /home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:492:16",
            "    at process._tickCallback (internal/process/next_tick.js:68:7)"
          ]
        }
      }
    }
  ],
  "data": null
}
Run Code Online (Sandbox Code Playgroud)

有人有想法吗?

javascript node.js typescript graphql nestjs

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

NestJS - 将静态(非导入)文件复制到 dist 文件夹的正确方法

我正在构建一个使用谷歌云 API(例如谷歌云存储)的应用程序。为了使用 api 对应用程序进行身份验证,我需要将keyfile.json包含身份验证凭据的文件的路径传递给 GCloud Api 初始化脚本。IE

const storage = new Storage({
      keyFilename: path.join(__dirname, '../../keyfile.json'),
});
Run Code Online (Sandbox Code Playgroud)

我将keyfile.json放入 NestJSsrc文件夹,但是当我构建应用程序时,该文件不会复制到dist.

在 NestJS 中处理静态文件复制到 dist 的推荐方法是什么?

static google-cloud-storage google-cloud-platform gcloud nestjs

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

typeOrm 唯一行

我正在尝试在我的 NestJS 上使用 typeOrm 创建一个实体,但它没有按我预期的那样工作。

我有以下实体

@Entity('TableOne')
export class TableOneModel {
  @PrimaryGeneratedColumn()
  id: number

  @PrimaryColumn()
  tableTwoID: number

  @PrimaryColumn()
  tableThreeID: number

  @CreateDateColumn()
  createdAt?: Date
}
Run Code Online (Sandbox Code Playgroud)

此代码生成一个迁移,该迁移生成一个类似于下面示例的表

+--------------+-------------+------+-----+----------------------+-------+
| Field        | Type        | Null | Key | Default              | Extra |
+--------------+-------------+------+-----+----------------------+-------+
| id           | int(11)     | NO   |     | NULL                 |       |
| tableTwoID   | int(11)     | NO   |     | NULL                 |       |
| tableThreeID | int(11)     | NO   |     | NULL                 |       |
| createdAt    | datetime(6) | NO   | …
Run Code Online (Sandbox Code Playgroud)

typeorm nestjs

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

在 Nest.js 应用程序的 main.js 中使用 ConfigService

我想弄清楚如何使用我的 ConfigService创建的,如此处所述。在我的应用程序的最顶层。

我的main.js文件看起来像这样:

import { NestFactory } from '@nestjs/core';
import { TypeormStore } from 'connect-typeorm';
import * as session from 'express-session';
import { getRepository } from 'typeorm';
import { Session } from '../../domains/session/Session';
import { AppModule } from './AppModule';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);

    app.use(session({
        resave: false,
        saveUninitialized: false,
        store: new TypeormStore({
            cleanupLimit: 2,
            ttl: 86400
        }).connect(getRepository(Session)),
        secret: process.env.COOKIE_SECRET as string
    }))

    await app.listen(3000);
}
bootstrap();

Run Code Online (Sandbox Code Playgroud)

我想要的是移动process.env.COOKIE_SECRET到内部的吸气剂ConfigService。我可以访问此级别的服务吗?

javascript middleware typescript nestjs

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

NestJS - 每个模块使用多个 MongoDB 连接

有没有办法为每个模块连接多个 MongoDB 连接?

app.module.ts

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/masterDB'),
    UserModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

同样,我们可以在另一个模块中定义另一个连接,它是 app.module 的子模块吗?

子模块.ts

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/childDB'),
    MongooseModule.forFeature([{ name: 'child', schema: ChildSchema }]),
  ],
  controllers: [ChildController],
  providers: [ChildService],
})
export class ChildModule { }

Run Code Online (Sandbox Code Playgroud)

或以任何其他方式同时访问不同的数据库。

提前致谢!

multiple-databases mongoose mongodb node.js nestjs

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

控制器的嵌套路由中的 Nestjs 验证失败(需要数字字符串)

我有一个使用@Controller('tasks')装饰器的控制器。在这个控制器中,我有一个路由@Get('/week'),通常请求应该去localhost:4000/tasks/week但它返回一个错误的请求:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Validation failed (numeric string is expected)"
}
Run Code Online (Sandbox Code Playgroud)

下面是我的代码:

@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
  constructor(private tasksService: TasksService) { }

  @Get('/:id')
  getTaskById(@Param('id', ParseIntPipe) id: number): Promise<Task> {
    return this.tasksService.getTaskById(id);
  }

  @Get('/week')
  getTasksByWeek(@GetUser() user: User): Promise<Task[]> {
    return this.tasksService.getTasksByWeek(user);
}
Run Code Online (Sandbox Code Playgroud)

从 Get() 装饰器中删除/week有效但不添加它。

预期结果:返回数据

实际结果

 {
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Validation failed (numeric string is expected)"
}
Run Code Online (Sandbox Code Playgroud)

nestjs

1
推荐指数
3
解决办法
3389
查看次数

NestJs - ParseUUIDPipe - 验证失败(需要 uuid vundefined)

我有一个基本的控制器设置:

@Controller('')
export class AController {
 @Get(':id')
  async getThing(@Param('id', ParseUUIDPipe) id: string): Promise<RegisterRead[] | IntervalRead[]> {
      return id
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Validation failed (uuid vundefined is expected)"
}
Run Code Online (Sandbox Code Playgroud)

另见:https : //github.com/nestjs/nest/issues/2960

nestjs

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

类验证器忽略嵌套对象

我正在为我的项目使用 NestJs 框架。在我的控制器中,我接受 POST 请求,并通过 ValidationPipe 将 body 转换为我的 CreateHouseDTO。ValidationPipe 正在使用白名单和转换。

当我像这样使用 JSON 尝试 api 时:

{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是我的应用程序记录的内容(console.log 输出):

CreateHouseDTO{
    name:'Test',
    floors[ {} ]
}
Run Code Online (Sandbox Code Playgroud)

当我在嵌套对象中犯一些错误时,它甚至会验证嵌套对象。例如,如果我将Floor对象中的name属性设置为Null或某个没有引号的数字

这是一个错误还是我做错了什么?请帮我。

我的代码:

{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

typescript class-validator nestjs

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

TypeORM 外键

我想将 a 引用module到 a queue。所以一个人queue可以有多个modules. 因此,我只是想存储idmodulequeue

根据 Typeorm 的文档,我应该以这种方式实现这种关系:

@ManyToOne(type => Module)
@JoinColumn({ name: "currentModuleId" })
module: Module;
Run Code Online (Sandbox Code Playgroud)

我只是想提供idmodule,而不是一个模块对象。所以我想出了这个解决方案:

模块实体

@Entity()
export class Module extends BaseEntity {
  @PrimaryColumn({ unique: true })
  public id: string;
}
Run Code Online (Sandbox Code Playgroud)

队列实体

@Entity()
export class Queue extends BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  public id: string;

  @OneToOne(() => Module)
  @JoinColumn({ name: 'currentModuleId' })
  currentModuleId: string;
}
Run Code Online (Sandbox Code Playgroud)

这有效,但我不太相信这是一个防错解决方案。我应该如何为 实现外键queue

另外:Typeorm …

postgresql foreign-keys typeorm nestjs

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

NestJS 视图未添加到 Dist

我的文件夹结构类似于下面。

public
views
src
  main.ts
  /users
       users.controller.ts
       /views
         my-view.hbs
  /books
       books.controller.ts
       /views
         my-view.hbs
Run Code Online (Sandbox Code Playgroud)

这是我用来添加模板和视图的

 const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
  );
  console.log(join(__dirname, 'public'));

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');
  hbs.registerPartials(join(__dirname, '..', 'views', 'partials'));

Run Code Online (Sandbox Code Playgroud)

我的 package.json 脚本看起来像这样

"scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/src/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk …
Run Code Online (Sandbox Code Playgroud)

node.js typescript nestjs

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