标签: nestjs

如何从 typeorm 实体中排除列,并且可以选择使用 Find 方法获取列

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@Column()
password: string;
}
Run Code Online (Sandbox Code Playgroud)

我在这里不需要密码,因为我想返回客户端:

const user = await User.find({where:{name:"test"}})
Run Code Online (Sandbox Code Playgroud)

当我想修改密码时我需要密码:

const user = await User.findOne({where:{name:"test"}})
user.password="password";
await user.save()
Run Code Online (Sandbox Code Playgroud)

有 Find、FindAndCount 甚至 FindOne 方法的解决方案吗?

我应该怎么做?

postgresql node.js typescript typeorm nestjs

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

如何在 Prisma ORM 中过滤关系

我目前正在从事课程服务工作。用户可以注册和取消注册课程。整个系统采用微服务架构构建,这意味着用户由另一个服务管理。因此,课程服务的数据模型如下所示:

model course {
  id                Int                @id @default(autoincrement())
  orderNumber       Int                @unique
  courseNumber      String             @unique @db.VarChar(255)
  courseName        String             @db.VarChar(255)
  courseOfficer     String             @db.VarChar(255)
  degree            String             @db.VarChar(255)
  ectCount          Int
  faculty           String             @db.VarChar(255)
  isWinter          Boolean            @default(false)
  isSummer          Boolean            @default(false)
  courseDescription String?            @db.VarChar(255)
  enrollmentCourse  enrollmentCourse[]
}

model enrollmentCourse {
  id       Int    @id @default(autoincrement())
  userId   String @db.VarChar(1024)
  course   course @relation(fields: [courseId], references: [id])
  courseId Int
}
Run Code Online (Sandbox Code Playgroud)

我想查找某个用户注册的所有课程。我写了2个查询。我们浏览一下课程并尝试筛选注册课程。然而,这个不起作用,我拿回了所有课程。而第二个则检查注册课程,然后使用映射返回课程。这是可行的,但我不喜欢这个解决方案,如果它有效的话,我更喜欢第一个查询:(我已经使用本指南来编写第一个查询:here

const result1 = await this.prisma.course.findMany({
  where: { enrollmentCourse: { every: { userId: user.id } } },
  include: …
Run Code Online (Sandbox Code Playgroud)

postgresql relation nestjs prisma

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

如何测试NestJs响应拦截器

我试图遵循这个线程,但我不断收到错误。

变换响应.interceptor.ts:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponseInterface } from '@walletxp/shared-interfaces';

@Injectable()
export class TransformResponseInterceptor<T>
  implements NestInterceptor<T, ApiResponseInterface<Record<string, unknown>>>
{
  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponseInterface<Record<string, unknown>>> {
    return next.handle().pipe(map((data) => ({ success: true, data })));
  }
}

Run Code Online (Sandbox Code Playgroud)

对于它的测试,transform-response.interceptor.spec.ts:

import { TransformResponseInterceptor } from './transform-response.interceptor';
const interceptor = new TransformResponseInterceptor();

const executionContext: any = {
  switchToHttp: jest.fn().mockReturnThis(),
  getRequest: jest.fn().mockReturnThis(),
}; …
Run Code Online (Sandbox Code Playgroud)

http interceptor typescript jestjs nestjs

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

NestJs 在 @Cron 装饰器上使用环境配置

我正在构建一个 NestJs 应用程序,具有调度和配置功能。我希望能够使用环境变量配置我的 Cron,但它似乎不起作用。

应用程序模块.ts:

@Module({
  imports: [
    ConfigModule.forRoot(),
    ScheduleModule.forRoot(),
    SchedulingModule,
    ...
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

Schedule.service.ts(来自我的SchedulingModule):

@Cron(process.env.CRON_VALUE)
scheduledJob() {
  this.logger.log('Scheduled : Job');
  ...
}
Run Code Online (Sandbox Code Playgroud)

.env:

...
CRON_VALUE=0 4 * * *
...
Run Code Online (Sandbox Code Playgroud)

显然,目前检查该值时它是空的。我收到以下错误:

(node:55016) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_isAMomentObject' of undefined
    at new CronTime (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:42:50)
    at new CronJob (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:527:19)
    at /Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/@nestjs/schedule/dist/scheduler.orchestrator.js:56:29 
    ...
Run Code Online (Sandbox Code Playgroud)

javascript node.js node-cron nestjs

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

NestJS 延迟加载导入 TypeORM 的模块不注册“连接”提供程序

我有一个DatabaseModule导入 TypeORM 并启动数据库连接(参见database.module.ts)。我在 CRUD 模块上使用该模块,并且在以经典方式注册模块时一切正常。

但是,当我延迟加载同一模块时,它会中断并出现“无法解析连接”错误。

“错误 [ExceptionsHandler] Nest 无法解析 ProductRepository 的依赖关系(?)。请确保索引 [0] 处的参数 Connection 在 TypeOrmModule 上下文中可用。”

我正在编写无服务器函数,因此尝试延迟加载。

// product.module.ts: the module I lazy-load
@Module({
imports: [
  DatabaseModule.register({
    entities: [Product],
  }),
],
Run Code Online (Sandbox Code Playgroud)
// database.module.ts: the module that creates the db connections
export interface DatabaseOptions {
  entities: any[];
}

@Module({})
export class DatabaseModule {
  static register(options: DatabaseOptions): DynamicModule {
    return {
      module: DatabaseModule,
      imports: [
        TypeOrmModule.forRoot({
          type: 'mysql',
          host: '0.0.0.0',
          port: 3306,
          username: …
Run Code Online (Sandbox Code Playgroud)

lazy-loading typeorm nestjs

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

NestJS如何在同一请求中传递@Param和@Query

我设置了这条路线:

  @Get('/name/like')
  findByLikeName(@Query() query: { supplierID: string; name: string }) {
    return this.supplierProductService.findByLikeName(query);
  }
Run Code Online (Sandbox Code Playgroud)

它利用底层服务中的查询参数:

  async findByLikeName({
    supplierID,
    name,
  }: {
    supplierID: string;
    name: string;
  }): Promise<SupplierProduct[]> {
    return await this.supplierProductRepository.findAll({
      where: {
        name: {
          [Op.like]: `%${name}%`,
        },
        supplierID: supplierID,
      },
    });
  }
Run Code Online (Sandbox Code Playgroud)

但是,假设我想将 sellerID 移动到 /:supplierID 路由参数中,同时在查询对象中维护名称(以及潜在的其他查询参数),我将如何实现这一点?

parameters query-string routeparams nestjs

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

将 Nestjs 部署到 Google 应用引擎时出现“sh: 1: exec: Nest: not found”错误

我正在尝试将 Nestjs 应用程序部署到 google 应用引擎,但出现sh: 1: exec: nest: not found错误

我的包.json

    "main": "dist/main.js",
    "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/main",
        "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
        "test": "jest",
        "test:watch": "jest --watch",
        "test:cov": "jest --coverage",
        "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
        "test:e2e": "jest --config ./test/jest-e2e.json",
        "gcp-build": "npm run build",
        "ae:deploy": "gcloud app deploy --quiet",
        "ae:browse": "gcloud app …
Run Code Online (Sandbox Code Playgroud)

google-app-engine node.js docker nestjs

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

如何使用 @nestjs/mongoose 中的 @Prop 装饰器添加嵌套对象数组

当我在 prop 装饰器中使用嵌套的对象数组时:

@Schema()
export class Child {
  @Prop()
  name: string;
}
    
@Schema()
export class Parent {
  @Prop({type: [Child], _id: false}) // don't need `_id` for nested objects
  children: Child[];
}

export const ParentSchema = SchemaFactory.createForClass(Parent);
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: Invalid schema configuration: `Child` is not a valid type within the array `children`.
Run Code Online (Sandbox Code Playgroud)

如果我需要使用@Prop({_id: false})(以保持嵌套模式独立),我该如何解决这个问题?


如果我们更改 prop 装饰器,@Prop([Child])它就可以工作,但是我们需要禁用_id嵌套对象:

@Schema({_id: false})
export class Child {
  @Prop()
  name: string;
}

@Schema()
export class Parent {
  @Prop([Child])
  children: Child[]; …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose typescript-decorator nestjs nestjs-mongoose

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

如何在没有DTO的情况下验证Nestjs中的Param字符串是否为MongoId

我的控制器中有请求,这@Param是 MongoId 的字符串版本。如果我使用无效的字符串格式(不匹配 MongoId 格式)调用此请求,则该请求将继续执行,直到 MongoDB 调用抛出内部服务器错误。

我如何验证例如"aaa"“ANWPINREBAFSOFASD”未经过验证并在我的请求中尽早停止

当前控制器端点:

@Get(':id')
  @ApiOperation({ summary: 'Get nice information' })
  findOne(
    @Param('id') id: string) {
    return this.niceService.findOne(id);
  }
Run Code Online (Sandbox Code Playgroud)

该服务称为:

async findOne(id: string): Promise<NiceDocument> {

    const niceResult: NiceDocument = await this.NiceSchema.findById(id)

    if (!niceResult) {
      throw new NotFoundException()
    }
    return table
  }
Run Code Online (Sandbox Code Playgroud)

javascript validation mongoose mongodb nestjs

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

使用 class-validator 和 Nest.js 验证对象数组

我将类验证器与 NestJS 结合使用,并尝试使用以下布局验证对象数组:

[
    {gameId: 1, numbers: [1, 2, 3, 5, 6]},
    {gameId: 2, numbers: [5, 6, 3, 5, 8]}
]
Run Code Online (Sandbox Code Playgroud)

我的解析器

createBet(@Args('createBetInput') createBetInput: CreateBetInput) {
    return this.betsService.create(createBetInput);
  }
Run Code Online (Sandbox Code Playgroud)

我的 createBetInput DTO

import { InputType, Field, Int } from '@nestjs/graphql';
import { IsArray, IsNumber } from 'class-validator';

@InputType()
export class CreateBetInput {
  @IsNumber()
  @Field(() => Int)
  gameId: number;

  @Field(() => [Int])
  @IsArray()
  numbers: number[];
}
Run Code Online (Sandbox Code Playgroud)

我尝试了一些解决方案,但没有成功,老实说,我不知道该怎么做。

如何修改 DTO 以获得必要的验证?

javascript typescript graphql class-validator nestjs

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