标签: nestjs

TypeError:存储库方法不是函数(NestJS / TypeORM)

我正在使用 NestJS 和 TypeORM。尝试调用存储库的 createMailLogEntry 方法时,出现以下错误:TypeError: this.mailLogEntryRepository.createMailLogEntry is not a function

我无法弄清楚出了什么问题。

mailing.service.ts

@Injectable()
export class MailingService {

    constructor(@InjectRepository(MailLogEntryRepository) private mailLogEntryRepository: MailLogEntryRepository) { }

        // ...

        if(transferResult) {
            await this.mailLogEntryRepository.createMailLogEntry({
                creationDate: new Date(Date.now()),
                from: mailContent.from,
                to: mailContent.to,
                subject: mailContent.subject,
                text: mailContent.text,
                html: mailContent.html,
                cc: mailContent.cc,
                bcc: mailContent.bcc,
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

邮件日志条目.repository.ts

@EntityRepository(MailLogEntry)
export class MailLogEntryRepository extends Repository<MailLogEntry> {

    async createMailLogEntry(mailLogEntryDto: MailLogEntryDto): Promise<MailLogEntry> {
        const mailLogEntry = MailLogEntryRepository.createMailLogEntryFromDto(mailLogEntryDto);
        return await mailLogEntry.save();
    }

    private static createMailLogEntryFromDto(mailLogEntryDto: MailLogEntryDto): MailLogEntry {
        const …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript typeorm nestjs

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

如何测试验证管道在 NestJS 上抛出错误形状的请求的期望错误

我正在使用 NestJS 7.0.2 并通过app.useGlobalPipes(new ValidationPipe());.

我希望能够进行单元测试,以验证是否在提供形状不正确的对象时抛出错误,但是编写的测试仍然通过。我已经看到一种解决方案是通过这篇文章在 e2e 中进行此测试,但我想知道是否有任何我遗漏的内容可以让我在单元测试中执行此操作。

我有一个非常简单的控制器和一个非常简单的 DTO。

控制器

async myApi(@Body() myInput: myDto): Promise<myDto | any> {
  return {};
}
Run Code Online (Sandbox Code Playgroud)

DTO

export class myDto {
  @IsNotEmpty()
  a: string;

  @IsNotEmpty()
  b: string | Array<string>
}
Run Code Online (Sandbox Code Playgroud)

规范文件

  describe('generate', () => {
    it('should require the proper type', async () => {
      const result = await controller.generate(<myDto>{});
      // TODO: I expect a validation error to occur here so I can test against it.
      expect(result).toEqual({})
    })
  }) …
Run Code Online (Sandbox Code Playgroud)

jestjs nestjs

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

NestJs Angular Universal 不工作 - 启用离线持久性时出错

使用最新版本的 angular、angularfire 和 angular Universal 时出现此错误。

服务

定期服务没问题...

ng 添加@nestjs/ng-universal

添加了通用,似乎安装得很好...

npm 运行构建:ssr

似乎编译,一些警告,但没有错误......

npm 运行服务:ssr

似乎可以正常工作,直到我在本地主机上加载页面并出现此错误:

启用离线持久性时出错。回退到持久性禁用:错误:ENOENT:没有这样的文件或目录,打开'C:\angular projects\testProject\dist\testproject\server\src\protos\google\firestore\v1\firestore.proto'

---------更新-----------

我删除了dist文件夹并重建,现在我得到了这个错误:

错误:ENOENT:没有这样的文件或目录,打开“google/protobuf/api.proto”

这是完整的错误:

PS C:\angular projects\testapp.io> npm run serve:ssr

> testapp@0.0.0 serve:ssr C:\angular projects\testapp.io
> node dist/testapp/server/main.js

C:\angular projects\testapp.io\dist\testapp\server\main.js:1
!function(e,a){for(var i in a)e[i]=a[i]}(exports,function(modules){var installedModules={},installedChunks={1:0};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}return __webpack_require__.e=function requireEnsure(chunkId){if(0!==installedChunks[chunkId]){var chunk=require("./"+({0:"firebase-functions",2:"vendors~firebase-auth",3:"vendors~firebase-functions"}[chunkId]||chunkId)+".js"),moreModules=chunk.modules,chunkIds=chunk.ids;for(var moduleId in moreModules)modules[moduleId]=moreModules[moduleId];for(var i=0;i<chunkIds.length;i++)installedChunks[chunkIds[i]]=0}return Promise.all([])},__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){

Error: ENOENT: no such file or directory, open 'google/protobuf/api.proto'
    at Object.openSync (fs.js:443:3)
    at Object.readFileSync (fs.js:343:35)
    at fetch (C:\angular projects\testapp.io\dist\testapp\server\main.js:1:1329786)
    at …
Run Code Online (Sandbox Code Playgroud)

firebase angular-universal angular google-cloud-firestore nestjs

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

在 nest.js 中使用带有 nestjsx-automapper 的配置文件

我正在使用Chau Tran 的nestjsx-automapper ( https://automapper.netlify.app/docs/usages/init/add-profile )(感谢这段很酷的代码)。我已经按照文档中所示和这里已经讨论过的方式实现了它: How use profiles from nartc/automapper into an nestjs application

但是我仍然无法从我的 Profile类中访问 AutoMapper

这是我的设置:

app.module.ts:

import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { MerchantModule } from './merchant/merchant.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AutomapperModule, AutoMapper } from 'nestjsx-automapper';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...
    }),
    AutomapperModule.withMapper(),
    MerchantModule
  ],
  providers: [],
  controllers: [],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

商户.module.ts:

import { Module } from …
Run Code Online (Sandbox Code Playgroud)

mapping automapper node.js nestjs

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

如何访问 nestjs 管道中的标头?

我正在编写一个验证管道,它需要从令牌中获取某些信息,所以我必须以某种方式将标头传递给验证管道。

nestjs

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

Nest.js 只接受在 DTO 中指定的字段

我目前正在使用 Nest.js 并有一个简单的应用程序,其中包含注册帐户的路径。我创建了一个包含几个字段和一个 mongodb 模式的 DTO。在 mongodb 模式中只有一个字段我不想让用户在创建时修改(=特权),所以我没有在 DTO 中指定它。

但是,如果用户使用正文中的权限属性发出请求,它仍将保存到 DTO,然后保存在架构中。

有没有办法“切断”身体中与 DTO 不匹配的任何数据?我敢肯定它曾经告诉我有一个它无法识别的领域,但它似乎不再起作用了。我试图找到一个类验证器或其他东西,但找不到任何合适的东西,我真的不想自己检查每个属性......

提前致谢!


来自 account.service.ts

  async register(body: RegisterAccountDto) {
    return new_account.save();
  }
Run Code Online (Sandbox Code Playgroud)

来自 account.controller.ts

  @ApiOperation({ summary: 'Register user', description: 'Register a new account' })
  @ApiConsumes('x-www-form-urlencoded')
  @ApiBody({ type: [RegisterAccountDto] })
  @Post('register')
  async register(@Body() body: RegisterAccountDto) {
    return this.accountService.register(body);
  }
Run Code Online (Sandbox Code Playgroud)

来自 account.schema.ts

  @Prop({ default: Privilege.USER })
  privilege: Privilege;
Run Code Online (Sandbox Code Playgroud)

dto typescript class-validator nestjs

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

Nestjs/TypeORM - 如何按列实现自定义搜索

我正在使用 TypeORM 和 MySQL 来玩 NestJs。

我已经阅读了文档,并且已经制作了在本地运行的基本 CRUD 应用程序。我已经通过 id 内置了搜索(通过 Repository),但我还需要通过自定义列实现搜索。

例如我有这个实体:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;

  @Column()
  first_name: string;

  @Column()
  last_Name: string;

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

在我的存储库中,我有这些内置方法:

async findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: string): Promise<User> {
    return this.usersRepository.findOne(id);
  }
  
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,它工作得很好。我需要另一个自定义搜索,所以我也可以按用户名搜索,我该如何实现?我需要这样的东西:

findByUsername(username: string): Promise<User> {
    return this.usersRepository.findByUsername(username);
  }
Run Code Online (Sandbox Code Playgroud)

我假设我必须实现自定义查询,但我不知道在哪里做:(

node.js typeorm nestjs

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

Jest Matcher 错误:接收到的值必须是一个承诺或一个返回承诺的函数

我是 TDD 从业者,我正在尝试实现一个异常。

下面是测试代码:

  it.each([[{ id: '', token: '', skills: [''] }, 'Unknown resource']])(
    'should return an Exception when incorrect dto data',
    async (addSkillsDto: AddSkillsDto) => {
      await expect(() => {
        controller.addSkills(addSkillsDto)
      }).rejects.toThrow()
    }
  )
Run Code Online (Sandbox Code Playgroud)

下面是相关代码:

  @Post('candidate/add-skills')
  async addSkills(
    @Body() skills: AddSkillsDto,
  ): Promise<StandardResponseObject<[]>> {
    const data = await this.candidateService.addSkills(skills)
    console.log(data, !data)
    if (!data) throw new HttpException('Unknown resource', HttpStatus.NOT_FOUND)
    else
      return {
        success: true,
        data,
        meta: null,
        message: ResponseMessage.SKILLS_ADDED,
      }
  }
Run Code Online (Sandbox Code Playgroud)

这是运行 Jest 时的控制台输出:

? Candidate Controller › should return …
Run Code Online (Sandbox Code Playgroud)

exception promise typescript jestjs nestjs

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

NestJS 中间件未执行

从模块连接时,NestJS 类或功能中间件不会运行。它也不适用于单个路径、控制器或每个路径。从 main.ts 连接功能中间件工作正常。

//main.ts
import { ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
import { AppModule } from './app.module'

declare const module: any

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter())

  app.useGlobalPipes(new ValidationPipe())

  await app.listen(2100)

  if (module.hot) {
    module.hot.accept()
    module.hot.dispose(() => app.close())
  }
}
bootstrap()
Run Code Online (Sandbox Code Playgroud)
//app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import { AuthMiddleware } from './middleware/auth.middleware'
import { UserModule } from './user/user.module' …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript nestjs fastify

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

从 Nestjs 中的可观察对象中的响应返回数据

我是Nestjs、Typescript 和后端开发的新手。我正在开发一个简单的 Weather 应用程序,在那里我从Open Weather API获取天气数据。我正在使用内置的 NestHttpModule来包装 Axios,然后使用HttpService它向 Open weather 发出 GET 请求。该请求正在返回一个 Observable,这对我来说完全是新闻。如何从 中的 observable 中提取实际响应数据Injectable service并将其返回给Controller

这是我的 weather.service.ts

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

@Injectable()
export class AppService {
  constructor(private httpService: HttpService) {}

  getWeather() {
    let obs = this.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a');
    
    console.log('just before subscribe');
    
    obs.subscribe((x) => {
        let {weather} = x.data;
        console.log(weather);
    })
    console.log('After subscribe');
    
    // TODO: Should extract and return response data f
    // return;
  } …
Run Code Online (Sandbox Code Playgroud)

observable typescript nestjs

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