CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 28d agoView on Hugging Face
1likes889downloads
nestjs.jsonl1334 linesDownload Raw Back to stackoverflow
1{"id":"stack-54958244","source":"stackoverflow","questionId":54958244,"title":"How to use query parameters in Nest.js?","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: How to use query parameters in Nest.js?\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am a freshman in Nest.js.\n\nAnd my code as below\n\n```\n@Get('findByFilter/:params')\nasync findByFilter(@Query() query): Promise {\n \n}\n```\n\nI have used `postman` to test this router\n\nhttp://localhost:3000/article/findByFilter/bug?google=1&baidu=2\n\nActually, I can get the query result `{ google: '1', baidu: '2' }`. But I'm not clear why the url has a string `'bug'`?\n\nIf I delete that word just like\n\nhttp://localhost:3000/article/findByFilter?google=1&baidu=2\n\nthen the postman will shows statusCode `404`.\n\nActually, I don't need the word `bug`, how to custom the router to realize my destination just like `http://localhost:3000/article/findByFilter?google=1&baidu=2`\n\nHere's another question is how to make mutiple router point to one method?\n\n========================================\n\nTop Answer:\nIf you have you parameter as part or url: */articles/${articleId}/details*, you wold use @Param\n\n```\n@Get('/articles/:ARTICLE_ID/details')\nasync getDetails(\n @Param('ARTICLE_ID') articleId: string\n)\n```\n\nIF you want to provide query params */article/findByFilter/bug?**google=1&baidu=2***, you could use\n\n```\n@Get('/article/findByFilter/bug')\nasync find(\n @Query('google') google: number,\n @Query('baidu') baidu: number,\n)\n```\n\n**EDIT**: The path part (`/article/findByFilter/bug`) should not have a trailing question mark even when you expect query parameters. When you specify a question mark (like `/article/findByFilter/bug?`) it makes the last `g` optional, as this string is treated as a regex.\n\n========================================\n\nCode:\n```js\n@Get('findByFilter/:params')\nasync findByFilter(@Query() query): Promise<Article[]> {\n    \n}\n```\n\n```text\npostman\n```\n\n```text\n{ google: '1', baidu: '2' }\n```\n\n```text\n'bug'\n```\n\n```text\n404\n```\n\n```text\nbug\n```\n\n```text\nhttp://localhost:3000/article/findByFilter?google=1&baidu=2\n```\n\n```text\n@Get('findByFilter')\nasync findByFilter(@Query() query): Promise<Article[]> {\n  // ...\n}\n```\n\n```text\n@Get('products/:id')\ngetProduct(@Param('id') id) {\n```\n\n```text\nlocalhost:3000/products/1\nlocalhost:3000/products/2abc\n// ...\n```\n\n```text\n@Get('other|te*st')\n```\n\n```text\nlocalhost:3000/other\nlocalhost:3000/test\nlocalhost:3000/te123st\n// ...\n```\n\n```text\n:params\n```\n\n```text\n:param\n```\n\n```text\nimport { Controller, Get, Req } from '@nestjs/common';\nimport { Request } from 'express';\n\n(...)\n\n@Get(':framework')\ngetData(@Req() request: Request): Object {\n    return {...request.params, ...request.query};\n}\n```\n\n```text\n{\n    \"framework\": \"nest\",\n    \"version\": \"7\"\n}\n```\n\n```text\n@Get()\n  findAll(\n    @Req() req: Request\n  ): Promise<any[]> {\n    console.log(req.query);\n    // another code ....\n  }\n```\n\n```text\n@Req\n```\n\n```text\n@Get('/articles/:ARTICLE_ID/details')\nasync getDetails(\n    @Param('ARTICLE_ID') articleId: string\n)\n```\n\n```text\n@Get('/article/findByFilter/bug')\nasync find(\n    @Query('google') google: number,\n    @Query('baidu') baidu: number,\n)\n```\n\n```text\n/article/findByFilter/bug\n```\n\n```text\n/article/findByFilter/bug?\n```\n\n```text\ng\n```\n\n```text\ngetSomeDataRoute(@Query() allQueryParams: { search?: string, page?: string })\n\n// or\n\ngetSomeDataRoute(@Query('search') search?: string, @Query('page') page?: string)\n```\n\n```text\nclass QueryDto {\n    @Type(() => Number)\n    @IsInt()\n    public readonly page: number;\n\n    @Type(() => Number)\n    @IsInt()\n    public readonly take: number;\n}\n\n@Injectable()\nclass QueryTransformPipe implements PipeTransform {\n    async transform(value: QueryRequestDto, { metatype }: ArgumentMetadata) {\n        if (!metatype) {\n            return value;\n        }\n\n        return plainToInstance(metatype, value);\n    }\n}\n\n\n@Controller()\nclass YourController {\n    @Get()\n    // also you can use it with pipe decorator\n    // @UsePipes(new QueryTransformPipe())\n    async getData(@Query(new QueryTransformPipe()) query?: QueryRequestDto) {\n        // here you get instanceof QueryTransformPipe\n        // with typeof query.page === 'number' && typeof query.take === 'number'\n    }\n}\n```\n\n========================================\n\nComments:\n- I had to put this code... import { Request } from 'express'; ...on top of the script for this to work!\n- @JonathanMartins Feel free to edit my answer\n- No need to do this, Nest helps you by abstracting a lot of the underlying Express request away: docs.nestjs.com/controllers#request-object\n- Actually might help when you are creating a proxy and want to transfer the params as is","metadata":{"transformedAt":"2026-08-18T18:33:02.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":237,"estimatedTokens":1143}}2{"id":"stack-58343262","source":"stackoverflow","questionId":58343262,"title":"Class-validator - validate array of objects","tags":["arrays","typescript","validation","nestjs","class-validator"],"text":"Title: Class-validator - validate array of objects\nTags: arrays, typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI am using class-validator package with NestJS and I am looking to validate an array of objects that need to have exactly 2 objects with the same layout:\n\nSo far I have:\n\n```\nimport { IsString, IsNumber } from 'class-validator';\n\nexport class AuthParam {\n @IsNumber()\n id: number;\n\n @IsString()\n type: string;\n\n @IsString()\n value: string;\n}\n```\n\nand \n\n```\nimport { IsArray, ValidateNested } from 'class-validator';\nimport { AuthParam } from './authParam.model';\n\nexport class SignIn {\n @IsArray()\n @ValidateNested({ each: true })\n authParameters: AuthParam[];\n}\n```\n\nper @kamilg response (I am able to enforce exacly 2 elements):\n\n```\nimport { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';\nimport { AuthParam } from './authParam.model';\n\nexport class SignInModel {\n @IsArray()\n @ValidateNested({ each: true })\n @ArrayMinSize(2)\n @ArrayMaxSize(2)\n authParameters: AuthParam[];\n}\n```\n\nI still can pass an empty array or an array with some other objects not related to AuthParam.\n\nHow I should modify it get validation? \n\nAlso how I can enforce mandatory 2 elements in the array? MinLength(2) seems to be regarding string... (resolved)\n\n========================================\n\nTop Answer:\nI Know I Am Late But Facing Some Issue With Type, Then Try Another Way To Implement This:\n\n```\nexport class AuthParam {\n @IsNumber()\n id: number;\n \n @IsString()\n type: string;\n \n @IsString()\n value: string;\n }\n```\n\nValidation function\n\n```\n@ValidatorConstraint()\nexport class IsAuthArray implements ValidatorConstraintInterface {\n public async validate(authData: AuthParam[], args: ValidationArguments) {\n return Array.isArray(authData) && authData.reduce((a, b) => a && (typeof b.id === \"number\") && typeof b.type === \"string\" && typeof b.field === \"string\", true);\n }\n}\n\nexport class SignInModel {\n @IsNotEmpty()\n @IsArray()\n @ArrayMinSize(2)\n @ArrayMaxSize(2)\n @Validate(IsAuthArray, {\n message: \"Enter valid value .\",\n })\n authParameters: AuthParam[];\n }\n```\n\nMaybe It Will Help Someone ๐Ÿ˜ƒ\n\n========================================\n\nCode:\n```text\nimport { IsString, IsNumber } from 'class-validator';\n\nexport class AuthParam {\n  @IsNumber()\n  id: number;\n\n  @IsString()\n  type: string;\n\n  @IsString()\n  value: string;\n}\n```\n\n```text\nimport { IsArray, ValidateNested } from 'class-validator';\nimport { AuthParam } from './authParam.model';\n\nexport class SignIn {\n  @IsArray()\n  @ValidateNested({ each: true })\n  authParameters: AuthParam[];\n}\n```\n\n```text\nimport { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';\nimport { AuthParam } from './authParam.model';\n\nexport class SignInModel {\n  @IsArray()\n  @ValidateNested({ each: true })\n  @ArrayMinSize(2)\n  @ArrayMaxSize(2)\n  authParameters: AuthParam[];\n}\n```\n\n```text\nimport { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';\nimport { AuthParam } from './authParam.model';\nimport { Type } from 'class-transformer';\n\nexport class SignInModel {\n  @IsArray()\n  @ValidateNested({ each: true })\n  @ArrayMinSize(2)\n  @ArrayMaxSize(2)\n  @Type(() => AuthParam)\n  authParameters: AuthParam[];\n}\n```\n\n```text\n@Type(() => AuthParam)\n```\n\n```text\nType\n```\n\n```text\nvalidator.arrayNotEmpty(array); // Checks if given array is not empty.\n```\n\n```text\nvalidator.arrayMinSize(array, min); // Checks if array's length is at least `min` number.\n```\n\n```text\nconst param1: AuthParam = Object.assign(new AuthParam(), {\n  id: 1,\n  type: 'grant',\n  value: 'password'\n})\n\nconst param2: AuthParam = Object.assign(new AuthParam(), {\n  id: 1,\n  type: 4,\n  value: 'password'\n})\n\nconst signInTest = new SignInModel()\nsignInTest.authParameters = [param1, param2]\n\nvalidate(signInTest).then(e => {\n  console.log(e[0].children[0].children[0])\n})\n```\n\n```text\nValidationError {\n  target: AuthParam { id: 1, type: 4, value: 'password' },\n  value: 4,\n  property: 'type',\n  children: [],\n  constraints: { isString: 'type must be a string' } }\n```\n\n```text\nconst param2: AuthParam = {\n  id: 1,\n  type: 4,\n  value: 'password'\n} as any\n```\n\n```text\nAuthParam\n```\n\n```text\n@Type\n```\n\n```text\nclass-transformer\n```\n\n```text\nexport class AuthParam {\n    @IsNumber()\n    id: number;\n  \n    @IsString()\n    type: string;\n  \n    @IsString()\n    value: string;\n  }\n```\n\n```text\n@ValidatorConstraint()\nexport class IsAuthArray implements ValidatorConstraintInterface {\n    public async validate(authData: AuthParam[], args: ValidationArguments) {\n        return Array.isArray(authData) && authData.reduce((a, b) => a && (typeof b.id === \"number\") && typeof b.type === \"string\" && typeof b.field === \"string\", true);\n    }\n}\n\nexport class SignInModel {\n    @IsNotEmpty()\n    @IsArray()\n    @ArrayMinSize(2)\n    @ArrayMaxSize(2)\n    @Validate(IsAuthArray, {\n        message: \"Enter valid value .\",\n    })\n    authParameters: AuthParam[];\n  }\n```\n\n```text\nimport { IsArray, ValidateNested} from 'class-validator';\n\nimport { Type } from 'class-transformer';\n\n\n\n\n  @IsArray()\n  @ValidateNested({ each: true })\n  @Type(() => TypeOfEachObject)\n  nameOfArray: TypeOfEachObject[];\n```\n\n```text\nimport { IsString, IsNumber } from 'class-validator';\n\nexport class AuthParam {\n  @IsNumber()\n  id: number;\n\n  @IsString()\n  type: string;\n\n  @IsString()\n  value: string;\n\nconstructor(payload: AuthParam) {\n    this.id = payload.id;\n    this.type = payload.type;\n    this.value = payload.value;\n  }\n}\n```\n\n```text\nimport { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';\nimport { AuthParam } from './authParam.model';\n\nexport class SignInModel {\n  @IsArray()\n  @ValidateNested({ each: true })\n  @ArrayMinSize(2)\n  @ArrayMaxSize(2)\n  authParameters: AuthParam[];\n  constructor(payload: SignInModel) {\n      if (isArray(payload.authParameters)) {\n         const authParameters = payload.authParameters.map(ap => new AuthParam(ap));\n         this.authParameters = authParameters;\n      } else {\n         this.authParameters = payload.authParameters;\n      }\n   }\n}\n```\n\n```text\n@Type\n```\n\n========================================\n\nComments:\n- github.com/typestack/class-validator/pull/295 Was just published in `v0.10.2`, so it should help, hopefully!\n- This is nicely resolve number of elements question - thank you. Validation of objects inside array still valid\n- Hi, any idea on how to achieve this for an array of numbers in a query param? imagine im trying to validate [www.url.com/path?ids=1,2,3] , where [ids] should be an array of numbers, and nothing else. tried converting your answer, but with no success so far.\n- Hi, I tried something similar and is working as expected. But I noticed that when the array contains an empty array (as opposed to say the AuthParam obj) it does not throw an error. How can I ensure that the array only contains objects and not arrays?\n- Trying something similar but it doesn't seem to be working: stackoverflow.com/questions/73654324/&hellip;\n- To answer @Zephyr question, use `@IsObject({ each: true })`. There is a short example here with the different errors you can get.\n- In case someone runs into the same issue I had, if you're writing unit tests, you might need to `import \"reflect-metadata\"` as the first line of your test, otherwise the `@Type` decorator is going to cause a `Reflect.getMetadata() is not a function` error\n- I worked ... but How on earth did I needed to use `class-transformer` to perform a nested validation with `class-validator`? ๐Ÿ˜ฎ","metadata":{"transformedAt":"2026-08-18T18:33:02.394Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":327,"estimatedTokens":1888}}3{"id":"stack-59435293","source":"stackoverflow","questionId":59435293,"title":"TypeORM Entity in NESTJS - Cannot use import statement outside a module","tags":["nestjs","typeorm"],"text":"Title: TypeORM Entity in NESTJS - Cannot use import statement outside a module\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nStarted new project with 'nest new' command. Works fine until I add entity file to it.\n\nGot following error:\n\n import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n \n ^^^^^^\n\n \n SyntaxError: Cannot use import statement outside a module\n\nWhat do I miss?\n\nAdding Entity to Module:\n\n```\nimport { Module } from '@nestjs/common';\nimport { BooksController } from './books.controller';\nimport { BooksService } from './books.service';\nimport { BookEntity } from './book.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forFeature([BookEntity])],\n controllers: [BooksController],\n providers: [BooksService],\n})\nexport class BooksModule {}\n```\n\napp.module.ts:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { BooksModule } from './books/books.module';\n\n@Module({\n imports: [TypeOrmModule.forRoot()],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n========================================\n\nTop Answer:\nIn the TypeORM documentation, i found a specific section for Typescript.\n\nThis section says:\n\n Install ts-node globally:\n\n```\nnpm install -g ts-node\n```\n\n \n Add typeorm command under scripts section in package.json\n\n```\n\"scripts\" {\n ...\n \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js\" \n}\n```\n\n \n Then you may run the command like this:\n\n```\nnpm run typeorm migration:run\n```\n\n \n If you need to pass parameter with dash to npm script, you will need\n to add them after --. For example, if you need to generate, the\n command is like this:\n\n```\nnpm run typeorm migration:generate -- -n migrationNameHere\n```\n\nThis works with my file config:\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"yourhost\",\n \"port\": 5423,\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"your_db\",\n \"synchronize\": true,\n \"entities\": [\n \"src/modules/**/*.entity.{ts,js}\"\n ],\n \"migrations\": [\n \"src/migrations/**/*.{ts,js}\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/modules\",\n \"migrationsDir\": \"src/migrations\"\n }\n}\n```\n\nThen you can run the generate command.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { BooksController } from './books.controller';\nimport { BooksService } from './books.service';\nimport { BookEntity } from './book.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([BookEntity])],\n  controllers: [BooksController],\n  providers: [BooksService],\n})\nexport class BooksModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { BooksModule } from './books/books.module';\n\n@Module({\n  imports: [TypeOrmModule.forRoot()],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nentities: ['src/**/*.entity.{ts,js}']\n```\n\n```text\nentities: ['../**/*.entity.{ts,js}']\n```\n\n```text\nentities: [join(__dirname, '**', '*.entity.{ts,js}')]\n```\n\n```json\nentities: [\"dist/**/*.entity.js\"]\n```\n\n```json\nautoLoadEntities: true,\n```\n\n```text\nTypeormModule\n```\n\n```text\nentities\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\njoin\n```\n\n```text\npath\n```\n\n```text\n__dirname\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\n.js\n```\n\n```text\nTypeormModule.forRoot()\n```\n\n```text\normconfig.json\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ProjectsService } from './projects.service';\nimport { Projects } from './projects.entity';\n\nimport { ProjectsResolvers } from './projects.resolvers';\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([Projects])],\n  providers: [\n    ProjectsService,\n    ProjectsResolvers\n  ],\n\n})\n\nexport class ProjectsModule {}\n```\n\n```text\n\"entities\"   : [\n      \"dist/entity/**/*.js\"\n   ],\n   \"migrations\" : [\n      \"dist/migration/**/*.js\"\n   ],\n   \"subscribers\": [\n      \"dist/subscriber/**/*.js\"\n   ],\n```\n\n```text\normconfig.json\n```\n\n```text\nts\n```\n\n```text\normconfig.json\n```\n\n```text\nnpm install -g ts-node\n```\n\n```text\n\"scripts\" {\n    ...\n    \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js\"    \n}\n```\n\n```text\nnpm run typeorm migration:run\n```\n\n```text\nnpm run typeorm migration:generate -- -n migrationNameHere\n```\n\n```text\n{\n    \"type\": \"postgres\",\n    \"host\": \"yourhost\",\n    \"port\": 5423,\n    \"username\": \"username\",\n    \"password\": \"password\",\n    \"database\": \"your_db\",\n    \"synchronize\": true,\n    \"entities\": [\n        \"src/modules/**/*.entity.{ts,js}\"\n    ],\n    \"migrations\": [\n        \"src/migrations/**/*.{ts,js}\"\n    ],\n    \"cli\": {\n        \"entitiesDir\": \"src/modules\",\n        \"migrationsDir\": \"src/migrations\"\n    }\n}\n```\n\n```text\n\"module\": \"es6\"\n```\n\n```text\n\"module\": \"commonjs\",\n```\n\n```text\nentities: ['dist/**/*.entity.js']\n```\n\n```text\n{\n  \"type\": \"mysql\",\n  \"host\": \"localhost\",\n  \"port\": 3306,\n  \"username\": \"xxxxxxxx\",\n  \"password\": \"xxxxxxxx\",\n  \"database\": \"typescript_orm\",\n  \"synchronize\": true,\n  \"logging\": false,\n  \"migrationTableName\": \"migrations\",\n  \"entities\": [\n    \"dist/**/*.entity.js\"\n  ],\n  \"migrations\": [\n    \"src/migration/**/*.{ts, js}\"\n  ],\n  \"suscribers\": [\n    \"src/suscriber/**/*.{ts, js}\"\n  ],\n  \"cli\": {\n    \"entitiesDir\": \"src/model\",\n    \"migrationDir\": \"src/migration\",\n    \"suscribersDir\": \"src/suscriber\"\n  }\n}\n```\n\n```text\n// This is your ormconfig.json file\n\n...\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"]\n...\n```\n\n```text\normconfig.json\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js  migration:generate -n <MirgrationName> -c <ConnectionType>\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js  migration:create -n AuthorHasMultipleBooks -c development\n```\n\n```text\normconfig.js\n```\n\n```text\nnode_modules\n```\n\n```js\n// FILE: src/config/ormconfig.ts\n\nconst connectionOptions: ConnectionOptions = {\n  \n  // Other configs here\n\n  // My ormconfig isn't in root folder\n  entities: [`${__dirname}/../**/*.entity.{ts,js}`],\n  synchronize: false,\n  dropSchema: false,\n  migrationsRun: false,\n  migrations: [getMigrationDirectory()],\n  cli: {\n    migrationsDir: 'src/migrations',\n  }\n}\n\nfunction getMigrationDirectory() {\n    const directory = process.env.NODE_ENV === 'migration' ? 'src' : `${__dirname}`;\n    return `${directory}/migrations/**/*{.ts,.js}`;\n}\n\nexport = connectionOptions;\n```\n\n```json\n// FILE package.json\n\n{\n  // Other configs here\n\n  \"scripts\": {\n    \"typeorm\": \"NODE_ENV=migration ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/database.ts\",\n    \"typeorm:migrate\": \"npm run typeorm migration:generate -- -n\",\n    \"typeorm:run\": \"npm run typeorm migration:run\",\n    \"typeorm:revert\": \"npm run typeorm migration:revert\"\n  }\n}\n```\n\n```text\n\"typeorm\": \"ts-node-dev ./node_modules/typeorm/cli.js\"\n```\n\n```text\nyarn typeorm migration:run\n```\n\n```text\ntsc\n```\n\n```text\nnodemon server.js\n```\n\n```text\nts-node server.ts\n```\n\n```text\nnode server.js\n```\n\n```text\ntsc\n```\n\n```sh\nnano ~/.zshrc\n```\n\n```sh\nalias typeorm=\"ts-node ./node_modules/typeorm/cli.js\"\n```\n\n```sh\n. ~/.zshrc\n```\n\n```text\nts-node\n```\n\n```text\nnode_modules\n```\n\n```text\nTYPEORM_ENTITIES=\"entities/*.ts\"\nTYPEORM_MIGRATIONS=\"migrations/*.ts\"\nTYPEORM_ENTITIES_DIR=\"entities\"\nTYPEORM_MIGRATIONS_DIR=\"migrations\"\n```\n\n```text\n{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"module\": \"commonjs\"\n  }\n}\n```\n\n```text\n\"local\": \"DOTENV_CONFIG_PATH=./.env ts-node -P ./tsconfig.yarn.json -r dotenv/config\"\n```\n\n```text\n\"typeorm:local\": \"yarn local ./node_modules/typeorm/cli.js\"\n```\n\n```text\n\"g:migration\": \"yarn typeorm:local migration:generate -n\"\n```\n\n```text\nnpm run g:migration -- User\n```\n\n```text\n.env\n```\n\n```text\normconfig.json\n```\n\n```text\n.js\n```\n\n```text\n*.ts\n```\n\n```text\nts-node\n```\n\n```text\normconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```js\nimport parseBoolean from '@eturino/ts-parse-boolean';\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport * as dotenv from 'dotenv';\nimport { join } from 'path';\n\ndotenv.config();\n\nexport = [\n  {\n    //name: 'default',\n    type: 'mssql',\n    host: process.env.DEFAULT_DB_HOST,\n    username: process.env.DEFAULT_DB_USERNAME,\n    password: process.env.DEFAULT_DB_PASSWORD,\n    database: process.env.DEFAULT_DB_NAME,\n    options: {\n      instanceName: process.env.DEFAULT_DB_INSTANCE,\n      enableArithAbort: false,\n    },\n    logging: parseBoolean(process.env.DEFAULT_DB_LOGGING),\n    dropSchema: false,\n    synchronize: false,\n    migrationsRun: parseBoolean(process.env.DEFAULT_DB_RUN_MIGRATIONS),\n    migrations: [join(__dirname, '..', 'model/migration/*.{ts,js}')],\n    cli: {\n      migrationsDir: 'src/model/migration',\n    },\n    entities: [\n      join(__dirname, '..', 'model/entity/default/**/*.entity.{ts,js}'),\n    ],\n  } as TypeOrmModuleOptions,\n  {\n    name: 'other',\n    type: 'mssql',\n    host: process.env.OTHER_DB_HOST,\n    username: process.env.OTHER_DB_USERNAME,\n    password: process.env.OTHER_DB_PASSWORD,\n    database: process.env.OTHER_DB_NAME,\n    options: {\n      instanceName: process.env.OTHER_DB_INSTANCE,\n      enableArithAbort: false,\n    },\n    logging: parseBoolean(process.env.OTHER_DB_LOGGING),\n    dropSchema: false,\n    synchronize: false,\n    migrationsRun: false,\n    entities: [],\n  } as TypeOrmModuleOptions,\n];\n```\n\n```js\nimport configuration from '@config/configuration';\nimport validationSchema from '@config/validation';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { LoggerService } from '@shared/logger/logger.service';\nimport { UsersModule } from '@user/user.module';\nimport { AppController } from './app.controller';\nimport ormconfig = require('./config/ormconfig'); //path mapping doesn't work here\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      cache: true,\n      isGlobal: true,\n      validationSchema: validationSchema,\n      load: [configuration],\n    }),\n    TypeOrmModule.forRoot(ormconfig[0]), //default\n    TypeOrmModule.forRoot(ormconfig[1]), //other db\n    LoggerService,\n    UsersModule,\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```json\n\"scripts\": {\n    ...\n    \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./src/config/ormconfig.ts\",\n    \"typeorm:migration:generate\": \"npm run typeorm -- migration:generate -n\",\n    \"typeorm:migration:run\": \"npm run typeorm -- migration:run\"\n  },\n```\n\n```text\nsrc/\nโ”œโ”€โ”€ app.controller.ts\nโ”œโ”€โ”€ app.module.ts\nโ”œโ”€โ”€ config\nโ”‚   โ”œโ”€โ”€ configuration.ts\nโ”‚   โ”œโ”€โ”€ ormconfig.ts\nโ”‚   โ””โ”€โ”€ validation.ts\nโ”œโ”€โ”€ main.ts\nโ”œโ”€โ”€ model\nโ”‚   โ”œโ”€โ”€ entity\nโ”‚   โ”œโ”€โ”€ migration\nโ”‚   โ””โ”€โ”€ repository\nโ”œโ”€โ”€ route\nโ”‚   โ””โ”€โ”€ user\nโ””โ”€โ”€ shared\n    โ””โ”€โ”€ logger\n```\n\n```text\nTYPEORM_ENTITIES = src/modules/*.entity.ts\nTYPEORM_MIGRATIONS = src/migrations/*.entity.ts\nTYPEORM_MIGRATIONS_RUN = src/migrations\nTYPEORM_ENTITIES_DIR = src/modules\nTYPEORM_MIGRATIONS_DIR = src/migrations\n```\n\n```text\nnest start\n```\n\n```text\nTYPEORM_ENTITIES = dist/modules/*.entity.js\n TYPEORM_MIGRATIONS = dist/migrations/*.entity.js\n TYPEORM_MIGRATIONS_RUN = dist/migrations\n TYPEORM_ENTITIES_DIR = dist/modules\n TYPEORM_MIGRATIONS_DIR = dist/migrations\n```\n\n```text\nnode-ts\n```\n\n```text\nnest start\n```\n\n```text\nnest start\n```\n\n```text\nmodule.exports = {\n   apps: [\n     {\n       name: \"app\",\n       script: \"./build/index.js\",\n     },\n   ],\n };\n```\n\n```text\n{\n   \"type\": \"postgres\",\n   \"host\": \"localhost\",\n   \"port\": 5432,\n   \"username\": \"postgres\",\n   \"password\": \"password\",\n   \"database\": \"db_name\",\n   \"synchronize\": false,\n   \"logging\": true,\n   \"entities\": [\n      \"../src/entity/**/*.ts\",  ===>>> this line is important\n      \"./build/entity/**/*.js\"\n   ],\n   \"migrations\": [\n      \"../src/migration/**/*.ts\",===>>> this line is important\n      \"./build/migration/**/*.js\"\n   ],\n   \"subscribers\": [\n      \"../src/subscriber/**/*.ts\",===>>> this line is important\n      \"./build/subscriber/**/*.js\"\n   ],\n   \"cli\": {\n      \"entitiesDir\": \"src/entity\",\n      \"migrationsDir\": \"src/migration\",\n      \"subscribersDir\": \"src/subscriber\"\n   }\n}\n```\n\n```text\n{\n   \"compilerOptions\": {\n      \"lib\": [\n         \"es5\",\n         \"es6\"\n      ],\n      \"target\": \"es5\",\n      \"module\": \"commonjs\",\n      \"moduleResolution\": \"node\",\n      \"outDir\": \"./build\",\n      \"emitDecoratorMetadata\": true,\n      \"experimentalDecorators\": true,\n      \"sourceMap\": true,\n      \"esModuleInterop\": true\n   }\n}\n```\n\n```text\ntsc  =>> This command generate \"build\" folder\n```\n\n```text\ntsc && pm2 start pm2.config.js\n```\n\n```text\npm2.config.js\n```\n\n```text\normconfig.js\n```\n\n```text\ntsconfig.json\n```\n\n```text\npm2\n```\n\n```text\n\"../src/entity/**/*.ts\"\n```\n\n```text\n\"src/entity/**/*.ts\"\n```\n\n```text\n\"nodemon --exec ts-node ./src/index.ts\"\n```\n\n```text\nimport { SomeClassFromTypeorm } from 'typeorm/browser';\n```\n\n```text\n'/browser'\n```\n\n```text\n{ \n  \"type\": \"cockroachdb\",\n  \"host\": \"localhost\",\n  \"port\": 26257,\n  \"username\": \"root\",\n  \"password\": \"\",\n  \"database\": \"test\",\n  \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n  \"migrations\": [\"migration/*.js\"],\n  \"synchronize\": false,\n  \"cli\": {\n    \"migrationsDir\": \"migration\"\n  }\n}\n```\n\n```text\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\"\n```\n\n```text\nnpm run typeorm migration:generate -- -o -n init\n```\n\n```text\nnpm run start:dev\n```\n\n```text\normconfig,json\n```\n\n```text\npackage.json\n```\n\n```text\n-o\n```\n\n```json\n\"scripts\": {\n      \"typeorm\": \"typeorm-ts-node-commonjs\"\n   }\n```\n\n```json\n\"scripts\": {\n      \"typeorm\": \"typeorm-ts-node-esm\"\n   }\n```\n\n```text\nnpm run -- typeorm migration:generate --dataSource path/to/data-source.ts NameOfMigration\n```\n\n```text\ntypeorm migration:generate\n```\n\n```text\nnpx typeorm init\n```\n\n```text\npackage.json\n```\n\n```text\nentities: ['src/**/*.entity.{ts,js}']\n```\n\n```text\nimport { Answer } from './entities/answer/answer.entity';\n\nentities: [Answer]\n```\n\n```text\nTypeOrmModule.forRoot({\n  type: 'postgres',\n  host: 'localhost',\n  port: 5432,\n  username: 'postgres',\n  password: '#GoHomeGota',\n  database: 'quiz',\n  **entities: [\"dist/**/*.entity{.ts,.js}\"],**\n  synchronize: true,\n}),\n```\n\n```text\n//content of cli-orm-config.ts\n\nimport { DataSource, DataSourceOptions } from \"typeorm\"\nimport 'dotenv/config'\n\nexport const cliOrmConfig: DataSourceOptions = {\n    type: 'postgres',\n    host: process.env.DATABASE_HOST,\n    port: (process.env.PG_DATABASE_PORT as any) as number,\n    username: process.env.PG_DATABASE_USER,\n    password: process.env.PG_DATABASE_PASSWORD,\n    database: process.env.DATABASE_NAME,\n    entities: [\"src/**/*/*.entity{.ts,.js}\"],\n    migrations: [\"src/**/*/*-Migration{.ts,.js}\"]\n}\n\nconst datasource = new DataSource(cliOrmConfig)\n\nexport default  datasource\n```\n\n```text\n//content of orm-config.ts, this is the one I use in nest TypeOrmModule.forRoot(ormConfig)\n\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport 'dotenv/config'\n\n\nexport const ormConfig: DataSourceOptions = {\n    type: 'postgres',\n    host: process.env.DATABASE_HOST,\n    port: (process.env.PG_DATABASE_PORT as any) as number,\n    username: process.env.PG_DATABASE_USER,\n    password: process.env.PG_DATABASE_PASSWORD,\n    database: process.env.DATABASE_NAME,\n    entities: [\"dist/src/**/*/*.entity{.ts,.js}\"]\n}\n\nconst datasource = new DataSource(ormConfig)\n\nexport default  datasource\n```\n\n```text\n// My package.json relevant scripts section\n\n\"typeorm\": \"ts-node ./node_modules/typeorm/cli -d ./src/db/cli-orm-config.ts\",\n\"nest:migration:generate\": \"npm run typeorm migration:generate ./src/db/migrations/Migration\",\n\"nest:migration:run\": \"npm run typeorm migration:run\"\n```\n\n```text\n\"module\": \"esnext\"\n```\n\n```text\n\"module\": \"commonjs\",\n```\n\n```text\ntsconfig.ts\n```\n\n```text\nnpx ts-node ./node_modules/.bin/typeorm migration:generate -n MigrationName -d src/migrations\n```\n\n```text\nnpx ts-node ./node_modules/.bin/typeorm migration:generate src/migration/MigrationName -d ormconfig.js\n```\n\n```js\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { ConfigService } from '@nestjs/config';\nimport { config } from 'dotenv';\nimport * as path from 'path';\nimport { User } from '../users/users.entity';\nimport { FileStorage } from '../storage/storage.entity';\n\n// Load environment variables\nconfig({ path: `.env.${process.env.ENV}` });\n\nconst configService = new ConfigService();\n\n// Minimal data source options\nexport const dataSourceOptionsMinimal = {\n  type: 'postgres',\n  host: configService.getOrThrow('DB_HOST'),\n  port: parseInt(configService.getOrThrow('DB_PORT'), 10),\n  username: configService.getOrThrow('DB_USERNAME'),\n  password: configService.getOrThrow('DB_PASSWORD'),\n  database: configService.getOrThrow('DB_DATABASE'),\n};\n\n// Full data source options\nexport const dataSourceOptions: DataSourceOptions = {\n  ...dataSourceOptionsMinimal,\n  type: 'postgres',\n  entities: [User, FileStorage],\n  migrations: [path.join(__dirname, 'migrations/**/*.{ts,js}')],\n  migrationsTableName: 'migrations',\n};\n\nexport default new DataSource(dataSourceOptions);\n```\n\n```text\nThis could happen if your project is set up in such a way that the working directory is not the root of your project but some other directory. Using /src ensures that the path is correctly resolved regardless of where the command is run.\n```\n\n```text\n\"dev\": \"nest start --watch\",\n```\n\n```text\n\"dev\": \"NODE_ENV=test 'ts-node' src/main.ts\",\n```\n\n```text\n.ts\n```\n\n```text\nts-node\n```\n\n```text\nnest start\n```\n\n```text\npackage.json\n```\n\n```text\nts-node\n```\n\n========================================\n\nComments:\n- import { Module } from '@nestjs/common';\n- @Preston care to elaborate on what you mean? Do you have to create a module for commonly shared files?\n- Are you getting the error from your linter or from a compilation? Where do you have this new file? Is it in your `src` directory? If you're using TypeORM, can you show your `TypeOrmModule` import in the `AppModule`'s `imports` array? There may be something wrong with the configuration we can't see\n- updated post with entity import info\n- Excellent. So does that mean you can ever have a base entity shared across multiple modules or would that base entity have to be part of a commons module of sorts?\n- I think i've already imported entity to module. Please take a look at updated post\n- Sorry Anton, I'm traveling on vacation now and can't help you until January. I would have to look at my old REST modules and I don't have them with me.\n- Anton, if you have already solved this then please post your solution to SO.\n- But this is a total mess. A typescript ORM that does not accept typescript for the migrations...\n- `deno` is the only native typescript code runner. `TypeORM`, while it uses Typescript, still works with `Node` and the JavaScript runtime. Maybe improvements can be made to accept `ts` files and compile them into JavaScript under the hood, then delete them so the end user doesn't see them, but that would need to be brought up as an issue on the TypeORM git repository\n- actually full line must be \"entities\": [\"dist/**/*.entity.js\"], because of json syntax.\n- I absolutely agree that having to reach into the transpiled JS for all this mess to work is a joke.\n- The Issue #4283 on Github explains in details why JavaScript should be used to read entities from Dist folder. This is the magic line I changed in `ormconfig.js` in the root folder, you too can try and see. `entities: ['dist&#47;**&#47;*.entity.js']` is the solution.\n- This is insane. Aren't we doing Typescript not to have to deal with this garbage?\n- The complaints in this thread is hilarious. How do you guys think Typescript works ๐Ÿคฃ? You can still write the migrations in typescript, you just have to point the configuration to the transpiled JS from the TS you wrote. You are still using Typescript for development, but the library uses the transpiled JS. If you are mad about why a library uses transpiled JS, consider evaluating why such an implementation detail even matters to you at all. You're literally not interacting with the JS directly, you are still coding in TS.\n- it actually accepts the .ts migration file, please check the \"Running the migrations\" topic at https://wanago.io/2022/07/25/api-nestjs-database-migrations-&zwnj;&#8203;typeorm/. Basically as for 2024 you have to manually add the migration file via import syntax to the migrations array since string paths will be deprecated. Hope it helps\n- The `src` should probably be changed to `dist` as that's where the runnable code is after being transpiled to javascript.\n- It took me a while: During runtime, code will be run off the 'dist' (Distribution) folder. And the *.entity.ts file containing the database model, will be translated to .js file by TypeOrm. Hence - entities entry should point to *.entity.js under the 'dist' folder. Thank you all. Save my day.\n- 22.04.23 I had to run this: `npm run typeorm migration:generate -- migrationNameHere -d .&#47;src&#47;data-source.ts`\n- not working \"Not enough non-option arguments: got 0, need at least 1\"\n- doesnt work. \"Missing required argument: dataSource\"\n- I had to update `migrations` to match your syntax\n- I used this solution only for production. for development I change \"../src/entity/**/*.ts\" to \"src/entity/**/*.ts\" and then run \"nodemon --exec ts-node ./src/index.ts\" and it works\n- It it helps anyone else, this exact same thing happened to me, on a nestjs & typeorm project. `import { Unique } from 'typeorm&#47;browser';` just needed to be changed to `import { Unique } from 'typeorm';`\n- That is not a solution. You just created a workaround and pretend that the problem is fixed.\n- I don't pretend that the problem is fixed, I just wanted to help and add the workaround that worked for me. Maybe it'll shad more light on the issue and help someone figure out a solution.\n- this idea sort of fixed for me...","metadata":{"transformedAt":"2026-08-18T18:33:02.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":125,"totalLines":1038,"estimatedTokens":5564}}4{"id":"stack-51448376","source":"stackoverflow","questionId":51448376,"title":"What's the difference between tsc (TypeScript compiler) and ts-node?","tags":["node.js","typescript","tsc","nestjs","ts-node"],"text":"Title: What's the difference between tsc (TypeScript compiler) and ts-node?\nTags: node.js, typescript, tsc, nestjs, ts-node\nSource: Stack Overflow\n\nQuestion:\nI'm very confused about the difference between `tsc` and `ts-node`. I'm learning TypeScript and I usually transpile server `.ts` files with `tsc` command.\n\nNow, I'm approaching nestjs framework, and I see that it uses `ts-node`.\n\nSo what's the difference between the two? Which one should I use?\n\n========================================\n\nTop Answer:\nMost common practice is that `tsc` is used for production build and `ts-node` for development purposes running in `--watch` mode along with `nodemon`. This is a command i often use for development mode for my node/typescript projects:\n\n```\n\"dev\": \"nodemon -w *.ts -e ts -x ts-node --files -H -T ./src/index.ts\"\n```\n\n========================================\n\nCode:\n```text\ntsc\n```\n\n```text\nts-node\n```\n\n```text\n.ts\n```\n\n```text\ntsc\n```\n\n```text\nts-node\n```\n\n```text\ntsc\n```\n\n```text\nts-node\n```\n\n```text\n\"dev\": \"nodemon -w *.ts -e ts -x ts-node --files -H -T ./src/index.ts\"\n```\n\n```text\ntsc\n```\n\n```text\nts-node\n```\n\n```text\n--watch\n```\n\n```text\nnodemon\n```\n\n========================================\n\nComments:\n- @jfriend00 can you elaborate your answer? AFAIK tsc will change `import` to the commonjs `require()`, which in turn will load the JavaScript source file (assuming in node_modules).\n- Read the first paragraph here: npmjs.com/package/ts-node\n- Some discussion at reddit.com/r/typescript/comments/8vkvzy/&hellip;\n- So which one to use and when?\n- Its a better practice to use tsc to build your project and then run it with node in production, its also faster\n- Sometimes you only need to compile one entrypoint and it's imports - `ts-node` is perfect for that and has no downsides.\n- i think that there is a ts-node-dev package which speeds build times up if performance is an issue\n- `tsc --watch` could've also been used which uses incremental builds and is faster than `nodemon`..\n- I'm wondering which builder should I use to build react applications nowadays\n- Quick update on this, ts-node CAN be used in production: stackoverflow.com/questions/60581617/&hellip; and there's a faster way than using nodemon: npmjs.com/package/ts-node-dev\n- `Quick update on this, ts-node CAN be used in production` Yeah no one said it can't, it's just the most common practice.\n- thank you for a working sample script in package json\n- what is the role of nodemon, if ts-node also have the --watch?","metadata":{"transformedAt":"2026-08-18T18:33:02.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":87,"estimatedTokens":627}}5{"id":"stack-47733390","source":"stackoverflow","questionId":47733390,"title":"nestjs vs plain express performance","tags":["nestjs"],"text":"Title: nestjs vs plain express performance\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI've just tested performance on a simple nest's controller, that returns text on a get request (no database).\nAnd the same simple GET controller (middleware) with express.\n\nI used WRK tool to test performance.\n\nAnd as a result plain express is 2 x times faster than nestjs.\nWhy is so much overhead created by nestjs?\n\n========================================\n\nCode:\n```text\nReq/sec  Trans/sec\nNest-Express    15370   3.17MB  \nNest-Fastify    30001   4.38MB  \nExpress         17208   3.53MB  \nFastify         33578   4.87MB\n```\n\n```text\napp.get('/', (req, res, next) => res.status(200).send('Hello world'));\n```\n\n```text\nRunning 10s test @ http://localhost:3000\n1024 connections\n\nStat         Avg    Stdev   Max\nLatency (ms) 225.67 109.97  762\nReq/Sec      4560   1034.78 5335\nBytes/Sec    990 kB 226 kB  1.18 MB\n\n46k requests in 10s, 9.8 MB read\n```\n\n```text\nRunning 10s test @ http://localhost:3000\n1024 connections\n\nStat         Avg    Stdev   Max\nLatency (ms) 297.79 55.5    593\nReq/Sec      3433.2 367.84  3649\nBytes/Sec    740 kB 81.9 kB 819 kB\n\n34k requests in 10s, 7.41 MB read\n```\n\n```text\nFastifyAdapter\n```\n\n```text\nv5.0.0\n```\n\n```text\nasync\n```\n\n```text\nbody-parser\n```\n\n```text\njson\n```\n\n```text\nurlencoded\n```\n\n```text\nsend()\n```\n\n```text\njson()\n```\n\n```text\nif\n```\n\n```text\nHello world\n```\n\n```text\nautocannon\n```\n\n```text\nautocannon -c 1024 -t30 http://localhost:3000\n```\n\n========================================\n\nComments:\n- Could you provide details of the tests performed? This is interesting to me\n- Just two simple Hello World string render with nestjs controller and plain express `wrk -t12 -c1024 --timeout 30s http:&#47;&#47;localhost:3000`\n- @Shadowfax which environment have you tested?\n- @Cozzbie unless you use the Fastify adapter, as stated above. Then Nest is faster than Express.\n- hi @Kamil, so this answer is from year 2018, and based on nest 4.5. Now we are in end of 2019 with nest 6.9.0, and at the same time we are having growing community which is eager to use nestjs, it would be very helpful if you guys keep updating this answer on frequently basis. At least once in 3 month??\n- @Kedar9444 I don't doubt Kamil would love to see this updated regularly but as you must realize he is just one man. The purpose of the community is to fill in the voids. So, if you are interested in the benchmark and would like to showcase your work, contributions you are eagerly encuraged to do so.\n- Do you have benchmark updates this year ?\n- Also in 2021 is native Fastify app faster than Nest.js on Fastify. In our company we testet Nest.js with our API vs. native Fastify version of the same API. The native version is 42% faster. In my experience, the difference in real applications is even greater. But that also has to do with the fact that we can optimize the application structure better than with Nest.js. the possibilities are simply better without a given cluttered framework.\n- How come that these numbers are fluctuating so much? See here for example: github.com/nestjs/nest/pull/7717/checks?check_run_id=3205746&zwnj;&#8203;219\n- Could you update your answer with 2021? I'm thinking of adopting Nestjs, but still not sure due to all these changing numbers. I would have chosen nest-fastify, but the docs say that I should use express instead since fastify does not support graphql playground, and using a non-stable release is out of the question.\n- I just just did test a simple query that returns a string with graphql and prisma in two scenarios: 1) default nestjs config 2) fastify and apollo server fastify. First scenario 13k req/10sec, Second scenario 40k/10s. So fastify is 3 times faster in my case. But having to use \"apollo-server-fastify\": \"^3.0.0-alpha.3\" means I will not be able to benefit of this performance gain\n- Just tested - fastify 3.26.0 vs. nest(fastify) 8.2.5 performance ... gist.github.com/ladisalves/f9b60d8b16f44c512ddd4070ef35026a results: fastify 64k requests, nestjs (fastify) 43k\n- Is nest.js still a viable api solution or have others come forward too? I'm curious how the performance is, and if anything has come along that others are now using, that is more performant?\n- So Nest is slower than Express","metadata":{"transformedAt":"2026-08-18T18:33:02.395Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":117,"estimatedTokens":1067}}6{"id":"stack-63285055","source":"stackoverflow","questionId":63285055,"title":"NestJS - How to use .env variables in main app module file for database connection","tags":["javascript","node.js","environment-variables","nestjs","dotenv"],"text":"Title: NestJS - How to use .env variables in main app module file for database connection\nTags: javascript, node.js, environment-variables, nestjs, dotenv\nSource: Stack Overflow\n\nQuestion:\nI am working on my first NestJS application, which was working fine with hardcoded database connecting string in `app.module.ts`.\n\nBut then as per our requirements, I had to pick the database config values from environment files. For that, I followed the configuration documentation on the nestjs documentation website - https://docs.nestjs.com/techniques/configuration\n\nBut the issue is that I need to use the .env variables inside the same file for database connection, which is failing.\n\nHere is my original code that was working fine:\n\n```\n@Module({\n imports: [\n MongooseModule.forRoot(`mongodb+srv://myusername:mypassword@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),\n ProductModule,\n CategoryModule,\n ],\n controllers: [\n AppController,\n HealthCheckController,\n ],\n providers: [AppService, CustomLogger],\n})\n```\n\nNow, I wanted to pick those DB values from .env files which are like `local.env`, `dev.env` etc. depending on the environment. Now, my this code is not working:\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }),\n MongooseModule.forRoot(`mongodb+srv://${ConfigModule.get('DB_USER')}:${ConfigModule.get('DB_PASS')}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),\n ProductModule,\n CategoryModule,\n ],\n controllers: [\n AppController,\n HealthCheckController,\n ],\n providers: [AppService, CustomLogger],\n})\n```\n\n========================================\n\nTop Answer:\nFrom Nestjs docs here - https://docs.nestjs.com/techniques/configuration\n\nThese steps worked for me with MySQL and TypeORM.\n\nInstall Nestjs config module - `npm i --save @nestjs/config`. It relies on dotenv\n\nCreate a `.env` file in your root folder and add your key/value pairs e.g. `DATABASE_USER=myusername`\n\nOpen app.module.ts and import the config module\n\n```\nimport { ConfigModule } from '@nestjs/config';\n```\n\n- Add below line to the imports section of `app.module.ts`. I added it a the first import. It will load the contents of the .env file automatically.\n\n```\nConfigModule.forRoot(),\n```\n\n- Then you can begin to use the env variables as per the usual process.env. in the database config section e.g.\n\n```\nprocess.env.DATABASE_USER\n```\n\nFor more configuration of the ConfigModule, see the link above. You can use a custom file/path and set the module visible globally.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    MongooseModule.forRoot(`mongodb+srv://myusername:mypassword@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),\n    ProductModule,\n    CategoryModule,\n  ],\n  controllers: [\n    AppController,\n    HealthCheckController,\n  ],\n  providers: [AppService, CustomLogger],\n})\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }),\n    MongooseModule.forRoot(`mongodb+srv://${ConfigModule.get('DB_USER')}:${ConfigModule.get('DB_PASS')}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }),\n    ProductModule,\n    CategoryModule,\n  ],\n  controllers: [\n    AppController,\n    HealthCheckController,\n  ],\n  providers: [AppService, CustomLogger],\n})\n```\n\n```text\napp.module.ts\n```\n\n```text\nlocal.env\n```\n\n```text\ndev.env\n```\n\n```json\n\"scripts\": {\n  \"start:local\": \"NODE_ENV=local npm run start\"\n  \"start:dev\": \"NODE_ENV=dev npm run start\"\n}\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }), \nMongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })\n    ...\n})\n```\n\n```bash\nnpm install dotenv\n```\n\n```json\n\"scripts\": {\n  ...\n  \"start:local\": \"NODE_ENV=local npm run start\"\n  \"start:dev\": \"NODE_ENV=dev npm run start\"\n}\n```\n\n```js\nrequire('dotenv').config({ path: `../${process.env.NODE_ENV}.env` });\n```\n\n```bash\nnpm install env-cmd\n```\n\n```json\n\"scripts\": {\n  ...\n  \"start:local\": \"env-cmd -f local.env npm run start\"\n  \"start:dev\": \"env-cmd -f dev.env npm run start\"\n}\n...\n```\n\n```js\nMongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })\n```\n\n```text\nnpm install -D cross-env\n```\n\n```js\n\"scripts\": {\n  \"start:local\": \"cross-env NODE_ENV=local npm run start\"\n  \"start:dev\": \"cross-env NODE_ENV=dev npm run start\"\n}\n```\n\n```text\nNODE_ENV\n```\n\n```text\nConfigModule\n```\n\n```text\ndotenv\n```\n\n```text\npackage.json\n```\n\n```text\ndotenv\n```\n\n```text\nmain.ts\n```\n\n```text\nenv-cmd\n```\n\n```text\nenv-cmd\n```\n\n```text\npackage.json\n```\n\n```text\nprocess.env.MONGO_CONNECTION_STRING\n```\n\n```text\ncross-env\n```\n\n```text\nMongooseModule.forRootAsync(() => {...})\n```\n\n```text\nMongooseModule.forRoot(...)\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config';\n```\n\n```text\nConfigModule.forRoot(),\n```\n\n```text\nprocess.env.DATABASE_USER\n```\n\n```text\nnpm i --save @nestjs/config\n```\n\n```text\n.env\n```\n\n```text\nDATABASE_USER=myusername\n```\n\n```text\napp.module.ts\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule.forRoot()],\n})\n\nexport class AppModule {}\n```\n\n```text\nDB_USER=mohit\n```\n\n```text\nMongooseModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    uri: configService.get<string>('MONGODB_URI'),\n  }),\n  inject: [ConfigService],\n});\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forRootAsync({\n      useFactory: () => ({\n        uri: process.env.CONNECTION_STRING,\n      }),\n    }),\n    ConfigModule.forRoot(\n      {\n        isGlobal: true\n      }\n    )\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nMongooseModule.forRootAsync({})\n```\n\n```text\nMongooseModule.forRootAsync({\n  useFactory: () => ({\n    uri: process.env.DB_CONNECTION\n  }),\n}),\nConfigModule.forRoot({isGlobal: true,}),\n```\n\n```text\nconst configService = app.get(ConfigService);\n```\n\n```text\nconst port = configService.get('PORT');\n```\n\n```text\nmain.ts\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config'\nimport { configuration } from '@testlib/config'\n\n// ...\n// hacky way to make it work\nConfigModule.forRoot(),\nConfigModule.forRoot({\n    load: [configuration],\n    isGlobal: true,\n}),\n```\n\n```text\nimport 'dotenv/config'\n\nlet configuration\nconst e = process.env\n\nif (e.NODE_ENV && e.NODE_ENV === 'development') {\n    // local dev config\n    configuration = {\n        test: e.TEST,\n        uri: 'http://localhost:2001/api/'\n    }\n} else {\n    // production config\n    configuration = {\n        test: e.TEST,\n        uri: e.URI\n    }\n}\n\nconst func = () => configuration\n\nexport { func as configuration }\n```\n\n```js\nimports: [\n    MongooseModule.forRootAsync({\n        imports: [ConfigModule],\n        useFactory: (configService: ConfigService) => ({\n            uri: configService.get('MONGODB_URI'),\n        }),\n        inject: [ConfigService],\n    }),\n],\n```\n\n```js\nimports: [\n    DatabaseModule,\n    DatabaseModule.forFeature([\n        { name: AnyDocumentYouWantToRegister.name, schema: AnySchemaYouWantToRegisterToMongoose },\n    ]),\n]\n```\n\n```text\n@nestjs/cli\n```\n\n```text\nConfigService\n```\n\n```text\n@nestjs/config\n```\n\n```text\nMONGODB_URI\n```\n\n```text\n.env\n```\n\n```text\nDatabaseModule\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { SnakeNamingStrategy } from 'typeorm-naming-strategies';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: () => ({\n        type: 'postgres',\n        host: process.env['DB_HOST'],\n        port: +process.env['DB_PORT'],\n        username: process.env['DB_USER'],\n        password: process.env['DB_PASSWORD'],\n        database: process.env['DB_DATABASE'],\n        synchronize: true,\n        logging: false,\n        entities: [__dirname + '/../**/*.entity.{js,ts}'],\n        autoLoadEntities: true,\n        namingStrategy: new SnakeNamingStrategy(),\n      }),\n    }),\n  ],\n})\nexport class DatabaseModule {}\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n      cache: true,\n      envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],\n    }),\n    CacheModule.register({\n      isGlobal: true,\n    }),\n    DatabaseModule,\n    BidsModule,\n    UsersModule,\n  ],})\n```\n\n========================================\n\nComments:\n- ConfigModule.get to be this.configService.get('database.host')\n- I updated my code as you suggested. But now I'm getting error - `Nest cannot export a module that is not part of the currently processed module`. Here is what I updated - `MongooseModule.forRootAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ uri: 'mongodb+srv:&#47;&#47;db_username:db_pass@myhost.net?retryWrites=tr&zwnj;&#8203;ue&w=majority', options: { useNewUrlParser: true, dbName: 'dbname' }, }), inject: [ConfigModule], }),`\n- fix the inject from `ConfigModule` to `ConfigService` ( the NestJS docs)\n- Thanks. I tried your first suggestion and it worked fine for me (the only thing was that the require('dotenv') line had to come before the import of AppModule). This solution is simple and quick :)\n- can you show me the main.ts and app module where you wrote this working code ?\n- you can just put the `require('dotenv').config({ path:`../${process.env.NODE_ENV}.env` });` at the top of your main.ts.\n- Nest config service already has 'dotenv' under the hood\n- I am facing an issue with this method then env file is not loading although NODE_ENV is set it can't read the env\n- I've got this error `'NODE_ENV' is not recognized as an internal or external command,` the script: ``` \"start\": \"NODE_ENV=dev nest start\", \"start:dev\": \"NODE_ENV=dev nest start --watch\", ```\n- Hi @AhmadDeel that's because the command was for linux. you may need cross-env package and use `cross-env NODE_ENV=dev nest start`\n- I'm using `SET NODE_ENV=prod&& node dist&#47;main` in windows now. somehow there should be no space between `prod` and `&&`\n- I tried to do this with the \"@nestjs/dotenv\" module but it did not work. Worked perfectly with \"@nestjs/config\". Thanks!\n- This IS what Nest.js documents recommend, and the paid Nest.js course. However, as of mid 2022, this is not working. I followed the steps in the documentation and course exactly, and I'm getting \"client password must be a string\". I'm getting ConfigModule dependencies and then that error is thrown.\n- you can also juste call ConfigModule.forRoot() as a normal function outside import and ask for process.env data, thanks\n- @MichaelJay I ran into the same issue and I had to use the async initialization function: `JwtModule.registerAsync({ useFactory: async () => ({ secretOrPrivateKey: process.env.JWT_SECRET_KEY, signOptions: { expiresIn: process.env.JWT_EXPIRATION_TIME, }, }), }),`\n- It seems that you have to run ConfigModule.forRoot() *before* referring to process.env.MY_VAR. This also means that you have to put the ConfigModule.forRoot() *before* any imports of modules that is in turn referring to process.env.MY_VAR. It is probably best to make sure to *not* put any references to such vars on the top level.\n- This does the job to get environment variables in runtime, but OP also wants to get environment variables while importing the module. With your solution, OP needs to load mongoose module asynchronously, as @Daniel pointed out.\n- Tried this. This does not load .env variables. And process.env can be used without even using ConfigModule\n- FYI - verify your .env file uses EQUALS and not COLON. This is right`DB_USER=mohit` and this is wrong `DB_USER:mohit`. I did this twice already :D\n- tanx, often forget to \"inject: [Configervice ] :)\n- This is the correct way to do it. Assuming you want to run everything through the config module which can run validation on vars before they are passed in.\n- it still gives me the same error.\n- One thing that I personally do, in my projects is, create a file env.ts, and export configuration from that file. Example:- `export const port = 8080`, then import it `import { port } from 'env'`. This should work without `forRootAsync` and should work with `forRoot` too. I haven't tried it.\n- Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.","metadata":{"transformedAt":"2026-08-18T18:33:02.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":56,"totalLines":490,"estimatedTokens":3247}}7{"id":"stack-51819504","source":"stackoverflow","questionId":51819504,"title":"Inject nestjs service from another module","tags":["javascript","node.js","typescript","dependency-injection","nestjs"],"text":"Title: Inject nestjs service from another module\nTags: javascript, node.js, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've got a `PlayersModule` and an `ItemsModule`.\n\nI want to use the `ItemsService` in the `PlayersService`.\n\nWhen I add it by injection:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from 'nestjs-typegoose';\nimport { ModelType, Ref } from 'typegoose';\nimport { Player } from './player.model';\nimport { Item } from '../items/item.model';\nimport { ItemsService } from '../items/items.service';\n\n@Injectable()\nexport class PlayersService {\n constructor(\n @InjectModel(Player) private readonly playerModel: ModelType,\n private readonly itemsService: ItemsService){}\n```\n\nI get this nest error :\n\n [Nest] 11592 - 2018-8-13 11:42:17 [ExceptionHandler] Nest can't\n resolve dependencies of the PlayersService (+, ?). Please make sure\n that the argument at index [1] is available in the current context.\n\nBoth modules are imported in the `app.module.ts`. Both services are working alone in their module.\n\n========================================\n\nTop Answer:\nLet' say you want to use AuthService from AuthModule in my TaskModule's controller\n\nfor that, you need to export authService from AuthModule\n\n```\n@Module({\n imports: [\n ....\n ],\n providers: [AuthService],\n controllers: [AuthController],\n exports:[AuthService]\n })\nexport class AuthModule {}\n```\n\nthen in TaskModule, you need to import AuthModule (note: import AuthModule not the AuthService in TaskModule)\n\n```\n@Module({\n imports:[\n AuthModule\n ],\n controllers: [TasksController],\n providers: [TasksService]\n })\nexport class TasksModule {}\n```\n\nNow you should be able to use DI in TaskController\n\n```\n@Controller('tasks')\nexport class TasksController {\n constructor(private authService: AuthService) {}\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from 'nestjs-typegoose';\nimport { ModelType, Ref } from 'typegoose';\nimport { Player } from './player.model';\nimport { Item } from '../items/item.model';\nimport { ItemsService } from '../items/items.service';\n\n@Injectable()\nexport class PlayersService {\n    constructor(\n        @InjectModel(Player) private readonly playerModel: ModelType<Player>,\n        private readonly itemsService: ItemsService){}\n```\n\n```text\nPlayersModule\n```\n\n```text\nItemsModule\n```\n\n```text\nItemsService\n```\n\n```text\nPlayersService\n```\n\n```text\napp.module.ts\n```\n\n```text\n@Module({\n  controllers: [ItemsController],\n  providers: [ItemsService],\n  exports: [ItemsService]\n  ^^^^^^^^^^^^^^^^^^^^^^^\n})\nexport class ItemsModule {}\n```\n\n```text\n@Module({\n  controllers: [PlayersController],\n  providers: [PlayersService],\n  imports: [ItemsModule]\n  ^^^^^^^^^^^^^^^^^^^^^^\n})\nexport class PlayersModule {}\n```\n\n```text\nItemsService\n```\n\n```text\n@Inject()\n```\n\n```text\n@Module({\n    imports: [\n     ....\n    ],\n    providers: [AuthService],\n    controllers: [AuthController],\n    exports:[AuthService]\n  })\nexport class AuthModule {}\n```\n\n```text\n@Module({\n    imports:[\n      AuthModule\n    ],\n    controllers: [TasksController],\n    providers: [TasksService]\n  })\nexport class TasksModule {}\n```\n\n```text\n@Controller('tasks')\nexport class TasksController {\n   constructor(private authService: AuthService) {}\n   ...\n}\n```\n\n```text\n@Module({\n    controllers: [CategoryController],\n    providers: [CategoryService],\n    exports: [CategoryService] // Remember to export\n  })\nexport class CategoryModule {}\n```\n\n```text\n@Module({\n    imports: [CategoryModule], // Make sure you imported the module you are using\n    controllers: [PostController],\n    providers: [PostService]\n  })\nexport class PostModule {}\n```\n\n```text\n@Injectable()  \nexport class PostService {\n  constructor(private readonly categoryService: CategoryService // This will be auto injected by Nestjs Injector) {}\n}\n```\n\n```text\nconstructor(private usersService: UsersService) {}\n```\n\n```text\nconstructor(@Inject(UsersService) private usersService: UsersService) {}\n            ^^^^^^^^^^^^^^^^^^^^^\n```\n\n```text\nimport { Global, Module } from '@nestjs/common';\n```\n\n```text\n@Global()\n@Module( /** Module Definition **/ )\nexport class SomeModule { }\n```\n\n```text\n// src/common/common.module.ts\nimport { Module } from '@nestjs/common';\nimport { PasswordService } from '../utils/password.service';\n\n@Module({\n  providers: [PasswordService],\n  exports: [PasswordService], // Export PasswordService so it can be used in other modules\n})\nexport class CommonModule {}\n\n\n// src/utils/password.service.ts\nimport { Injectable } from '@nestjs/common';\nimport * as bcrypt from 'bcrypt';\n\n@Injectable()\nexport class PasswordService {\n  private readonly saltRounds = 10; // This can be moved to a configuration file if needed\n\n  async generateHash(plainText: string): Promise<string> {\n    return await bcrypt.hash(plainText, this.saltRounds);\n  }\n}\n\n\n// src/users/users.service.ts\nimport { Injectable, InternalServerErrorException, Logger, ConflictException } from '@nestjs/common';\nimport { CreateUserDTO } from './create-user.dto';\nimport { PrismaService } from 'src/prisma.service';\nimport { PasswordService } from '../utils/password.service'; // Import PasswordService\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    private prisma: PrismaService,\n    private passwordService: PasswordService, // Inject PasswordService\n  ) {}\n\n  async signup(createUserDTO: CreateUserDTO) {\n    try {\n      const hash = await this.passwordService.generateHash(createUserDTO.password);\n      createUserDTO.password = hash;\n\n      return await this.prisma.user.create({\n        data: createUserDTO,\n        select: { email: true, id: true },\n      });\n    } catch (error) {\n      \n      throw new InternalServerErrorException('Signup user failed', {\n        cause: new Error(),\n        description: 'Error while signing up user',\n      });\n    }\n  }\n}\n\n\n// src/app.module.ts\nimport { Module } from '@nestjs/common';\nimport { PrismaService } from './prisma.service';\nimport { UsersService } from './users/users.service';\nimport { CommonModule } from './common/common.module';\n\n@Module({\n  imports: [CommonModule],\n  providers: [PrismaService, UsersService],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- Ok, thanks you. So i have to import ItemsModule into PlayersModule even if it is already known by AppModule ?\n- If you want to use it in the PlayersModule, yes.\n- I used @KimKern 's suggestion, still see the errors that the injected service is not recognized.\n- @Liangjun There are also other reasons why a dependency can not be injected. You can always open a new question.\n- I actually had the problem solved by just restarting my Visual Studio Code. strange. Thanks.\n- Was trying to import the Service itself, turned out importing the module itself worked. Thank you\n- @nasta did you still need to additionally import the service inside PlayersService? i.e. `import { ItemsService } from '..&#47;items&#47;items.service';`. In addition, is there some kind of decorator we use here inside the constructor? `@Inject private readonly itemsService: ItemsService`\n- @baku Yes, you need the js import. See this answer stackoverflow.com/a/51516526/4694994\n- Currently this won't work... You will still need to add ItemsService in the providers of the providers array of the PlayersModule\n- @OmarHossamAhmed You should not add the `ItemsService` to the `PlayersModule`. Did you export the `ItemsService` in the `ItemsModule` before importing it in the `PlayersModule`?\n- Yes I was working on something similar and it only seemed to work when I added it in the providers module. It was a service registered in module x and exported by said module. Now, the weirdest thing I tried it again now and it worked! Sorry for my false information, but I noticed some weird behaviour with dependency injection lately.,\n- Hi Kim Kern. This works perfect sir. I had one problem. I want to the TypeOrm repository from one module to other. I tried this in case of Repository but it didn't work.\n- @SushantKeni Thanks, I'm glad this answer is helpful. :-) It's difficult to answer your question without seeing your code. Consider opening a new question for it and include the relevant code snippets.\n- Is it possible to have a service class without @Injectable annotattion, and also this class does not belong to any module?, I saw an example like that, where this service belongs to a commons folder, and it was registered in another module in the the providers array, and it injected in other service's constructor method\n- @Hector I am not sure I understood your use case fully, but I had these two thoughts: You can define regular JS classes outside of nests application container and then just create them where you need them (-> no injection possible). Also, there are global modules, that only need to be imported once (also see stackoverflow.com/a/55181002/4694994). If this does not help, consider opening a new question and add more details to it, ideally a minimal code snippet explaining your scenario.\n- If you get into circular. Use `forwardRef`, docs.nestjs.com/fundamentals/circular-dependency\n- My mistake was not adding `@` before `Module` decorator and `nest.js` didn't complain about this\n- after trying this solution out I keep getting an error `Error: Cannot find module 'src&#47;item&#47;item.service'` the app I'm working on has an `app.module.ts` which imports both modules. could that be the issue?\n- Thanks, alghough this is terrible...It would have been nicer to have a \"ModuleWithProviders\" to use in the root and then providers. It doesn't make much sense to me exporting a service...in Angular export is mostly for Components and Modules...Providers are handled differently! Or at least, I never exported a provider in Angular... Thanks a lot by the way, it worked!\n- I think you will have to import the module itself\n- I thought this problem just because services didn't export, it's different from Angular.\n- So in this case where we use @Inject() , the Service need not be declared in a module. Right?\n- Hello @Justin I did the same but it throws error that service function not found, is not a function\n- Can I have your giot repo or sandbox code then I can take a look at? @RiteshKhatri\n- Sorry I cannot the code.\n- @RiteshKhatri Maybe you missing add `@Injectable` in PlayersService class, so NestJS doesn't understand the function import from other module\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":319,"estimatedTokens":2688}}8{"id":"stack-54863655","source":"stackoverflow","questionId":54863655,"title":"What's the difference between Interceptor vs Middleware vs Filter in Nest.js?","tags":["node.js","typescript","nestjs"],"text":"Title: What's the difference between Interceptor vs Middleware vs Filter in Nest.js?\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhat's the difference between an Interceptor, Filter and Middleware in Nest.js framework? When should one of them be used and favored over the other?\n\nThanks\n\n========================================\n\nTop Answer:\nFor those of us who \"get it\" better visually, I've created this NestJs pipeline digram based on the latest `v6.10` version. Please feel free to point out any inaccuracies. I'll review and update it promptly, if needed.\n\nhttps://i.sstatic.net/2lFhd.jpg\n\n========================================\n\nCode:\n```text\n@UseInterceptors()\n```\n\n```text\napp.useGlobalInterceptors()\n```\n\n```text\nmain.ts\n```\n\n```text\nnull\n```\n\n```text\n[]\n```\n\n```text\nusers\n```\n\n```text\n{users: users}\n```\n\n```text\nresponse\n```\n\n```text\n@Res()\n```\n\n```text\napp.use()\n```\n\n```text\nmain.ts\n```\n\n```text\nindex.html\n```\n\n```text\nbody-parser\n```\n\n```text\nmorgan\n```\n\n```text\n@UseFilters()\n```\n\n```text\napp.useGlobalFilters()\n```\n\n```text\nmain.ts\n```\n\n```text\nindex.html\n```\n\n```text\nindex.html\n```\n\n```text\nNotFoundException\n```\n\n```text\nv6.10\n```\n\n```text\nnext()\n```\n\n========================================\n\nComments:\n- Thanks @Kim for the detailed illustration. Can you an example of using \"ResultMapping\"?\n- I'm glad you found it helpful. :-) Have a look at this post. Here, the result is mapped to an exception. You just have to replace `tap(...)` by `map(data => ({response: data})` and you have mapped whatever data to a nested object. Does that answer your question? stackoverflow.com/a/51918372/4694994\n- one more question. You mentioned that i can use any middleware for nodejs and express in nestjs. Do you have an example of that? Thanks\n- Just add the middleware function in your `main.ts` with `app.use()`, e.g. `app.use(bodyParser.json());`\n- There are also Guards which are executed after each middleware, but before any interceptor or pipe.\n- You mentioned, `you cannot use Interceptors when you use the response with @Res() objects in your route handler.`, just checked with nest js version `6.12.6`, I am able to call the interceptor, was that an older version?\n- @pravindot17 Interceptors are called twice: Once before the controller and once after it. When you send the response with `@Res`, the interceptor won't be called after the controller; the same goes for ExceptionFilters. I will edit the answer to make it more clear, thanks for the hint. :-)\n- @KimKern thanks, but I did two checks one with @Res() and other without it, in both cases the interceptor got called.\n- @pravindot17 When you do `res.send()` the response is immediately sent out. Logically, the interceptor cannot alter the response after it was sent. Please have a look at the docs: \"The main disadvantages are that you lose compatibility with Nest features that depend on Nest standard response handling, such as Interceptors and the @HttpCode() decorator.\"\n- It's perfect! What about pipes?\n- middlewares could also be registered by using the consumer.forRoutes()... in the main app module's configure function\n- This is very useful.\n- I wonder if this image represents 2022?\n- @buryo it does.\n- *Just for anyone who doesn't know it* This is the official page explaining the **Request lifecycle**: docs.nestjs.com/faq/request-lifecycle I found it to be a great complement to @demisx's diagram. *The text helps you understand, and the diagram enables you to remember. What a great combination!*\n- Extremely helpful! Thanks for taking the time to create","metadata":{"transformedAt":"2026-08-18T18:33:02.395Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":126,"estimatedTokens":895}}9{"id":"stack-51112952","source":"stackoverflow","questionId":51112952,"title":"What is the nestjs error handling approach (business logic error vs. http error)?","tags":["javascript","node.js","typescript","error-handling","nestjs"],"text":"Title: What is the nestjs error handling approach (business logic error vs. http error)?\nTags: javascript, node.js, typescript, error-handling, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhile using NestJS to create API's I was wondering which is the best way to handle errors/exception.\nI have found two different approaches :\n\n- Have individual services and validation pipes `throw new Error()`, have the controller `catch` them and then throw the appropriate kind of `HttpException`(`BadRequestException`, `ForbiddenException` etc..)\n\n- Have the controller simply call the service/validation pipe method responsible for handling that part of business logic, and throw the appropriate `HttpException`.\n\nThere are pros and cons to both approaches:\n\n- This seems the right way, however, the service can return `Error` for different reasons, how do I know from the controller which would be the corresponding kind of `HttpException` to return?\n\n- Very flexible, but having `Http` related stuff in services just seems wrong.\n\nI was wondering, which one (if any) is the \"nest js\" way of doing it?\n\nHow do you handle this matter?\n\n========================================\n\nTop Answer:\nNest Js provides an exception filter that handles error not handled in the application layer, so i have modified it to return 500, internal server error for exceptions that are not Http. Then logging the exception to the server, then you can know what's wrong and fix it.\n\n```\nimport 'dotenv/config';\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';\n\n@Catch()\nexport class HttpErrorFilter implements ExceptionFilter {\n private readonly logger : Logger \n constructor(){\n this.logger = new Logger \n }\n catch(exception: Error, host: ArgumentsHost): any {\n const ctx = host.switchToHttp();\n const request = ctx.getRequest();\n const response = ctx.getResponse();\n\n const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR\n const message = exception instanceof HttpException ? exception.message || exception.message?.error: 'Internal server error'\n\n const devErrorResponse: any = {\n statusCode,\n timestamp: new Date().toISOString(),\n path: request.url,\n method: request.method,\n errorName: exception?.name,\n message: exception?.message\n };\n\n const prodErrorResponse: any = {\n statusCode,\n message\n };\n this.logger.log( `request method: ${request.method} request url${request.url}`, JSON.stringify(devErrorResponse));\n response.status(statusCode).json( process.env.NODE_ENV === 'development'? devErrorResponse: prodErrorResponse);\n }\n}\n```\n\n========================================\n\nCode:\n```text\nthrow new Error()\n```\n\n```text\ncatch\n```\n\n```text\nHttpException\n```\n\n```text\nBadRequestException\n```\n\n```text\nForbiddenException\n```\n\n```text\nHttpException\n```\n\n```text\nError\n```\n\n```text\nHttpException\n```\n\n```text\nHttp\n```\n\n```text\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    // next.handle() is an Observable of the controller's result value\n    return next.handle()\n      .pipe(catchError(error => {\n        if (error instanceof EntityNotFoundError) {\n          throw new NotFoundException(error.message);\n        } else {\n          throw error;\n        }\n      }));\n  }\n}\n```\n\n```text\nEntityNotFoundError\n```\n\n```text\nNotFoundException\n```\n\n```text\nInterceptor\n```\n\n```text\n@UseInterceptors(NotFoundInterceptor)\n```\n\n```ts\nimport { BadRequestException, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class HttpHelperService {\n  async transformExceptions(action: Promise<any>): Promise<any> {\n    try {\n      return await action;\n    } catch (error) {\n      if (error.name === 'QueryFailedError') {\n        if (/^duplicate key value violates unique constraint/.test(error.message)) {\n          throw new BadRequestException(error.detail);\n        } else if (/violates foreign key constraint/.test(error.message)) {\n          throw new BadRequestException(error.detail);\n        } else {\n          throw error;\n        }\n      } else {\n        throw error;\n      }\n    }\n  }\n}\n```\n\n```text\nimport 'dotenv/config';\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';\n\n@Catch()\nexport class HttpErrorFilter implements ExceptionFilter {\n  private readonly logger : Logger \n  constructor(){\n    this.logger = new Logger \n  }\n  catch(exception: Error, host: ArgumentsHost): any {\n    const ctx = host.switchToHttp();\n    const request = ctx.getRequest();\n    const response = ctx.getResponse();\n\n    const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR\n    const message = exception instanceof HttpException ?  exception.message || exception.message?.error: 'Internal server error'\n\n    const devErrorResponse: any = {\n      statusCode,\n      timestamp: new Date().toISOString(),\n      path: request.url,\n      method: request.method,\n      errorName: exception?.name,\n      message: exception?.message\n    };\n\n    const prodErrorResponse: any = {\n      statusCode,\n      message\n    };\n    this.logger.log( `request method: ${request.method} request url${request.url}`, JSON.stringify(devErrorResponse));\n    response.status(statusCode).json( process.env.NODE_ENV === 'development'? devErrorResponse: prodErrorResponse);\n  }\n}\n```\n\n```text\n@Controller('example')\nexport class ExampleController {\n\n  @Post('make')\n  async make(@Res() res, @Body() data: dataDTO): Promise<any> {\n   \n    try {\n      //process result...\n       return res.status(HttpStatus.OK).json(result);\n    } catch (error) {\n      throw AppErrorHandler.createHttpException(error); //<---here is the error type mapping\n    };\n  };\n\n};\n```\n\n```text\nimport { Controller, Post, UploadedFiles, UseInterceptors, Body, Get } from '@nestjs/common';\nimport { BadRequestException } from '@nestjs/common';\nimport { FilesInterceptor } from '@nestjs/platform-express';\n\n\n\n@Post('/multiple')\n  @UseInterceptors(FilesInterceptor('files'))\n  async uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>, @Body() body: any) {\n    console.log('body :', body);\n    if (!files || !files.length) {\n      throw new BadRequestException('files should have at least one object');\n    }\n    const req: FileDataReq = {\n      files,\n      ...body,\n    };\n    return req;\n  }\n```\n\n========================================\n\nComments:\n- Thanks Alex. How would you use the code you posted? In the controller?\n- How did you implement this service?\n- Note, that the code snippet already uses the new nest v6 interceptor. For an v5 example, have a look at the codesandbox.\n- The nestjs exception filter looks more adapted for that job docs.nestjs.com/exception-filters\n- While this works, it should not be the accepted answer. As @AlexandreMorgaut mentioned, Nest's ExceptionFilters are meant for this exact use case.\n- When you need to do some failure in database you can't use ExceptionFilter then only Interceptor is the only solution\n- Nice implementation! I think you can also use NestJS dependency injection syntax, so you don't have to declare a private property \"logger\" and then instantiate it. You can just use \"private readonly logger : Logger\" inside the constructor and it is instantiated automatically.\n- Thank you, noted will implement and update the answer.\n- At least for my use case, this is the best answer.\n- FYI @MarcusCastanho - it seems you can't use NestJS DI, at least when using a global filter -- because you have to instantiate the filter yourself.\n- To return the correct error message you need to do something like this: `const message = exception instanceof HttpException ? exception.getResponse()?.['message'] ? exception.getResponse()?.['message'] : exception['message'] : 'Internal server error';`\n- @LuscaDev I don't think anybody ever should do something like this. At least not the way you posted, it's impossible to read.","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":253,"estimatedTokens":2005}}10{"id":"stack-52783959","source":"stackoverflow","questionId":52783959,"title":"Nest.js - request entity too large PayloadTooLargeError: request entity too large","tags":["javascript","node.js","nestjs"],"text":"Title: Nest.js - request entity too large PayloadTooLargeError: request entity too large\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to save a `JSON` into a Nest.js server but the server crash when I try to do it, and this is the issue that I'm seeing on the console.log:\n\n`[Nest] 1976 - 2018-10-12 09:52:04 [ExceptionsHandler] request entity too large PayloadTooLargeError: request entity too large`\n\nOne thing is the size of the JSON request is 1095922 bytes, Does any one know How in Nest.js increase the size of a valid request? Thanks!\n\n========================================\n\nTop Answer:\nyou can also import `urlencoded` & `json` from express\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { urlencoded, json } from 'express';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.setGlobalPrefix('api');\n app.use(json({ limit: '50mb' }));\n app.use(urlencoded({ extended: true, limit: '50mb' }));\n await app.listen(process.env.PORT || 3000);\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nJSON\n```\n\n```text\n[Nest] 1976   - 2018-10-12 09:52:04   [ExceptionsHandler] request entity too large PayloadTooLargeError: request entity too large\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport * as bodyParser from 'body-parser';\n\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useStaticAssets(`${__dirname}/public`);\n  // the next two lines did the trick\n  app.use(bodyParser.json({limit: '50mb'}));\n  app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));\n  app.enableCors();\n  await app.listen(3001);\n}\nbootstrap();\n```\n\n```text\nmain.ts\n```\n\n```text\nbody-parser\n```\n\n```text\nJSON\n```\n\n```text\napp\n```\n\n```text\nconst app = await NestFactory.create<NestFastifyApplication>(\nAppModule,\nnew FastifyAdapter({ bodyLimit: 10048576 }),\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { urlencoded, json } from 'express';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.setGlobalPrefix('api');\n  app.use(json({ limit: '50mb' }));\n  app.use(urlencoded({ extended: true, limit: '50mb' }));\n  await app.listen(process.env.PORT || 3000);\n}\nbootstrap();\n```\n\n```text\nurlencoded\n```\n\n```text\njson\n```\n\n```js\napp.use(express.json({limit: '50mb'}));\napp.use(express.urlencoded({limit: '50mb'}));\n```\n\n```text\nimport { json as expressJson, urlencoded as expressUrlEncoded } from 'express';\n\n// You init your app here: app = await NestFactory.create(AppModule\n\nif (app !== undefined) { \n  app.use(expressJson({ limit: '50mb' }));\n  app.use(expressUrlEncoded({ limit: '50mb', extended: true }));\n}\n```\n\n```text\napp.useBodyParser\n```\n\n```js\napp.use(json({ limit: '50mb' }));\n```\n\n```text\nclient_max_body_size 5M;\n```\n\n```text\n/etc/nginx/nginx.conf\n```\n\n```text\napp.use('/files', json({ limit: '10mb' }));\n app.use(json({ limit: '100kb' }));\n```\n\n```text\nimport multipart from '@fastify/multipart'\n\n...\n\nawait app.register(multipart, {\n    limits: {\n      fileSize: 10 * 1024 * 1024, // 10 MB\n    },\n  })\n```\n\n```text\nawait app.register(require('@fastify/multipart'), {\n    limits: {\n      fileSize: 5 * 1024 * 1024, // 5 MB\n    },\n  });\n```\n\n```text\nProperty 'useBodyParser' does not exist on type 'INestApplication<any>'.\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { NestExpressApplication } from '@nestjs/platform-express';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(AppModule);\n\n  // Increase the body parser limit\n  app.useBodyParser('json', { limit: '50mb' });\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nNestFactory.create\n```\n\n```text\n<NestExpressApplication>\n```\n\n```text\nuseBodyParser\n```\n\n```text\nNestExpressApplication\n```\n\n```text\nuseBodyParser\n```\n\n```text\nNestFactory.create\n```\n\n```text\n<NestExpressApplication>\n```\n\n```text\napp.useBodyParser('json', { limit: '50mb' });\n```\n\n```text\n{ bodyParser: false }\n```\n\n```text\nNestFactory.create\n```\n\n```text\n@Body()\n```\n\n```text\napp.useBodyParser()\n```\n\n========================================\n\nComments:\n- if express verion is higer than 4.x. the code is like `app.use(express.urlencoded({ limit: '50mb' }))` expressjs.com/en/4x/api.html#express-json-middleware\n- This is the right solution for Nest Fastify Apps.\n- the link is dead and doesnt appear to work with the latest version of nest\n- much better solution than adding extra library\n- @NenadJovicic actually the `body-parser` is already included and used by `express` and author of NestJS recommends using it: github.com/nestjs/nest/issues/529#issuecomment-376576929 So it's most probably the same.\n- This worked for me, thanks! For completeness you may want to add import { json, urlencoded } from 'express';\n- Right answer for nestjs 10+","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":248,"estimatedTokens":1286}}11{"id":"stack-53786383","source":"stackoverflow","questionId":53786383,"title":"Validate nested objects using class validator and nestjs","tags":["javascript","node.js","typescript","nestjs","class-validator"],"text":"Title: Validate nested objects using class validator and nestjs\nTags: javascript, node.js, typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to validate nested objects using class-validator and NestJS. I've already tried following this thread by using the `@Type` decorator from class-transform and didn't have any luck. This what I have:\n\n**DTO:**\n\n```\nclass PositionDto {\n @IsNumber()\n cost: number;\n\n @IsNumber()\n quantity: number;\n}\n\nexport class FreeAgentsCreateEventDto {\n\n @IsNumber()\n eventId: number;\n\n @IsEnum(FinderGamesSkillLevel)\n skillLevel: FinderGamesSkillLevel;\n\n @ValidateNested({ each: true })\n @Type(() => PositionDto)\n positions: PositionDto[];\n\n}\n```\n\nI'm also using built-in nestjs validation pipe, this is my bootstrap:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(ServerModule);\n app.useGlobalPipes(new ValidationPipe());\n await app.listen(config.PORT);\n}\nbootstrap();\n```\n\nIt's working fine for other properties, the array of objects is the only one not working.\n\n========================================\n\nTop Answer:\nfor me, I would able to validate nested object with `'class-transformer'`\n\n```\nimport { Type } from 'class-transformer';\n```\n\nfull example:\n\n```\nimport {\n MinLength,\n MaxLength,\n IsNotEmpty,\n ValidateNested,\n IsDefined,\n IsNotEmptyObject,\n IsObject,\n IsString,\n} from 'class-validator';\nimport { Type } from 'class-transformer';\n\nclass MultiLanguageDTO {\n @IsString()\n @IsNotEmpty()\n @MinLength(4)\n @MaxLength(40)\n en: string;\n\n @IsString()\n @IsNotEmpty()\n @MinLength(4)\n @MaxLength(40)\n ar: string;\n}\n\nexport class VideoDTO {\n @IsDefined()\n @IsNotEmptyObject()\n @IsObject()\n @ValidateNested()\n @Type(() => MultiLanguageDTO)\n name!: MultiLanguageDTO;\n}\n```\n\n========================================\n\nCode:\n```text\nclass PositionDto {\n  @IsNumber()\n  cost: number;\n\n  @IsNumber()\n  quantity: number;\n}\n\nexport class FreeAgentsCreateEventDto {\n\n  @IsNumber()\n  eventId: number;\n\n  @IsEnum(FinderGamesSkillLevel)\n  skillLevel: FinderGamesSkillLevel;\n\n  @ValidateNested({ each: true })\n  @Type(() => PositionDto)\n  positions: PositionDto[];\n\n}\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(ServerModule);\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(config.PORT);\n}\nbootstrap();\n```\n\n```text\n@Type\n```\n\n```text\nimport { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';\n\nexport function IsNonPrimitiveArray(validationOptions?: ValidationOptions) {\n  return (object: any, propertyName: string) => {\n    registerDecorator({\n      name: 'IsNonPrimitiveArray',\n      target: object.constructor,\n      propertyName,\n      constraints: [],\n      options: validationOptions,\n      validator: {\n        validate(value: any, args: ValidationArguments) {\n          return Array.isArray(value) && value.reduce((a, b) => a && typeof b === 'object' && !Array.isArray(b), true);\n        },\n      },\n    });\n  };\n}\n```\n\n```text\n@ValidateNested({ each: true })\n@IsNonPrimitiveArray()\n@Type(() => PositionDto)\npositions: PositionDto[];\n```\n\n```text\npositions: [1]\n```\n\n```text\nboolean\n```\n\n```text\nstring\n```\n\n```text\nnumber\n```\n\n```text\narray\n```\n\n```text\nimport { Type } from 'class-transformer';\n```\n\n```text\nimport {\n  MinLength,\n  MaxLength,\n  IsNotEmpty,\n  ValidateNested,\n  IsDefined,\n  IsNotEmptyObject,\n  IsObject,\n  IsString,\n} from 'class-validator';\nimport { Type } from 'class-transformer';\n\nclass MultiLanguageDTO {\n  @IsString()\n  @IsNotEmpty()\n  @MinLength(4)\n  @MaxLength(40)\n  en: string;\n\n  @IsString()\n  @IsNotEmpty()\n  @MinLength(4)\n  @MaxLength(40)\n  ar: string;\n}\n\nexport class VideoDTO {\n  @IsDefined()\n  @IsNotEmptyObject()\n  @IsObject()\n  @ValidateNested()\n  @Type(() => MultiLanguageDTO)\n  name!: MultiLanguageDTO;\n}\n```\n\n```text\n'class-transformer'\n```\n\n```text\nimport {\n  ValidationOptions,\n  registerDecorator,\n  ValidationArguments,\n  validateSync,\n} from 'class-validator';\nimport { plainToClass } from 'class-transformer';\n\n/**\n * @decorator\n * @description A custom decorator to validate a validation-schema within a validation schema upload N levels\n * @param schema The validation Class\n */\nexport function ValidateNested(\n  schema: new () => any,\n  validationOptions?: ValidationOptions\n) {\n  return function (object: Object, propertyName: string) {\n    registerDecorator({\n      name: 'ValidateNested',\n      target: object.constructor,\n      propertyName: propertyName,\n      constraints: [],\n      options: validationOptions,\n      validator: {\n        validate(value: any, args: ValidationArguments) {\n          args.value;\n          if (Array.isArray(value)) {\n            for (let i = 0; i < (<Array<any>>value).length; i++) {\n              if (validateSync(plainToClass(schema, value[i])).length) {\n                return false;\n              }\n            }\n            return true;\n          } else\n            return validateSync(plainToClass(schema, value)).length\n              ? false\n              : true;\n        },\n        defaultMessage(args) {\n          if (Array.isArray(args.value)) {\n            for (let i = 0; i < (<Array<any>>args.value).length; i++) {\n              return (\n                `${args.property}::index${i} -> ` +\n                validateSync(plainToClass(schema, args.value[i]))\n                  .map((e) => e.constraints)\n                  .reduce((acc, next) => acc.concat(Object.values(next)), [])\n              ).toString();\n            }\n          } else\n            return (\n              `${args.property}: ` +\n              validateSync(plainToClass(schema, args.value))\n                .map((e) => e.constraints)\n                .reduce((acc, next) => acc.concat(Object.values(next)), [])\n            ).toString();\n        },\n      },\n    });\n  };\n}\n```\n\n```text\nclass Schema2 {\n\n  @IsNotEmpty()\n  @IsString()\n  prop1: string;\n\n  @IsNotEmpty()\n  @IsString()\n  prop2: string;\n}\n\n\nclass Schema1 {\n  @IsNotEmpty()\n  @IsString()\n  prop3: string;\n\n  @ValidateNested(Schema2)\n  nested_prop: Schema2;\n}\n```\n\n```text\nValidateNested\n```\n\n```text\nimport {\n ValidateNested,\n IsDefined,\n IsNotEmptyObject,\n} from 'class-validator';\n\nimport { Type } from 'class-transformer';\nimport { ApiProperty } from '@nestjs/swagger';\n\n@IsDefined()\n@IsNotEmptyObject()\n@ValidateNested()\n@ApiProperty()\n@Type(() => AddressDto)\naddress: AddressDto;\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(ServerModule);\n  app.useGlobalPipes(new ValidationPipe({ transform: true })); // enable transform\n  await app.listen(config.PORT);\n}\nbootstrap();\n```\n\n```text\ntransform\n```\n\n```text\nValidationPipe\n```\n\n========================================\n\nComments:\n- I've just put your code in an empty sample project and it seems to work for me. What specific value is \"not working\"? What are your expectations? If you for example put `\"positions\": [{\"other\": true}]` in your body it rejects with 400. `positions: []` is a valid value though.\n- I'm expecting that if you try `positions: [1]`, it throws an error\n- `@ArrayNotEmpty()`?\n- 2023 and people still using this library... Thanks for question and answers!\n- Is this supposed to transform each element of `positions` to `PositionDto` with its internal elements? If not, how can it be achieved, or do I necessarily have to do the transformations manually?\n- @AdrianGonz&#225;lez Check this answer for nested validation/transformation: stackoverflow.com/a/53685045/4694994\n- Use class-transformer-validator to validate it easily.\n- Why have you used the \"!\" on `VideoDTO.name` here?\n- I don't the `@ValidateNested(Schema2)` is still valid with the current version of class-validator `v0.14.0`\n- Thank you this worked. But i'm getting some typing issue Type '(args: ValidationArguments | undefined) => string | undefined' is not assignable to type '(validationArguments?: ValidationArguments | undefined) => string'. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. No overload matches this call. Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike): string[]', gave the following error. Argument of type '{ [type: string]: string; } | undefined' is not assignable to","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":366,"estimatedTokens":2060}}12{"id":"stack-50949231","source":"stackoverflow","questionId":50949231,"title":"NestJS enable cors in production","tags":["javascript","node.js","typescript","cors","nestjs"],"text":"Title: NestJS enable cors in production\nTags: javascript, node.js, typescript, cors, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've enabled CORS in my NestJS app following the official tutorial, so my `main.ts` looks like the following:\n\n```\nimport { FastifyAdapter, NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule, new FastifyAdapter(), { cors: true });\n await app.listen(3000);\n}\nbootstrap();\n```\n\nand it works when I run the application using `npm run start:dev`.\n\nHowever when I try to first compile the application using `npm run webpack` and then running it using `node server.js`, the cors will not work.\n\nThe http request from the client will fail with:\n\n Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 404.\n\n========================================\n\nTop Answer:\nTry the approach described here in the official docs: https://docs.nestjs.com/techniques/security/cors\n\n```\nconst app = await NestFactory.create(ApplicationModule);\napp.enableCors();\nawait app.listen(3000);\n```\n\n========================================\n\nCode:\n```text\nimport { FastifyAdapter, NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, new FastifyAdapter(), { cors: true });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nmain.ts\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nnpm run webpack\n```\n\n```text\nnode server.js\n```\n\n```text\nnpm run webpack\n```\n\n```text\nprestart:prod\n```\n\n```text\nconst app = await NestFactory.create(ApplicationModule);\napp.enableCors();\nawait app.listen(3000);\n```\n\n```text\nconst app = await NestFactory.create(ApplicationModule);\napp.enableCors();\nawait app.listen(3000);\n```\n\n```text\napp.use((req, res, next) => {\n  res.header('Access-Control-Allow-Origin', '*');\n  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');\n  res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');\n  next();\n});\n```\n\n```text\nGraphQLModule.forRoot({\n            debug: process.env.NODE_ENV !== 'production',\n            playground: process.env.NODE_ENV !== 'production',\n            typePaths: ['./**/*.graphql'],\n            installSubscriptionHandlers: true,\n            context: ({req}) => {\n                return {req};\n            },\n            cors: {\n                credentials: true,\n                origin: true,\n            },\n        }),\n```\n\n```text\napp.enableCors({\n            origin: true,\n            methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',\n            credentials: true,\n        });\n```\n\n```text\nvar whitelist = ['https://website.com', 'https://www.website.com'];\napp.enableCors({\norigin: function (origin, callback) {\n  if (whitelist.indexOf(origin) !== -1) {\n    console.log(\"allowed cors for:\", origin)\n    callback(null, true)\n  } else {\n    console.log(\"blocked cors for:\", origin)\n    callback(new Error('Not allowed by CORS'))\n  }\n},\nallowedHeaders: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Observe',\nmethods: \"GET,PUT,POST,DELETE,UPDATE,OPTIONS\",\ncredentials: true,\n});\n```\n\n```text\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\n```\n\n```text\nconst whitelist = ['example.com', 'api.example.com'];\napp.enableCors({\n  origin: function (origin, callback) {\n    if (!origin || whitelist.indexOf(origin) !== -1) {\n      callback(null, true)\n    } else {\n      callback(new Error('Not allowed by CORS'))\n    }\n  },\n  ...\n});\n```\n\n```text\nundefined\n```\n\n```text\n!origin\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const PORT = 5000;\n  const app = await NestFactory.create(AppModule);\n\n  app.enableCors({credentials: true, origin: \"http://localhost:3000\"});\n\n  await app.listen(PORT, () => console.log(`Server started`));\n}\n\nbootstrap();\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { join } from 'path';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n    const app = await NestFactory.create<NestExpressApplication>(\n        AppModule,\n    );\n\n    app.useStaticAssets(join(__dirname, '..', 'public'));\n    app.setBaseViewsDir(join(__dirname, '..', 'views'));\n    app.setViewEngine('hbs');\n\n    app.use((req, res, next) => {\n        res.header('Access-Control-Allow-Origin', '*');\n        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');\n        res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');\n        next();\n    });\n\n    app.enableCors({\n        allowedHeaders:\"*\",\n        origin: \"*\"\n    });\n\n    await app.listen(3000);\n}\n\nbootstrap();\n```\n\n```text\nnest start\n```\n\n```text\nmain.ts\n```\n\n```text\nmain.ts\n```\n\n```js\napp.enableCors({\n  origin: [\n    'http://localhost:3000',\n    'http://example.com',\n    'http://www.example.com',\n    'http://app.example.com',\n    'https://example.com',\n    'https://www.example.com',\n    'https://app.example.com',\n  ],\n  methods: [\"GET\", \"POST\"],\n  credentials: true,\n});\n```\n\n```text\nasync function bootstrap() {\nconst app = await NestFactory.create(AppModule, new FastifyAdapter());\napp.enableCors()\nawait app.listen(3000); \n}\nbootstrap();\n```\n\n```text\nnpm run start:prod\n```\n\n```text\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\napp.enableCors();\n```\n\n```text\nconst app = await NestFactory.create(AppModule, { cors: true });\nawait app.listen(3000);\n```\n\n```text\napp.enableCors({\n    credentials: true,\n    origin: async (requestOrigin: string, next: (err: Error | null, origin?: string[]) => void) => {\n        const origins = await app.get(AppService).getOrigins();\n\n        // origins: StaticOrigin = ['https://google.com', 'http://localhost'];\n        next(null, origins);\n    },\n});\n```\n\n```text\nconst app = await NestFactory.create(AppModule, { cors: true });\n```\n\n```text\napp.enableCors({\n  origin: ['http://localhost:4200'],\n  methods: ['GET', 'POST'],\n  credentials: true,\n });\n```\n\n```text\napp.enableCors({\n allowedHeaders:\"*\",\n origin: \"*\"\n});\n```\n\n```text\nawait app.init();\n```\n\n```text\nawait app.listen(process.env.PORT)\n```\n\n========================================\n\nComments:\n- check if you have some extension in the browser blocking 3rd javascript, e.g. NoScript and Privacy Badger\n- Also, I have a question: why do you build your server app using webpack? Usually, just simple `tsc` call is used.\n- Thank you but I've already tried this solution and unfortunately it does not work. I compile for production using `npm run webpack` which I guess it's the default way to do it with NestJS, isn't it?\n- ShinDarth, have a look at this official example. There you can find how the app gets built github.com/nestjs/nest/tree/master/sample/10-fastify.\n- Try to build your app using this example as a basis.\n- Here is the compilation command from the `scripts` section of the package.json: `\"prestart:prod\": \"tsc\"`. Just try to play with this example. In case you'll have questions - just put them here.\n- `app.enableCors()` uses default configs which seem to be invalid for some browsers (at least Chrome complains that wildcard is not allowed). Correct way would be to use `app.enableCors({ origin: &#47;.+&#47; });`\n- Is this one still relevant ? As I saw the issue described here now we can use `app.enableCors()` directly github.com/nestjs/graphql/issues/2752\n- A bit of more explanation regarding what does \"if you do not want to block REST tools or server-to-server request\" mean: I was configuring my NestJS app and then I realized that I am getting CORS error when I try to open swagger doc in my browser, so after reading this stackoverflow Q&A I understood what was wrong with my app; since I was sending a request to my NestJS app from the same origin, browser was not adding the origin header to the request. So we need to allow those requests to pass our CORS policy enforcer.\n- What's the question?","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":316,"estimatedTokens":2058}}13{"id":"stack-55093055","source":"stackoverflow","questionId":55093055,"title":"Logging request/response in Nest.js","tags":["typescript","nestjs"],"text":"Title: Logging request/response in Nest.js\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nNew to Nest.js,\n\nI am trying to implement a simple logger for tracing HTTP requests like :\n\n```\n:method :url :status :res[content-length] - :response-time ms\n```\n\nFrom my understanding the best place for that would be interceptors. But I Also use Guards and as mentionned, Guards are triggered **after** middlewares but **before** interceptors.\n\nMeaning, my forrbidden accesses are not logged. I could write the logging part in two different places but rather not. Any idea?\n\nThanks!\n\nMy Interceptor code:\n\n```\nimport { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, tap } from 'rxjs/operators';\n\n@Injectable()\nexport class HTTPLoggingInterceptor implements NestInterceptor {\n\n intercept(context: ExecutionContext, call$: Observable): Observable {\n const now = Date.now();\n const request = context.switchToHttp().getRequest();\n\n const method = request.method;\n const url = request.originalUrl;\n\n return call$.pipe(\n tap(() => {\n const response = context.switchToHttp().getResponse();\n const delay = Date.now() - now;\n console.log(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);\n }),\n catchError((error) => {\n const response = context.switchToHttp().getResponse();\n const delay = Date.now() - now;\n console.error(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);\n return throwError(error);\n }),\n );\n }\n}\n```\n\n========================================\n\nTop Answer:\nhttps://github.com/julien-sarazin/nest-playground/issues/1#issuecomment-682588094\n\nYou can use middleware for that.\n\n```\nimport { Injectable, NestMiddleware, Logger } from '@nestjs/common';\n\nimport { Request, Response, NextFunction } from 'express';\n\n@Injectable()\nexport class AppLoggerMiddleware implements NestMiddleware {\n private logger = new Logger('HTTP');\n\n use(request: Request, response: Response, next: NextFunction): void {\n const { ip, method, path: url } = request;\n const userAgent = request.get('user-agent') || '';\n\n response.on('close', () => {\n const { statusCode } = response;\n const contentLength = response.get('content-length');\n\n this.logger.log(\n `${method} ${url} ${statusCode} ${contentLength} - ${userAgent} ${ip}`\n );\n });\n\n next();\n }\n}\n```\n\nand in the AppModule\n\n```\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer): void {\n consumer.apply(AppLoggerMiddleware).forRoutes('*');\n }\n}\n```\n\n========================================\n\nCode:\n```text\n:method :url :status :res[content-length] - :response-time ms\n```\n\n```text\nimport { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError, tap } from 'rxjs/operators';\n\n@Injectable()\nexport class HTTPLoggingInterceptor implements NestInterceptor {\n\n  intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {\n    const now = Date.now();\n    const request = context.switchToHttp().getRequest();\n\n    const method = request.method;\n    const url = request.originalUrl;\n\n    return call$.pipe(\n      tap(() => {\n        const response = context.switchToHttp().getResponse();\n        const delay = Date.now() - now;\n        console.log(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);\n      }),\n      catchError((error) => {\n        const response = context.switchToHttp().getResponse();\n        const delay = Date.now() - now;\n        console.error(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);\n        return throwError(error);\n      }),\n    );\n  }\n}\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';\nimport { ApplicationModule } from './app.module';\nimport * as morgan from 'morgan';\n\nasync function bootstrap() {\n    const app = await NestFactory.create<NestFastifyApplication>(ApplicationModule, new FastifyAdapter());\n    app.use(morgan('tiny'));\n\n    await app.listen(process.env.PORT, '0.0.0.0');\n}\n\nif (isNaN(parseInt(process.env.PORT))) {\n    console.error('No port provided. ๐Ÿ‘');\n    process.exit(666);\n}\n\nbootstrap().then(() => console.log('Service listening ๐Ÿ‘: ', process.env.PORT));\n```\n\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes('*');\n  }\n}\n\nclass LoggerMiddleware implements NestMiddleware {\n  use(req: Request, res: Response, next: Function) {\n    console.log('Request', req.method, req.originalUrl, /*...*/);\n    next();\n    console.log('Response', res.statusCode, res.statusMessage, /*...*/);\n  }\n}\n```\n\n```text\n@Injectable()\nexport class LoggerMiddleware implements NestMiddleware {\n    use(req: Request, res: Response, next: Function) {\n        const { ip, method, originalUrl: url  } = req;\n        const hostname = require('os').hostname();\n        const userAgent = req.get('user-agent') || '';\n        const referer = req.get('referer') || '';\n\n        res.on('close', () => {\n            const { statusCode, statusMessage } = res;\n            const contentLength = res.get('content-length');\n            logger.log(`[${hostname}] \"${method} ${url}\" ${statusCode} ${statusMessage} ${contentLength} \"${referer}\" \"${userAgent}\" \"${ip}\"`);\n        });\n\n        next();\n    }\n}\n```\n\n```text\nimport { Injectable, NestMiddleware, Logger } from '@nestjs/common';\n\nimport { Request, Response, NextFunction } from 'express';\n\n@Injectable()\nexport class AppLoggerMiddleware implements NestMiddleware {\n  private logger = new Logger('HTTP');\n\n  use(request: Request, response: Response, next: NextFunction): void {\n    const { ip, method, path: url } = request;\n    const userAgent = request.get('user-agent') || '';\n\n    response.on('close', () => {\n      const { statusCode } = response;\n      const contentLength = response.get('content-length');\n\n      this.logger.log(\n        `${method} ${url} ${statusCode} ${contentLength} - ${userAgent} ${ip}`\n      );\n    });\n\n    next();\n  }\n}\n```\n\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer): void {\n    consumer.apply(AppLoggerMiddleware).forRoutes('*');\n  }\n}\n```\n\n```js\nimport { Request, Response, NextFunction } from \"express\";\nimport { Injectable, NestMiddleware, Logger } from \"@nestjs/common\";\n\n@Injectable()\nexport class LoggerMiddleware implements NestMiddleware {\n  private logger = new Logger(\"HTTP\");\n\n  use(request: Request, response: Response, next: NextFunction): void {\n    const { ip, method, originalUrl } = request;\n    const userAgent = request.get(\"user-agent\") || \"\";\n\n    response.on(\"finish\", () => {\n      const { statusCode } = response;\n      const contentLength = response.get(\"content-length\");\n\n      this.logger.log(\n        `${method} ${originalUrl} ${statusCode} ${contentLength} - ${userAgent} ${ip}`,\n      );\n    });\n\n    next();\n  }\n}\n```\n\n```text\nfinish\n```\n\n```text\nclose\n```\n\n```text\nexpress\n```\n\n```text\nclose\n```\n\n```text\nresponse\n```\n\n```text\n// middleware/request-logging.ts\nimport { Logger } from '@nestjs/common';\nimport morgan, { format } from 'morgan';\n\nexport function useRequestLogging(app) {\n    const logger = new Logger('Request');\n    app.use(\n        morgan('tiny', {\n            stream: {\n                write: (message) => logger.log(message.replace('\\n', '')),\n            },\n        }),\n    );\n}\n```\n\n```text\n// main.ts\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { useRequestLogging } from './middleware/request-logging';\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    useRequestLogging(app);\n    await app.listen(configService.get<number>('SERVER_PORT'));\n    logger.log(`Application is running on: ${await app.getUrl()}`);\n}\n```\n\n```text\nimport { NestMiddleware, Injectable } from '@nestjs/common';\nimport { FastifyRequest, FastifyReply } from 'fastify';\nimport { InjectPinoLogger, PinoLogger } from 'nestjs-pino';\nimport serializers from 'pino-std-serializers';\nimport { merge, fromEvent, first } from 'rxjs';\n\n\n@Injectable()\nexport class LoggerMiddleware implements NestMiddleware {\n  constructor(\n    @InjectPinoLogger(LoggerMiddleware.name)\n    private readonly logger: PinoLogger,\n  ) {}\n\n  use(req: FastifyRequest, res: FastifyReply['raw'], next: (error?: Error) => void) {\n    const method = req.method;\n    const url = req.url;\n    const now = Date.now();\n    const traceId = this.cls.get<IAsyncStorage>(TRACE_ID);\n\n    this.logger.assign({ traceIdContext: traceId.value });\n\n    this.logger.debug({\n      info: {\n        url,\n        now,\n        method,\n        country,\n        request: serializers.req(req),\n        requestType: 'external-request',\n      },\n    });\n\n    const loggerData = {\n      info: {\n        url,\n        method,\n        country,\n        response: serializers.res(res),\n        requestType: 'response-from',\n        data: '<omited>', // JSON.stringify(this.responseJson),\n      },\n    };\n\n    const event$ = merge(fromEvent(res, 'finish'), fromEvent(res, 'close'));\n    const eventError$ = merge(fromEvent(res, 'error'));\n\n    event$.pipe(first()).subscribe({\n      next: () => {\n        this.logger.debug(loggerData);\n      },\n    });\n\n    eventError$.pipe(first()).subscribe({\n      next: () => {\n        this.logger.error(loggerData);\n      },\n    });\n\n    return next();\n  }\n}\n```\n\n```text\n// Import required modules\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { catchError, tap } from 'rxjs/operators';\n\n@Injectable()\nexport class ReqLoggingInterceptor implements NestInterceptor {\n  private readonly logger = new Logger('HTTP_REQUEST');\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    // Extract request and response objects\n    const req = context.switchToHttp().getRequest();\n    const res = context.switchToHttp().getResponse();\n\n    // Record current timestamp\n    const now = Date.now();\n\n    // Determine if in production\n    const isProduction = process.env.DB_HOST?.toLowerCase()?.includes('stage') || process.env.NODE_ENV === 'local';\n\n    // Construct log message\n    const logMessage =\n      `METHOD - ${req.method} | URL - ${req.url} | ` +\n      (!isProduction\n        ? ''\n        : `QUERY - ${JSON.stringify(req.query)} | PARAMS - ${JSON.stringify(req.params)} | BODY - ${JSON.stringify(req.body)} `) +\n      `${this.getColorizedStatusCode(res.statusCode)} ${Date.now() - now} ms`;\n\n    // Handle the observable\n    return next.handle().pipe(\n      tap(() => {\n        // Log request details on success\n       req.url && this.logger.log(logMessage);\n      }),\n      catchError((error) => {\n        // Log request details on error and rethrow the error\n      req.url && this.logger.log(logMessage);\n        throw error;\n      }),\n    );\n  }\n\n  private getColorizedStatusCode(statusCode: number): string {\n    // ANSI escape codes for colorization\n    const yellow = '\\x1b[33m';\n    const reset = '\\x1b[0m';\n\n    return `${yellow}${statusCode}${reset}`;\n  }\n}\n```\n\n========================================\n\nComments:\n- See also stackoverflow.com/questions/58970970/&hellip;\n- Thanks for the post. I am not sure this is a way i am confortable with. In my service definition many actions are done through POST request but half of them reply with a 204 since no data needs to be returned. Moreover I do not understand why a \"workaround\" solution is needed for such basic need. I mean i have been a heavy user of nodeJS since a while, used tons of frameworks (express, Hapi, Loopback, Sails) I have even developed my own.. Seeing how well design Nest is I am absolutely sure we are missing something. I will post back as soon as i find a solution.\n- I was not really comfortable with this either. I agree it seems like it's something that you can do in frameworks like express very easily. The other option I found that worked was to put a wrap the logic that is actually logging the request in a setTimeout and a time of 0. This seemed to allow the status code from my filter to be set properly and I didn't have to assume the status code. However I thought this solution was even less ideal then assuming a 201 vs 200. If you find a more ideal solution please do post it back.\n- You can implement a class-based `middleware`, so that you can take advantage of Nestjs `dependency injection`. And even `morgan` uses some hack to record the request and response. So we can just implement our `middleware` similarly.\n- res.statusCode is always 200 and res.finised is always false.\n- But close callback is never called\n- Response data is missing from response object ?\n- how can add response body in log\n- To log the body, add `Request Body: ${JSON.stringify(request.body)}`\n- What about fastify\n- @HafizTemuri, it won't log the response body, it logs request's body.\n- Yes, you probably won't need to log the response body. Most likely you want to log the request body, so you can reproduce the request later.\n- How to get data that sent to user in response object in that middleware? @Stark Joen\n- Well actually I guess you can look into `response` side\n- I dont find data in Response object?Could you please check that ?@Stark\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This is good only if your application does not contain sensitive data, but if it's not the case, this implementation could increase the risk since any credentials are being exposed in the server terminal or the server logs files.","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":445,"estimatedTokens":3492}}14{"id":"stack-64735881","source":"stackoverflow","questionId":64735881,"title":"TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest'","tags":["typescript","axios","nestjs"],"text":"Title: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest'\nTags: typescript, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am a nest.js beginner and I am trying to implement Axios with my code and this error occurs and I would like to fix it.\n\n```\n--> starting at object with constructor 'ClientRequest'\n | property 'socket' -> object with constructor 'Socket'\n --- property '_httpMessage' closes the circle +188941ms\nTypeError: Converting circular structure to JSON\n --> starting at object with constructor 'ClientRequest'\n | property 'socket' -> object with constructor 'Socket'\n --- property '_httpMessage' closes the circle\n at JSON.stringify ()\n at stringify (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\express\\lib\\response.js:1123:12)\n at ServerResponse.json (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\express\\lib\\response.js:260:14)\n at ExpressAdapter.reply (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\platform-express\\adapters\\express-adapter.js:24:57)\n at RouterResponseController.apply (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-response-controller.js:13:36)\n at D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:173:48\n at processTicksAndRejections (internal/process/task_queues.js:93:5)\n at async D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:47:13\n at async D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\nThis is my app.service.ts\n\n```\nasync validateSSO(appticket): Promise {\n let instance = axios.create({\n baseURL: \"http://localhost:8080/\",\n headers: {\n 'DeeAppId': config.DeeAppId,\n 'DeeAppSecret': config.DeeAppSecret,\n 'DeeTicket': appticket\n }\n });\n instance.get(\"/serviceValidation\")\n .then(response => {\n this.ssoContent = response;\n })\n .catch(error => {\n return (error);\n });\n\n return this.ssoContent;\n\n }\n```\n\nand this is my app.controller.ts\n\n```\n@Get('validation/:appticket')\n async validateSSO(\n @Param('appticket') appticket: string\n //DeeAppTicket is sented via Front-end\n ): Promise {\n return this.registeringService.validateSSO(appticket);\n }\n```\n\nThank you for your help :)\n\n========================================\n\nTop Answer:\nToday I had this problem and one way I managed to solve it was instead of return:\n\n```\nthis.ssoContent = response;\n```\n\nI returned:\n\n```\nthis.ssoContent = response.data;\n```\n\n========================================\n\nCode:\n```text\n--> starting at object with constructor 'ClientRequest'\n    |     property 'socket' -> object with constructor 'Socket'\n    --- property '_httpMessage' closes the circle +188941ms\nTypeError: Converting circular structure to JSON\n    --> starting at object with constructor 'ClientRequest'\n    |     property 'socket' -> object with constructor 'Socket'\n    --- property '_httpMessage' closes the circle\n    at JSON.stringify (<anonymous>)\n    at stringify (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\express\\lib\\response.js:1123:12)\n    at ServerResponse.json (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\express\\lib\\response.js:260:14)\n    at ExpressAdapter.reply (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\platform-express\\adapters\\express-adapter.js:24:57)\n    at RouterResponseController.apply (D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-response-controller.js:13:36)\n    at D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:173:48\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)\n    at async D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:47:13\n    at async D:\\CUSportcomplex-register\\sso-reg\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\nasync validateSSO(appticket): Promise<SsoContent> {\n        let instance = axios.create({\n            baseURL: \"http://localhost:8080/\",\n            headers: {\n                'DeeAppId': config.DeeAppId,\n                'DeeAppSecret': config.DeeAppSecret,\n                'DeeTicket': appticket\n            }\n        });\n        instance.get(\"/serviceValidation\")\n            .then(response => {\n                this.ssoContent = response;\n            })\n            .catch(error => {\n                return (error);\n            });\n\n        return this.ssoContent;\n\n    }\n```\n\n```text\n@Get('validation/:appticket')\n    async validateSSO(\n        @Param('appticket') appticket: string\n        //DeeAppTicket is sented via Front-end\n    ): Promise<SsoContent> {\n        return this.registeringService.validateSSO(appticket);\n    }\n```\n\n```text\ndata\n```\n\n```text\nawait\n```\n\n```text\nasync\n```\n\n```js\nthis.ssoContent = response;\n```\n\n```js\nthis.ssoContent = response.data;\n```\n\n```text\nTypeError: Converting circular structure to JSON\n--> starting at object with constructor 'EntityMetadata'\n|     property 'ownColumns' -> object with constructor 'Array'\n|     index 0 -> object with constructor 'ColumnMetadata'\n--- property 'entityMetadata' closes the circle\n```\n\n```text\ngetOne()\n```\n\n```text\ngetMany()\n```\n\n```text\nconst CircularJSON = require('circular-json');\nconst obj=CircularJSON.stringify(object)\n```\n\n```text\ncircular json\n```\n\n```text\nnpm i circular-json\n```\n\n```text\nnpm i circular-json --force\n```\n\n```text\ntype Test = unknown\nconst test:Test\n{test ? <div>test</div> : null}\n```\n\n```text\n{Boolean(test) ? <div>test</div> : null}\n```\n\n```text\nconst response = await axios(url, body, options );\nreturn response.data;\n```\n\n```text\nconst payload = { name: \"M Hmzara Rajput\" }\nconsole.log(\"request:\", JSON.stringify(payload));\nconst response = await axios.post(`http://server:port/endpoint`, payload);\n// Don't JSON.stringify to an http object instead response.data\nconsole.log(\"response:\", JSON.stringify(response));\n```\n\n```text\nconst payload = { name: \"M Hmzara Rajput\" }\nconsole.log(\"request:\", JSON.stringify(payload));\nconst response = await axios.post(`http://server:port/endpoint`, payload);\nconsole.log(\"response:\", JSON.stringify(response.data));\n```\n\n```text\n@Post()\nasync someRequestName() {\n  return this.httpService.post( // this is Observable<AxiosResponse>\n    'http://localhost:3001/api/some-endpoint',\n  );\n}\n```\n\n```text\n@Post()\nasync someRequestName() {\n  return firstValueFrom( // this is Promise<Observable<AxiosResponse>>\n    this.httpService.post(\n      'http://localhost:3001/api/some-endpoint',\n    ),\n  );\n}\n```\n\n```text\n@Post()\nasync someRequestName() {\n  const data = await firstValueFrom(\n    this.httpService.post(\n      'http://localhost:3001/api/some-endpoint',\n    ),\n  );\n  return data; // this is as well Promise<Observable<AxiosResponse>>\n}\n```\n\n```text\n@Post()\nasync someRequestName() {\n  const data = await firstValueFrom(\n    this.httpService.post(\n      'http://localhost:3001/api/some-endpoint',\n    ),\n  );\n  return data.data; // this is JSON response\n}\n```\n\n```text\ndata.data\n```\n\n```text\nfor (const record of records) {\n     const { createdAt } = record;\n     const dateOnly = createdAt.toISOString().split('T')[0]\n     if (!organizedData[`${dateOnly}`]) {\n         organizedData[`${dateOnly}`] = [];\n         }\n     const joinedData = { ...record }; //<<< This is causing error for me>>>\n     organizedData[`${dateOnly}`].push(joinedData);\n}\n```\n\n```js\nreturn {\n    log,\n    db,\n    notifications,\n    crons,\n    scheduler,\n    storage,\n    env: ENV,\n    services,\n    toJSON() {\n      return \"Ctx\";\n    }\n  };\n```\n\n```text\nJSON.stringify\n```\n\n```text\ntoJSON\n```\n\n========================================\n\nComments:\n- I faced the same siily mistake.. you probably want to do this `this.ssoContent = response.data`\n- No problem. If you will struggle more. Let us know, and we will try to help you! :)\n- alr use flatted package but still not solve\n- Thanks man simple but notable\n- Async await has nothing to do with the circular dependency. It is more of a mechanism to return promises. Whereas circular dependency is caused by returning the entire response object inside an HTTP response again. Hence we just extract the data object from the response and return it, to avoid the circular dependency.\n- You need to it helps others. just returning data actually works\n- This should be the absolute worst-case solution; it's best to solve the original cause.","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":312,"estimatedTokens":2099}}15{"id":"stack-60306654","source":"stackoverflow","questionId":60306654,"title":"How to copy non-ts files to dist when building typescript?","tags":["typescript","build","nestjs"],"text":"Title: How to copy non-ts files to dist when building typescript?\nTags: typescript, build, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have Mail module in folder with this structure:\n\n```\n- Mail\n - templates\n - \n - mail.module.ts\n```\n\nWhen I build (compile) TypeScript project, my `template` folder is not included in `build` folder.\nHow to move those kind of files into `dist` when building?\n\nIs it different for development vs production builds?\n\n========================================\n\nTop Answer:\nTS compiler doesn't handle files that are other than TypeScript or JS (e.g. `.ts`, `.js`, `.tsx`, etc.).\n\nOne way of doing it, just running `cp` to copy those files after you compile NestJS. In your `package.json` replace the line \n\n```\n\"build\": \"nest build\",\n```\n\nwith \n\n```\n\"build\": \"nest build && cp ./Mail/templates ./build\",\n```\n\nIdeally, I would switch to Webpack (or similar) to transpile TypeScript and copy artifacts. NestJs has a basic example on how to build with Webpack here. To extend it to have a \"copy\" phase, install `copy-webpack-plugin` npm package and add those additions in webpack config file:\n\n```\nconst copyFiles = require('copy-webpack-plugin');\n// ... omitted for abbreviation\n\nmodule.exports = function(options) {\n return {\n // ... omitted for abbreviation\n ,\n plugins: [\n // ... omitted for abbreviation\n new copyFiles([\n { from: 'Mail/templates', to: 'templates' }\n ])\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n- Mail\n  - templates\n      - <Handlebars files>\n  - mail.module.ts\n```\n\n```text\ntemplate\n```\n\n```text\nbuild\n```\n\n```text\ndist\n```\n\n```text\n\"assets\":[\"**/Mail/templates/*\"]\n```\n\n```text\n\"assets\":[\"**/*.template\"]\n```\n\n```js\n\"build\": \"nest build\",\n```\n\n```js\n\"build\": \"nest build && cp ./Mail/templates ./build\",\n```\n\n```js\nconst copyFiles = require('copy-webpack-plugin');\n// ... omitted for abbreviation\n\nmodule.exports = function(options) {\n   return {\n   // ... omitted for abbreviation\n   ,\n    plugins: [\n      // ... omitted for abbreviation\n      new copyFiles([\n            { from: 'Mail/templates', to: 'templates' }\n        ])\n    ]\n}\n```\n\n```text\n.ts\n```\n\n```text\n.js\n```\n\n```text\n.tsx\n```\n\n```text\ncp\n```\n\n```text\npackage.json\n```\n\n```text\ncopy-webpack-plugin\n```\n\n```text\nnpm install --save-dev copyfiles\n```\n\n```text\n\"postbundle\": \"copyfiles -u 1 src/**/*.template dist/\"\n```\n\n```text\n\"bundle\": \"tsc\"\n```\n\n```sh\n# Copy\n$ tscp\n\n# Copy for TS project references\n$ tscp -b\n\n# Watcher\n$ tscp -w\n\n# Watcher for TS project references\n$ tscp -b -w\n\n# Custom compiler settings\n$ tscp -p tsconfig.production.json\n\n# Help\n$ tscp -h\n```\n\n```text\ntscp\n```\n\n```text\nts-node\n```\n\n```text\nnode\n```\n\n```text\nts-node\n```\n\n```text\njs\n```\n\n```text\nts-node\n```\n\n```text\n\"compilerOptions\": {\n    \"assets\": [\"*.proto\"],\n    \"watchAssets\": true\n  }\n```\n\n```json\n{\n  \"$schema\" : \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\" : \".\",\n  \"compilerOptions\" : {\n    \"assets\" : [\"config.*.yaml\", \"assets/**\"]\n  },\n  \"entryFile\" : \"src/main\"\n}\n```\n\n```text\nsrc\n```\n\n```text\nsrc\n```\n\n```text\nsourceRoot\n```\n\n```text\nentryFile\n```\n\n```text\nnest-cli.json\n```\n\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"assets\": [\"**/*.html\"]\n  }\n}\n```\n\n```text\n\"build\": \"pnpm i && tsc --build && cp public/legal.html dist/legal.html\",\n```\n\n```bash\npnpm add -D rimraf copyfiles\nnpm install --save-dev rimraf copyfiles\nyarn add -D rimraf copyfiles\n```\n\n```json\n\"scripts\": {\n    ...\n    \"clean\": \"rimraf build/\",\n    \"copyfiles\": \"copyfiles -u 1 src/templates/**/* build/\"\n},\n```\n\n```bash\npnpm copy-files\npnpm clean\n```\n\n```json\n\"scripts\": {\n    ...\n    \"clean\": \"rimraf build/\",\n    \"copyfiles\": \"copyfiles -u 1 src/templates/**/* build/\",\n    \"build\": \"pnpm clean && tsc && pnpm copyfiles\"\n}\n```\n\n```text\n\"build\"\n```\n\n```text\n\"dist\"\n```\n\n```text\ntsc\n```\n\n========================================\n\nComments:\n- FYI but cp is not necessarily cross platform compatible.\n- It is not, this is why I thought webpack is a better option\n- just to mention, that `\"assets\":[\"**&#47;Mail&#47;templates&#47;*\"]` should be placed inside `compilerOptions` object\n- It's worth mentioning that `ts-node` should NOT be used in production, at least not without adjusting it. See this: stackoverflow.com/questions/60581617/&hellip;\n- @A-S the link you posted literally says it can be used in production with the --transpile-only flag\n- Some people just like to overcomplicate things that should be simple.\n- @Nando - I already wrote it cannot be used as-is in production, and some steps should be taken (I also included an article about it)... How did your comment add any value, other than rephrasing my comment and demotivating me?\n- Because it actually can be used as-is in production. I have at least one public API using it now, without any compilation folder. The value my comment adds is to point out the distinction between the objective \"can\" and your \"should\".\n- You save me. All solution I tried is wrong except you.","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":295,"estimatedTokens":1260}}16{"id":"stack-57469252","source":"stackoverflow","questionId":57469252,"title":"Is there a recommended way to update NestJS?","tags":["nestjs"],"text":"Title: Is there a recommended way to update NestJS?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm currently using 6.0.4, I'd like to get to 6.5.2. What is the best way to do this? Is there something in the CLI? Do I manually update each @nestjs package?\n\nCurrent dependencies are:\n\n```\n\"@nestjs/common\": \"^6.0.4\",\n \"@nestjs/core\": \"^6.0.4\",\n \"@nestjs/microservices\": \"^6.0.4\",\n \"@nestjs/passport\": \"^6.1.0\",\n \"@nestjs/platform-express\": \"^6.0.4\",\n \"@nestjs/swagger\": \"^3.0.2\",\n```\n\n========================================\n\nTop Answer:\nForce update with the command:\n\n```\nnest update -f -t latest\n\nnest info \n\n_ _ _ ___ _____ _____ _ _____\n| \\ | | | | |_ |/ ___|/ __ \\| | |_ _|\n| \\| | ___ ___ | |_ | |\\ `--. | / \\/| | | |\n| . ` | / _ \\/ __|| __| | | `--. \\| | | | | |\n| |\\ || __/\\__ \\| |_ /\\__/ //\\__/ /| \\__/\\| |_____| |_\n\\_| \\_/ \\___||___/ \\__|\\____/ \\____/ \\____/\\_____/\\___/\n\n[System Information]\nOS Version : macOS Catalina\nNodeJS Version : v12.16.1\nNPM Version : 6.13.4\n[Nest Information]\nplatform-express version : 7.4.2\nmicroservices version : 7.4.2\ncommon version : 7.4.2\ncore version : 7.4.2\n```\n\nYou can check at this post\n\nNest Docs: nest update\n\n========================================\n\nCode:\n```text\n\"@nestjs/common\": \"^6.0.4\",\n    \"@nestjs/core\": \"^6.0.4\",\n    \"@nestjs/microservices\": \"^6.0.4\",\n    \"@nestjs/passport\": \"^6.1.0\",\n    \"@nestjs/platform-express\": \"^6.0.4\",\n    \"@nestjs/swagger\": \"^3.0.2\",\n```\n\n```text\n$ npm install -g @nestjs/cli\n$ nest update\n```\n\n```text\nnest update --force\n```\n\n```text\n$ nest u\n```\n\n```text\n--force\n```\n\n```text\nupdate\n```\n\n```text\nnpm i @nestjs/common@latest @nestjs/core@latest ...\n```\n\n```text\nfeature/upgrade\n```\n\n```text\nnest update -f -t latest\n\nnest info \n\n\n\n_   _             _      ___  _____  _____  _     _____\n| \\ | |           | |    |_  |/  ___|/  __ \\| |   |_   _|\n|  \\| |  ___  ___ | |_     | |\\ `--. | /  \\/| |     | |\n| . ` | / _ \\/ __|| __|    | | `--. \\| |    | |     | |\n| |\\  ||  __/\\__ \\| |_ /\\__/ //\\__/ /| \\__/\\| |_____| |_\n\\_| \\_/ \\___||___/ \\__|\\____/ \\____/  \\____/\\_____/\\___/\n\n\n[System Information]\nOS Version     : macOS Catalina\nNodeJS Version : v12.16.1\nNPM Version    : 6.13.4\n[Nest Information]\nplatform-express version : 7.4.2\nmicroservices version    : 7.4.2\ncommon version           : 7.4.2\ncore version             : 7.4.2\n```\n\n```text\nnpx nest update -f\n```\n\n```text\nnpm install -g @nestjs/cli\nnpx npm-check-updates \"/nestjs*/\" -u\n```\n\n```text\nnpm-check\n```\n\n```text\nnpm-check -u\n```\n\n```text\n$ npm install -g @nestjs/cli\n$ ncu -u\n$ npm i\n```\n\n```text\nnpm i npm-check-updates\n```\n\n```text\nnpx ncu -u -f \"/nestjs*/\"\n```\n\n```text\nnpm install\n```\n\n```text\nnpm i @nestjs/config\n\nnpm i @nestjs/jwt\n\nnpm i @nestjs/platform-express\n\nnpm i @nestjs/core\n\nnpm i @nestjs/common\n\nnpm i @nestjs/typeorm --force\n```\n\n```text\nyarn add npm-check-updates\n```\n\n```text\nyarn npm-check-updates -u -f \"/nestjs*/\"\n```\n\n```text\nyarn\n```\n\n```text\nnest update\n```\n\n```text\nnpm-check-updates\n```\n\n```text\nnpm-check-updates\n```\n\n```text\nnestjs\n```\n\n```text\npackage.json\n```\n\n```text\nCannot find module...\n```\n\n```text\nnpm-check-updates\n```\n\n```text\nnpm cache clean --force\nnvm i 16.13.0\nnvm use default 16.13.0\nnpm i -g npm-check-updates\nncu -u\nnpm i\n```\n\n```text\nyarn\n```\n\n```text\nyarn add npm-check-updates\n```\n\n```text\nncu u\n```\n\n```text\nnpm i -g npm-check-updates\nncu -u -f /^@nestjs/\n```\n\n```text\nrm package-lock.json\nrm -rf node_modules\nnpm install\n```\n\n```text\nnpx npm-check-updates -i\n```\n\n========================================\n\nComments:\n- This didnt do anything for me (had 6.x and wanted 7.x) but `nest update --force` does an **upgrade**.\n- I had an old version of the cli installed - had to upgrade that by rerunning `npm install -g @nestjs&#47;cli` before nest update would work properly\n- doesnt work. Just sits there saying installation in progress.\n- If you are here, to upgrade nestjs9, use `ncu` because `nest update` is deprecated in nestjs9.\n- just reporting that I used it to upgrade nest 8 to 9 and worked fine.\n- @BrunoLamps impossible, in nest9 nest update is deprecated.\n- But if you try to upgrade nest 8, the command will be there, right? I did it last month &#175;_(ใƒ„)_/&#175;\n- This suggestion can fix the same problem on my machine.","metadata":{"transformedAt":"2026-08-18T18:33:02.396Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":253,"estimatedTokens":1060}}17{"id":"stack-54081720","source":"stackoverflow","questionId":54081720,"title":"How to use Nest.js's @Headers properly?","tags":["node.js","http-headers","nestjs"],"text":"Title: How to use Nest.js's @Headers properly?\nTags: node.js, http-headers, nestjs\nSource: Stack Overflow\n\nQuestion:\nAccording to the controller docs I can use `@Headers(param?: string)` or `req.headers` or `req.headers[param]` to get header value. I tried the first approach, I have following in my request headers from Postman\n\n```\nContent-Type:application/json\nMy-Id:test12345\n```\n\nI have following controller sample code\n\n```\n@Put('/aa/:aa/bb/:bb/')\n@UsePipes(new ValidationPipe({ transform: true }))\npublic async DoMyJob(@Body() request: MyRequestDto,\n @Param('aa') aa: number,\n @Param('bb') bb: string,\n @Headers('My-Id') id: string): Promise {\n // More code here\n}\n```\n\nWhen I set break point to inspect the value from `My-Id` header it is undefined.\n\nSo how shall I do in Nest.Js properly to get the header value from RESTful service client?\n\n========================================\n\nTop Answer:\nImplementation of @Headers decorator. This can help you to create your own custom decorators:\n\n```\nimport { IncomingMessage } from 'http';\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nconst Header = createParamDecorator((name: string, ctx: ExecutionContext): string | undefined => {\n const req = ctx.switchToHttp().getRequest();\n const { headers } = req;\n\n return headers[name] as string;\n});\n```\n\nIf you want to create a custom decorator based on Headers:\n\n```\nconst IsMobileClient = createParamDecorator((_: never, ctx: ExecutionContext): boolean => {\n const req = ctx.switchToHttp().getRequest();\n const isMobile = req.headers['user-agent']?.toLowerCase().includes('mobi');\n\n return Boolean(isMobile);\n});\n```\n\nAnd usage example:\n\n```\n@Get()\npublic async yourRequest(\n @Headers('cookie') cookie?: string,\n @IsMobileClient() isMobile: boolean,\n): Promise {\n console.log(cookie, isMobile);\n // ...other code\n}\n```\n\n========================================\n\nCode:\n```text\nContent-Type:application/json\nMy-Id:test12345\n```\n\n```text\n@Put('/aa/:aa/bb/:bb/')\n@UsePipes(new ValidationPipe({ transform: true }))\npublic async DoMyJob(@Body() request: MyRequestDto,\n                                @Param('aa') aa: number,\n                                @Param('bb') bb: string,\n                                @Headers('My-Id') id: string): Promise<MyResponseDto> {\n    // More code here\n}\n```\n\n```text\n@Headers(param?: string)\n```\n\n```text\nreq.headers\n```\n\n```text\nreq.headers[param]\n```\n\n```text\nMy-Id\n```\n\n```text\nimport { Headers } from '@nestjs/common';\n...\n@Put('/')\npublic async put(@Headers() headers) {\n    console.log(headers);\n}\n```\n\n```text\n@Headers('my-id')\n```\n\n```text\nheaders\n```\n\n```text\nreq.headers\n```\n\n```text\nimport { IncomingMessage } from 'http';\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nconst Header = createParamDecorator((name: string, ctx: ExecutionContext): string | undefined => {\n    const req = ctx.switchToHttp().getRequest<IncomingMessage>();\n    const { headers } = req;\n\n    return headers[name] as string;\n});\n```\n\n```text\nconst IsMobileClient = createParamDecorator((_: never, ctx: ExecutionContext): boolean => {\n    const req = ctx.switchToHttp().getRequest<IncomingMessage>();\n    const isMobile = req.headers['user-agent']?.toLowerCase().includes('mobi');\n\n    return Boolean(isMobile);\n});\n```\n\n```text\n@Get()\npublic async yourRequest(\n    @Headers('cookie') cookie?: string,\n    @IsMobileClient() isMobile: boolean,\n): Promise<any> {\n    console.log(cookie, isMobile);\n    // ...other code\n}\n```\n\n========================================\n\nComments:\n- Also valid - extracting a single header: `@Headers(\"x-something\") something?: string` (typescript example)\n- I was trying to use `return headers[someString] as string`, but I can't send it to the api. Can you explain how you send a header like this from postman?","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":163,"estimatedTokens":955}}18{"id":"stack-54979729","source":"stackoverflow","questionId":54979729,"title":"Howto get req.user in services in Nest JS","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Howto get req.user in services in Nest JS\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn a controller, I add the user object with a guard, inject some service and call that service to get some response. I have removed a lot of code for brevity.\n\n```\n@Controller()\n@UseGuards(AuthGuard())\nexport class UserController() {\n constructor(private readonly userService: UsersService) {\n }\n\n @Get(':id')\n async findOne(@Param('id') id) {\n return await this.userService.findOne(id);\n }\n}\n```\n\nSince I have the `AuthGuard`, I now know the user is logged in before entering `:id` route.\n\nIn the service I would do something like\n\n```\n@Injectable()\nexport class UsersService {\n async findOne(id: number): Promise {\n return await this.usersRepository.findOne({where: {id: id}});\n }\n}\n```\n\nBut of course we want to have some checks that the logged in user has access to the user it is querying. The question is now how do I get the current logged in user. I can send it as a parameter from the controller, but since a lot of the backend would need security checked on the current user, I'm not sure that is a good idea.\n\n```\n@Get(':id')\nasync findOne(@Param('id') id, @Req() req: any) {\n return await this.userService.findOne(id, req.user);\n}\n```\n\nIdeally, which doesn't work, I would be able to get it in the UserService:\n\n```\nasync findOne(id: number, @Req req: any): Promise {\n if (id === req.user.id || req.user.roles.contains('ADMIN')) {\n return await this.userRepository.findOne({where: {id: id}});\n }\n}\n```\n\nOr perhaps through injection in the `UserService` constructor\n\n```\nconstructor(@Inject(REQUEST_OBJECT) private readonly req: any) {}\n```\n\nSo, is there a better way to send the user object through the backend than always sending the request object in each function call?\n\n========================================\n\nTop Answer:\n@Injectable({ scope: Scope.REQUEST }) worked for me, but I had a lot\nof problems when need inject on anothers services.\n\nExist a another alternative:\n\nhttps://github.com/abonifacio/nestjs-request-context\n\nFor while its ok.\n\nInject(REQUEST) doesn't work with any passport strategy due to its global state - issue. https://github.com/abonifacio/nestjs-request-context works fine.\n\n========================================\n\nCode:\n```text\n@Controller()\n@UseGuards(AuthGuard())\nexport class UserController() {\n   constructor(private readonly userService: UsersService) {\n   }\n\n   @Get(':id')\n   async findOne(@Param('id') id) {\n      return await this.userService.findOne(id);\n   }\n}\n```\n\n```text\n@Injectable()\nexport class UsersService {\n   async findOne(id: number): Promise<User> {\n      return await this.usersRepository.findOne({where: {id: id}});\n   }\n}\n```\n\n```text\n@Get(':id')\nasync findOne(@Param('id') id, @Req() req: any) {\n   return await this.userService.findOne(id, req.user);\n}\n```\n\n```text\nasync findOne(id: number, @Req req: any): Promise<User> {\n   if (id === req.user.id || req.user.roles.contains('ADMIN')) {\n      return await this.userRepository.findOne({where: {id: id}});\n   }\n}\n```\n\n```text\nconstructor(@Inject(REQUEST_OBJECT) private readonly req: any) {}\n```\n\n```text\nAuthGuard\n```\n\n```text\n:id\n```\n\n```text\nUserService\n```\n\n```text\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class UsersService {\n  constructor(@Inject(REQUEST) private readonly request: Request) {}\n}\n```\n\n```text\nexport const User = createParamDecorator((data, req) => {\n  return req.user;\n});\n```\n\n```text\n@UseGuards(AuthGuard()) \n@Get(':id')\nasync findOne(@Param('id') id, @User() user) {\n   return await this.userService.findOne(id, user);\n}\n```\n\n```text\nrequest\n```\n\n```text\n@User\n```\n\n```text\nRolesGuard\n```\n\n========================================\n\nComments:\n- I still have to send the user object to the services. Since most of the logic resides inside services, this seems like a bad idea. I already have RolesGuard but removed it from the examples since it isn't a solution. Let's say I should only be able to see one group of data inside the database. The entry point in the controller will be the same, but the service should filter out the data. Then again I have to send the user from the controller to the service.\n- The roles guard of course is only a solution if you want to restrict the access completely. Sometimes it might make to have different routes with different access levels. But if the logic is complex and lies in the service then of course the service needs all the required data to get passed in. (It is better to use a decorator than to pass in the request object, since otherwise interceptors, error filters won't be called.) As I wrote, this might change in version 6 but I don't know the details, yet.\n- Hehe, the downvote was before I saw the \"Not possible\". I think you edited the post and added that after I voted :) Well, I agree on the decorator, actually I already use that. But it seems a bit strange that this isn't supported. All backends I create will have groups of users where the backend will respond differently on each user. I don't see this as complex, but a normal backend task. So most of the service calls will need the user to validate what it should return.\n- I have tried your solution of V6. And command shows error `ReferenceError: Request is not defined`. I did `import { REQUEST } from '@nestjs&#47;core';`\n- @Eve Are you using a request-scoped provider?\n- For anyone getting an error about request, make sure you have `import { Request } from 'express';` in your imports. By default `Request` is available as a type in `lib.d.ts` so doesn't work properly.\n- Be careful, as per official docs, the request-scoped providers will have an impact on application performance. You can read also this testimonial.\n- Does it work with graphql too?\n- I have tried your solution for V6. `this.request.user` returns a useless object `{ username: undefined; userId: undefined }`.\n- In my service, I'm using the onModuleInit to add intercepts to my axios. In these interceptors, I need the user info. How can I accomplish that using the custom decorator approach?\n- Is that package still working for you? I have the same issue and need a solution.\n- Is that package still working for you? I have the same issue and need a solution.","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":183,"estimatedTokens":1579}}19{"id":"stack-62696628","source":"stackoverflow","questionId":62696628,"title":"How can I create columns with type Date and type DateTime in nestjs with typeORM?","tags":["mysql","date","orm","nestjs","typeorm"],"text":"Title: How can I create columns with type Date and type DateTime in nestjs with typeORM?\nTags: mysql, date, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am new with nestjs. How can I set columns that accepts Date format and dateTime format?\n\nNot in both cases, the columns are two differents column, one accept Date and other dateTime.\n\n========================================\n\nTop Answer:\nHow about ?\n\n```\n@CreateDateColumn()\ncreated_at: Date;\n \n@UpdateDateColumn()\nupdated_at: Date;\n```\n\nEDIT\n\nYou can find more info here\n\n========================================\n\nCode:\n```text\n@Column({ type: 'date' })\ndate_only: string;\n\n@Column({ type: 'timestamptz' }) // Recommended\ndate_time_with_timezone: Date;\n\n@Column({ type: 'timestamp' }) // Not recommended\ndate_time_without_timezone: Date;\n```\n\n```text\n@CreateDateColumn()\ncreated_at: Date; // Creation date\n\n@UpdateDateColumn()\nupdated_at: Date; // Last updated date\n\n@DeleteDateColumn()\ndeleted_at: Date; // Deletion date\n```\n\n```text\ndate_only\n```\n\n```text\n@CreateDateColumn()\n```\n\n```text\n@UpdateDateColumn()\n```\n\n```text\n@DeleteDateColumn()\n```\n\n```text\n@CreateDateColumn()\ncreated_at: Date;\n    \n@UpdateDateColumn()\nupdated_at: Date;\n```\n\n```js\n/**\n   * Start DateTime\n   */\n  @Column({\n    type: 'datetime',\n    default: () => 'NOW()',\n  })\n  @Index()\n  start: string;\n\n  /**\n   * End DateTime\n   */\n  @Column({\n    type: 'datetime',\n    nullable: true,\n  })\n  @Index()\n  end: string;\n```\n\n```text\n@CreateDateColumn()\n```\n\n```text\n@UpdateDateColumn()\n```\n\n```text\n@CreateDateColumn({ name: 'created_at'})\ncreatedAt: Date;\n\n@UpdateDateColumn({ name: 'updated_at' })\nupdatedAt: Date;\n\n@DeleteDateColumn({ name: 'deleted_at' })\ndeletedAt: Date;\n```\n\n```text\nclass SomeEntity {\n\n    @Column({\n        name: 'created_at',\n        type: 'timestamptz',\n    })\n    createdAt?: Date;\n\n    @Column({\n        name: 'updated_at',\n        type: 'timestamptz',\n    })\n    updatedAt?: Date;\n\n    @BeforeInsert()\n    protected setCreatedAt(): void {\n        this.createdAt = new Date();\n    }\n\n    @BeforeUpdate()\n    protected setUpdatedAt(): void {\n        this.updatedAt = new Date();\n    }\n}\n```\n\n========================================\n\nComments:\n- This answer is not correct. The type returned by typeorm for `type: 'date'` is a string - not a date object with the time set to 0. See github.com/typeorm/typeorm/issues/2176\n- @sarfata I've updated my answer. Let me know what you think!\n- @CarloCorradini awesome! I like that you clearly recommend `timestamptz` too ;)\n- would timestamp be ok when using mysql? as timestamptz is not supported?\n- Ok, but how to use \"timestamptz\" with GraphQL? What should I use inside ObjectType and InputType to fix the issue with the wrong DateTime types?\n- @EugeneZalivadnyi I use GraphQL Scalars library with a date/time scalar mapping. E.g. `GraphQLTimestamp` for UNIX epoch or `GraphQLDateTime` for UTC. You decide what best suits your needs since the input given to the scalar is always a `Date` instance (`timestamptz`).\n- @CarloCorradini any reason why \"timestamptz\" is recommended over \"timestamp\"?\n- @bilard See stackoverflow.com/a/22925669/6676781\n- Anyone who comes here and doesn't find how to include the columns stackoverflow.com/questions/64941148/&hellip;\n- This should be the correct answer, simple and handled automatically by typeorm on save.\n- I don't believe this should be the correct answer, or upvoted as it is. There are more uses for timestamp columns than just created_at and updated_at values\n- @Eazash that's why I provided a link to the rest of the docs :D\n- Does this mean that `start` and `end` are of type `string` and not `Date`?\n- No, they are `type: 'datetime'`\n- Yes, that is w.r.t MySQL. I wanted to know about how they would appear in JS.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":162,"estimatedTokens":1004}}20{"id":"stack-53922503","source":"stackoverflow","questionId":53922503,"title":"How to implement pagination in NestJS with TypeORM","tags":["typescript","nestjs","typeorm"],"text":"Title: How to implement pagination in NestJS with TypeORM\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs there any way to get the total count and records with a single query, instead of running it as 2 separate queries?\n\nIf it's not possible, is there any way to reuse the where condition in both queries?\n\n```\nasync findAll(query): Promise {\n const take = query.take || 10\n const skip = query.skip || 0\n const keyword = query.keyword || ''\n\n const builder = this.userRepository.createQueryBuilder(\"user\")\n const total = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).getCount()\n const data = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).orderBy('name', 'DESC').skip(skip).take(take).getMany();\n\n return {\n data: data,\n count: total\n }\n}\n\n{\n count: 10,\n data: [\n {\n id: 1,\n name: 'David'\n },\n {\n id: 2,\n name: 'Alex'\n }]\n}\n```\n\n========================================\n\nTop Answer:\nsumming up...\n\nThis middleware checks if you have the take and skip parameters in the URL, if it does, it converts from string to number, if you don't use the default values. 10 for take and 0 for skip.\n\ntake is the number of results per page and skip, from where it should start reading records.\n\nWith that, I set up to intercept the \"product / paged\" route just for the GET method.\n\nWith this I can retrieve these values in the controller and pass to TypeORM or an SQL query.\n\nhttps://i.sstatic.net/fAZAv.png\n\n```\n@Injectable()\nexport class PagerMiddleware implements NestMiddleware {\n use(req: any, res: any, next: () => void) {\n req.query.take = +req.query.take || 10;\n req.query.skip = +req.query.skip || 0;\n next();\n }\n}\n```\n\n### and apply in module.\n\n```\nexport class AdminFeatureApi implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(PagerMiddleware)\n .forRoutes({ path: 'product/paged', method: RequestMethod.GET })\n }\n}\n```\n\n### Controller\n\n```\n@Controller('product')\nexport class TrainingDomainController {\n constructor(private service: YourService) {}\n\n @Get('paged')\n get(@Query() { take, skip }) {\n return this.service.findAll(take, skip);\n }\n}\n```\n\n### and service\n\n```\n@Injectable()\nexport class YourService {\n constructor(\n @InjectRepository(YourEntity)\n private readonly repo: MongoRepository\n ) {}\n\n async findAll(take: number = 10, skip: number = 0) {\n const [data, total] = await this.repo.findAndCount({ take, skip });\n return { data, total };\n }\n}\n```\n\nok?\n\n========================================\n\nCode:\n```ts\nasync findAll(query): Promise<Paginate> {\n  const take = query.take || 10\n  const skip = query.skip || 0\n  const keyword = query.keyword || ''\n\n  const builder = this.userRepository.createQueryBuilder(\"user\")\n  const total = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).getCount()\n  const data = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).orderBy('name', 'DESC').skip(skip).take(take).getMany();\n\n  return {\n    data: data,\n    count: total\n  }\n}\n\n{\n  count: 10,\n  data: [\n    {\n      id: 1,\n      name: 'David'\n    },\n    {\n      id: 2,\n      name: 'Alex'\n    }]\n}\n```\n\n```text\nasync findAll(query): Promise<Paginate> {\n    const take = query.take || 10\n    const skip = query.skip || 0\n    const keyword = query.keyword || ''\n\n    const [result, total] = await this.userRepository.findAndCount(\n        {\n            where: { name: Like('%' + keyword + '%') }, order: { name: \"DESC\" },\n            take: take,\n            skip: skip\n        }\n    );\n\n    return {\n        data: result,\n        count: total\n    }\n}\n```\n\n```text\ntypeorm\n```\n\n```text\nfindAndCount\n```\n\n```text\nRepository\n```\n\n```text\nasync getPaginatedResults(query: any, transactionManager?: EntityManager): Promise<any> {\n\n}\n```\n\n```text\n@Injectable()\nexport class PagerMiddleware implements NestMiddleware {\n  use(req: any, res: any, next: () => void) {\n    req.query.take = +req.query.take || 10;\n    req.query.skip = +req.query.skip || 0;\n    next();\n  }\n}\n```\n\n```text\nexport class AdminFeatureApi implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(PagerMiddleware)\n    .forRoutes({ path: 'product/paged', method: RequestMethod.GET })\n  }\n}\n```\n\n```text\n@Controller('product')\nexport class TrainingDomainController {\n  constructor(private service: YourService) {}\n\n  @Get('paged')\n  get(@Query() { take, skip }) {\n    return this.service.findAll(take, skip);\n  }\n}\n```\n\n```text\n@Injectable()\nexport class YourService {\n  constructor(\n    @InjectRepository(YourEntity)\n    private readonly repo: MongoRepository<YourEntity>\n  ) {}\n\n  async findAll(take: number = 10, skip: number = 0) {\n    const [data, total] = await this.repo.findAndCount({ take, skip });\n    return { data, total };\n  }\n}\n```\n\n```text\nasync findAll(query): Promise<Paginate> {\n    const take = query.take || 10\n    const page=query.page || 1;\n    const skip= (page-1) * take ;\n    const keyword = query.keyword || ''\n\n    const [result, total] = await this.userRepository.findAndCount(\n        {\n            where: { name: Like('%' + keyword + '%') }, order: { name: \"DESC\" },\n            take: take,\n            skip: skip\n        }\n    );\n\n    return {\n        data: result,\n        count: total\n    }\n}\n```\n\n```text\nasync findAll(query): Promise<Paginate> {\n     const take= query.take || 10\n     const page=query.page || 1;\n     const skip= (page-1) * take ;\n     const keyword = query.keyword || ''\n\n     const data = await this.userRepository.findAndCount(\n         {\n             where: { name: Like('%' + keyword + '%') }, order: { name: \"DESC\" },\n             take: take,\n             skip: skip\n         }\n     );\n     return paginateResponse(data ,page,take)\n\n }\n```\n\n```text\nexport function paginateResponse(data,page,limit) {\n  const [result, total]=data;\n  const lastPage=Math.ceil(total/limit);\n  const nextPage=page+1 >lastPage ? null :page+1;\n  const prevPage=page-1 < 1 ? null :page-1;\n  return {\n    statusCode: 'success',\n    data: [...result],\n    count: total,\n    currentPage: page,\n    nextPage: nextPage,\n    prevPage: prevPage,\n    lastPage: lastPage,\n  }\n}\n```\n\n```text\n/users?page=4&take=3\n```\n\n```text\nconst userRepository = dataSource.getRepository(User);\nconst _take = query.take || 10;\nconst _skip = query.skip || 0;\n```\n\n```text\nconst qb = await dataSource\n    .getRepository(User)\n    .createQueryBuilder(\"user\")\n    .orderBy(\"user.id\", \"DESC\")\n    .take(_take)\n    .skip(_skip);\n\n    const users = await qb.getMany();\n    const total = await qb.getCount();\n```\n\n```text\nconst [users, total]  = await userRepository.findAndCount({\n        order: {\n            id: 'DESC'\n        }\n        skip: _skip,\n        take: _take\n});\n```\n\n========================================\n\nComments:\n- Great example but please add a note that the Like('%' + keyword + '%') will work only on SQL database and not on mongodb.\n- I can't find findAndCount on my model... only find\n- If you want to use the ClassSerializerInterceptor, I made some changes to it so it accepts a return value of type `[Array, number]`. Kind of useful in this context. So you can simply return `getManyAndCount()` and the data will be serialized anyway. Check it out: gist.github.com/ericjeker/08f719aae3b730c820b62136efec9708\n- I am confused. In the docs it says now `findAndCount - Finds entities that match given find options. Also counts all entities that match given conditions, but ignores pagination settings (skip and take options).` Did they change this?\n- OK i figured it out, only the count ignores pagination settings to give total count. Also to everyone trying to use this, in the linked example you definitely want to set skip to be `options.page * options.limit`. Its commented in the linked code and won't give proper result otherwise\n- please describe your answer\n- This middleware checks if you have the take and skip parameters in the URL, if it does, it converts from string to number, if you don't use the default values. 10 for take and 0 for skip. take is the number of results per page and skip, from where it should start reading records. With that, I set up to intercept the \"product / paged\" route just for the GET method. With this I can retrieve these values in the controller and pass to TypeORM or an SQL query.\n- You probably don't need middleware and just perform standard DTOs it's much cleaner.\n- This is a good solution if you want to standardize it throughout the entire app using decorators. Well done\n- This may be too late but we should `parseInt(page)` in `paginateResponse` before dealing with `nextPage` and `prevPage` if we are not parsing it anywhere else.","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":332,"estimatedTokens":2167}}21{"id":"stack-53963007","source":"stackoverflow","questionId":53963007,"title":"Error while running nestjs in production mode, cannot find module","tags":["typescript","nestjs"],"text":"Title: Error while running nestjs in production mode, cannot find module\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have implemented a generic class as below which might be causing the problem, \n\n```\nimport { Logger } from '@nestjs/common';\n import { PaginationOptionsInterface, Pagination } from './paginate';\n import { Repository } from 'typeorm';\n\n export class EntityService {\n private repository: Repository;\n constructor(repository) {\n this.repository = repository;\n }\n\n async getEntityWithPagination(\n options: PaginationOptionsInterface,\n ): Promise> {\n const [results, total] = await this.repository.findAndCount({\n take: options.limit,\n skip: (options.page - 1) * options.limit,\n });\n return new Pagination({ results, total });\n }\n }\n```\n\nand using with other entity services, such as \n\n```\n@Injectable()\n export class CarService extends EntityService {\n constructor(\n @InjectRepository(CarEntity)\n private carRepository: Repository,\n ) {\n super(carRepository);\n }\n```\n\nthe code is working perfectly fine with `npm run start:dev` but throwing below error when trying to run with production `npm run start:prod` \n\n```\ninternal/modules/cjs/loader.js:582\n throw err;\n ^\n\n Error: Cannot find module 'src/shared/entity.service'\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)\n at Function.Module._load (internal/modules/cjs/loader.js:506:25)\n at Module.require (internal/modules/cjs/loader.js:636:17)\n at require (internal/modules/cjs/helpers.js:20:18)\n at Object. (/home/tejas/Code/web/project/dist/car/car.service.js:27:26)\n at Module._compile (internal/modules/cjs/loader.js:688:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n at Module.load (internal/modules/cjs/loader.js:598:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n npm ERR! code ELIFECYCLE\n npm ERR! errno 1\n npm ERR! project@0.0.0 start:prod: `node dist/main.js`\n npm ERR! Exit status 1\n```\n\nI have tried deleting dist folder, but still no luck. I have tried updating packages also, package.json is as follows. I have no clue how to debug this.\n\n```\ndependencies\": {\n \"@nestjs/common\": \"^5.5.0\",\n \"@nestjs/core\": \"^5.5.0\",\n \"@nestjs/jwt\": \"^0.2.1\",\n \"@nestjs/passport\": \"^5.1.0\",\n \"@nestjs/typeorm\": \"^5.2.2\",\n \"bcryptjs\": \"^2.4.3\",\n \"glob\": \"^7.1.3\",\n \"passport\": \"^0.4.0\",\n \"passport-http-bearer\": \"^1.0.1\",\n \"passport-jwt\": \"^4.0.0\",\n \"pg\": \"^7.7.1\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.2.2\",\n \"typeorm\": \"^0.2.9\",\n \"typescript\": \"^3.2.2\"\n },\n \"devDependencies\": {\n \"@nestjs/testing\": \"^5.5.0\",\n \"@types/express\": \"^4.16.0\",\n \"@types/jest\": \"^23.3.1\",\n \"@types/node\": \"^10.12.18\",\n \"@types/supertest\": \"^2.0.7\",\n \"jest\": \"^23.5.0\",\n \"nodemon\": \"^1.18.9\",\n \"prettier\": \"^1.14.2\",\n \"supertest\": \"^3.1.0\",\n \"ts-jest\": \"^23.1.3\",\n \"ts-loader\": \"^4.4.2\",\n \"ts-node\": \"^7.0.1\",\n \"tsconfig-paths\": \"^3.5.0\",\n \"tslint\": \"5.11.0\",\n \"webpack\": \"^4.28.2\",\n \"webpack-cli\": \"^3.1.2\",\n \"webpack-node-externals\": \"^1.7.2\"\n },\n```\n\n========================================\n\nTop Answer:\nDelete the dist directory and run again with:\n`npm run start:dev`\n\n========================================\n\nCode:\n```text\nimport { Logger } from '@nestjs/common';\n    import { PaginationOptionsInterface, Pagination } from './paginate';\n    import { Repository } from 'typeorm';\n\n    export class EntityService<T> {\n      private repository: Repository<T>;\n      constructor(repository) {\n        this.repository = repository;\n      }\n\n      async getEntityWithPagination(\n        options: PaginationOptionsInterface,\n      ): Promise<Pagination<T>> {\n        const [results, total] = await this.repository.findAndCount({\n          take: options.limit,\n          skip: (options.page - 1) * options.limit,\n        });\n        return new Pagination<T>({ results, total });\n      }\n    }\n```\n\n```text\n@Injectable()\n    export class CarService extends EntityService<CarEntity> {\n      constructor(\n        @InjectRepository(CarEntity)\n        private carRepository: Repository<CarEntity>,\n      ) {\n        super(carRepository);\n      }\n```\n\n```text\ninternal/modules/cjs/loader.js:582\n            throw err;\n            ^\n\n        Error: Cannot find module 'src/shared/entity.service'\n            at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)\n            at Function.Module._load (internal/modules/cjs/loader.js:506:25)\n            at Module.require (internal/modules/cjs/loader.js:636:17)\n            at require (internal/modules/cjs/helpers.js:20:18)\n            at Object.<anonymous> (/home/tejas/Code/web/project/dist/car/car.service.js:27:26)\n            at Module._compile (internal/modules/cjs/loader.js:688:30)\n            at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n            at Module.load (internal/modules/cjs/loader.js:598:32)\n            at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n            at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n        npm ERR! code ELIFECYCLE\n        npm ERR! errno 1\n        npm ERR! project@0.0.0 start:prod: `node dist/main.js`\n        npm ERR! Exit status 1\n```\n\n```text\ndependencies\": {\n            \"@nestjs/common\": \"^5.5.0\",\n            \"@nestjs/core\": \"^5.5.0\",\n            \"@nestjs/jwt\": \"^0.2.1\",\n            \"@nestjs/passport\": \"^5.1.0\",\n            \"@nestjs/typeorm\": \"^5.2.2\",\n            \"bcryptjs\": \"^2.4.3\",\n            \"glob\": \"^7.1.3\",\n            \"passport\": \"^0.4.0\",\n            \"passport-http-bearer\": \"^1.0.1\",\n            \"passport-jwt\": \"^4.0.0\",\n            \"pg\": \"^7.7.1\",\n            \"reflect-metadata\": \"^0.1.12\",\n            \"rimraf\": \"^2.6.2\",\n            \"rxjs\": \"^6.2.2\",\n            \"typeorm\": \"^0.2.9\",\n            \"typescript\": \"^3.2.2\"\n        },\n        \"devDependencies\": {\n            \"@nestjs/testing\": \"^5.5.0\",\n            \"@types/express\": \"^4.16.0\",\n            \"@types/jest\": \"^23.3.1\",\n            \"@types/node\": \"^10.12.18\",\n            \"@types/supertest\": \"^2.0.7\",\n            \"jest\": \"^23.5.0\",\n            \"nodemon\": \"^1.18.9\",\n            \"prettier\": \"^1.14.2\",\n            \"supertest\": \"^3.1.0\",\n            \"ts-jest\": \"^23.1.3\",\n            \"ts-loader\": \"^4.4.2\",\n            \"ts-node\": \"^7.0.1\",\n            \"tsconfig-paths\": \"^3.5.0\",\n            \"tslint\": \"5.11.0\",\n            \"webpack\": \"^4.28.2\",\n            \"webpack-cli\": \"^3.1.2\",\n            \"webpack-node-externals\": \"^1.7.2\"\n        },\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nnpm run start:prod\n```\n\n```text\nimport { EntityService } from '../shared/service-common'; //correct way\n\nimport { EntityService } from 'src/shared/service-common'; // wrong autoimport\n```\n\n```text\n\"typescript.preferences.importModuleSpecifier\": \"relative\"\n```\n\n```js\nimport { SomeClass } from './Some.class';\n```\n\n```text\nsome.class.ts\n```\n\n```text\nKey-store.entity.ts -> key-store.entity.ts\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nnoEmit\n```\n\n```text\ncompilerOptions\n```\n\n```text\nyarn add @mikro-orm/core @mikro-orm/nestjs\n```\n\n```text\nstart:prod\n```\n\n```text\nnpm run start:prod\n```\n\n```text\ntsconfig.build.tsbuildinfo\n```\n\n```text\n\"start:prod\": \"node dist/src/main\"\n```\n\n```text\ngetElement(svc: TypeA | TypeB) {\n  svc instanceof TypeA\n}\n```\n\n========================================\n\nComments:\n- hello, I want to know why I add ` \"paths\": { \"src/*\": [\"src/*\"] } ` in tsconfig.json also throw error when use absolute import.\n- Would you please explain why is that so? Thank you very much!\n- is there any way that we can use this \"src/..\" path when importing?\n- It's not a good solution, because I want to use `absolute path`.\n- My eyes have glossed over from staring at this too long and I never would have caught this without your suggestionโ€”Thank you!\n- Such a silly thing, but big help! not sure why it even allows this when i use wrong case on local\n- Lots of thanks. Nest is Angular-like, but has some weird problems Angular doesn't have.\n- This doesn't answer the question, as it runs the app in development mode, not in production mode.\n- this fixed it for me, dunno why though\n- that fixed it for me. but why?\n- This fix it for me. Many Thanks, would've spent eternity fixing what is not broken many thanks\n- This solved it for me as well. Thnk you!\n- Why would this help?\n- Yes, this has already been said\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This was my exact problem, and this is valid because files outside of the src folder aren't accounted for by your tsconfig, so moving the seed file from the prisma folder generated by prisma init into my src folder solved the error.","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":301,"estimatedTokens":2224}}22{"id":"stack-55366037","source":"stackoverflow","questionId":55366037,"title":"Inject TypeORM repository into NestJS service for mock data testing","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Inject TypeORM repository into NestJS service for mock data testing\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nThere's a longish discussion about how to do this in this issue.\n\nI've experimented with a number of the proposed solutions but I'm not having much luck.\n\nCould anyone provide a concrete example of how to test a service with an injected repository and mock data?\n\n========================================\n\nTop Answer:\nMy solution uses sqlite memory database where I insert all the needed data and create schema before every test run. So each test counts with the same set of data and you do not have to mock any TypeORM methods:\n\n```\nimport { Test, TestingModule } from \"@nestjs/testing\";\nimport { CompanyInfo } from '../../src/company-info/company-info.entity';\nimport { CompanyInfoService } from \"../../src/company-info/company-info.service\";\nimport { Repository, createConnection, getConnection, getRepository } from \"typeorm\";\nimport { getRepositoryToken } from \"@nestjs/typeorm\";\n\ndescribe('CompanyInfoService', () => {\n let service: CompanyInfoService;\n let repository: Repository;\n let testingModule: TestingModule;\n\n const testConnectionName = 'testConnection';\n\n beforeEach(async () => {\n testingModule = await Test.createTestingModule({\n providers: [\n CompanyInfoService,\n {\n provide: getRepositoryToken(CompanyInfo),\n useClass: Repository,\n },\n ],\n }).compile();\n\n let connection = await createConnection({\n type: \"sqlite\",\n database: \":memory:\",\n dropSchema: true,\n entities: [CompanyInfo],\n synchronize: true,\n logging: false,\n name: testConnectionName\n }); \n\n repository = getRepository(CompanyInfo, testConnectionName);\n service = new CompanyInfoService(repository);\n\n return connection;\n });\n\n afterEach(async () => {\n await getConnection(testConnectionName).close()\n }); \n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n it('should return company info for findOne', async () => {\n // prepare data, insert them to be tested\n const companyInfoData: CompanyInfo = {\n id: 1,\n };\n\n await repository.insert(companyInfoData);\n\n // test data retrieval itself\n expect(await service.findOne()).toEqual(companyInfoData);\n });\n});\n```\n\nI got inspired here: https://gist.github.com/Ciantic/be6a8b8ca27ee15e2223f642b5e01549\n\n========================================\n\nCode:\n```text\nexport class UserService {\n  constructor(@InjectRepository(UserEntity) private userRepository: Repository<UserEntity>) {\n  }\n\n  async findUser(userId: string): Promise<UserEntity> {\n    return this.userRepository.findOne(userId);\n  }\n}\n```\n\n```text\n// @ts-ignore\nexport const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({\n  findOne: jest.fn(entity => entity),\n  // ...\n}));\n```\n\n```text\ndescribe('UserService', () => {\n  let service: UserService;\n  let repositoryMock: MockType<Repository<UserEntity>>;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        UserService,\n        // Provide your mock instead of the actual repository\n        { provide: getRepositoryToken(UserEntity), useFactory: repositoryMockFactory },\n      ],\n    }).compile();\n    service = module.get<UserService>(UserService);\n    repositoryMock = module.get(getRepositoryToken(UserEntity));\n  });\n\n  it('should find a user', async () => {\n    const user = {name: 'Alni', id: '123'};\n    // Now you can control the return value of your mock's methods\n    repositoryMock.findOne.mockReturnValue(user);\n    expect(service.findUser(user.id)).toEqual(user);\n    // And make assertions on how often and with what params your mock's methods are called\n    expect(repositoryMock.findOne).toHaveBeenCalledWith(user.id);\n  });\n});\n```\n\n```text\nexport type MockType<T> = {\n  [P in keyof T]?: jest.Mock<{}>;\n};\n```\n\n```text\nUserRepository\n```\n\n```text\nexport const mockRepository = jest.fn(() => ({\n  metadata: {\n    columns: [],\n    relations: [],\n  },\n}));\n```\n\n```text\nconst module: TestingModule = await Test.createTestingModule({\n      providers: [{ provide: getRepositoryToken(Entity), useClass: mockRepository }],\n    }).compile();\n```\n\n```text\nimport { Test, TestingModule } from \"@nestjs/testing\";\nimport { CompanyInfo } from '../../src/company-info/company-info.entity';\nimport { CompanyInfoService } from \"../../src/company-info/company-info.service\";\nimport { Repository, createConnection, getConnection, getRepository } from \"typeorm\";\nimport { getRepositoryToken } from \"@nestjs/typeorm\";\n\ndescribe('CompanyInfoService', () => {\n  let service: CompanyInfoService;\n  let repository: Repository<CompanyInfo>;\n  let testingModule: TestingModule;\n\n  const testConnectionName = 'testConnection';\n\n  beforeEach(async () => {\n    testingModule = await Test.createTestingModule({\n      providers: [\n        CompanyInfoService,\n        {\n          provide: getRepositoryToken(CompanyInfo),\n          useClass: Repository,\n        },\n      ],\n    }).compile();\n\n    let connection = await createConnection({\n        type: \"sqlite\",\n        database: \":memory:\",\n        dropSchema: true,\n        entities: [CompanyInfo],\n        synchronize: true,\n        logging: false,\n        name: testConnectionName\n    });    \n\n    repository = getRepository(CompanyInfo, testConnectionName);\n    service = new CompanyInfoService(repository);\n\n    return connection;\n  });\n\n  afterEach(async () => {\n    await getConnection(testConnectionName).close()\n  });  \n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n\n  it('should return company info for findOne', async () => {\n    // prepare data, insert them to be tested\n    const companyInfoData: CompanyInfo = {\n      id: 1,\n    };\n\n    await repository.insert(companyInfoData);\n\n    // test data retrieval itself\n    expect(await service.findOne()).toEqual(companyInfoData);\n  });\n});\n```\n\n```text\ndescribe('EmployeesService', () => {\n  let employeesService: EmployeesService;\n  let moduleRef: TestingModule;\n\n  beforeEach(async () => {\n    moduleRef = await Test.createTestingModule({\n      imports: [\n        TypeOrmModule.forRoot({\n          type: 'postgres',\n          url: 'postgres://postgres:@db:5432/test', // read this from env\n          autoLoadEntities: true,\n          synchronize: true,\n          dropSchema: true,\n        }),\n      ],\n      providers: [EmployeesService],\n    }).compile();\n\n    employeesService = moduleRef.get<EmployeesService>(EmployeesService);\n  });\n\n  afterEach(async () => {\n    await moduleRef.close();\n  });\n\n  describe('findOne', () => {\n    it('returns empty array', async () => {\n      expect(await employeesService.findAll()).toStrictEqual([]);\n    });\n  });\n});\n```\n\n```text\ntypeorm@0.3.7\n```\n\n```text\n@nestjs/typeorm@9.0.0\n```\n\n```text\nexport type MockType<T> = {\n    [P in keyof T]?: jest.Mock<unknown>;\n};\n\nexport class MockFactory {\n    static getMock<T>(type: new (...args: any[]) => T, includes?: string[]): MockType<T> {\n        const mock: MockType<T> = {};\n\n        Object.getOwnPropertyNames(type.prototype)\n            .filter((key: string) => key !== 'constructor' && (!includes || includes.includes(key)))\n            .map((key: string) => {\n                mock[key] = jest.fn();\n            });\n\n        return mock;\n    }\n}\n\nconst module: TestingModule = await Test.createTestingModule({\n    providers: [\n        {\n            provide: getRepositoryToken(MyCustomRepository),\n            useValue: MockFactory.getMock(MyCustomRepository)\n        }\n    ]\n}).compile();\n```\n\n```text\nimport { Test } from '@nestjs/testing';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport {\n  Repository,\n  createConnection,\n  getConnection,\n  getRepository,\n  Connection,\n} from 'typeorm';\nimport { Order } from './order';\nimport { OrdersService } from './orders.service';\n\ndescribe('Test Orders', () => {\n  let repository: Repository<Order>;\n  let service: OrdersService;\n  let connection: Connection;\n  beforeEach(async () => {\n    connection = await createConnection({\n      type: 'sqlite',\n      database: './test.db',\n      dropSchema: true,\n      entities: [Order],\n      synchronize: true,\n      logging: true,\n    });\n    repository = getRepository(Order);\n    const testingModule = await Test.createTestingModule({\n      providers: [\n        OrdersService,\n        {\n          provide: getRepositoryToken(Order, connection),\n          useFactory: () => {\n            return repository;\n          },\n        },\n      ],\n    }).compile();\n    console.log('Getting Service from NEST');\n    service = testingModule.get<OrdersService>(OrdersService);\n    return connection;\n  });\n\n  afterEach(async () => {\n    await getConnection().close();\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n\n  it('CRUD Order Test', async () => {\n    const order = new Order();\n    order.currency = 'EURO';\n    order.unitPrice = 12.0;\n    order.issueDate = new Date();\n    const inserted = await service.create(order);\n    console.log('Inserted order ', inserted.id); // id is the @PrimaryGeneratedColumn() key\n    let allOrders = await service.findAll();\n    expect(allOrders.length).toBe(1);\n    await service.delete(inserted.id);\n    allOrders = await service.findAll();\n    expect(allOrders.length).toBe(0);\n  });\n});\n```\n\n```js\ntype ArgsType<T> = T extends (...args: infer A) => unknown ? A : never;\n\nexport type TypedMockType<T> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [P in keyof T]: T[P] extends (...args: any) => unknown\n    ? jest.Mock<ReturnType<T[P]>, ArgsType<T[P]>>\n    : never;\n};\n```\n\n```text\nthis.repository\n  .createQueryBuilder(tableName)\n  .select(\"table_id AS id, name\")\n  .where(`${tableName}.productId='${id}'`)\n  .orWhere(`${tableName}.productNumber='${id}'`)\n  .getRawMany();\n```\n\n```text\ndescribe(\"GET\", () => {\nit(\"should return a record\", async () => {\n  const getRawMany = jest.fn();\n  const orWhere = jest.fn(() => ({ getRawMany }));\n  const where = jest.fn(() => ({ orWhere }));\n  const select = jest.fn(() => ({ where }));\n  spyRepository.createQueryBuilder = jest.fn(() => ({ select }));\n\n  await service.findOneById(productId);\n  expect(spyRepository.createQueryBuilder).toHaveBeenCalledWith(tableName);\n  expect(where).toHaveBeenCalledWith(`${tableName}.productId='${Number(id)}'`);\n  expect(orWhere).toHaveBeenCalledWith(`${tableName}.productNumber='${String(id)}'`);\n});\n```\n\n```text\ncreateQueryBulder\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nexport type MockType<T> = {\n  [P in keyof T]?: jest.Mock<unknown>;\n};\n\nexport function getMock<T>(\n  type: new (...args: any[]) => T,\n  includes?: string[]\n): MockType<T> {\n  const mock: MockType<T> = {};\n  let currentPrototype = type.prototype;\n\n  while (currentPrototype) {\n    Object.getOwnPropertyNames(currentPrototype)\n      .filter((key: string) => {\n        return key !== 'constructor' && (!includes || includes.includes(key));\n      })\n      .forEach((key: string) => {\n        mock[key] = jest.fn();\n      });\n\n    currentPrototype = Object.getPrototypeOf(currentPrototype);\n  }\n\n  Object.getOwnPropertyNames(type.prototype);\n\n  return mock;\n}\n```\n\n```text\nconst repositoryMock = getMock(ExampleRepository, ['find', 'save'])\n```\n\n========================================\n\nComments:\n- What is MockType?\n- @jackabe see the last paragraph. It's a type definition that's supposed to make using jest mocks more comfortable but it has a couple of limitations.\n- In my case, I need to add `await` before `service.findUser(user.id)`\n- It doesnt work for me, i have error on \" TypeError: Right-hand side of 'instanceof' is not an object\" on the line of @InjectRepository(MyEntity)\n- What if someone change the query: `findOne({ id: userId, type: 'admin' })`, so the function could be return null, but the test still pass.\n- Like the approach of having a test DB. this can be further improved.\n- If you want faster tests, you can create the SQLite DB once in `beforeAll`. Duplicate the sqlite database file, and run tests against the copy. Every time you want to reset the database state, delete the copy and copy the original again. It's considerably faster than re-creating the db every time, certainly if you have seed data.\n- i like this but sqlite doesn't support all the datatypes we're using from postgres - so now i'm populating a postgres each time :/\n- @kiloton kiloton, you can also use github.com/oguimbal/pg-mem which is a bit difficult to setup initially but will give you an in-memory postgresql implementation.\n- `autoLoadEntities` didn't work for me, so I used string path. Huge thanx for this easy setup example! It is also possible to create test_db with init migration.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":449,"estimatedTokens":3237}}23{"id":"stack-50808189","source":"stackoverflow","questionId":50808189,"title":"Nest can't resolve dependencies of the PhotoService (?)","tags":["node.js","typescript","nestjs"],"text":"Title: Nest can't resolve dependencies of the PhotoService (?)\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm starting with Nest.js and I'm getting an error after I create a service:\n\nNest can't resolve dependencies of the PhotoService (?). Please verify whether [0] argument is available in the current context.\n\nI'm following the database example: https://docs.nestjs.com/techniques/database\n\nHere is my full code:\nhttps://github.com/marceloHashzen/nestjsbasics\n\n========================================\n\nTop Answer:\nPlease remove any `providers` and `controllers` from `app.module.ts`.\nEven if they were added by the CLI tool.\n\nIn `app.module.ts` you are only supposed to load other modules in the `imports`\n\n```\nimports: [\n WaterModule,\n FireModule,\n AirModule,\n EarthModule,\n]\n```\n\nIs up to each specific module to explicit define what `imports`, `providers` and `exports` can be used.\n\nin: `fire.module.ts`\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([FireRepository])],\n controllers: [FireController],\n providers: [FireService],\n exports: [FireService],\n})\nexport class FireModule {}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  // ...prev code\n  exports: [PhotoService],\n})\n```\n\n```text\napp.module.ts\n```\n\n```text\nPhotoService\n```\n\n```text\nPhotoModule\n```\n\n```text\nPhotoService\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { PhotoController } from './photo.controller';\nimport { PhotoService } from './photo.service';\n\ndescribe('PhotoController', () => {\n  let module: TestingModule;\n  let photoController: PhotoController;\n  let photoService: PhotoService;\n\n  const resultAll = ['test'];\n\n  const mockPhotoService = {\n    findAll: () => (resultAll),\n  };\n\n  const photoServiceProvider = {\n    provide: PhotoService,\n    useValue: mockPhotoService,\n  };\n\n  beforeAll(async () => {\n    module = await Test.createTestingModule({\n      controllers: [PhotoController],\n      providers: [photoServiceProvider],\n    }).compile();\n\n    photoService = module.get<PhotoService>(PhotoService);\n    photoController = module.get<PhotoController>(PhotoController);\n  });\n\n  describe('findAll', () => {\n    it('should return collection of photos', async () => {\n      jest.spyOn(photoService, 'findAll').mockImplementation(() => resultAll);\n\n      expect(await photoController.findAll()).toBe(resultAll);\n    });\n  });\n});\n```\n\n```text\nimports: [\n  WaterModule,\n  FireModule,\n  AirModule,\n  EarthModule,\n]\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([FireRepository])],\n  controllers: [FireController],\n  providers: [FireService],\n  exports: [FireService],\n})\nexport class FireModule {}\n```\n\n```text\nproviders\n```\n\n```text\ncontrollers\n```\n\n```text\napp.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nimports\n```\n\n```text\nimports\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n```text\nfire.module.ts\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { Repository, Connection } from 'typeorm';\nimport { AuthorEntity } from '../entities/AuthorEntity';\n\n@Injectable()\nexport class AuthorsService {\n    usersRepository: Repository<AuthorEntity>;\n\n    constructor(private connection: Connection) {\n        this.usersRepository = connection.getRepository(AuthorEntity);\n    }\n...\n}\n```\n\n```text\n// shared.module.ts\n\nMyServiceOne\nMyServiceTwo\n```\n\n```text\n// my-service-one.service.ts\n\nexport class MyServiceOne {\n  constructor(@InjectModel(MyOne.name) private myOneModel: Model<MyOneModelDocument>,\n    private myServiceTwo: MyServiceTwo) {}\n}\n```\n\n```text\nshared.module.ts\n```\n\n```text\nconstructor\n```\n\n```js\n@Module({\n  imports: [MongooseModule.forFeature([{ name: 'ModelName', schema: ModelNameSchema }])], // <-- THIS WAS MISSING\n  providers: [ModelNameService],\n  controllers: [ModelNameController]\n})\nexport class ModelNameModule {}\n```\n\n```text\nimports\n```\n\n```text\nimport type { MyService } from '../my.service'\n```\n\n```text\nimport { MyService } from '../my.service'\n```\n\n========================================\n\nComments:\n- If you are using Nestjs 5 then check out this issue: github.com/nestjs/nest/issues/723. Add your name if it applies.\n- Hello Preston, I'm not sure if my problem is the same. I started a new project already with Nest 5, and Vladyslav's answer solved my problem.\n- Hello @Vladyslav, this solved my problem! But I'm a little confused of why, the PhotoService was added by the `nest g service` command, I need to always create the services manually and then export them at their own module?\n- I had the similar issue you had and I asked a question, this is the answer - stackoverflow.com/questions/50822301/&hellip; . I think it's the best explanation.\n- Thanks, this helped me a lot!\n- This is not working. I've fetched repository from Marcelo, changed the things and nothing... there has to be another solution\n- Thank you, @VladyslavMoisieienkov. Your answer helped me a lot!\n- it fixed my problem, but now im mad because I've just followed the docs '-'","metadata":{"transformedAt":"2026-08-18T18:33:02.397Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":239,"estimatedTokens":1249}}24{"id":"stack-54802832","source":"stackoverflow","questionId":54802832,"title":"How to protect/require Authentication to access the NestJS Swagger Explorer?","tags":["typescript","swagger-ui","openapi","nestjs"],"text":"Title: How to protect/require Authentication to access the NestJS Swagger Explorer?\nTags: typescript, swagger-ui, openapi, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm currently using Swagger in my NestJS project, and I have the explorer enabled:\n\nin `main.js`\n\n```\nconst options = new DocumentBuilder()\n .setTitle('My App')\n .setSchemes('https')\n .setDescription('My App API documentation')\n .setVersion('1.0')\n .build()\n\nconst document = SwaggerModule.createDocument(app, options)\nSwaggerModule.setup('docs', app, document, {\n customSiteTitle: 'My App documentation',\n})\n```\n\nWith this, the explorer is accessible in `/docs` which is what I expected. But I was wondering if it's possible to add any Authentication layer to the explorer, so only certain requests are accepted.\n\nI want to make this explorer accessible in production, but only for authenticated users.\n\n========================================\n\nTop Answer:\nJust add `.addBearerAuth()` (without any parameters) to your swagger options\n\nand `@ApiBearerAuth()` to your Controller methods\n\n```\nconst options = new DocumentBuilder()\n .setTitle('My App')\n .setSchemes('https')\n .setDescription('My App API documentation')\n .setVersion('1.0')\n .addBearerAuth()\n .build()\n```\n\n========================================\n\nCode:\n```text\nconst options = new DocumentBuilder()\n    .setTitle('My App')\n    .setSchemes('https')\n    .setDescription('My App API documentation')\n    .setVersion('1.0')\n    .build()\n\nconst document = SwaggerModule.createDocument(app, options)\nSwaggerModule.setup('docs', app, document, {\n    customSiteTitle: 'My App documentation',\n})\n```\n\n```text\nmain.js\n```\n\n```text\n/docs\n```\n\n```ts\nimport * as basicAuth from \"express-basic-auth\";\n\n// ...\n\n// Sometime after NestFactory add this to add HTTP Basic Auth\napp.use(\n  // Paths you want to protect with basic auth โ€“ย since Express v5 appending splat is necessary\n  \"/docs*splat\",\n  basicAuth({\n    challenge: true,\n    users: {\n      yourUserName: \"p4ssw0rd\",\n    },\n  })\n);\n\n// Your code\nconst options = new DocumentBuilder()\n  .setTitle(\"My App\")\n  .setSchemes(\"https\")\n  .setDescription(\"My App API documentation\")\n  .setVersion(\"1.0\")\n  .build();\n\nconst document = SwaggerModule.createDocument(app, options);\nSwaggerModule.setup(\n  // Make sure you use the same path just without `/` and `*`\n  \"docs\",\n  app,\n  document,\n  {\n    customSiteTitle: \"My App documentation\",\n  }\n);\n\n// ...\n```\n\n```text\nnpm i express-basic-auth\n```\n\n```text\nmain.{ts,js}\n```\n\n```text\n/docs\n```\n\n```text\n*\n```\n\n```text\n/docs-json\n```\n\n```text\n/docs-json\n```\n\n```text\n/docs\n```\n\n```text\n['/docs', '/docs-json', '/docs-yaml']\n```\n\n```text\n.env\n```\n\n```text\nconst options = new DocumentBuilder()\n.setTitle('Sample Project API')\n.setDescription('This is a sample project to demonstrate auth in Swagger UI')\n.setVersion('1.0')\n.addTag('Nestjs Swagger UI')\n.setContactEmail('your_contact@mail.com')\n.addBearerAuth('Authorization', 'header', 'basic')\n.setBasePath('api')\n.build();\nconst document = SwaggerModule.createDocument(app, options);\nSwaggerModule.setup('docs', app, document);\n```\n\n```text\nbasic\n```\n\n```text\nbearer\n```\n\n```text\napikey\n```\n\n```text\nconst options = new DocumentBuilder()\n.setTitle('My API')\n.setDescription('API used for testing purpose')\n.setVersion('1.0.0')\n.setBasePath('api')\n.addBearerAuth(\n  { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },\n  'access-token',\n)\n.build();\n\nconst document = SwaggerModule.createDocument(app, options);\n```\n\n```text\n@Get('/test')\n@ApiBearerAuth()\n```\n\n```text\ncurl -X GET \"http://localhost:3004/test\" -H \"accept: application/json\" -H \"Authorization: Bearer test-token\"\n```\n\n```text\nDocumentBuilder\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\naccess-token\n```\n\n```text\nconst options = new DocumentBuilder()\n    .setTitle('My App')\n    .setSchemes('https')\n    .setDescription('My App API documentation')\n    .setVersion('1.0')\n    .addBearerAuth()\n    .build()\n```\n\n```text\n.addBearerAuth()\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\nconst options = new DocumentBuilder()\n    .setTitle('Api docs for mobile')\n    .setDescription('The api docs for the mobile application')\n    .setVersion('1.0')\n    .addBearerAuth({ in: 'header', type: 'http' })\n    .build();\n```\n\n```js\naddBearerAuth(options = {\n        type: 'http'\n    }, name = 'bearer') {\n        this.addSecurity(name, Object.assign({ scheme: 'bearer', bearerFormat: 'JWT' }, options));\n        return this;\n    }\n```\n\n```text\n.addBearerAuth({ in: 'header', type: 'http' })\n```\n\n```text\nin\n```\n\n```text\ntype\n```\n\n```text\naddBearerAuth\n```\n\n```text\nconst options = new DocumentBuilder()\n        .setTitle('CMOR')\n        .setDescription('CMOR API documentation')\n        .setVersion('1.0')\n        .addServer('/api')\n        .addApiKey({\n            type: 'apiKey', // this should be apiKey\n            name: 'api-key', // this is the name of the key you expect in header\n            in: 'header',\n        }, 'access-key' // this is the name to show and used in swagger\n        ) \n        .build();\n```\n\n```text\n@ApiTags('analyzer')\n@ApiSecurity('access-key') // this is the name you set in Document builder\n@Controller('analyzer')\nexport class ScreenAnalyzerController {\n```\n\n```text\napiKey\n```\n\n```text\nconst options = new DocumentBuilder()\n        .setTitle('my-title')\n        .setDescription('my-descirption')\n        .setVersion('1.0')\n        .addBearerAuth(\n          {\n            type: 'http',\n            scheme: 'bearer',\n            bearerFormat: 'JWT',\n            name: 'JWT',\n            description: 'Enter JWT token',\n            in: 'header',\n          },\n          'JWT-auth', // This name here is important for matching up with @ApiBearerAuth() in your controller!\n        )\n        .build();\n      const document = SwaggerModule.createDocument(app, options);\n      SwaggerModule.setup('api', app, document);\n```\n\n```text\n@Roles(Role.Admin)\n      @UseGuards(JwtAuthGuard, RolesGuard)\n      @ApiTags('Admin')\n      @ApiOperation({ summary: 'Get admin section' })\n      @Get('admin')\n      @ApiBearerAuth('JWT-auth') // This is the one that needs to match the name in main.ts\n      getAdminArea(@Request() req) {\n        return req.user;\n      }\n```\n\n```text\nconst options = new DocumentBuilder()\n    .setTitle('API')\n    .setDescription('API')\n    .setVersion('1.0')\n    .setSchemes('https', 'http')\n    .addOAuth2('implicit', AUTH_URL, TOKEN_URL)\n    .build();\n\nconst document = SwaggerModule.createDocument(app, options);\n\nSwaggerModule.setup(swaggerPath, app, document, {\n    swaggerOptions: {\n        oauth2RedirectUrl: REDIRECT_URL, // after successfully logging\n        oauth: {\n            clientId: CLIENT_ID,\n        },\n    },\n});\n```\n\n```text\nconst options = new DocumentBuilder()\n    .setTitle('API')\n    .setDescription('API description')\n    .setVersion(version)\n    .addServer(host)\n    .addOAuth2(\n        {\n            type: 'oauth2',\n            flows: {\n                implicit: {\n                    authorizationUrl: AUTH_URL + `?nonce=${getRandomNumber(9)}`, // nonce parameter is required and can be random, for example nonce=123456789\n                    tokenUrl: TOKEN_URL,\n                    scopes: SCOPES, // { profile: 'profile' }\n                },\n            },\n        },\n        'Authentication'\n    )\n    .build();\n\nconst document = SwaggerModule.createDocument(app, options);\n\nSwaggerModule.setup(swaggerPath, app, document, {\n    swaggerOptions: {\n        oauth2RedirectUrl: REDIRECT_URL, // after successfully logging\n        oauth: {\n            clientId: CLIENT_ID,\n        },\n    },\n});\n```\n\n```text\naddApiKey\n```\n\n```text\naddBearerAuth\n```\n\n```text\nconst options = new DocumentBuilder()\n.setTitle('My API')\n.setDescription('My api')\n.setVersion('1.0.0')\n.addBearerAuth(\n  {\n    type: 'http',\n    scheme: 'bearer',\n    bearerFormat: 'JWT',\n    name: 'JWT',\n    description: 'Enter JWT token',\n    in: 'header',\n  },\n  'token'\n)\n.build();\n```\n\n```text\n@Controller('api')\n@ApiBearerAuth('token')\n```\n\n```text\n.addBearerAuth(\n{\n    type: 'http',\n    scheme: 'bearer',\n    bearerFormat: 'JWT',\n    name: 'JWT',\n    description: 'Enter JWT token',\n    in: 'header',\n})\n```\n\n```text\n@ApiBearerAuth('token')\n```\n\n```text\n.addBearerAuth({...}, 'token')\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\nType 'typeof expressBasicAuth' has no call signatures.\n\nType originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead\n```\n\n```text\nimport * as basicAuth from 'express-basic-auth';\n\nasync function bootstrap() {\n\n  app.use(['/docs'], basicAuth.default({\n    challenge: true,\n    users: {\n      [process.env.SWAGGER_USERNAME]: process.env.SWAGGER_PASSWORD,\n    },\n  }));\n\n  const options = new DocumentBuilder()\n      .setTitle('api')\n      .setDescription('API description')\n      .setVersion('1.0')\n      .build();\n  const document = SwaggerModule.createDocument(app, options);\n  SwaggerModule.setup('docs', app, document);\n\n}\n```\n\n```text\nexpress-basic-auth\n```\n\n```text\n.default\n```\n\n```text\nconst config = new DocumentBuilder()\n    .setTitle('App title')\n    .setDescription(\"Api description\")\n    .setVersion('1.0')\n    .addTag('ApiTag')\n    .setContact('name', 'ulr', \"email\")\n    .addBearerAuth({ type: 'http', schema: 'Bearer', bearerFormat: 'Token' } as SecuritySchemeObject, 'Bearer')\n    .build();\n```\n\n```text\n@ApiBearerAuth(\"Bearer\")\n@Controller('posts')\nexport class PostController {\n  constructor(private readonly postService: PostService) { }\n}\n```\n\n```js\nimport basicAuth from \"express-basic-auth\";\nimport { Request } from \"express\";\n\napp.use([\"/\", \"/-json\"], function (req: Request, res, next) {\n  if (req.accepts().includes(\"application/json\")) {\n    next();\n  } else {\n    const auth = basicAuth({\n      challenge: true,\n      users: {\n        [process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,\n      },\n    });\n    auth(req, res, next);\n  }\n});\n```\n\n```text\nSwaggerModule.setup('docs', app, document, {\n    swaggerOptions: {\n        persistAuthorization: true, // this\n    },\n});\n```\n\n```text\n.addBearerAuth()\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\nconst document = SwaggerModule.createDocument(\n      app,\n      new DocumentBuilder()\n        .setTitle('Book store')\n        .setDescription('The Book store API description')\n        .setVersion('1.0')\n        .addBearerAuth(\n          {\n            type: 'http',\n            scheme: 'Bearer',\n            bearerFormat: 'JWT',\n            in: 'header',\n          },\n          'token',\n        )\n        .addSecurityRequirements('token')\n        .build(),\n    );\n\n    // access http://localhost:${PORT}/docs\n    SwaggerModule.setup('docs', app, document);\n    app.use('/apidoc-json/', (req: Request, res: any) => res.send(document));\n```\n\n```text\nconst apiDocumentationCredentials = {\n  name: 'admin',\n  pass: 'admin',\n};\nasync function bootstrap() {\n  const app = await NestFactory.create<INestApplication>(ApplicationModule);\n  const httpAdapter = app.getHttpAdapter();\n  httpAdapter.use('/api-docs', (req, res, next) => {\n    function parseAuthHeader(input: string): { name: string; pass: string } {\n      const [, encodedPart] = input.split(' ');\n      const buff = Buffer.from(encodedPart, 'base64');\n      const text = buff.toString('ascii');\n      const [name, pass] = text.split(':');\n      return { name, pass };\n    }\n    function unauthorizedResponse(): void {\n      if (httpAdapter.getType() === 'fastify') {\n        res.statusCode = 401;\n        res.setHeader('WWW-Authenticate', 'Basic');\n      } else {\n        res.status(401);\n        res.set('WWW-Authenticate', 'Basic');\n      }\n      next();\n    }\n    if (!req.headers.authorization) {\n      return unauthorizedResponse();\n    }\n    const credentials = parseAuthHeader(req.headers.authorization);\n    if (\n      credentials?.name !== apiDocumentationCredentials.name ||\n      credentials?.pass !== apiDocumentationCredentials.pass\n    ) {\n      return unauthorizedResponse();\n    }\n    next();\n  });\n}\n```\n\n```text\n/api-docs\n```\n\n```text\nmain.ts\n```\n\n```text\n.addBearerAuth()\n```\n\n```text\nEmpty Cache and Hard Reload\n```\n\n```text\nctrl+f5\n```\n\n========================================\n\nComments:\n- Most of the time, the way I see this is people pull explorer *out* of their production instance...\n- I would suggest to add a security in your reverse proxy (apache or nginx or varnish etc). Quite easy to add a rule with basic auth or blocking the access for instance. If you really want to manage it within Nest, using a Middleware should do the trick\n- Yeah, I my plan was to use one of the middlewares we have for the application, but maybe move this to a different layer (or even remove from production altogether is the only way) :)\n- @zenbeni I want to do that, however, I can't send authorization headers within iframe src or browser url, how did you solve that?\n- I got an error when specifying \"bearer\" as the authentication-type to the .addBearerAuth method. Turns out if you just don't include the third parameter, it enables bearer authentication. Using the 'basic' value did turn on username/password http auth-\n- they made a huge change on the DocumentBuilder methods and their params, I hope someone makes an example of this changes.\n- Somehow this does not work for me, the header does not get applied to the request - the curl output stays - curl -X GET \"localhost:3000/unit-type\" -H \"accept: */*\"\n- @Jacobdo can you see lock icon on your endpoint in swagger doc? You can click on it and pass the access token, if not then you need to add `@ApiBearerAuth()` in controller function, see updated answer\n- This tells about the security of your endpoints, not the swagger itself.\n- just `.addBearerAuth({ in: 'header', type: 'http' })`\n- The question is about securing access to the swagger page itself, not showing the auth options on routes swagger displays. See my answer for actually securing your `&#47;docs` endpoint with HTTP Basic Auth.\n- I assumed the top level bearer would apply it to everything, but I was wrong -- I guess you really do need it on every controller. Edit: is there any way to persist the authentication between refreshes?\n- Better solution then using @ApiBearerAuth: stackoverflow.com/questions/64269804/&hellip;\n- Ugh, finally. This is the only write-up that actually explained it well enough for my idiot brain to get it. One additional thing that could be added is that `@ApiBearerAuth('JWT-auth')` can be used as a decorator on the entire controller class, too. like `@Controller('users') @ApiBearerAuth('JWT-auth') export class UserController {...}` You can also put `.addSecurityRequirements('JWT-auth')` before `.build()` in the `main.ts` to apply that auth scheme to the whole system.\n- Because there is also a /docs-yaml endpoint I ended up specifying `['&#47;docs*'`]\n- @EamonnGahan From Express v5 onwards you need to use `&#47;docs*splat`, I've updated my answer.\n- I followed this demo with the swagger4 but I'm having an issue with the scopes object, To register the API I used the scopeURL, and when I set only the name like you suggested **profile**, I get an error which says that I can't request this scope\n- Actually, I have not used the scopeURL. I have set the scope as an object like in an example. and there can be added many properties like `{profile: 'profile', email:'email', ...}`. The value of `scopes` can be also an array, like `['profile', 'email', ...]`. But I'm not sure that you can use scopeURL as a value of the `scope` parameter since it can't be a string. You can check the module codes and see that.\n- it'd be even better if it didn't require the `@ApiBearerAuth` decorator on controllers/routes.\n- In Your controller add this @ApiBearerAuth(\"Bearer\")\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- a good solution\n- thanks! After so many trial-error, your way worked!","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":64,"totalLines":630,"estimatedTokens":4024}}25{"id":"stack-49794140","source":"stackoverflow","questionId":49794140,"title":"Connection \"default\" was not found with TypeORM","tags":["node.js","postgresql","typeorm","nestjs"],"text":"Title: Connection \"default\" was not found with TypeORM\nTags: node.js, postgresql, typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use TypeORM with NestJS and I am not able to save properly an entity. \n\nThe connection creation works, postgres is running on 5432 port. Credentials are OK too. \n\nHowever when I need to save a resource with entity.save() I got :\n\n```\nConnection \"default\" was not found.\n\nError\n at new ConnectionNotFoundError (/.../ConnectionNotFoundError.ts:11:22)\n```\n\nI checked the source file of TypeORM ConnectionManager (https://github.com/typeorm/typeorm/blob/master/src/connection/ConnectionManager.ts) but it seems that the first time TypeORM creates connection it attributes \"default\" name if we don't provide one, which is the case for me.\n\nI setup TypeORM with TypeOrmModule as \n\n```\nTypeOrmModule.forRoot({\n type: config.db.type,\n host: config.db.host,\n port: config.db.port,\n username: config.db.user,\n password: config.db.password,\n database: config.db.database,\n entities: [\n __dirname + '/../../dtos/entities/*.entity.js',\n ]\n })\n```\n\nOf course my constants are correct. Any ideas ?\n\n========================================\n\nTop Answer:\nthe upvoted answer is not necessarily correct, if you not specify the connection name it will default to \"default\".\n\n```\nconst manager = getConnectionManager().get('your_orm_name');\nconst repository = manager.getRepository(Model);\n```\n\n========================================\n\nCode:\n```text\nConnection \"default\" was not found.\n\n\nError\n    at new ConnectionNotFoundError (/.../ConnectionNotFoundError.ts:11:22)\n```\n\n```text\nTypeOrmModule.forRoot({\n      type: config.db.type,\n      host: config.db.host,\n      port: config.db.port,\n      username: config.db.user,\n      password: config.db.password,\n      database: config.db.database,\n      entities: [\n        __dirname + '/../../dtos/entities/*.entity.js',\n      ]\n    })\n```\n\n```text\nconst shopkeeperRepository = getRepository(Shopkeeper);\n```\n\n```text\ntypeORM\n```\n\n```text\n@Entity()\n```\n\n```text\nBaseEntity\n```\n\n```text\nconst manager = getConnectionManager().get('your_orm_name');\nconst repository = manager.getRepository<AModel>(Model);\n```\n\n```text\nexport const dbConfig = {\n    name: 'myDB',\n    ...\n}\n\nawait createConnection(dbConfig) // like this\n```\n\n```text\n@Service() // typedi\nexport class Service {\n    constructor(\n        // inject without name -> fallback to default\n        @InjectRepository() private readonly repository\n    ) {}\n}\n```\n\n```text\nname\n```\n\n```text\nmyDB\n```\n\n```text\ndefault\n```\n\n```text\nname\n```\n\n```text\ndefault\n```\n\n```text\ndefault\n```\n\n```text\nname\n```\n\n```text\nmyDB\n```\n\n```text\nInjectRepository\n```\n\n```text\n@InjectRepository('myDB')\n```\n\n```text\nconst router = Router();\n\nrouter.get(\"/\", async function (req: Request, res: Response) {\n  // here we will have logic to return all users\n  const userRepository = getRepository(User);\n  const users = await userRepository.find();\n  res.json(users);\n});\n\nrouter.get(\"/:id\", async function (req: Request, res: Response) {\n  // here we will have logic to return user by id\n  const userRepository = getRepository(User);\n  const results = await userRepository.findOne(req.params.id);\n  return res.send(results);\n});\n```\n\n```text\ngetRepository()\n```\n\n```text\ngetRepository()\n```\n\n```text\nconst userRepo = getConnection(process.env.NODE_ENV).getRepository(User)\n```\n\n```text\nuser.save()\n```\n\n```text\nuserRepo.save(user)\n```\n\n```text\nconst connectionOptions = await getConnectionOptions(process.env.NODE_ENV);\nawait createConnection({...connectionOptions, name:\"default\"});\n```\n\n```text\n[\n{\n    \"name\" : \"development\",\n    \"type\": \"USER\",\n    \"host\": \"localhost\",\n    \"port\": 5432,\n    \"username\": \"postgres\",\n    \"password\": \"PASS\",\n    \"database\": \"YOURDB\"\n},\n{\n    \"name\" : \"test\",\n    \"type\": \"USERTEST\",\n    \"host\": \"localhost\",\n    \"port\": 5432,\n    \"username\": \"postgres\",\n    \"password\": \"PASSTEST\",\n    \"database\": \"YOURDBTEST\"\n}\n]\n```\n\n```text\ngetConnectionOptions\n```\n\n```text\ngetConnectionOptions\n```\n\n```text\normconfig.json\n```\n\n```text\nconnectionOptions\n```\n\n```text\ncreateConnection\n```\n\n```text\nconnectionOptions\n```\n\n```text\nimport { Connection, ConnectionManager, ConnectionOptions, createConnection, getConnectionManager } from 'typeorm';\n\nexport class Database {\n  private connectionManager: ConnectionManager;\n\n  constructor() {\n    this.connectionManager = getConnectionManager();\n  }\n\n  public async getConnection(name: string): Promise<Connection> {\n    const CONNECTION_NAME: string = name;\n    let connection: Connection;\n    const hasConnection = this.connectionManager.has(CONNECTION_NAME);\n    if (hasConnection) {\n      connection = this.connectionManager.get(CONNECTION_NAME);\n      if (!connection.isConnected) {\n        connection = await connection.connect();\n      }\n    } else {\n\n      const connectionOptions: ConnectionOptions = {\n        name: 'default',\n        type: 'mysql',\n        host: 'localhost',\n        port: 3306,\n        username: 'root',\n        password: 'password',\n        database: 'DemoDb',\n        synchronize: false,\n        logging: true,\n        entities: ['src/entities/**/*.js'],\n        migrations: ['src/migration/**/*.js'],\n        subscribers: ['src/subscriber/**/*.js'],\n      };\n      connection = await createConnection(connectionOptions);\n    }\n    return connection;\n  }\n}\n```\n\n```text\nimport {User} from 'src/entities/User.ts';\n    import {Album} from 'src/entities/Album.ts';\n    import {Photos} from 'src/entities/Photos.ts';\n    const connectionOptions: ConnectionOptions = {\n        name: 'default',\n        type: 'mysql',\n        host: 'localhost',\n        port: 3306,\n        username: 'root',\n        password: 'password',\n        database: 'DemoDb',\n        synchronize: false,\n        logging: true,\n        entities: [User, Album, Photos],\n        migrations: ['src/migration/**/*.js'],\n        subscribers: ['src/subscriber/**/*.js'],\n      };\n```\n\n```text\nconst connectionName = 'default';\n  const database = new Database();\n  const dbConn: Connection = await database.getConnection(connectionName);\n  const MspRepository = dbConn.getRepository(Msp);\n  await MspRepository.delete(mspId);\n```\n\n```text\nDatabase\n```\n\n```text\nWindows\n```\n\n```text\nd:/apps/app-name/etc\n```\n\n```text\nD\n```\n\n```text\nD:/apps/app-name/etc\n```\n\n```text\nlerna\n```\n\n```text\nA\n```\n\n```text\nB\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn install\n```\n\n```text\nnpm install\n```\n\n```text\nyarn.lock\n```\n\n```text\ntypeorm\n```\n\n```js\nimport { Connection, getConnectionManager, getConnectionOptions, \n  createConnection, getConnection, QueryRunner } from 'typeorm';\n    \n    async init() {\n    let connection: Connection;\n    let queryRunner: QueryRunner;\n\n     if (!getConnectionManager().has('default')) {\n        const connectionOptions = await getConnectionOptions();\n        connection = await createConnection(connectionOptions);\n      } else {\n        connection = getConnection();\n      }\n\n    queryRunner = connection.createQueryRunner(); \n }\n```\n\n```text\n.has()\n```\n\n```text\ngetConnectionManager()\n```\n\n```js\ncreateConnections([\n  {\n    name: 'default',\n    type: 'mysql',\n    host: 'localhost',\n    port: 3306,\n    username: 'root',\n    password: 'root',\n    database: 'users',\n    entities: [`${__dirname}/entity/*{.js,.ts}`],\n    synchronize: true,\n    logging: true\n  }\n]);\n```\n\n```js\nimport {getConnection} from \"typeorm\";\n\nconst db1Connection = getConnection(\"db1Connection\");\n// you can work with \"db1\" database now...\n```\n\n```text\ndefault\n```\n\n```text\nimport { createConnection } from \"typeorm\";\n\nexport const getDBConnection = async () => {\n  const dbConnection = await createConnection();\n  if (!dbConnection.isConnected) await dbConnection.connect();\n  return dbConnection;\n}\n```\n\n```text\nimport { Router } from 'express';\n\nconst router = Router();\n\n/* ... route configurations ... */\n\nexport default router;\n```\n\n```text\nconst bootstrap = async () => {\n  try {\n    // wait on connection to be established\n    await getDBConnection();\n  } catch (error) {\n    // log error then throw\n    throw error;\n  }\n\n  // create app\n  const app = express();\n\n  // some middleware configuration...\n\n  // now import and setup the router\n  const { default: router } = await import(\"./routers\");\n  app.use(\"/api\", router);\n\n  // some more middleware configuration...\n\n  const server = http.createServer(app);\n  server.listen(3000, () => console.log('app running at port: 3000'));\n};\n\nbootstrap();\n```\n\n```text\nindex\n```\n\n```text\nrouter\n```\n\n```text\ngetRepository\n```\n\n```text\ngetRepository\n```\n\n```text\ndb/index.ts\n```\n\n```text\ngetDBConnection\n```\n\n```text\nrouters/index.ts\n```\n\n```text\napp.ts\n```\n\n```text\nimport { HttpException, Inject, NotFoundException } from \"@nestjs/common\";\nimport { Not } from \"typeorm\";\nimport { Transactional } from \"typeorm-transactional-cls-hooked\";\nimport { TENANT_CONNECTION } from \"../tenant/tenant.module\";\nimport {Feriados} from './feriados.entity';  \n\nexport class FeriadosService {\n   repository: any;\n\nconstructor(\n@Inject(TENANT_CONNECTION) private connection)\n{\n  this.repository = connection.getRepository(Feriados)\n}\n\n@Transactional()\nasync agregar(tablaNueva: Feriados): Promise<Number> {\n  const tablaAGuardar = await this.repository.create(tablaNueva)\n  return await this.guardar(tablaAGuardar)\n}\n\n@Transactional()\nasync actualizar(tablaActualizada: Feriados): Promise<Number>{\n  const tablaAGuardar = await this.repository.merge(tablaActualizada);\n  return await this.guardar(tablaAGuardar)\n}\n\nasync guardar(tabla:Feriados){ \n  await this.repository.save(tabla)\n  return tabla.id \n}\n```\n\n```text\ntypeorm v0.3\n```\n\n```text\nConnection\n```\n\n```text\nDataSource\n```\n\n```text\ngetConnection\n```\n\n```text\nConnection \"default\" was not found\n```\n\n```text\ngetConnection\n```\n\n```text\napp.get(DataSource)\n```\n\n```text\nexport class AppModule {\n    constructor(private dataSource: DataSource) {}\n\n    getDataSource() {\n       return this.dataSource;\n    }\n}\n```\n\n```text\nconst repository = app\n    .get(AppModule)\n    .getDataSource()\n    .getRepository('Entity_name');\n```\n\n========================================\n\nComments:\n- I assume you must provide `entities` to the TypeORM configuration (e.g. `entities: 'src&#47;*&#47;**.entity.ts'`).\n- Yes I have referenced my entities this way : `entities: [ __dirname + '&#47;..&#47;..&#47;dtos&#47;entities&#47;*.entity.js', ]`, I edit my post\n- Not if you're using active record pattern: github.com/typeorm/typeorm/blob/master/docs/&hellip;\n- Ut works fine when I launch it with `ts-node` and starts to fail after transpilation. What do you mean `two can't live together`? Can you elaborate?\n- I have tried that connectionManager but i am getting the same error.\n- Thanks, it works. But calling getRepository in each route is not a good way.\n- If you got this error when using `npm link`, use `npm install $(npm pack | tail -1)` instead. This ensures that only one matching typeorm version is installed in the target project (if the typeorm semver versions match).\n- how can I use `app.get(DataSource)` in my service class?","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":76,"totalLines":590,"estimatedTokens":2763}}26{"id":"stack-55571773","source":"stackoverflow","questionId":55571773,"title":"Validation on optional Parameter using class-validator in nestjs?","tags":["javascript","node.js","validation","nestjs","class-validator"],"text":"Title: Validation on optional Parameter using class-validator in nestjs?\nTags: javascript, node.js, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI want to apply validation on request payload like, there is field name with string type. But name is not compulsory field but if it exist it must execute `@IsNotEmpty()`\n\nI tried something like this\n`@IsNotEmpty() name?: string` // it not considering `?` optional constraint\n\n========================================\n\nTop Answer:\nclass-validator has an `@IsOptional()` validator that you can add on along with any other validators you defined like so:\n\n```\n@IsOptional() @IsNotEmpty() name: string;\n```\n\nThe decorators are commutative so validation doesn't depend on the order of the validators. If the need to validate depends on something other than presence, you can use `@ValidateIf()` which takes a function argument.\n\n========================================\n\nCode:\n```text\n@IsNotEmpty()\n```\n\n```text\n@IsNotEmpty() name?: string\n```\n\n```text\n?\n```\n\n```text\n@IsOptional()\n```\n\n```text\n=== null\n```\n\n```text\n=== undefined\n```\n\n```text\nskipMissingProperties: true\n```\n\n```js\n@IsOptional() @IsNotEmpty() name: string;\n```\n\n```text\n@IsOptional()\n```\n\n```text\n@ValidateIf()\n```\n\n```text\nexport class Post {\n  otherProperty: string;\n\n  @ValidateIf(o => o.otherProperty === 'value')\n  @IsNotEmpty()\n  example: string;\n}\n```\n\n```text\ntrue\n```\n\n```text\no.otherProperty === 'value'\n```\n\n```text\ntrue\n```\n\n```text\n@IsNotEmpty\n```\n\n```text\nimport { IsOptional, ValidateIf, ValidationOptions } from 'class-validator'\n\nexport function IsOptionalNonNullable(data?: {\n  nullable: boolean\n  validationOptions?: ValidationOptions\n}) {\n  const { nullable = false, validationOptions = undefined } = data || {}\n\n  if (nullable) {\n    // IsOptional allows null\n    return IsOptional(validationOptions)\n  }\n\n  return ValidateIf((ob: any, v: any) => {\n    return v !== undefined\n  }, validationOptions)\n}\n\n// Example usage \nexport class SomeUpdateDTO {\n  @IsInt()\n  // Param can be undefined, but not null \n  @IsOptionalNonNullable()\n  nbOfViews?: number\n}\n\n// Example of why IsOptional is a problem\nexport class SomeOtherUpdateDTO {\n  @IsInt()\n  @IsOptional()\n  // Null is not specified, but IsOptional will allow it! \n  // Could end up nulling a required field in the db\n  nbOfViews?: number\n}\n```\n\n```text\nIsOptional()\n```\n\n========================================\n\nComments:\n- Then why null values were not filtered by class-validator while I configure class-validator to do whitelist for me. I mean I expect to have no null/undefined value for any defined property, however I do have. And it was an error prone behavior in my case.\n- Could you give an example on where to put this property in the pipes? Thanks\n- You can apply a validation pipe globally and pass this config as a option to the pipe's constructor. See the docs.\n- well, that's a nice one","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":138,"estimatedTokens":728}}27{"id":"stack-52969037","source":"stackoverflow","questionId":52969037,"title":"Nestjs Dependency Injection and DDD / Clean Architecture","tags":["typescript","dependency-injection","domain-driven-design","nestjs","clean-architecture"],"text":"Title: Nestjs Dependency Injection and DDD / Clean Architecture\nTags: typescript, dependency-injection, domain-driven-design, nestjs, clean-architecture\nSource: Stack Overflow\n\nQuestion:\nI'm experimenting with Nestjs by trying to implement a clean-architecture structure and I'd like to validate my solution because I'm not sure I understand the best way to do it.\nPlease note that the example is almost pseudo-code and a lot of types are missing or generic because they're not the focus of the discussion.\n\nStarting from my domain logic, I might want to implement it in a class like the following:\n\n```\n@Injectable()\nexport class ProfileDomainEntity {\n async addAge(profileId: string, age: number): Promise {\n const profile = await this.profilesRepository.getOne(profileId)\n profile.age = age\n await this.profilesRepository.updateOne(profileId, profile)\n }\n}\n```\n\nHere I need to get access to the `profileRepository`, but following the principles of the clean architecture, I don't want to be bothered with the implementation just now so I write an interface for it:\n\n```\ninterface IProfilesRepository {\n getOne (profileId: string): object\n updateOne (profileId: string, profile: object): bool\n}\n```\n\nThen I inject the dependency in the `ProfileDomainEntity` constructor and I make sure it's gonna the expected interface:\n\n```\nexport class ProfileDomainEntity {\n constructor(\n private readonly profilesRepository: IProfilesRepository\n ){}\n\n async addAge(profileId: string, age: number): Promise {\n const profile = await this.profilesRepository.getOne(profileId)\n profile.age = age\n\n await this.profilesRepository.updateOne(profileId, profile)\n }\n}\n```\n\nAnd then I create a simple in memory implementation that let me run the code:\n\n```\nclass ProfilesRepository implements IProfileRepository {\n private profiles = {}\n\n getOne(profileId: string) {\n return Promise.resolve(this.profiles[profileId])\n }\n\n updateOne(profileId: string, profile: object) {\n this.profiles[profileId] = profile\n return Promise.resolve(true)\n }\n}\n```\n\nNow it's time to wiring everything together by using a module:\n\n```\n@Module({\n providers: [\n ProfileDomainEntity,\n ProfilesRepository\n ]\n})\nexport class ProfilesModule {}\n```\n\nThe problem here is that obviously `ProfileRepository` implements `IProfilesRepository` but it's not `IProfilesRepository` and therefore, as far as I understand, the token is different and Nest is not able to resolve the dependency.\n\nThe only solution that I've found to this is to user a custom provider to manually set the token:\n\n```\n@Module({\n providers: [\n ProfileDomainEntity,\n {\n provide: 'IProfilesRepository',\n useClass: ProfilesRepository\n }\n ]\n})\nexport class ProfilesModule {}\n```\n\nAnd modify the `ProfileDomainEntity` by specifying the token to use with `@Inject`:\n\n```\nexport class ProfileDomainEntity {\n constructor(\n @Inject('IProfilesRepository') private readonly profilesRepository: IProfilesRepository\n ){}\n}\n```\n\nIs this a reasonable approach to use to deal wit all my dependencies or am I completely off-track? \nIs there any better solution?\nI'm new fairly new to all of these things (NestJs, clean architecture/DDD and Typescript as well) so I might be totally wrong here.\n\nThanks\n\n========================================\n\nTop Answer:\nExport a symbol or a string along with your interface with the same name\n\n```\nexport interface IService {\n get(): Promise \n}\n\nexport const IService = Symbol(\"IService\");\n```\n\nNow you can basically use `IService` as both the interface and the dependency token\n\n```\nimport { IService } from '../interfaces/service';\n\n@Injectable()\nexport class ServiceImplementation implements IService { // Used as an interface\n get(): Promise {\n return Promise.resolve(`Hello World`);\n }\n}\n```\n\n```\nimport { IService } from './interfaces/service';\nimport { ServiceImplementation} from './impl/service';\n...\n\n@Module({\n imports: [],\n controllers: [AppController],\n providers: [{\n provide: IService, // Used as a symbol\n useClass: ServiceImplementation\n }],\n})\nexport class AppModule {}\n```\n\n```\nimport { IService } from '../interfaces/service';\n\n@Controller()\nexport class AppController {\n // Used both as interface and symbol\n constructor(@Inject(IService) private readonly service: IService) {}\n\n @Get()\n index(): Promise {\n return this.service.get(); // returns Hello World\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class ProfileDomainEntity {\n  async addAge(profileId: string, age: number): Promise<void> {\n    const profile = await this.profilesRepository.getOne(profileId)\n    profile.age = age\n    await this.profilesRepository.updateOne(profileId, profile)\n  }\n}\n```\n\n```text\ninterface IProfilesRepository {\n  getOne (profileId: string): object\n  updateOne (profileId: string, profile: object): bool\n}\n```\n\n```text\nexport class ProfileDomainEntity {\n  constructor(\n    private readonly profilesRepository: IProfilesRepository\n  ){}\n\n  async addAge(profileId: string, age: number): Promise<void> {\n    const profile = await this.profilesRepository.getOne(profileId)\n    profile.age = age\n\n    await this.profilesRepository.updateOne(profileId, profile)\n  }\n}\n```\n\n```text\nclass ProfilesRepository implements IProfileRepository {\n  private profiles = {}\n\n  getOne(profileId: string) {\n    return Promise.resolve(this.profiles[profileId])\n  }\n\n  updateOne(profileId: string, profile: object) {\n    this.profiles[profileId] = profile\n    return Promise.resolve(true)\n  }\n}\n```\n\n```text\n@Module({\n  providers: [\n    ProfileDomainEntity,\n    ProfilesRepository\n  ]\n})\nexport class ProfilesModule {}\n```\n\n```text\n@Module({\n  providers: [\n    ProfileDomainEntity,\n    {\n      provide: 'IProfilesRepository',\n      useClass: ProfilesRepository\n    }\n  ]\n})\nexport class ProfilesModule {}\n```\n\n```text\nexport class ProfileDomainEntity {\n  constructor(\n    @Inject('IProfilesRepository') private readonly profilesRepository: IProfilesRepository\n  ){}\n}\n```\n\n```text\nprofileRepository\n```\n\n```text\nProfileDomainEntity\n```\n\n```text\nProfileRepository\n```\n\n```text\nIProfilesRepository\n```\n\n```text\nIProfilesRepository\n```\n\n```text\nProfileDomainEntity\n```\n\n```text\n@Inject\n```\n\n```text\n// *** app.module.ts ***\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { AppServiceMock } from './app.service.mock';\n\nprocess.env.NODE_ENV = 'test'; // or 'development'\n\nconst appServiceProvider = {\n  provide: AppService, // or string token 'AppService'\n  useClass: process.env.NODE_ENV === 'test' ? AppServiceMock : AppService,\n};\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [appServiceProvider],\n})\nexport class AppModule {}\n\n// *** app.controller.ts ***\nimport { Get, Controller } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  root(): string {\n    return this.appService.root();\n  }\n}\n```\n\n```text\nAppServiceMock\n```\n\n```text\nAppService\n```\n\n```text\nroot(): string\n```\n\n```js\nexport abstract class IFoo {\n    abstract foo(): string;\n}\n```\n\n```js\nexport class Foo implements IFoo {\n   foo(): string {\n       return \"\"\n   }\n}\n```\n\n```js\nconst fooProvider = {\n    provide: IFoo,\n    useClass: Foo,\n};\n```\n\n```js\nexport class AppController {\n    constructor(private foo: IFoo) {}\n  \n    @Get(\"/\")\n    getRoot() {\n        return this.foo.foo()\n    }\n}\n```\n\n```text\n// injectors.ts\nexport const InjectProfilesRepository = Inject('PROFILES/PROFILE_REPOSITORY');\n\n// profiles.module.ts\n@Module({\n  providers: [\n    ProfileDomainEntity,\n    {\n      provide: 'PROFILES/PROFILE_REPOSITORY',\n      useClass: ProfilesRepository\n    }\n  ]\n})\nexport class ProfilesModule {}\n\n// profile-domain.entity.ts\nexport class ProfileDomainEntity {\n  constructor(\n    @InjectProfilesRepository private readonly profilesRepository: IProfilesRepository\n  ){}\n}\n```\n\n```text\nexport interface IService {\n  get(): Promise<string>  \n}\n\nexport const IService = Symbol(\"IService\");\n```\n\n```text\nimport { IService } from '../interfaces/service';\n\n@Injectable()\nexport class ServiceImplementation implements IService { // Used as an interface\n  get(): Promise<string> {\n    return Promise.resolve(`Hello World`);\n  }\n}\n```\n\n```text\nimport { IService } from './interfaces/service';\nimport { ServiceImplementation} from './impl/service';\n...\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [{\n    provide: IService, // Used as a symbol\n    useClass: ServiceImplementation\n  }],\n})\nexport class AppModule {}\n```\n\n```text\nimport { IService } from '../interfaces/service';\n\n@Controller()\nexport class AppController {\n  // Used both as interface and symbol\n  constructor(@Inject(IService) private readonly service: IService) {}\n\n  @Get()\n  index(): Promise<string> {\n    return this.service.get(); // returns Hello World\n  }\n}\n```\n\n```text\nIService\n```\n\n```text\nexport abstract class MyServiceContract {\n  abstract myFunction(data: any): Promise<void>;\n}\n\n@Injectable()\nexport class MyInjectClass implements MyServiceContract {\n\n  constructor() {}\n\n  async myFunction(data: any): Promise<void> {\n     //some code...\n  }\n}\n```\n\n```text\nproviders: [\n    {\n      provide: MyServiceContract,\n      useClass: MyInjectClass\n    },\n]\n```\n\n```text\n@Injectable()\nexport class MyService {\n  constructor(private readonly myServiceContract: MyServiceContract) {}\n\n  async execute(data: any): Promise<void> {\n    await this.myServiceContract.myFunction(data);\n  }\n}\n```\n\n========================================\n\nComments:\n- any advantage of using abstract classes(+no default functionality) over interface (+ string provider) ? or opposite.\n- Is it OK for `Foo` to only implement `IFoo` without extending it too, provided the abstract class has not shared logic and merely is a inject-via-interface hack in TypeScript?\n- Yes it is OK for you to implement only.\n- any advantage of using abstract classes(+no default functionality) over interface (+ string provider) ? or opposite.\n- in this instance, you will need to use an abstract class to keep it (therefore the reference for the DI) in the JS world, as interface simply aren't transpiled\n- I loved this approach since it keeps the DI clean and the interfaces files are responsible for managing their symbols.\n- For all who were also surprised about a const and an interface with the same name: stackoverflow.com/questions/49798156/&hellip;\n- It seems to me that defining IService as value in providers: [{ provide: IService, // Used as a symbol useClass: ServiceImplementation }], will make compiler upset. I think it should be string otherwise Error: 'IService' only refers to a type, but is being used as a value here\n- I tried adding the interface to one module and exporting it to another. However, NestJS failed to resolve the dependency in that instance. Will this only work for the same module DI?","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":482,"estimatedTokens":2739}}28{"id":"stack-54346465","source":"stackoverflow","questionId":54346465,"title":"Access raw body of Stripe webhook in Nest.js","tags":["node.js","typescript","express","stripe-payments","nestjs"],"text":"Title: Access raw body of Stripe webhook in Nest.js\nTags: node.js, typescript, express, stripe-payments, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to access the raw body of the webhook request from Stripe in my Nest.js application.\n\nFollowing this example, I added the below to the module which has a controller method that is needing the raw body.\n\n```\nfunction addRawBody(req, res, next) {\n req.setEncoding('utf8');\n\n let data = '';\n\n req.on('data', (chunk) => {\n data += chunk;\n });\n\n req.on('end', () => {\n req.rawBody = data;\n\n next();\n });\n}\n\nexport class SubscriptionModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(addRawBody)\n .forRoutes('subscriptions/stripe');\n }\n}\n```\n\nIn the controller I am using `@Req() req`and then `req.rawBody` to get the raw body. I need the raw body because the constructEvent of the Stripe api is using it to verify the request.\n\nThe problem is that the request is stuck. It seems that the req.on is not called either for data nor for the end event. So `next()` is not called in the middleware.\n\nI did also try to use `raw-body` like here but I got pretty much the same result. In that case the req.readable is always false, so I am stuck there as well.\n\nI guess this is an issue with Nest.js but I am not sure...\n\n========================================\n\nTop Answer:\nFor anyone looking for a more elegant solution, turn off the `bodyParser` in `main.ts`. Create two middleware functions, one for `rawbody` and the other for `json-parsed-body`.\n\n**json-body.middleware.ts**\n\n```\nimport type { Request, Response } from 'express';\nimport * as bodyParser from 'body-parser';\nimport { Injectable, NestMiddleware } from '@nestjs/common';\n\n@Injectable()\nexport class JsonBodyMiddleware implements NestMiddleware {\n use(req: Request, res: Response, next: () => any) {\n bodyParser.json()(req, res, next);\n }\n}\n```\n\n**raw-body.middleware.ts**\n\n```\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport * as bodyParser from 'body-parser';\n\n@Injectable()\nexport class RawBodyMiddleware implements NestMiddleware {\n use(req: Request, res: Response, next: () => any) {\n bodyParser.raw({type: '*/*'})(req, res, next);\n }\n}\n```\n\nApply the middleware functions to appropriate routes in `app.module.ts`.\n\n**app.module.ts**\n\n```\n[...]\n\nexport class AppModule implements NestModule {\n public configure(consumer: MiddlewareConsumer): void {\n consumer\n .apply(RawBodyMiddleware)\n .forRoutes({\n path: '/stripe-webhooks',\n method: RequestMethod.POST,\n })\n .apply(JsonBodyMiddleware)\n .forRoutes('*');\n }\n}\n\n[...]\n```\n\nAnd tweak initialization of Nest to turn off bodyParser:\n\n**main.ts**\n\n```\n[...]\n\nconst app = await NestFactory.create(AppModule, { bodyParser: false })\n\n[...]\n```\n\nBTW `req.rawbody` has been removed from `express` long ago.\n\nhttps://github.com/expressjs/express/issues/897\n\n========================================\n\nCode:\n```text\nfunction addRawBody(req, res, next) {\n  req.setEncoding('utf8');\n\n  let data = '';\n\n  req.on('data', (chunk) => {\n    data += chunk;\n  });\n\n  req.on('end', () => {\n    req.rawBody = data;\n\n    next();\n  });\n}\n\nexport class SubscriptionModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(addRawBody)\n      .forRoutes('subscriptions/stripe');\n  }\n}\n```\n\n```text\n@Req() req\n```\n\n```text\nreq.rawBody\n```\n\n```text\nnext()\n```\n\n```text\nraw-body\n```\n\n```text\nconst app = await NestFactory.create(AppModule, {\n        bodyParser: false\n    });\n\n    const rawBodyBuffer = (req, res, buf, encoding) => {\n        if (buf && buf.length) {\n            req.rawBody = buf.toString(encoding || 'utf8');\n        }\n    };\n\n    app.use(bodyParser.urlencoded({verify: rawBodyBuffer, extended: true }));\n    app.use(bodyParser.json({ verify: rawBodyBuffer }));\n```\n\n```text\nconst isVerified = (req) => {\n    const signature = req.headers['x-slack-signature'];\n    const timestamp = req.headers['x-slack-request-timestamp'];\n    const hmac = crypto.createHmac('sha256', 'somekey');\n    const [version, hash] = signature.split('=');\n\n    // Check if the timestamp is too old\n    // tslint:disable-next-line:no-bitwise\n    const fiveMinutesAgo = ~~(Date.now() / 1000) - (60 * 5);\n    if (timestamp < fiveMinutesAgo) { return false; }\n\n    hmac.update(`${version}:${timestamp}:${req.rawBody}`);\n\n    // check that the request signature matches expected value\n    return timingSafeCompare(hmac.digest('hex'), hash);\n};\n\nexport async function slackTokenAuthentication(req, res, next) {\n    if (!isVerified(req)) {\n        next(new HttpException('Not Authorized Slack', HttpStatus.FORBIDDEN));\n    }\n    next();\n}\n```\n\n```js\nconst app = await NestFactory.create(AppModule, { rawBody: true });\n```\n\n```js\n@Post()\n webhook(@Req() req: RawBodyRequest<Request>) { \n  const rawBody = req.rawBody;\n }\n```\n\n```text\nrawBody\n```\n\n```js\nimport type { Request, Response } from 'express';\nimport * as bodyParser from 'body-parser';\nimport { Injectable, NestMiddleware } from '@nestjs/common';\n\n@Injectable()\nexport class JsonBodyMiddleware implements NestMiddleware {\n    use(req: Request, res: Response, next: () => any) {\n        bodyParser.json()(req, res, next);\n    }\n}\n```\n\n```js\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport * as bodyParser from 'body-parser';\n\n@Injectable()\nexport class RawBodyMiddleware implements NestMiddleware {\n    use(req: Request, res: Response, next: () => any) {\n        bodyParser.raw({type: '*/*'})(req, res, next);\n    }\n}\n```\n\n```js\n[...]\n\nexport class AppModule implements NestModule {\n    public configure(consumer: MiddlewareConsumer): void {\n        consumer\n            .apply(RawBodyMiddleware)\n            .forRoutes({\n                path: '/stripe-webhooks',\n                method: RequestMethod.POST,\n            })\n            .apply(JsonBodyMiddleware)\n            .forRoutes('*');\n    }\n}\n\n[...]\n```\n\n```js\n[...]\n\nconst app = await NestFactory.create(AppModule, { bodyParser: false })\n\n[...]\n```\n\n```text\nbodyParser\n```\n\n```text\nmain.ts\n```\n\n```text\nrawbody\n```\n\n```text\njson-parsed-body\n```\n\n```text\napp.module.ts\n```\n\n```text\nreq.rawbody\n```\n\n```text\nexpress\n```\n\n```text\napp.use('/payment/hooks', bodyParser.raw({type: 'application/json'}));\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { NestExpressApplication } from \"@nestjs/platform-express\";\n\nimport { json, urlencoded } from \"express\";\nimport type { Request } from \"express\";\nimport type http from \"http\";\n\nexport const HTTP_REQUEST_RAW_BODY = \"rawBody\";\n\n/**\n * make sure you configure the nest app with <code>preserveRawBodyInRequest</code>\n * @example\n * webhook(@RawBody() rawBody: string): Record<string, unknown> {\n *   return { received: true };\n * }\n * @see preserveRawBodyInRequest\n */\nexport const RawBody = createParamDecorator(\n  async (data: unknown, context: ExecutionContext) => {\n    const request = context\n      .switchToHttp()\n      .getRequest<Request>()\n    ;\n\n    if (!(HTTP_REQUEST_RAW_BODY in request)) {\n      throw new Error(\n        `RawBody not preserved for request in handler: ${context.getClass().name}::${context.getHandler().name}`,\n      );\n    }\n\n    const rawBody = request[HTTP_REQUEST_RAW_BODY];\n\n    return rawBody;\n  },\n);\n\n/**\n * @example\n * const app = await NestFactory.create<NestExpressApplication>(\n *   AppModule,\n *   {\n *     bodyParser: false, // it is prerequisite to disable nest's default body parser\n *   },\n * );\n * preserveRawBodyInRequest(\n *   app,\n *   \"signature-header\",\n * );\n * @param app\n * @param ifRequestContainsHeader\n */\nexport function preserveRawBodyInRequest(\n  app: NestExpressApplication,\n  ...ifRequestContainsHeader: string[]\n): void {\n  const rawBodyBuffer = (\n    req: http.IncomingMessage,\n    res: http.ServerResponse,\n    buf: Buffer,\n  ): void => {\n    if (\n      buf?.length\n      && (ifRequestContainsHeader.length === 0\n        || ifRequestContainsHeader.some(filterHeader => req.headers[filterHeader])\n      )\n    ) {\n      req[HTTP_REQUEST_RAW_BODY] = buf.toString(\"utf8\");\n    }\n  };\n\n  app.use(\n    urlencoded(\n      {\n        verify: rawBodyBuffer,\n        extended: true,\n      },\n    ),\n  );\n  app.use(\n    json(\n      {\n        verify: rawBodyBuffer,\n      },\n    ),\n  );\n}\n```\n\n```text\npreserveRawBodyInRequest\n```\n\n```text\n\"stripe-signature\"\n```\n\n```text\nRawBody\n```\n\n```text\nimport { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'\nimport { raw } from 'body-parser'\n\nimport { PaymentIntentController } from './payment-intent.controller'\nimport { PaymentIntentService } from './payment-intent.service'\n\n@Module({\n    controllers: [PaymentIntentController],\n    providers: [PaymentIntentService]\n})\nexport class PaymentIntentModule implements NestModule {\n    configure(consumer: MiddlewareConsumer) {\n        consumer.apply(raw({ type: 'application/json' })).forRoutes(PaymentIntentController)\n    }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core'\n\nimport { AppModule } from './module'\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule, { cors: true, bodyParser: false })\n\n    await app.listen(8080)\n}\n\nbootstrap()\n```\n\n```text\nbodyParser\n```\n\n```js\nimport { Injectable, NestMiddleware } from \"@nestjs/common\";\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class RawBodyMiddleware implements NestMiddleware {\n  use(req: Request, res: Response, next: () => unknown) {\n    req.headers[\"content-type\"] = \"text/plain\";\n    next();\n  }\n}\n```\n\n```text\nimport * as express from 'express';\n\nasync function bootstrap() {\n...\n  app.use('/your-stripe-webhook', express.raw({ type: \"*/*\" })); // <- add this!\n...\n  await app.listen(8080)\n}\n```\n\n```text\nmain.ts\n```\n\n```text\nimport { raw } from 'express';\n\nasync function bootstrap() {\n...\n  app.use('/webhook', raw({ type: \"*/*\" })); // <- add this!\n...\n  await app.listen(3000)\n}\n```\n\n```text\nimport { Stripe } from 'stripe';\n\nasync function controller() {\n  stripeClient: Stripe;\n  constructor(\n  ) {\n    this.stripeClient = new Stripe(process.env.STRIPE_KEY, {\n      apiVersion: '2020-08-27',\n      typescript: true,\n    });\n  }\n\n  @Post('')\n  async stripe(\n    @Body() rawBody: Buffer,\n    @Headers('stripe-signature') signature: string,\n  ) {\n    let event: Stripe.Event;\n    try {\n      event = this.stripeClient.webhooks.constructEvent(\n        rawBody,\n        signature,\n        process.env.STRIPE_WEBHOOK_KEY,\n      );\n    } catch (error) {\n      throw new Error(error);\n    }\n  }\n}\n```\n\n```text\nmain.ts\n```\n\n```text\nwebhook.controller.ts\n```\n\n```js\nimport { NextFunction, Request, Response } from 'express';\n\nexport type NextHandleFunction = (req: Request, res: Response, next: NextFunction) => void;\n\nexport interface MiddlewareRoute {\n    /**\n     * Exact match with `request.originalUrl`. Optionally matches via\n     * `request.originalUrl.startsWith` when ending with a `*`.\n     */\n    path: string;\n    middleware: NextHandleFunction;\n}\n\n/**\n * Runs middleware if a route is matching `request.originalUrl`.\n * @param routes Order of routes is important. When using a catch all route like\n * `'*'`, make sure it is the last in the array.\n */\nexport function middlewareRouter(routes: MiddlewareRoute[]) {\n    return (req: Request, res: Response, next: NextFunction) => {\n        const nextMiddleware = routes.reduce((prev, curr) => {\n            if (prev) {\n                return prev;\n            }\n\n            const isMatch = curr.path.endsWith('*')\n                ? req.originalUrl.startsWith(curr.path.slice(0, -1))\n                : req.originalUrl === curr.path;\n\n            return isMatch ? curr : prev;\n        }, undefined) as MiddlewareRoute | undefined;\n        nextMiddleware ? nextMiddleware.middleware(req, res, next) : next();\n    };\n}\n```\n\n```js\nimport { MiddlewareRoute, middlewareRouter } from './express-middleware-router';\n\nconst middlewareRoutes: MiddlewareRoute[] = [\n    {\n        path: '/stripe',\n        middleware: text({ type: '*/*' }),\n    },\n    {\n        path: '/high-json-limit/*',\n        middleware: json({ limit: '10mb' }),\n    },\n    {\n        path: '*',\n        middleware: json(),\n    },\n];\n\nconst app = await NestFactory.create(ApiModule, {\n    bodyParser: false,\n});\n\napp.use(middlewareRouter(middlewareRoutes));\n```\n\n```text\nexpress-middleware-router.ts\n```\n\n```text\nmain.ts\n```\n\n```bash\nnpm update @nestjs/core\nnpm update @nestjs/common\nnpm update @nestjs/common\nnpm update @nestjs/platform-express //if you are using express\n```\n\n```text\nrawBody\n```\n\n```text\nconst app = await NestFactory.create(AppModule, {\n  rawBody: true,\n  bodyParser: true,\n  ...\n```\n\n```text\n@Public()\n  @Post(\"webhooks\")\n  async createStripeWebhookAction(\n    @Req() req: RawBodyRequest<Request>,\n    @Res() res: Response,\n  ) {\n  //... do stuff with it\n```\n\n```text\napp.use(json({ limit: '50mb' }));\napp.use(urlencoded({ extended: true, limit: '50mb' }));\n```\n\n```text\napp.useBodyParser('json', { limit: '50mb' });\napp.useBodyParser('urlencoded', { limit: '50mb' });\n```\n\n```text\nconst app = await NestFactory.create<NestExpressApplication>(AppModule, {\n  rawBody: true,\n});\n```\n\n```text\n@Req() req: RawBodyRequest<Request>\n```\n\n```text\n// Enable raw body for webhooks signature verification.\n  app.use(['<route>'], express.raw({ type: 'application/json' }));\n```\n\n```text\n@Post('<route>')\n@HttpCode(200)\nhandleWebHooks(@Req() request: RawBodyRequest<Request>, @Headers('signature') signature: string)\n```\n\n```text\nrequest.body\n```\n\n```text\nimport * as bodyParser from 'body-parser';\n\nconst app = await NestFactory.create(AppModule, {\n  rawBody: true,\n  bodyParser: true,\n    });\n```\n\n========================================\n\nComments:\n- you probably didn't disable the Nest's default `bodyParser` when creating the `NestApplication` in `bootsrap` method\n- Note: the NestJS embedded rawBody is not compatible with other JSON body parser parameters like changing the \"limit\" (e.g. to '50mb'), afaik. Your initial answer worked better for me.\n- Nest.js have just recently done an update on this part : You can now mix body-parser options like `limit`..etc with rawBody by specifying body-parser options with .useBodyParser. Here is an example\n- Thanks for the clear answer! If I may suggest moving the newer solution to the top of the answer so that newcomers to the question can see the updated solution first.\n- This is the best solution using Nest IMHO, should be the accepted answer.\n- this is the best solution. Thank you\n- This is a great answer but remeber to tweak initialization of nestjs to turn off bodyParser: const app = await NestFactory.create(AppModule, { bodyParser: false, })\n- Amazing! Works like a charm once you turn off the built-in bodyParser. Could it be added to the answer?\n- this is the optimal solution.\n- this is a better solution!\n- I think you should call .exclude({ path: '/stripe-webhooks', method: RequestMethod.POST, }) for the JsonBodyMiddleware ??\n- Body parser is deprecated. Both `json` and `raw` are now available in `express`. For example: `import { Request, Response, raw, json } from 'express';`\n- And you should call `await app.init()` after `const app = ....`\n- It works! Remember to read body like this @Body() body: Buffer, and not like this @RawBody() body: Buffer.\n- In the controller of hooks it would be something like this `handleWebhook(@Body() raw: Buffer)`\n- @a7md0 I could get `raw` data on the controller hooks, can you please more details\n- @zulqarnain For stripe I just passed the raw which is type of Buffer to the `eventConstructor` body\n- This seems like the simplest solution. Also remember to import it correctly: `import * as bodyParser from 'body-parser'`\n- Great solution, and it works. Better to use `import { raw } from 'express';` and `raw({ type: 'application&#47;json' })` though with modern implementations.\n- If you have multiple parsers configured, make sure the more specific ones come before the general ones. `app.use('&#47;payment&#47;hooks', bodyParser.raw({type: 'application&#47;json'})); app.use(bodyParser.json());`\n- This worked great for me, especially since we are using an older version of Nest that didn't have the \"rawBody\" option. I also like that it limits using the raw body to certain paths since it seems like that could use up more memory.\n- Works great on NestJS v.7.1.1\n- Great find, it work for me as well!\n- For some reason, this is not working for me\n- @Jeremiah I could help you if you provide a bit more context\n- It worked. But I had to deploy it to test ... I couldn't test locally but it works. Thanks\n- @Jeremiah I was running into an issue with this locally as well. My problem was that I was using the signing secret provided for the webhook I set up, but if you're forwarding events using the CLI, you need to use the secret provided in the terminal when you call stripe listen.\n- tried, does not work neither locally nor in production..\n- this seems to work fine for me as well and also seems the easiest approach...\n- This should be the correct answer (2025), I wasted an hour asking different LLMs. Also, there is one `@RawBody()` decorator\n- Works ! thanks and after trying most of answers i confirm that this is the best answer and the official one too","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":52,"totalLines":695,"estimatedTokens":4322}}29{"id":"stack-68317383","source":"stackoverflow","questionId":68317383,"title":"TypeError: rxjs_1.lastValueFrom is not a function","tags":["postgresql","nestjs","typeorm"],"text":"Title: TypeError: rxjs_1.lastValueFrom is not a function\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am building an api using nestjs. After adding the typeorm and pg dependencies and adding the `TypeOrmModule.forRoot({})` code in `app.module.ts` like shown below.\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { CoffeesModule } from './coffees/coffees.module';\n\n@Module({\n imports: [CoffeesModule, TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'xxx',\n database: 'postgres',\n autoLoadEntities: true,\n synchronize: true\n })],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\nI get an error `TypeError: rxjs_1.lastValueFrom is not a function` with but no error when I exclude `TypeOrmModule.forRoot({})`.\n\nWhat could be the reason for the error ?\n\n========================================\n\nTop Answer:\n### The real answer\n\nThe issue is conflict with nest version.. anyone who see this - just make sure all your nestJs packages are of version 7 or 8 - don't mix them. especially those:\n\n- @nestjs/common\n\n- @nestjs/core\n\n- @nestjs/typeorm\n\nfrom here: https://github.com/nestjs/nest/issues/7468#issuecomment-876174870\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { CoffeesModule } from './coffees/coffees.module';\n\n@Module({\n  imports: [CoffeesModule, TypeOrmModule.forRoot({\n    type: 'postgres',\n    host: 'localhost',\n    port: 5432,\n    username: 'postgres',\n    password: 'xxx',\n    database: 'postgres',\n    autoLoadEntities: true,\n    synchronize: true\n  })],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nTypeOrmModule.forRoot({})\n```\n\n```text\napp.module.ts\n```\n\n```text\nTypeError: rxjs_1.lastValueFrom is not a function\n```\n\n```text\nTypeOrmModule.forRoot({})\n```\n\n```sh\nnpm i rxjs@^7\nyarn add rxjs@^7\npnpm i rxjs @^7\n```\n\n```text\ntoPromise()\n```\n\n```text\nlastValueFrom\n```\n\n```text\nrxjs\n```\n\n```text\nentities: [__dirname + '/src/**/*.entity{.ts,.js}'],\n```\n\n```text\nentities: [__dirname + '/**/*entity{.ts,.js}'],\n```\n\n========================================\n\nComments:\n- maybe: github.com/nestjs/nest/issues/7468","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":640}}30{"id":"stack-50360101","source":"stackoverflow","questionId":50360101,"title":"How to exclude entity field from returned by controller JSON. NestJS + Typeorm","tags":["node.js","typescript","nestjs","typeorm"],"text":"Title: How to exclude entity field from returned by controller JSON. NestJS + Typeorm\nTags: node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to exclude password field from returned JSON. \nI am using NestJS and Typeorm. \n\nThe solution provided on this question doesn't work for me or in NestJS. I can post my code if needed.\nAny other ideas or solutions? Thanks.\n\n========================================\n\nTop Answer:\nLots of good answers in this thread. To build on apun's answer above, I think the following approach is the least likely to accidentally leak a password field:\n\n```\n@Column({ select: false })\npassword: string\n```\n\nIf the entity doesn't select that field by default, and it can only be explicitly queried (e.g. via `addSelect()` if using the query builder), I think it is a lot less likely that there's a slip somewhere, and there's less reliance on the \"magic\" of a framework (which is ultimately the `class-transformer` library) to ensure security. Realistically in many projects the only place you'd explicitly select it is where you check credentials.\n\nThis approach can also help keep the password hash from accidentally leaking into log entries, etc, which is a consideration that hasn't been mentioned yet. It feels much safer to toss around the user object knowing that it doesn't include sensitive information, especially if it could end up serialized in a log entry somewhere.\n\nAll said, the documented approach for NestJS is to use the `@Exclude()` decorator and the accepted answer is from the project's founder.\n\nI definitely make frequent use of the `Exclude()` decorator, but not necessarily for password or salt fields.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class TransformInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    return call$.pipe(map(data => classToPlain(data)));\n  }\n}\n```\n\n```text\nimport { Exclude } from 'class-transformer';\n\nexport class User {\n    id: number;\n    email: string;\n\n    @Exclude()\n    password: string;\n}\n```\n\n```text\n@Exclude()\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\nimport { Exclude } from 'class-transformer';\n\nexport class User {\n    /** other properties */    \n\n    @Exclude()\n    password: string;\n}\n```\n\n```text\n@SerializeOptions({\n  excludePrefixes: ['_'],\n  groups: ['admin']\n})\n```\n\n```text\n@Expose({ groups: [\"admin\"] })\nadminInfo: string;\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\n@Exclude\n```\n\n```text\n@SerializeOptions()\n```\n\n```js\n@Entity()\nexport class User extends BaseAbstractEntity implements IUser {\n  static passwordMinLength: number = 7;\n\n  @ApiModelProperty({ example: faker.internet.email() })\n  @IsEmail()\n  @Column({ unique: true })\n  email: string;\n\n  @IsOptional()\n  @IsString()\n  @MinLength(User.passwordMinLength)\n  @Exclude({ toPlainOnly: true })\n  @Column({ select: false })\n  password: string;\n\n  @IsOptional()\n  @IsString()\n  @Exclude({ toPlainOnly: true })\n  @Column({ select: false })\n  passwordSalt: string;\n\n  toJSON() {\n    return classToPlain(this);\n  }\n\n  validatePassword(password: string) {\n    if (!this.password || !this.passwordSalt) {\n      return false;\n    }\n    return comparedToHashed(password, this.password, this.passwordSalt);\n  }\n}\n```\n\n```text\n@Column({ select: false })\npassword: string\n```\n\n```text\n@Column({ select: false })\npassword: string\n```\n\n```text\naddSelect()\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Exclude()\n```\n\n```text\nExclude()\n```\n\n```js\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'users' })\nexport class User {\n  @PrimaryGeneratedColumn('uuid')\n  id: string | undefined;\n\n  @Column({ type: 'varchar', length: 100, unique: true })\n  email: string | undefined;\n\n  @Column({ type: 'text' })\n  password: string | undefined;\n\n  static removePassword(userObj: User) {\n    return Object.fromEntries(\n      Object.entries(userObj).filter(([key, val]) => key !== 'password')\n    );\n  }\n}\n```\n\n```js\nimport { Router, Request, Response, NextFunction } from 'express';\nimport { User } from '../../entity/User';\nimport { getRepository } from 'typeorm';\n\nconst router = Router();\n\nrouter.post(\n  '/api/users/signin',\n  (req: Request, res: Response, next: NextFunction) => {\n    const { email } = req.body;\n\n    getRepository(User)\n      .findOne({ email })\n      .then(user =>\n        user ? res.send(User.removePassword(user)) : res.send('No such user:(')\n      )\n      .catch(err => next(new Error(err.message)));\n  }\n);\n\nexport { router as signinRouter };\n```\n\n```js\nwithoutPassword() {\n  return Object.fromEntries(\n    Object.entries(this).filter(([key, val]) => key !== 'password')\n  );\n}\n```\n\n```js\nres.send(user.withoutPassword());\n```\n\n```text\nremovePassword()\n```\n\n```text\nfilter()\n```\n\n```text\nfilter()\n```\n\n```text\nasync validateUser(email: string, password: string): Promise<UserWithoutPassword | null> {\n    const user = await this.usersService.findOne({ email });\n\n    if (user && await compare(password, user.password))\n    {\n        return plainToClass(UserWithoutPassword, user.toObject());\n    }\n\n    return null;\n}\n```\n\n```text\nplainToClass\n```\n\n```text\ntoJSON() { return classToPlain(this); }\n```\n\n```text\n@Post()\n@SerializeOptions({\n  groups: ['admin','user'],\n})\nasync create(\n  @Body() createProjectDto: CreateProjectDto,\n) {\n  const data = await this.projectsService.create(createProjectDto);\n  return classToClass(data, { groups: ['admin','DYNAMIC_GROUP'] });\n  //Or you can return\n  //return plainToClass(Project, plainObject, {groups: ['admin','DYNAMIC_GROUP']});\n}\n```\n\n```text\n@SerializeOptions\n```\n\n```text\nclassToClass\n```\n\n```text\nplainToClass\n```\n\n```text\nclassToClass\n```\n\n```text\nplainToClass\n```\n\n```text\n@SerializeOptions\n```\n\n```text\n@Injectable()\nexport default class TransformInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    next: CallHandler,\n  ): Observable<AnyObject> {\n    return next.handle().pipe(map((args) => instanceToPlain(args)));\n  }\n}\n```\n\n```text\nimport { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class ExcludeFieldsInterceptor implements NestInterceptor {\n  private readonly excludedFields = ['password', 'secretKey']; // List of fields to remove\n\n  intercept(context: ExecutionContext, next: CallHandler) {\n    return next.handle().pipe(map((data) => this.cleanData(data)));\n  }\n\n  private cleanData(data: any): any {\n    if (Array.isArray(data)) return data.map(this.cleanData.bind(this));\n    if (data && typeof data === 'object') {\n      this.excludedFields.forEach((field) => delete data[field]);\n      Object.values(data).forEach((value) => this.cleanData(value)); // Recursively clean nested objects\n    }\n    return data;\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ExcludeFieldsInterceptor } from './interceptors/exclude-fields.interceptor';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalInterceptors(new ExcludeFieldsInterceptor()); // Apply globally\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- Silva, Could you please point out a reference to \"exlude properties using groups.\"? I was not able find it. Thanks\n- That's ti @kamil-myล›liwiec :-D Best answer for the creator.\n- Thank you, @kamil-myล›liwiec . I will try this asap.\n- Also, you can exclude fields during database query (in ORM, or SQL query). Example for TypeORM - github.com/typeorm/typeorm/issues/535 .\n- I don't understand how to implement TransformInterceptor class in nest :( ?\n- The built in `ClassSerializerInterceptor` can be used here if im not mistaken\n- Is there anyway to do this with a prisma? Prisma doesn't seem to use the entity flow at all :(\n- @Kamil Myล›liwiec and where to inject TransformInterceptor class?\n- You wouldn't happen to know if the built-in class supports defining groups, i.e `@Expose({ groups: [\"user\", \"admin\"] })`? I've been struggling to figure out how you'd indicate which group should be used from within the controller. From the `class-transformer` docs I can see it supports `classToPlain(user, { groups: [\"user\"] })`, but I'm a little confused where nest is calling it, and if I can pass through those options.\n- just a newbie question: where do you define the \"groups\", i.e how class-transformer would know which group the user is in? shall we define Group model first and make user has multiple groups kinda relation? i.e the user would have user.groups = ['editor', user']? Then how do we pass the user of the current request to the intercepter so it would show/hide fields accordingly?\n- @AhmetCetin The `SerializeOptions` only work if the `groups` are static per endpoint. If you want to dynamically determine the `groups` based on the request, you have to implement a custom interceptor for that.\n- See this answer, where the groups are dynamically determined for validation, you need to do something similar, but for serialization (in your case interceptor instead of pipe): stackoverflow.com/a/54057206/4694994\n- @KimKern, `@Expose` did not work as expected on method level on `POST` request. I am using nestjs `6.5.3`\n- @ddsultan Please open a new question about this; it's not possible to debug your issue in the comments without more details: a minimal example so that the problem can be reproduced and your expected behavior or output. Thanks :-)\n- Check my reply as below for how to use class-transformer groups in a dynamic way in Nestjs.\n- is there any document aboud toJSON() ?\n- toJSON method is a method that can be overriden in any javascript class. It defines how a class is converted to a regular object. When calling JSON.stringify, the toJSON method of the class is called. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/&hellip; See the description section.\n- Only adding @Exclude({ toPlainOnly: true }) was what I was looking for\n- `classToPlain` is now deprecated. Use `instanceToPlain` instead.\n- Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.\n- Sure. I thought it was self explanatory.\n- Awesome. My problem solved with it\n- Please accompany your answer with an explanation","metadata":{"transformedAt":"2026-08-18T18:33:02.398Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":365,"estimatedTokens":2644}}31{"id":"stack-60749439","source":"stackoverflow","questionId":60749439,"title":"Circular Dependency with Nestjs Swagger 4","tags":["swagger","nestjs","circular-dependency"],"text":"Title: Circular Dependency with Nestjs Swagger 4\nTags: swagger, nestjs, circular-dependency\nSource: Stack Overflow\n\nQuestion:\nWhen I updated the **@nest/swagger** library to version 4, this error happened:\n\n```\n(node:16134) UnhandledPromiseRejectionWarning: Error: A circular dependency has been detected (property key: \"customer\"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers (\"type: () => ClassType\").\n at SchemaObjectFactory.createNotBuiltInTypeReference (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:182:19)\n at SchemaObjectFactory.mergePropertyWithMetadata (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:117:25)\n at /opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:66:35\n at Array.map ()\n at SchemaObjectFactory.exploreModelSchema (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:65:52)\n at SchemaObjectFactory.createNotBuiltInTypeReference (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:187:37)\n at SchemaObjectFactory.mergePropertyWithMetadata (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:117:25)\n at /opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:66:35\n at Array.map ()\n at SchemaObjectFactory.exploreModelSchema (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:65:52)\n```\n\nMy model class seems to this:\n\n```\n@Entity()\nexport class Job {\n.\n.\n.\n @ManyToOne(type => Customer, customer => customer.jobs)\n @ApiProperty({ type: Customer })\n customer: Customer;\n}\n```\n\n========================================\n\nTop Answer:\nThere are at least three more cases where you get the same error message, even though they have nothing to do with bidirectional relationships:\n\n### Enum as type\n\nWrong:\n\n```\n@ApiProperty({\n type: Salutation\n})\npublic salutation: Salutation;\n```\n\nCorrect:\n\n```\n@ApiProperty({\n enum: Salutation\n})\npublic salutation: Salutation;\n```\n\n### Anonymous types\n\nWrong:\n\n```\n@ApiProperty({\n})\npublic address: {\n street: string;\n houseNumber: string;\n};\n```\n\nCorrect:\n\n```\n@ApiProperty({\n type: Address\n})\npublic address: Address;\n```\n\n### null\n\nWrong:\n\n```\n@ApiProperty({\n description: 'This always returns null for downward compatibility'\n})\npublic someLegacyField: null;\n```\n\nCorrect:\n\n```\n@ApiProperty({\n description: 'This always returns null for downward compatibility',\n type: String; // needed to avoid error\n})\npublic someLegacyField: null;\n```\n\nI created an issue on Github for this: https://github.com/nestjs/swagger/issues/1475\n\n========================================\n\nCode:\n```sh\n(node:16134) UnhandledPromiseRejectionWarning: Error: A circular dependency has been detected (property key: \"customer\"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers (\"type: () => ClassType\").\n    at SchemaObjectFactory.createNotBuiltInTypeReference (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:182:19)\n    at SchemaObjectFactory.mergePropertyWithMetadata (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:117:25)\n    at /opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:66:35\n    at Array.map (<anonymous>)\n    at SchemaObjectFactory.exploreModelSchema (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:65:52)\n    at SchemaObjectFactory.createNotBuiltInTypeReference (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:187:37)\n    at SchemaObjectFactory.mergePropertyWithMetadata (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:117:25)\n    at /opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:66:35\n    at Array.map (<anonymous>)\n    at SchemaObjectFactory.exploreModelSchema (/opt/desenvolvimento/Haizen/projectx_back/node_modules/@nestjs/swagger/dist/services/schema-object-factory.js:65:52)\n```\n\n```js\n@Entity()\nexport class Job {\n.\n.\n.\n    @ManyToOne(type => Customer, customer => customer.jobs)\n    @ApiProperty({ type: Customer })\n    customer: Customer;\n}\n```\n\n```js\n@Entity()\nexport class Job {\n.\n.\n.\n    @ManyToOne(type => Customer, customer => customer.jobs)\n    @ApiProperty({ type: () => Customer })\n    customer: Customer;\n}\n```\n\n```text\ntype\n```\n\n```text\nenum\n```\n\n```text\n@ApiProperty\n```\n\n```js\n@ApiProperty({\n    type: Salutation\n})\npublic salutation: Salutation;\n```\n\n```js\n@ApiProperty({\n    enum: Salutation\n})\npublic salutation: Salutation;\n```\n\n```js\n@ApiProperty({\n})\npublic address: {\n    street: string;\n    houseNumber: string;\n};\n```\n\n```js\n@ApiProperty({\n    type: Address\n})\npublic address: Address;\n```\n\n```js\n@ApiProperty({\n    description: 'This always returns null for downward compatibility'\n})\npublic someLegacyField: null;\n```\n\n```js\n@ApiProperty({\n    description: 'This always returns null for downward compatibility',\n    type: String; // needed to avoid error\n})\npublic someLegacyField: null;\n```\n\n```text\nnest build\n```\n\n```text\nnode dist/main\n```\n\n```text\nexport class BookLikes {\n  bookLikes: {\n    user: User;\n    book: Book;\n  }[];\n}\n```\n\n```text\nexport class BookLikes {\n  bookLikes: BookLike[];\n}\n\nexport class BookLike {\n  user: User;\n  book: Book;\n}\n```\n\n```text\n@ApiProperty({\n    enum: ProcessCat,\n    enumName: 'ProcessCat',\n    isArray: true,\n  })\n  category: ProcessCat;\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger'\n\nexport class CreateCatDto {\n  @ApiProperty({ type: [String] })\n  kittenNames: string[]\n}\n```\n\n```text\ngrounding_docs: { name: string; url: string; }[];\n```\n\n```text\n@IsArray()\ngrounding_docs: { name: string; url: string; }[];\n```\n\n```text\nexport class IType {\n  @ApiProperty({ type: () => Node })\n    node: Node;\n   }\n```\n\n```text\nexport class IType {\n        node: Node;\n  }\n```\n\n```js\nimport metadata from './metadata';\n// ...\n  await SwaggerModule.loadPluginMetadata(async () => metadata);\n// ...\n```\n\n```js\nimport metadata from './metadata';\n// ...\n  await SwaggerModule.loadPluginMetadata(metadata);\n// ...\n// Error: A circular dependency has been detected...\n```\n\n```text\nmetadata\n```\n\n```text\nswagger\n```\n\n```text\nmetadata.ts\n```\n\n```text\nnestjs\n```\n\n========================================\n\nComments:\n- I still have the problem. UnhandledPromiseRejectionWarning: Error: A circular dependency has been detected (property key: \"KM\"). Please, make sure that each side of a bidirectional relationships are using lazy resolvers (\"type: () => ClassType\").\n- Here is my enum enum EmissionUnitEnum { KM = 'km', MINUTE = 'minute', MINUTES = 'minutes', HOUR = 'hour', HOURS = 'hours', FIXED = 'fixed', SERVING = 'serving', }\n- If your `Customer` class also contains `@ApiProperty` decorators, don't forget to use arrow functions there as well.\n- Good recommendation! Please note that the `@ApiProperty({ type: () => {any class} })` should be in your DTO, not the Entity\n- You are the best!\n- Thank you, I don't undersatnd why it works like this but it saved my day\n- This works only if the property is an enum. Otherwise, Swagger will display it incorrectly when exposing it.\n- The correct answer.\n- This is the one that worked for me.\n- The \"Enum as type\" was my issue.\n- This should be marked as a correct answer\n- The correct answer, I spent a good half an hour debugging and trying out different hypothesis: null type wrecks every time. Issue appears as \"closed\" but the bug is still there. As a extra, use ` @ApiProperty({ type: () => 'null' })`, that way the swagger UI will reflect the actual null type (otherwise, the type used in the lazy resolver will be shown)\n- Using a function helped! Thanks a lot! --- `@ApiProperty({ type: () => Node })`","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":318,"estimatedTokens":2070}}32{"id":"stack-64105940","source":"stackoverflow","questionId":64105940,"title":"GraphQLError: Query root type must be provided","tags":["postgresql","graphql","nestjs","typeorm"],"text":"Title: GraphQLError: Query root type must be provided\nTags: postgresql, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS, TypeORM and GraphQL for my backend API. I'm getting the following error:\n\n```\nGraphQLError [Object]: Query root type must be provided.\n at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19)\n at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13)\n at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3)\n at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59\n at new Promise ()\n at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10)\n at GraphQLSchemaFactory. (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52)\n at Generator.next ()\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75\n```\n\nThis is what my file structure and code looks like:\nhttps://i.sstatic.net/fpUEL.png\n\nCan someone please help me. My repo: https://github.com/wise-introvert/nestjs-graphql-api.git\n\n========================================\n\nTop Answer:\nAlso ensure the Resolver is added in the module providers\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: true,\n }),\n ],\n controllers: [],\n providers: [FooResolver], //< This\n})\nexport class FooModule {}\n```\n\n========================================\n\nCode:\n```text\nGraphQLError [Object]: Query root type must be provided.\n      at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19)\n      at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13)\n      at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3)\n      at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62)\n      at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59\n      at new Promise (<anonymous>)\n      at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10)\n      at GraphQLSchemaFactory.<anonymous> (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52)\n      at Generator.next (<anonymous>)\n      at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75\n```\n\n```js\n@Resolver()\nexport class FooResolver {\n\n  @Query(() => String)\n  sayHello(): string {\n    return 'Hello World!';\n  }\n}\n```\n\n```text\n@Query()\n```\n\n```js\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      installSubscriptionHandlers: true,\n      autoSchemaFile: true,\n    }),\n  ],\n  controllers: [],\n  providers: [FooResolver], //< This\n})\nexport class FooModule {}\n```\n\n```js\n// Correct\nimport { Resolver, Query } from '@nestjs/graphql';\n\n// Incorrect in NestJS\nimport { Resolver, Query } from 'type-graphql';\n```\n\n```text\n@Module({ providers: [NftsResolver, NftsService] })\nexport class NftsModule {}\n```\n\n```text\nnfts.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```js\n@Module({\n  imports: [\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n      typePaths: ['./**/*.graphql'],\n      definitions: {\n        path: join(process.cwd(), 'src/graphql.ts'),\n        outputAs: 'class',\n      },\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n```\n\n```text\ntypePaths\n```\n\n```text\ndefinitions\n```\n\n```text\n*.graphql\n```\n\n========================================\n\nComments:\n- I've added a dummy function under `@Query` decorator in my resolver but it's still throwing the same error.\n- Thanks! This was the issue for me. The accepted answer did not solve the bug for me.\n- What was missing for me was `autoSchemaFile: true` in the options object.","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":147,"estimatedTokens":1136}}33{"id":"stack-59635276","source":"stackoverflow","questionId":59635276,"title":"How to correctly build NestJS app for production with node_modules dependencies in bundle?","tags":["javascript","node.js","typescript","webpack","nestjs"],"text":"Title: How to correctly build NestJS app for production with node_modules dependencies in bundle?\nTags: javascript, node.js, typescript, webpack, nestjs\nSource: Stack Overflow\n\nQuestion:\nAfter `nest build` or `nest build --webpack` dist folder does not contain all required modules and I got `Error: Cannot find module '@nestjs/core'` when trying to run `node main.js`.\n\nI could not find any clear instructions on https://docs.nestjs.com/ on how to correctly build app for production, so maybe I missed something?\n\n========================================\n\nTop Answer:\nFor anyone interested, ncc does a great job for bundling a complete NestJs app into a single js file:\n\n`ncc build src/main.ts --out dist/main.js`\n\nNo further config needed for me, although you may need to fix some of your `import` paths. It does tree shaking and even detects bindings and copies them in separate folders too.\n\n========================================\n\nCode:\n```text\nnest build\n```\n\n```text\nnest build --webpack\n```\n\n```text\nError: Cannot find module '@nestjs/core'\n```\n\n```text\nnode main.js\n```\n\n```text\nnode_modules\n```\n\n```text\ndist\n```\n\n```text\nwebpack.IgnorePlugin\n```\n\n```js\nconst path = require('path');\nconst MakeOptionalPlugin = require('./make-optional-plugin');\nmodule.exports = (defaultOptions, webpack) => {\n    return {\n        externals: {},  // make it not exclude `node_modules`\n                        // https://github.com/nestjs/nest-cli/blob/v7.0.1/lib/compiler/defaults/webpack-defaults.ts#L24\n        resolve: {\n            ...defaultOptions.resolve,\n            extensions: [...defaultOptions.resolve.extensions, '.json'], // some packages require json files\n                                                                         // https://unpkg.com/browse/babel-plugin-polyfill-corejs3@0.4.0/core-js-compat/data.js\n                                                                         // https://unpkg.com/browse/core-js-compat@3.19.1/data.json\n            alias: {\n                // an issue with rollup plugins\n                // https://github.com/webpack/enhanced-resolve/issues/319\n                '@rollup/plugin-json': '/app/node_modules/@rollup/plugin-json/dist/index.js',\n                '@rollup/plugin-replace': '/app/node_modules/@rollup/plugin-replace/dist/rollup-plugin-replace.cjs.js',\n                '@rollup/plugin-commonjs': '/app/node_modules/@rollup/plugin-commonjs/dist/index.js',\n            },\n        },\n        module: {\n            ...defaultOptions.module,\n            rules: [\n                ...defaultOptions.module.rules,\n\n                // a context dependency\n                // https://github.com/RobinBuschmann/sequelize-typescript/blob/v2.1.1/src/sequelize/sequelize/sequelize-service.ts#L51\n                {test: path.resolve('node_modules/sequelize-typescript/dist/sequelize/sequelize/sequelize-service.js'),\n                use: [\n                    {loader: path.resolve('rewrite-require-loader.js'),\n                    options: {\n                        search: 'fullPath',\n                        context: {\n                            directory: path.resolve('src'),\n                            useSubdirectories: true,\n                            regExp: '/\\\\.entity\\\\.ts$/',\n                            transform: \".replace('/app/src', '.').replace(/$/, '.ts')\",\n                        },\n                    }},\n                ]},\n\n                // adminjs resolves some files using stack (relative to the requiring module)\n                // and actually it needs them in the filesystem at runtime\n                // so you need to leave node_modules/@adminjs/upload\n                // I failed to find a workaround\n                // it bundles them to `$prj_root/.adminjs` using `rollup`, probably on production too\n                // https://github.com/SoftwareBrothers/adminjs-upload/blob/v2.0.1/src/features/upload-file/upload-file.feature.ts#L92-L100\n                {test: path.resolve('node_modules/@adminjs/upload/build/features/upload-file/upload-file.feature.js'),\n                use: [\n                    {loader: path.resolve('rewrite-code-loader.js'),\n                    options: {\n                        replacements: [\n                            {search: /adminjs_1\\.default\\.bundle\\('\\.\\.\\/\\.\\.\\/\\.\\.\\/src\\/features\\/upload-file\\/components\\/edit'\\)/,\n                            replace: \"adminjs_1.default.bundle('/app/node_modules/@adminjs/upload/src/features/upload-file/components/edit')\"},\n\n                            {search: /adminjs_1\\.default\\.bundle\\('\\.\\.\\/\\.\\.\\/\\.\\.\\/src\\/features\\/upload-file\\/components\\/list'\\)/,\n                            replace: \"adminjs_1.default.bundle('/app/node_modules/@adminjs/upload/src/features/upload-file/components/list')\"},\n\n                            {search: /adminjs_1\\.default\\.bundle\\('\\.\\.\\/\\.\\.\\/\\.\\.\\/src\\/features\\/upload-file\\/components\\/show'\\)/,\n                            replace: \"adminjs_1.default.bundle('/app/node_modules/@adminjs/upload/src/features/upload-file/components/show')\"},\n                        ],\n                    }},\n                ]},\n\n                // not sure what babel does here\n                // I made it return standardizedName\n                // https://github.com/babel/babel/blob/v7.16.4/packages/babel-core/src/config/files/plugins.ts#L100\n                {test: path.resolve('node_modules/@babel/core/lib/config/files/plugins.js'),\n                use: [\n                    {loader: path.resolve('rewrite-code-loader.js'),\n                    options: {\n                        replacements: [\n                            {search: /const standardizedName = [^;]+;/,\n                            replace: match => `${match} return standardizedName;`},\n                        ],\n                    }},\n                ]},\n\n                // a context dependency\n                // https://github.com/babel/babel/blob/v7.16.4/packages/babel-core/src/config/files/module-types.ts#L51\n                {test: path.resolve('node_modules/@babel/core/lib/config/files/module-types.js'),\n                use: [\n                    {loader: path.resolve('rewrite-require-loader.js'),\n                    options: {\n                        search: 'filepath',\n                        context: {\n                            directory: path.resolve('node_modules/@babel'),\n                            useSubdirectories: true,\n                            regExp: '/(preset-env\\\\/lib\\\\/index\\\\.js|preset-react\\\\/lib\\\\/index\\\\.js|preset-typescript\\\\/lib\\\\/index\\\\.js)$/',\n                            transform: \".replace('./node_modules/@babel', '.')\",\n                        },\n                    }},\n                ]},\n            ],\n        },\n        plugins: [\n            ...defaultOptions.plugins,\n            // some optional dependencies, like this:\n            // https://github.com/nestjs/nest/blob/master/packages/core/nest-application.ts#L45-L52\n            // `webpack` detects optional dependencies when they are in try/catch\n            // https://github.com/webpack/webpack/blob/main/lib/dependencies/CommonJsImportsParserPlugin.js#L152\n            new MakeOptionalPlugin([\n                '@nestjs/websockets/socket-module',\n                '@nestjs/microservices/microservices-module',\n                'class-transformer/storage',\n                'fastify-swagger',\n                'pg-native',\n            ]),\n        ],\n\n        // to have have module names in the bundle, not some numbers\n        // although numbers are sometimes useful\n        // not really needed\n        optimization: {\n            moduleIds: 'named',\n        }\n    };\n};\n```\n\n```js\nclass MakeOptionalPlugin {\n    constructor(deps) {\n        this.deps = deps;\n    }\n\n    apply(compiler) {\n        compiler.hooks.compilation.tap('HelloCompilationPlugin', compilation => {\n            compilation.hooks.succeedModule.tap(\n                'MakeOptionalPlugin', (module) => {\n                    module.dependencies.forEach(d => {\n                        this.deps.forEach(d2 => {\n                            if (d.request == d2)\n                                d.optional = true;\n                        });\n                    });\n                }\n            );\n        });\n    }\n}\n\nmodule.exports = MakeOptionalPlugin;\n```\n\n```js\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping\nfunction escapeRegExp(string) {\n  return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\nfunction processFile(source, search, replace) {\n    const re = `require\\\\(${escapeRegExp(search)}\\\\)`;\n    return source.replace(\n        new RegExp(re, 'g'),\n        `require(${replace})`);\n}\n\nfunction processFileContext(source, search, context) {\n    const re = `require\\\\(${escapeRegExp(search)}\\\\)`;\n    const _d = JSON.stringify(context.directory);\n    const _us = JSON.stringify(context.useSubdirectories);\n    const _re = context.regExp;\n    const _t = context.transform || '';\n    const r = source.replace(\n        new RegExp(re, 'g'),\n        match => `require.context(${_d}, ${_us}, ${_re})(${search}${_t})`);\n    return r;\n}\n\nmodule.exports = function(source) {\n    const options = this.getOptions();\n    return options.context\n        ? processFileContext(source, options.search, options.context)\n        : processFile(source, options.search, options.replace);\n};\n```\n\n```js\nfunction processFile(source, search, replace) {\n    return source.replace(search, replace);\n}\n\nmodule.exports = function(source) {\n    const options = this.getOptions();\n    return options.replacements.reduce(\n        (prv, cur) => {\n            return prv.replace(cur.search, cur.replace);\n        },\n        source);\n};\n```\n\n```text\n$ nest build --webpack\n```\n\n```text\nbundle-nest\n```\n\n```text\nmongo\n```\n\n```text\nnode_modules\n```\n\n```text\nnestjs\n```\n\n```text\nadminjs\n```\n\n```text\nrollup\n```\n\n```text\nbabel\n```\n\n```text\nwatch\n```\n\n```text\nnestjs\n```\n\n```text\nmysql\n```\n\n```text\nnestjs\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nwebpack-5.58.2\n```\n\n```text\n@nestjs/cli-8.1.4\n```\n\n```text\nmake-optional-plugin.js\n```\n\n```text\nrewrite-require-loader.js\n```\n\n```text\nrewrite-code-loader.js\n```\n\n```text\nnodejs\n```\n\n```text\nadminjs\n```\n\n```text\nncc build src/main.ts --out dist/main.js\n```\n\n```text\nimport\n```\n\n```text\nnpm i -g @vercel/ncc\nnpm install -g pkg\nncc build src/main.ts --out dist/ncc-main.js\npkg dist/ncc-main.js/index.js -o myapp -t latest-linux-x64\n```\n\n========================================\n\nComments:\n- Are you trying to deploy the artifact/dist folder directly? You should note that some libraries have machine specific code and have to be built on the target machine, e.g. bcrypt. When I deploy my production application I run `nest build` on the target server (after `npm install`).\n- The problem is the absent of code, machine specific or not. You'll get the same error even with simple app generated by `nest new my_project` if you'll move resulting `dist` to other location on the same machine for example.\n- `node_modules` is not bundled, no. This should be possible with webpack though. I assume you want to remove the source code and only keep the dist folder, right? Why?\n- Strange question. Why people build \"binaries\"? To minimize dependencies, size, number of files to deploy. What's the profit of building then if need the same complex environment as for just `nest start`?\n- Usually, reducing file size is more of an issue for client side applications; saving storage capacity (of the order of kB) is mostly not very relevant on server side. However, (re)-starting a built application is much quicker than first transpiling the TypeScript files on every startup, that's why you still built it. If you have set the node environment to `production` (or call `npm install --production`) no unnecessary dependenies will be installed.\n- Server app requirements can wary a lot. For someone the (re)starting time does not matter at all, but thousands of files does. So summarizing, nest-cli could not build some kind of a bundle (or small amount of bundles) like for example angular does, right?\n- Out of the box, not that I know of. But I've seen webpack configurations that bundle the `node_modules` folder. Maybe you'll find an example that works with nest right away. This thread seems to be an interesting lead: github.com/nestjs/nest/issues/1706#issuecomment-474514484\n- This seems to be an example of a nest application including dependencies in the bundle: github.com/ZenSoftware/bundled-nest\n- Ok, thank you! Can you format it as a short answer so I can accept it. May be this will save some time for others...\n- still an awesome valid solution for building a node + typeorm app 7 years later\n- For me, it does throw an `new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')` do you have any idea on the reason why ?\n- @Rapha&#235;lBalet this seems to be related to one of your dependencies having a native binding and node not being able to find the precompiled package. I would try npm rebuild before running ncc.","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":352,"estimatedTokens":3277}}34{"id":"stack-68437734","source":"stackoverflow","questionId":68437734,"title":"Jest has detected the following 1 open handle potentially keeping Jest from exiting: TCPSERVERWRAP","tags":["typescript","jestjs","graphql","nestjs","supertest"],"text":"Title: Jest has detected the following 1 open handle potentially keeping Jest from exiting: TCPSERVERWRAP\nTags: typescript, jestjs, graphql, nestjs, supertest\nSource: Stack Overflow\n\nQuestion:\nI am doing a basic end to end testing here, for the moment it's failing, but first I can't get rid of the open handle.\n\n```\nRan all test suites.\n\nJest has detected the following 1 open handle potentially keeping Jest from exiting:\n\n โ— TCPSERVERWRAP\n\n 40 | }\n 41 | return request(app.getHttpServer())\n > 42 | .post('/graphql')\n | ^\n 43 | .send(mutation)\n 44 | .expect(HttpStatus.OK)\n 45 | .expect((response) => {\n\n at Test.Object..Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)\n at new Test (../node_modules/supertest/lib/test.js:38:12)\n at Object.obj. [as post] (../node_modules/supertest/index.js:27:14)\n at Object. (app.e2e-spec.ts:42:8)\n```\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n })\n\n afterAll(async () => {\n await app.close()\n })\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n\n it('mutation', async () => {\n const mutation = {\n query: `mutation Create($title: String!) {\n create(title: $title) {\n id,\n title\n }\n }`,\n variables: {\n title: 'Mon programme',\n },\n }\n return request(app.getHttpServer())\n .post('/graphql')\n .send(mutation)\n .expect(HttpStatus.OK)\n .expect( (response) => {\n expect(response.body).toBe({\n id: expect.any(String),\n title: 'Mon programme',\n })\n })\n })\n})\n```\n\nAny idea what's blocking the test runner ?\n\nNote that, as I am using NestJs, I shouldn't need to use the `.end(done)` method at the end of the test.\n\nPS: apparently I have to much code on this question and I need to add some more details, but have no clue what I can say more.\n\n========================================\n\nTop Answer:\nThis is the problem right here\n\n```\nit('/ (GET)', () => {\n return request(app.getHttpServer())\n ^^^^^^^^^^^^^^^^^^^^^\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n```\n\nThe server isn't being closed and remains open after the test. You need to create a variable to reference the instance and close it after each test.\nI just spent a couple of hours trying to figure this out. And hope this helps anyone experiencing similar issues.\n\nHere is an example of your code with my idea for a fix:\n\n```\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n let server: SERVER_TYPE\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n // Reference the server instance\n server = app.getHttpServer()\n })\n\n afterEach(async () => {\n await app.close()\n // Close the server instance after each test\n server.close()\n })\n\n it('/ (GET)', async () => {\n // Make the request on the server instance\n return await request(server)\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n```\n\nAlso, I noticed you're using `beforeEach` and `afterAll`. You're creating a new app each time for each test so I think that could also cause some issues for the HTTP server. I'm not certain on that though.\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\nbeforeEach(() => {\n ...\n})\n\nafterEach(() => {\n ...\n})\n\ndescribe('tests', () => {\n ...\n})\n```\n\nBut, that's just my preference, up to you. :)\n\nUPDATE: Meant to use `beforeEach` not `beforeAll` because we need to close the server before EACH test, not a global setup and teardown.\n\nUPDATE 2: Using async/await otherwise, it will always pass because request is asynchronous and doesn't complete unless you wait for it to finish.\n\n========================================\n\nCode:\n```text\nRan all test suites.\n\nJest has detected the following 1 open handle potentially keeping Jest from exiting:\n\n  โ—  TCPSERVERWRAP\n\n      40 |     }\n      41 |     return request(app.getHttpServer())\n    > 42 |       .post('/graphql')\n         |        ^\n      43 |       .send(mutation)\n      44 |       .expect(HttpStatus.OK)\n      45 |       .expect((response) => {\n\n      at Test.Object.<anonymous>.Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)\n      at new Test (../node_modules/supertest/lib/test.js:38:12)\n      at Object.obj.<computed> [as post] (../node_modules/supertest/index.js:27:14)\n      at Object.<anonymous> (app.e2e-spec.ts:42:8)\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\ndescribe('AppController (e2e)', () => {\n  let app: INestApplication\n\n  beforeEach(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile()\n\n    app = moduleFixture.createNestApplication()\n    await app.init()\n  })\n\n  afterAll(async () => {\n    await app.close()\n  })\n\n  it('/ (GET)', () => {\n    return request(app.getHttpServer())\n      .get('/')\n      .expect(HttpStatus.OK)\n      .expect('Hello World!')\n  })\n\n  it('mutation', async () => {\n    const mutation = {\n      query: `mutation Create($title: String!) {\n        create(title: $title) {\n          id,\n          title\n        }\n      }`,\n      variables: {\n        title: 'Mon programme',\n      },\n    }\n    return request(app.getHttpServer())\n      .post('/graphql')\n      .send(mutation)\n      .expect(HttpStatus.OK)\n      .expect( (response) => {\n        expect(response.body).toBe({\n          id: expect.any(String),\n          title: 'Mon programme',\n        })\n      })\n  })\n})\n```\n\n```text\n.end(done)\n```\n\n```text\njest --config ./test/jest-e2e.json --forceExit\n```\n\n```text\nbeforeEach\n```\n\n```text\nafterAll\n```\n\n```text\nrequest\n```\n\n```text\nbeforeEach\n```\n\n```text\nbeforeAll\n```\n\n```text\ntest('mutation', async (done) => {\n    const mutation = {\n      query: `mutation Create($title: String!) {\n        create(title: $title) {\n          id,\n          title\n        }\n      }`,\n      variables: {\n        title: 'Mon programme',\n      },\n    }\n    const response = request(app.getHttpServer())\n      .post('/graphql')\n      .send(mutation)\n     expect(response).to.be(HttpStatus.Ok)\n     done()\n  })\n```\n\n```text\nit\n```\n\n```text\ntest\n```\n\n```text\ndone\n```\n\n```js\nit('the description', (done) => {\n        request(app)\n          .get('/some-path')\n          .end(done);\n  });\n```\n\n```js\nit('/ (GET)', () => {\n    return request(app.getHttpServer())\n                  ^^^^^^^^^^^^^^^^^^^^^\n      .get('/')\n      .expect(HttpStatus.OK)\n      .expect('Hello World!')\n  })\n```\n\n```js\ndescribe('AppController (e2e)', () => {\n  let app: INestApplication\n  let server: SERVER_TYPE\n\n  beforeEach(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile()\n\n    app = moduleFixture.createNestApplication()\n    await app.init()\n    // Reference the server instance\n    server = app.getHttpServer()\n  })\n\n  afterEach(async () => {\n    await app.close()\n    // Close the server instance after each test\n    server.close()\n  })\n\n  it('/ (GET)', async () => {\n    // Make the request on the server instance\n    return await request(server)\n      .get('/')\n      .expect(HttpStatus.OK)\n      .expect('Hello World!')\n  })\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\nbeforeEach(() => {\n  ...\n})\n\nafterEach(() => {\n  ...\n})\n\ndescribe('tests', () => {\n  ...\n})\n```\n\n```text\nbeforeEach\n```\n\n```text\nafterAll\n```\n\n```text\nbeforeEach\n```\n\n```text\nbeforeAll\n```\n\n```text\nafterEach\n```\n\n```text\nafterEach(async () => {\n```\n\n```text\nawait userService.logout();\n```\n\n```text\n});\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\ntest:e2e\n```\n\n```text\n--detectOpenHandles\n```\n\n```text\n\"test:e2e\": \"jest --config ./test/jest-e2e.json --forceExit\"\n```\n\n```text\n--no-cache --watchAll\n```\n\n```text\n\"test\": \"jest --watchAll --no-cache --detectOpenHandles\"\n```\n\n```text\n\"test:e2e\": \"jest --config ./test/jest-e2e.json --no-cache --detectOpenHandles\",\n```\n\n```text\nafterAll(async () => {\n await server.close();\n await pool.end();\n});\n```\n\n```text\nprocess.exit()\n```\n\n========================================\n\nComments:\n- Thank for the answer. But unfortunately it has no effect.\n- @AMehmeto hm, strange, are you running multiple tests in parallel or just one file?\n- Just one file only.\n- @AMehmeto my second guess is that something is happening within your app that keeps it from exiting. Have you read through this thread, expecially the linked comment?\n- thank you so much I have spent hours trying to mock the setInterval() function causing problems but it didn't work. This is an easy, simple fix.\n- I had --forceExit and --detectOpenHandles in my script after removed --detectOpenHandles it solved \"test:e2e\": \"jest --config ./test/jest-e2e.json --forceExit\"\n- adding `--no-cache --watchAll` fixed for me, as answered by tonskton. my script: `jest --config .&#47;test&#47;jest-e2e.json --detectOpenHandles --watchAll --no-cache`\n- i don't think you need `--detectOpenHandles` in your script since that's more for debugging. I guess if you want to always have that output, then sure, but it's not necessary to get jest to exit.\n- `--watchAll` fixes the issue for me too but then requires interaction. This isn't great in a CI/CD build though.\n- No joy here. So far only the `--forceExit` options works for me.\n- it and test are the same\n- Actually there are two approaches mixed here, either use async or the done callback. You will notice using both isn't possible in Typescript, where it refuses to run this code.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- I don't know why, but this is the only thing that worked for me, `--no-cache --watchAll` did the trick. `--watchAll` is not optional which makes no sense to me, however I'm happy it works, I am using mongoose and mongodb-memory-server\n- but it seems like not the best option due to: \"The cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower.\" from official docs","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":468,"estimatedTokens":2763}}35{"id":"stack-69438275","source":"stackoverflow","questionId":69438275,"title":"Nest.js validate array of strings if there are defined strings only","tags":["typescript","validation","request","nestjs","class-validator"],"text":"Title: Nest.js validate array of strings if there are defined strings only\nTags: typescript, validation, request, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nIn the nest.js application on controller level I have to validate DTO.\n\nI've faced with difficulty to check if item is not null (request should be rejected if any list item is `null` or `undefined`)\n\nCode bellow demonstrates my configured verifications.\n\n```\nimport { ArrayMinSize, IsArray } from 'class-validator'\n\nexport class ReminderPayload {\n // ...\n @IsArray()\n @ArrayMinSize(1)\n recipients: string[]\n}\n```\n\n### Question\n\n- I'm looking for help to reject requests with body data like\n\n```\n{\n \"recipients\": [\n null\n ]\n}\n```\n\n- How to validate if array items are `string` only (it should reject handling if object is in the array item position)?\n\n### P.S.\n\n`'class-validator'` injected successfully, and it produces some validation results for my API.\n\n========================================\n\nTop Answer:\nFor someone who wants to validate specific strings in array:\n\n```\nclass MyDto {\n @IsIn(['monday', 'tuesday', 'wednesday', 'thursday', 'friday'], { each: true })\n weekdays: string[];\n\n // regex mask validation\n @Matches('^[a-zA-Z\\\\s]+$', undefined, { each: true })\n words: string[];\n\n @Contains('hello', { each: true })\n greetings: string[];\n}\n```\n\nFor custom validation:\n\n```\nimport {\n ArrayNotEmpty,\n IsArray,\n Validate,\n ValidateNested,\n ValidatorConstraint,\n ValidatorConstraintInterface\n} from 'class-validator'\n\n@ValidatorConstraint({ name: 'arrayPrefixValidator' })\nexport class ArrayPrefixValidator implements ValidatorConstraintInterface {\n validate(values: string[] = []): boolean {\n if (values.length) {\n return values.every((value) => value.startsWith('user-'))\n }\n return false\n }\n}\n\nclass MyDto {\n // Each item contains a prefix str-\n @Validate(ArrayPrefixValidator, { message: 'No user- prefix' })\n accounts: string[];\n}\n```\n\nFor more information go to official docs\n\n========================================\n\nCode:\n```text\nimport { ArrayMinSize, IsArray } from 'class-validator'\n\nexport class ReminderPayload {\n    // ...\n    @IsArray()\n    @ArrayMinSize(1)\n    recipients: string[]\n}\n```\n\n```text\n{\n    \"recipients\": [\n        null\n    ]\n}\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n```text\nstring\n```\n\n```text\n'class-validator'\n```\n\n```text\nimport { ArrayMinSize, IsArray, IsString } from 'class-validator';\n\nexport class ReminderPayloadDto {\n  // ...\n  @IsArray()\n  @IsString({ each: true })  // \"each\" tells class-validator to run the validation on each item of the array\n  @ArrayMinSize(1)\n  recipients: string[];\n}\n```\n\n```text\nclass-validator\n```\n\n```text\neach\n```\n\n```text\nclass MyDto {\n    @IsIn(['monday', 'tuesday', 'wednesday', 'thursday', 'friday'], { each: true })\n    weekdays: string[];\n\n    // regex mask validation\n    @Matches('^[a-zA-Z\\\\s]+$', undefined, { each: true })\n    words: string[];\n\n    @Contains('hello', { each: true })\n    greetings: string[];\n}\n```\n\n```text\nimport {\n  ArrayNotEmpty,\n  IsArray,\n  Validate,\n  ValidateNested,\n  ValidatorConstraint,\n  ValidatorConstraintInterface\n} from 'class-validator'\n\n@ValidatorConstraint({ name: 'arrayPrefixValidator' })\nexport class ArrayPrefixValidator implements ValidatorConstraintInterface {\n  validate(values: string[] = []): boolean {\n    if (values.length) {\n      return values.every((value) => value.startsWith('user-'))\n    }\n    return false\n  }\n}\n\nclass MyDto {\n    // Each item contains a prefix str-\n    @Validate(ArrayPrefixValidator, { message: 'No user- prefix' })\n    accounts: string[];\n}\n```\n\n========================================\n\nComments:\n- Brilliant! You've missed `@IsNotEmpty({ each: true })`, but I've got the idea and missed documentation part\n- @Sergii, I think IsString() will cover IsNotEmpty(). please correct me if I'm wrong.\n- @Mahmoud, @IsString() verifies only input value type. It fails if input value is number type for example.\n- what's the difference when the `each: true` is set on the `@isString` and when set on the `@IsArray`\n- You can read `each` as \"each item in the array\". `@IsString({ each: true })` means \"each item of the array is a string\". `@IsArray({ each: true })` would mean \"each item of the array is also an array\". The reason behind being able to specify whether you're talking about the array as a whole, or each item in the array, is so that you can validate the two separately. I can define a max length for the array, then define string validation to every item inside.\n- It seems like we don't need to specify @IsArray anymore, each does this itself: (property) ValidationOptions.each?: boolean Specifies if validated value is an array and each of its items must be validated.","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":198,"estimatedTokens":1180}}36{"id":"stack-60451337","source":"stackoverflow","questionId":60451337,"title":"Password confirmation in TypeScript with `class-validator`","tags":["typescript","nestjs","class-validator"],"text":"Title: Password confirmation in TypeScript with `class-validator`\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nToday, I am trying to figure out how to validate a Sign Up form in the backend side (NestJS) of the app. I am just wondering if exists a way to validate `password` and `passwordConfirm` matching, using `class-validator` package to build up a custom validator or exploit provided ones. I am thinking about a class validator, not a field one.\n\n```\n// Maybe validator here\nexport class SignUpDto {\n @IsString()\n @MinLength(4)\n @MaxLength(20)\n username: string;\n\n @IsString()\n @MinLength(4)\n @MaxLength(20)\n @Matches(/((?=.*\\d)|(?=.*\\W+))(?![.\\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})\n password: string;\n\n @IsString()\n @MinLength(4)\n @MaxLength(20)\n passwordConfirm: string;\n}\n```\n\nWhat do you suggest?\n\n========================================\n\nTop Answer:\nFor the validating password, I suggest using `@IsStrongPassword` from `class-validator`\n\nIt could be like this\n\n```\n@IsStrongPassword({\n minLength: 8,\n minLowercase: 1,\n minNumbers: 1,\n minSymbols: 1,\n minUppercase: 1\n })\n password: string;\n```\n\n========================================\n\nCode:\n```text\n// Maybe validator here\nexport class SignUpDto {\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    username: string;\n\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    @Matches(/((?=.*\\d)|(?=.*\\W+))(?![.\\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})\n    password: string;\n\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    passwordConfirm: string;\n}\n```\n\n```text\npassword\n```\n\n```text\npasswordConfirm\n```\n\n```text\nclass-validator\n```\n\n```text\nexport class SignUpDto {\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    username: string;\n\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    @Matches(/((?=.*\\d)|(?=.*\\W+))(?![.\\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})\n    password: string;\n\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    @Match('password')\n    passwordConfirm: string;\n}\n```\n\n```text\nimport {registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';\n\nexport function Match(property: string, validationOptions?: ValidationOptions) {\n    return (object: any, propertyName: string) => {\n        registerDecorator({\n            target: object.constructor,\n            propertyName,\n            options: validationOptions,\n            constraints: [property],\n            validator: MatchConstraint,\n        });\n    };\n}\n\n@ValidatorConstraint({name: 'Match'})\nexport class MatchConstraint implements ValidatorConstraintInterface {\n\n    validate(value: any, args: ValidationArguments) {\n        const [relatedPropertyName] = args.constraints;\n        const relatedValue = (args.object as any)[relatedPropertyName];\n        return value === relatedValue;\n    }\n\n}\n```\n\n```text\nimport { \n    registerDecorator, \n    ValidationArguments, \n    ValidationOptions \n} from 'class-validator';\n\nexport function IsEqualTo(property: string, validationOptions?: ValidationOptions) {\n    return (object: any, propertyName: string) => {\n      registerDecorator({\n        name: 'isEqualTo',\n        target: object.constructor,\n        propertyName,\n        constraints: [property],\n        options: validationOptions,\n        validator: {\n          validate(value: any, args: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          const relatedValue = (args.object as any)[relatedPropertyName];\n          return value === relatedValue;\n        },\n\n        defaultMessage(args: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          return `${propertyName} must match ${relatedPropertyName} exactly`;\n        },\n      },\n    });\n  };\n}\n```\n\n```text\n@IsEqualTo\n```\n\n```text\n@MinLength(requiredlength ex: 5)\n @MaxLength(requiredlength ex:5)\n```\n\n```js\n@Match('passwordd')\n//              ๐Ÿ‘†\n```\n\n```js\n@Match(SignUpDto, (s) => s.password)\n```\n\n```js\nimport { ClassConstructor } from \"class-transformer\";\n\nexport const Match = <T>(\n  type: ClassConstructor<T>,\n  property: (o: T) => any,\n  validationOptions?: ValidationOptions,\n) => {\n  return (object: any, propertyName: string) => {\n    registerDecorator({\n      target: object.constructor,\n      propertyName,\n      options: validationOptions,\n      constraints: [property],\n      validator: MatchConstraint,\n    });\n  };\n};\n\n@ValidatorConstraint({ name: \"Match\" })\nexport class MatchConstraint implements ValidatorConstraintInterface {\n  validate(value: any, args: ValidationArguments) {\n    const [fn] = args.constraints;\n    return fn(args.object) === value;\n  }\n\n  defaultMessage(args: ValidationArguments) {\n    const [constraintProperty]: (() => any)[] = args.constraints;\n    return `${constraintProperty} and ${args.property} does not match`;\n  }\n}\n```\n\n```js\nexport class SignUpDto {\n  // ...\n  password: string;\n\n  // finally, we have ๐Ÿ˜Ž\n  @Match(SignUpDto, (s) => s.password)\n  passwordConfirm: string;\n}\n```\n\n```text\nGenerics\n```\n\n```text\nMatch\n```\n\n```text\nimport {\n  registerDecorator,\n  ValidationArguments,\n  ValidationOptions,\n} from 'class-validator';\n\nexport function IsEqualTo<T>(\n  property: keyof T,\n  validationOptions?: ValidationOptions,\n) {\n  return (object: any, propertyName: string) => {\n    registerDecorator({\n      name: 'isEqualTo',\n      target: object.constructor,\n      propertyName,\n      constraints: [property],\n      options: validationOptions,\n      validator: {\n        validate(value: any, args: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          const relatedValue = (args.object as any)[relatedPropertyName];\n          return value === relatedValue;\n        },\n\n        defaultMessage(args: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          return `${propertyName} must match ${relatedPropertyName} exactly`;\n        },\n      },\n    });\n  };\n}\n```\n\n```text\nexport class CreateUserDto {\n  @IsEqualTo<CreateUserDto>('password')\n  readonly password_confirmation: string;\n}\n```\n\n```text\n@ValidatorConstraint({ name: 'CustomMatchPasswords', async: false })\nexport class CustomMatchPasswords implements ValidatorConstraintInterface {\n   validate(password: string, args: ValidationArguments) {\n\n      if (password !== (args.object as any)[args.constraints[0]]) return false;\n      return true;\n   }\n\n   defaultMessage(args: ValidationArguments) {\n      return \"Passwords do not match!\";\n   }\n}\n```\n\n```text\n@IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    @Matches(/((?=.*\\d)|(?=.*\\W+))(?![.\\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})\n    password: string;\n\n    @IsString()\n    @MinLength(4)\n    @MaxLength(20)\n    @Validate(CustomMatchPasswords, ['password'])\n    passwordConfirm: string;\n```\n\n```js\nimport {\n  ValidatorConstraint,\n  ValidatorConstraintInterface,\n  ValidationOptions,\n  registerDecorator,\n  ValidationArguments\n} from 'class-validator'\nimport { ClassConstructor } from 'class-transformer'\n\ntype Tfn<T> = (o: T) => any\n\nexport const Match = <T>(\n  type: ClassConstructor<T>,\n  property: Tfn<T>,\n  validationOptions?: ValidationOptions\n) => {\n  return (object: unknown, propertyName: string) => {\n    registerDecorator({\n      target: object.constructor,\n      propertyName,\n      options: validationOptions,\n      constraints: [property],\n      validator: MatchConstraint<T>\n    })\n  }\n}\n\n@ValidatorConstraint({ name: 'Match' })\nexport class MatchConstraint<T> implements ValidatorConstraintInterface {\n  validate(value: any, args: ValidationArguments) {\n    const [fn] = args.constraints as Tfn<T>[]\n    return fn(args.object as T) === value\n  }\n}\n```\n\n```text\n@IsStrongPassword({\n    minLength: 8,\n    minLowercase: 1,\n    minNumbers: 1,\n    minSymbols: 1,\n    minUppercase: 1\n  })\n  password: string;\n```\n\n```text\n@IsStrongPassword\n```\n\n```text\nclass-validator\n```\n\n```js\nimport { Type } from \"@nestjs/common\";\nimport { ValidationArguments, ValidationOptions, registerDecorator } from \"class-validator\";\n\nexport function IsMatchWith<T, K extends keyof T>(classRef: Type<T>, property?: readonly K[], validationOpt?: ValidationOptions) {\n    return (obj: any, propertyName: string) => {\n        registerDecorator({\n            target: obj.constructor,\n            propertyName,\n            options: validationOpt,\n            constraints: [property],\n            validator: {\n                validate(value: any, args: ValidationArguments) {\n                    return !(value !== (args.object as any)[args.constraints[0]])\n                },\n\n                defaultMessage({ property, constraints }: ValidationArguments): string {\n                    return `${property} must match ${constraints[0]}`;\n                }\n            }\n        })\n    }\n}\n```\n\n```text\n@nestjs/mapped-types\n```\n\n```js\nimport {\n  IsDefined,\n  IsIn,\n  IsString,\n  MinLength,\n  ValidateIf,\n} from 'class-validator';\n\nexport class ForgotReturnPasswordDto {\n  @IsString()\n  @IsDefined()\n  @MinLength(3)\n  password: string;\n\n  @IsString()\n  @IsDefined()\n  @IsIn([Math.random()], {\n    message: 'Passwords do not match',\n  })\n  @ValidateIf((o) => o.password !== o.repeatPassword)\n  repeatPassword: string;\n}\n```\n\n```text\n@IsStrongPassword(\n{\n  minLength: 8,\n  minLowercase: 1,\n  minUppercase: 1,\n  minNumbers: 1,\n  minSymbols: 0,\n},\n{\n  message:\n    'The password should contain at least 1 uppercase character, 1 lowercase, 1 number and should be at least 8 characters long.'\n },\n)\n  password!: string;\n```\n\n```text\n@ApiPropertyOptional({ minLength: 6 })\n  @IsString()\n  @MinLength(6)\n  password?: string;\n\n  @ApiPropertyOptional()\n  @IsString()\n  @MinLength(6)\n  @ValidateIf((o) => o.password !== o.passwordConfirm)\n  @Equals('password', { message: 'confirmPassword must match password' })\n  passwordConfirm?: string;\n```\n\n========================================\n\nComments:\n- Don't think it supports this yet: github.com/typestack/class-validator/issues/486\n- @AndreiTฤƒtar What a pity! Thanks for your answer!\n- @piero: It's not supported yet as mentioned. But here's an example decorator (@IsLongerThan): github.com/typestack/class-validator/tree/master/sample/&hellip; .... it checks if a property is longer than another one. So it's possible to compare one property against another. You can use this example to create a decorator that does what you want.\n- @ChristopheGeers I will give it a try as soon as possible. Thanks for your comment!\n- @ChristopheGeers thanks for your help! It worked!\n- @PieroMacaluso I would not set a maxlength on passwords, see: stackoverflow.com/questions/98768/&hellip; i also hope you hash the passwords\n- @YAMM, you are right! It was just an example. By the way, I think that it could be better to set a very high max length to avoid problems with very large inputs (see: stackoverflow.com/a/98857/7358319).\n- @PieroMacaluso ok thats a valid point... on the other hand if you use bcrypt... mscharhag.com/software-development/&hellip;\n- @YAMM Thanks for the link! Very interesting!\n- Late to the game but why even send the password confirmation to the service? The entire (somewhat misguided) reason for the password confirmation is to ensure that the user has entered the password they intended to. That validation can take place entirely on the UI-side and only one password property needs to be sent to the service.\n- @BillDagg I was just about to write exactly that comment!\n- @AbandonedCrypt It's probably the API is designed to be used like a \"API resources\" for bulk users insert or something like that\n- It seems a very good solution, but it has a lot of problem with the *TypeScript* linting.\n- You can add this method to MatchConstraint class for error message: `defaultMessage(args: ValidationArguments){ return args.property + \" must match \" + args.constraints[0]; }`\n- But password is stored in db in hashed form, so there will be issues with validation. Take even length\n- nice....perfect solution\n- What is `requiredlength ex:5`?\n- Which module is `ClassConstructor` from? I can't seem to find it anywhere.\n- You need to import it from class-transformer: `import { ClassConstructor } from \"class-transformer\"`;\n- this should be the top answer right now\n- this is the true and simple\n- this is works fine","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":471,"estimatedTokens":3096}}37{"id":"stack-55478828","source":"stackoverflow","questionId":55478828,"title":"Is it possible to set default values for a DTO?","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Is it possible to set default values for a DTO?\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there some way to use default values when a query is empty?\n\nIf I have the following DTO for a query:\n\n```\nexport class MyQuery {\n readonly myQueryItem: string;\n}\n```\n\nAnd my request contains no query, then `myQuery.myQueryItem`ย will be undefined. How do I make it so it has a default value ?\n\n========================================\n\nTop Answer:\nHere I want to set the default value of a status\n\n```\nexport class CreateOrderDto {\n @IsInt()\n @IsNotEmpty()\n cost: number;\n \n @IsEnum(ORDER_STATUS)\n @IsString()\n status: string;\n \n constructor(partial: Partial) {\n Object.assign(this, partial);\n this.status = this.status || 'Pending';\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport class MyQuery {\n  readonly myQueryItem: string;\n}\n```\n\n```text\nmyQuery.myQueryItem\n```\n\n```text\nexport class MyQuery {\n  readonly myQueryItem = 'mydefault';\n}\n```\n\n```text\n@Get()\n@UsePipes(new ValidationPipe({ transform: true }))\ngetHello(@Query() query: MyQuery) {\n  return query;\n}\n```\n\n```text\nclass Person {\n  firstname: string;\n  lastname?: string = 'May';\n\n  constructor(person) {\n    Object.assign(this, person);\n  }\n}\n\n// You can use Person as a type for a plain object -> no default value\nconst personInput: Person = { firstname: 'Yuna' };\n\n// When an actual instance of the class is created, it uses the default value\nconst personInstance: Person = new Person(personInput);\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\n@Body()\n```\n\n```text\n@Param()\n```\n\n```text\n@Query()\n```\n\n```text\nParseIntPipe\n```\n\n```text\nValidationPipe\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\ntransform: true\n```\n\n```text\nexport class CreateOrderDto {\n  @IsInt()\n  @IsNotEmpty()\n  cost: number;\n    \n  @IsEnum(ORDER_STATUS)\n  @IsString()\n  status: string;\n    \n  constructor(partial: Partial<CreateOrderDto>) {\n    Object.assign(this, partial);\n    this.status = this.status || 'Pending';\n  }\n}\n```\n\n========================================\n\nComments:\n- I tried doing this. First, I had to `npm install class-validator`. Then I got the following message in the console when sending a request: `No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies`. And I can't manage to understand what's going wrong (Google is of no help here).\n- Yes, you need to install both `class-validator` and `class-transformer`. Make sure that `class-validator` is listed only once in your `package.json`. Then try reinstalling your dependencies with `npm ci`.\n- I ensured my package.json contains both of these packages once each, and did `npm ci`, but nothing has changed.\n- Could you please explain me how the ValidationPipe works? For now I still can't get the magic of it. ValidationPipe is a kind of middleware, right? I can apply it to the function (like in our example), or to a specific DTO (`@Query(new ValidationPipe())`), right? What exactly does `tranform: true`? Why is it needed to use the default values of a DTO and why aren't these default values used otherwise?\n- This does not work with class-validator\n- This answer is incomplete. You need to also set `transformOptions: { exposeDefaultValues: true }` in the options for `ValidationPipe`.\n- Not sure why, but I verified this over and over with all the recommendations, and at least on NestJS common v8.4.3 and class-validator v0.13.2, I only had to set `transform` to `true` to get this to work as described.","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":154,"estimatedTokens":910}}38{"id":"stack-70884240","source":"stackoverflow","questionId":70884240,"title":"Test functions cannot both take a 'done' callback","tags":["javascript","unit-testing","jestjs","nestjs"],"text":"Title: Test functions cannot both take a 'done' callback\nTags: javascript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a simple test with nestjs, and I'm getting this error\n\nTest functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.\n\nReturned value: Promise {}\n\nThe unit test is so simple, but I get an error when I use done();\n\n```\nit('throws an error if a user signs up with an email that is in use', async (done) => {\nfakeUsersService.find = () => Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);\ntry {\n await service.signup('asdf@asdf.com', 'asdf');\n} catch (err) {\n done();\n}\n});\n```\n\n========================================\n\nTop Answer:\nfor the last version from jest, you can't use `async/await , promise and done together.\n\nthe solution is\n\n```\nit(\"throws an error if user sings up with email that is in use\", async () => {\n fakeUsersService.find = () =>\n Promise.resolve([{ id: 1, email: \"a\", password: \"1\" } as User]);\n await expect(service.signup(\"asdf@asdf.com\", \"asdf\")).rejects.toThrow(\n BadRequestException\n );\n });\n```\n\nchange `BadRequestException` according to your listening exception\n\n========================================\n\nCode:\n```text\nit('throws an error if a user signs up with an email that is in use', async (done) => {\nfakeUsersService.find = () => Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);\ntry {\n  await service.signup('asdf@asdf.com', 'asdf');\n} catch (err) {\n  done();\n}\n});\n```\n\n```text\nit('throws an error if user signs up with email that is in use', async () => {\n    try {\n        await service();\n        expect(...);\n    } catch (err) {\n    }\n});\n```\n\n```text\nit('throws an error if user signs up with email that is in use', (done) => {\n    ...\n    service()\n     .then( ...) {}\n     .catch( ...) {}\n    }\n    done();\n});\n```\n\n```text\nit(\"throws an error if user sings up with email that is in use\", async () => {\n    fakeUsersService.find = () =>\n      Promise.resolve([{ id: 1, email: \"a\", password: \"1\" } as User]);\n    await expect(service.signup(\"asdf@asdf.com\", \"asdf\")).rejects.toThrow(\n      BadRequestException\n    );\n  });\n```\n\n```text\nBadRequestException\n```\n\n```text\n// config-overrides.js\nmodule.exports.jest = (config) => {\n    config.testRunner = 'jest-jasmine2';\n    return config;\n};\n```\n\n```text\nimport {\n  Entity,\n  Column,\n  PrimaryGeneratedColumn,\n  AfterInsert,\n  AfterRemove,\n  AfterUpdate,\n} from 'typeorm';\n\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  email: string;\n\n  @Column()\n\n  password: string;\n\n  @AfterInsert()\n  logInsert() {\n    console.log('Inserted User with id', this.id);\n  }\n\n  @AfterUpdate()\n  logUpdate() {\n    console.log('Updated User with id', this.id);\n  }\n\n  @AfterRemove()\n  logRemove() {\n    console.log('Removed User with id', this.id);\n  }\n}\n```\n\n```text\nit('throws an error if user signs up with email that is in use', async () => {\n    fakeUsersService.find = () =>\n      Promise.resolve([{ id: 1, email: 'typescript@nestjs.jestjs', password: '1' } as User]);\n\n    expect(async () => {\n      const email = 'asdf@asdf.com';\n      const password = 'asdf';\n      await service.signup(email, password);\n    }).rejects.toThrow(BadRequestException);\n  });\n```\n\n```text\nit('throws an error if a user signs up with an email that is in use', async () => {\n    await service.signup('asdf@asdf.com', 'asdf');\n    try {\n     await service.signup('asdf@asdf.com', 'asdf');\n    } catch (e) {\n      expect(e.toString()).toMatch('email in use');\n    }\n  });\n```\n\n```text\nit('throws an error if a user signs up with an email that is in use', async () => {\nfakeUsersService.find = () =>\n  Promise.resolve([\n    { id: 1, email: 'test@test.com', password: 'somePassword' } as User,\n  ]);\n  expect(async () => {\n  await service.signup('test@test.com', 'somePassword')\n  }).rejects.toThrow(BadRequestException)\n});\n```\n\n```text\nit('should make an api request', (done) => {\n  const asyncCall = async () => {\n    await callbackWithApiInside();\n\n    setTimeout(() => {\n      expect(api).toHaveBeenNthCalledWith(1, payload);\n      done();\n    }, 1000);\n  };\n\n  asyncCall();\n});\n```\n\n```text\nit('throws an error if a user signs up with an email that is in use', async () => {\n  fakeUsersService.find = () =>\n    Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);\n  try {\n    await service.signup('asdf@asdf.com', 'asdf');\n  } catch {\n    return;\n  }\n});\n```\n\n```text\nreturn\n```\n\n```text\ndone()\n```\n\n========================================\n\nComments:\n- jestjs.io/docs/asynchronous\n- this answer is misleading, its about jest v27 & not using jasmine2.\n- which is the config most people in the future will have, right? @ToKra\n- Please don't post answers like this because this is a comment. If you keep doing this you will be rendered unable to ask questions in SO due to the downvotes you going to receive. So please read this, I'm trying to help not being rood.\n- This is an answer that worked for me.\n- Thanks very helpful, using expect().rejects.toThrow() was the only solution that worked for me.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- this is terrible and not what anyone should do. Flaky tests that now take a ton of time because of some setTimeout.","metadata":{"transformedAt":"2026-08-18T18:33:02.399Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":221,"estimatedTokens":1391}}39{"id":"stack-55673424","source":"stackoverflow","questionId":55673424,"title":"NestJs: Unable to read env variables in module files but able in service files?","tags":["javascript","node.js","typescript","nestjs","dotenv"],"text":"Title: NestJs: Unable to read env variables in module files but able in service files?\nTags: javascript, node.js, typescript, nestjs, dotenv\nSource: Stack Overflow\n\nQuestion:\nI have an `.env` file at the root of my NestJs project with some env variables in it. \n\nThe strange thing is that I am able to read the variables in service files but not in module files. \n\nSo in a service file like `users.service.ts`, this works:\n\n```\nsaveAvatar() {\n const path = process.env.AVATAR_PATH // returns value from .env\n}\n```\n\nHowever, when accessing a path in a module file like `auth.module.ts`, this returns an empty value:\n\n```\n@Module({\n imports: [\n JwtModule.register({\n secretOrPrivateKey: process.env.SECRET // process.env.SECRET returns an empty string\n })\n ]\n})\n```\n\nWhy is that so? How can I reliably access environmental variables in the `.env` file in NestJs?\n\n========================================\n\nTop Answer:\nThe declaring order is important in your use case.\n\nThis works:\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot(),\n ScheduleModule.forRoot(),\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: process.env.SYN_MONGO_HOST,\n port: +process.env.SYN_MONGO_PORT,\n username: process.env.SYN_MONGO_USERNAME,\n password: process.env.SYN_MONGO_PASSWORD,\n database: process.env.SYN_MONGO_DATABASE,\n authSource: 'admin',\n autoLoadEntities: true,\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class ConfigurationModule {}\n```\n\nWhen this doesn't\n\n```\n@Module({\n imports: [\n ScheduleModule.forRoot(),\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: process.env.SYN_MONGO_HOST,\n port: +process.env.SYN_MONGO_PORT,\n username: process.env.SYN_MONGO_USERNAME,\n password: process.env.SYN_MONGO_PASSWORD,\n database: process.env.SYN_MONGO_DATABASE,\n authSource: 'admin',\n autoLoadEntities: true,\n }),\n ConfigModule.forRoot(),\n ],\n controllers: [],\n providers: [],\n})\nexport class ConfigurationModule {}\n```\n\nThis is because ConfigModule is load before or after TypeOrmModule.\n\n========================================\n\nCode:\n```text\nsaveAvatar() {\n    const path = process.env.AVATAR_PATH    // returns value from .env\n}\n```\n\n```text\n@Module({\n    imports: [\n       JwtModule.register({\n          secretOrPrivateKey: process.env.SECRET   // process.env.SECRET returns an empty string\n       })\n    ]\n})\n```\n\n```text\n.env\n```\n\n```text\nusers.service.ts\n```\n\n```text\nauth.module.ts\n```\n\n```text\n.env\n```\n\n```text\nJwtModule.registerAsync({\n    imports: [ConfigModule],\n    useFactory: async (configService: ConfigService) => ({\n      secret: configService.jwtSecret,\n    }),\n    inject: [ConfigService],\n}),\n```\n\n```text\n.env\n```\n\n```text\nJwtModule\n```\n\n```text\nmain.ts\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\nConfigModule.forRoot({\n  isGlobal: true\n});\n```\n\n```text\n@Module({})\nexport class AuthModule {\n\n    static forRoot(): DynamicModule {\n        return {\n            imports: [\n                JwtModule.register({\n                    secretOrPrivateKey: process.env.SECRET   // process.env.SECRET will return the proper value\n                })\n            ],\n            module: AuthModule\n        }\n    }\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n    imports: [ConfigModule.forRoot(), AuthModule.forRoot()]\n})\n```\n\n```text\nAuthModule.forRoot(process.env.SECRET)\n```\n\n```text\nprocess.env.SECRET\n```\n\n```text\nimport dotenv from \"dotenv\";\n\ndotenv.config({path:<path-to-env-file>})\n```\n\n```js\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    ScheduleModule.forRoot(),\n    TypeOrmModule.forRoot({\n      type: 'mongodb',\n      host: process.env.SYN_MONGO_HOST,\n      port: +process.env.SYN_MONGO_PORT,\n      username: process.env.SYN_MONGO_USERNAME,\n      password: process.env.SYN_MONGO_PASSWORD,\n      database: process.env.SYN_MONGO_DATABASE,\n      authSource: 'admin',\n      autoLoadEntities: true,\n    }),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class ConfigurationModule {}\n```\n\n```js\n@Module({\n  imports: [\n    ScheduleModule.forRoot(),\n    TypeOrmModule.forRoot({\n      type: 'mongodb',\n      host: process.env.SYN_MONGO_HOST,\n      port: +process.env.SYN_MONGO_PORT,\n      username: process.env.SYN_MONGO_USERNAME,\n      password: process.env.SYN_MONGO_PASSWORD,\n      database: process.env.SYN_MONGO_DATABASE,\n      authSource: 'admin',\n      autoLoadEntities: true,\n    }),\n    ConfigModule.forRoot(),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class ConfigurationModule {}\n```\n\n```js\n@Module({\n    imports: [ConfigModule.forRoot({\n        envFilePath: join(process.cwd(), 'env', `.env.${process.env.SCOPE.trim()}`),\n    })]\n})\n```\n\n```text\ntrim()\n```\n\n```text\nbaseUrl\n```\n\n```text\ntsconfig.json\n```\n\n```text\npaths\n```\n\n```js\n@Module({\n  imports: [\n  ConfigModule.forRoot({\n    isGlobal: true,\n    envFilePath:'.env',\n  })\n]\n```\n\n```js\nconstructor(private readonly configService: ConfigService) {\n        const secretKey =this.configService.get('STRIPE_SECRET_KEY');\n        }\n```\n\n```text\nenvFilePath:'.env'\n```\n\n```text\napp.module.ts\n```\n\n```text\nprocess.env.VARIABLE_NAME\n```\n\n```text\nconfigService.get('')\n```\n\n```text\nimport 'dotenv/config'\nimport { AppModule } from './app.module';\n```\n\n```text\nimport 'dotenv/config';\n```\n\n```text\nauth.module.ts\n```\n\n```text\n\"esModuleInterop\": true\n```\n\n```text\n\"allowSyntheticDefaultImports\": true\n```\n\n========================================\n\nComments:\n- Where (and when) are you reading in the `.env` file?\n- @KimKern I'm reading the file in a module file which resides in the module's folder. The .env file is in the root of the project. I've updated my question to show when they are used.\n- You can also use it this way: `JwtModule.registerAsync({ useFactory: async () => ({ secret: process.env.JWT_SECRET_KEY, signOptions: { expiresIn: process.env.JWT_EXPIRATION_TIME }, }), }),`. There is no need for a ConfigService to load environment variables. Use registerAsync with useFactory\n- We can use --env-file .env prefix with \"nest start \" to load the env file before config module and make it work.\n- @Kekson have you re-start app after set it? and please take care \"ConfigModule is been loaded in the root module (e.g., AppModule)\"\n- yes but restart did not help, in my app.module.ts i have set this ConfigModule.forRoot({ isGlobal: true }) and in other modules i have process.env.PORT but it still does not read from env\n- If i put ConfigModule.forRoot() in other modules imports as well as in AppModule (as isGlobal: true) than it works fine... seems weird but it works\n- @Kekson Other modules should be a child of your main module. If the other modules are not chield may you have define it again.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- but in some project you does't need to import config and install config it will work but in some nest project it will work. is any idea in as according to me in nest does not need to install env file\n- @jaswantpatel: I still could not got your question? Can you explain that again? *\"in some project you does't need to import config and install config it will work but in some nest project it will work\"*\n- This is the only answer that really solved all my problems with env variables in nest.js. I have read all the official documentation but haven't found a solution. This makes all sense.","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":331,"estimatedTokens":1879}}40{"id":"stack-62704600","source":"stackoverflow","questionId":62704600,"title":"Mongoose Subdocuments in Nest.js","tags":["reference","schema","nestjs","subdocument"],"text":"Title: Mongoose Subdocuments in Nest.js\nTags: reference, schema, nestjs, subdocument\nSource: Stack Overflow\n\nQuestion:\nI'm moving my app from express.js to Nest.js, and I can't find a way to reference one mongoose Schema in another, without using old way of declaring Schema with mongoose.Schema({...}).\n\nLet's use example from docs, so I can clarify my problem:\n\n```\n@Schema()\n export class Cat extends Document {\n @Prop()\n name: string;\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\nNow, what I want is something like this:\n\n```\n@Schema()\nexport class Owner extends Document {\n @Prop({type: [Cat], required: true})\n cats: Cat[];\n}\n\nexport const OwnerSchema = SchemaFactory.createForClass(Owner);\n```\n\nWhen I define schemas this way I'd get an error, something like this: Invalid schema configuration: `Cat` is not a valid\ntype within the array `cats`\n\nSo, what is the proper way for referencing one Schema inside another, using this more OO approach for defining Schemas?\n\n========================================\n\nTop Answer:\nCreate `SchemaFactory.createForClass` for the SubDocument and refer to its type in the Document.\n\n```\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n \n @Schema()\n export class SubDocument {\n @Prop()\n name: string;\n \n @Prop()\n description: number;\n }\n \n const subDocumentSchema = SchemaFactory.createForClass(SubDocument);\n \n @Schema()\n export class Document {\n @Prop()\n name: string;\n \n @Prop({ type: subDocumentSchema })\n subDocument: SubDocument;\n }\n \n export const documentSchema = SchemaFactory.createForClass(Document);\n```\n\n========================================\n\nCode:\n```js\n@Schema()\n  export class Cat extends Document {\n  @Prop()\n  name: string;\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\n```js\n@Schema()\nexport class Owner extends Document {\n  @Prop({type: [Cat], required: true})\n  cats: Cat[];\n}\n\nexport const OwnerSchema = SchemaFactory.createForClass(Owner);\n```\n\n```text\nCat\n```\n\n```text\ncats\n```\n\n```js\n@Schema()\nexport class Cat extends Document {\n  @Prop()\n  name: string;\n}\nexport const catSchema = SchemaFactory.createForClass(Cat);\n```\n\n```js\nconst schema = new mongoose.Schema({\n    name: { type: String } // Notice that `String` is now uppercase.\n});\n```\n\n```js\nexport function Prop(options?: PropOptions): PropertyDecorator {\n  return (target: object, propertyKey: string | symbol) => {\n    options = (options || {}) as mongoose.SchemaTypeOpts<unknown>;\n\n    const isRawDefinition = options[RAW_OBJECT_DEFINITION];\n    if (!options.type && !Array.isArray(options) && !isRawDefinition) {\n      const type = Reflect.getMetadata(TYPE_METADATA_KEY, target, propertyKey);\n\n      if (type === Array) {\n        options.type = [];\n      } else if (type && type !== Object) {\n        options.type = type;\n      }\n    }\n\n    TypeMetadataStorage.addPropertyMetadata({\n      target: target.constructor,\n      propertyKey: propertyKey as string,\n      options,\n    });\n  };\n}\n```\n\n```js\n@Prop()\nname: string;\n```\n\n```js\nconst type = Reflect.getMetadata(TYPE_METADATA_KEY, target, propertyKey);\n```\n\n```js\n{\n    target: User,\n    propertyKey: โ€˜nameโ€™,\n    options: { type: String }\n}\n```\n\n```js\nexport class TypeMetadataStorageHost {\n  private schemas = new Array<SchemaMetadata>();\n  private properties = new Array<PropertyMetadata>();\n\n  addPropertyMetadata(metadata: PropertyMetadata) {\n    this.properties.push(metadata);\n  }\n}\n```\n\n```js\nexport class SchemaFactory {\n  static createForClass(target: Type<unknown>) {\n    const schemaDefinition = DefinitionsFactory.createForClass(target);\n    const schemaMetadata = TypeMetadataStorage.getSchemaMetadataByTarget(\n      target,\n    );\n    return new mongoose.Schema(\n      schemaDefinition,\n      schemaMetadata && schemaMetadata.options,\n    );\n  }\n}\n```\n\n```js\nexport class DefinitionsFactory {\n  static createForClass(target: Type<unknown>): mongoose.SchemaDefinition {\n    let schemaDefinition: mongoose.SchemaDefinition = {};\n\n  schemaMetadata.properties?.forEach((item) => {\n    const options = this.inspectTypeDefinition(item.options as any);\n    schemaDefinition = {\n    [item.propertyKey]: options as any,\n      โ€ฆschemaDefinition,\n    };\n  });\n\n    return schemaDefinition;\n}\n```\n\n```js\n[\n    {\n        target: User,\n        propertyKey: โ€˜nameโ€™,\n        options: { type: String }\n    }\n]\n```\n\n```js\n{\n    name: { type: String }\n}\n```\n\n```js\nreturn new mongoose.Schema(\n    schemaDefinition,\n    schemaMetadata && schemaMetadata.options,\n);\n```\n\n```js\nschemaMetadata.properties?.forEach((item) => {\n  const options = this.inspectTypeDefinition(item.options as any);\n  schemaDefinition = {\n    [item.propertyKey]: options as any,\n    โ€ฆschemaDefinition,\n  };\n});\n```\n\n```js\nprivate static inspectTypeDefinition(options: mongoose.SchemaTypeOpts<unknown> | Function): PropOptions {\n  if (typeof options === 'function') {\n    if (this.isPrimitive(options)) {\n      return options;\n    } else if (this.isMongooseSchemaType(options)) {\n      return options;\n    }\n    return this.createForClass(options as Type<unknown>);   \n  } else if (typeof options.type === 'function') {\n    options.type = this.inspectTypeDefinition(options.type);\n    return options;\n  } else if (Array.isArray(options)) {\n    return options.length > 0\n      ? [this.inspectTypeDefinition(options[0])]\n      : options;\n  }\n  return options;\n}\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Schema as MongooseSchema } from 'mongoose';\nimport { Owner } from './owner.schema.ts';\n\n@Schema()\nexport class Cat extends Document {\n  @Prop()\n  name: string;\n\n  @Prop({ type: MongooseSchema.Types.ObjectId, ref: Owner.name })\n  owner: Owner;\n}\n\nexport const catSchema = SchemaFactory.createForClass(Cat);\n```\n\n```js\n@Prop([{ type: MongooseSchema.Types.ObjectId, ref: Cat.name }])\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\n@Schema()\nexport class ImageVariant {\n  @Prop()\n  url: string;\n\n  @Prop()\n  width: number;\n\n  @Prop()\n  height: number;\n\n  @Prop()\n  size: number;\n}\n\nexport const imageVariantSchema = SchemaFactory.createForClass(ImageVariant);\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\nimport { imageVariantSchema, ImageVariant } from './imagevariant.schema';\n\n@Schema()\nexport class Image extends Document {\n  @Prop({ type: imageVariantSchema })\n  large: ImageVariant;\n\n  @Prop({ type: imageVariantSchema })\n  medium: ImageVariant;\n\n  @Prop({ type: imageVariantSchema })\n  small: ImageVariant;\n}\n\nexport const imageSchema = SchemaFactory.createForClass(Image);\n```\n\n```text\nSchemaFactory.createForClass\n```\n\n```text\nSchemaFactory.createForClass(Cat)\n```\n\n```text\nProp()\n```\n\n```text\nProp\n```\n\n```text\nReflect\n```\n\n```text\nname: string\n```\n\n```text\ntype\n```\n\n```text\nString\n```\n\n```text\nstring\n```\n\n```text\nReflect\n```\n\n```text\nnumber\n```\n\n```text\nNumber\n```\n\n```text\nstring\n```\n\n```text\nString\n```\n\n```text\nboolean\n```\n\n```text\nBoolean\n```\n\n```text\nTypeMetadataStorage.addPropertyMetadata\n```\n\n```text\nproperties\n```\n\n```text\nTypeMetadataStorageHost\n```\n\n```text\nTypeMetadataStorageHost\n```\n\n```text\nSchemaFactory.createForClass(Cat)\n```\n\n```text\nconst schemaDefinition = DefinitionsFactory.createForClass(target);\n```\n\n```text\nCat\n```\n\n```text\nschemaMetadata.properties\n```\n\n```text\nTypeMetadataStorage.addPropertyMetadata\n```\n\n```text\nforEach\n```\n\n```text\nmongoose.Schema\n```\n\n```text\nProp()\n```\n\n```text\nforEach\n```\n\n```text\noptions\n```\n\n```text\ninspectTypeDefinition\n```\n\n```text\noptions\n```\n\n```text\nfunction\n```\n\n```text\nString\n```\n\n```text\nSchemaType\n```\n\n```text\noptions\n```\n\n```text\nArray\n```\n\n```text\noptions\n```\n\n```text\nArray\n```\n\n```text\nfunction\n```\n\n```text\nobject\n```\n\n```text\n{ type: String, required: true }\n```\n\n```text\nCat\n```\n\n```text\nOwner\n```\n\n```text\nOwner\n```\n\n```text\nCat\n```\n\n```js\nimport { Prop, raw, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Education } from '../../education/schemas';\nimport { RECORD_STATUS } from '../../common/common.constants';\nimport { Employment } from '../../employment/schemas';\nimport {\n    JOB_SEARCH_STATUS,\n    LANGUAGE_PROFICIENCY\n} from '../user-profile.constants';\n\nconst externalLinks = {\n    linkedInUrl: { type: String },\n    githubUrl: { type: String },\n    twitterUrl: { type: String },\n    blogUrl: { type: String },\n    websiteUrl: { type: String },\n    stackoverflowUrl: { type: String }\n};\n\nconst address = {\n    line1: { type: String, required: true },\n    line2: { type: String },\n    zipCode: { type: String },\n    cityId: { type: Number },\n    countryId: { type: Number }\n};\n\nconst language = {\n    name: { type: String, require: true },\n    code: { type: String, required: true },\n    proficiency: { type: String, required: true, enum: LANGUAGE_PROFICIENCY }\n};\n\nconst options = {\n    timestamps: true,\n};\n\nexport type UserProfileDocument = UserProfile & mongoose.Document;\n\n@Schema(options)\nexport class UserProfile {\n\n    _id: string;\n\n    @Prop()\n    firstName: string;\n\n    @Prop()\n    lastName: string;\n\n    @Prop()\n    headline: string;\n\n    @Prop({\n        unique: true,\n        trim: true,\n        lowercase: true\n    })\n    email: string;\n\n    @Prop()\n    phoneNumber: string\n\n    @Prop(raw({\n        jobSearchStatus: { type: String, enum: JOB_SEARCH_STATUS, required: true }\n    }))\n    jobPreferences: Record<string, any>;\n\n    @Prop(raw(externalLinks))\n    externalLinks: Record<string, any>;\n\n    @Prop([String])\n    skills: string[];\n\n    @Prop(raw({ type: address, required: false }))\n    address: Record<string, any>;\n\n    @Prop()\n    birthDate: Date;\n\n    @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Employment' }] })\n    employments: Employment[];\n\n    @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Education' }] })\n    educations: Education[];\n\n    @Prop(raw([language]))\n    languages: Record<string, any>[];\n\n    @Prop()\n    timeZone: string;\n\n    @Prop()\n    createdAt: Date;\n\n    @Prop()\n    updatedAt: Date;\n\n    @Prop({\n        enum: RECORD_STATUS,\n        required: true,\n        default: RECORD_STATUS.Active\n    })\n    recordStatus: string;\n}\n\nexport const UserProfileSchema = SchemaFactory.createForClass(UserProfile);\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n    \n    @Schema()\n    export class SubDocument {\n     @Prop()\n      name: string;\n    \n      @Prop()\n      description: number;\n    }\n    \n    const subDocumentSchema = SchemaFactory.createForClass(SubDocument);\n    \n    @Schema()\n    export class Document {\n      @Prop()\n      name: string;\n    \n      @Prop({ type: subDocumentSchema })\n      subDocument: SubDocument;\n    }\n    \n    export const documentSchema = SchemaFactory.createForClass(Document);\n```\n\n```text\nSchemaFactory.createForClass\n```\n\n========================================\n\nComments:\n- Works like a charm! Great explanation, thanks a lot!\n- This does not answer the question though. How to create nested schema with decorators?\n- @Sinandro instead of @Prop({type: [Cat]}) you write @Prop([{ type: MongooseSchema.Types.ObjectId, ref: Cat.name }]) . Could you provide an example on what you mean?\n- Well, this is not a nested schema, it's only a foreign key to the Cat schema. The question was how to create a nested schema. The cat should be saved inside the Owner, not on a separate collection.\n- @Sinandro The question was \"referencing one Schema inside another\" not \"embedding schema inside another\". Your question is a different question. Please take a look at `else if (typeof options.type === 'function')` in the `inspectTypeDefinition` method. That's the answer that you want.\n- @EdwardAnthony in your example, how would you save a Cat inside an Owner.cats array ? I use Owner.cats.push(catDocument) and it saves an entire document instead of just the id. If I push only the id - I get a type error because the Owner Schema is defined as \"cats: Cat[]\"\n- @Yaron It won't save the entire document. As long as you specify the `ref` in the `@Prop` decorator, it will be saved as a relation reference, therefore it will only save the id. This functionality doesn't come from `@nestjs&#47;mongoose` library, it comes from Mongoose.\n- What about the mongoose helper functions such as `parent.subdoc.id(someID)` since the types are defined on class props and typescript will complain they don't exist on the type. Simply adding an intersection like `@Prop({ type: Schema.Types.ObjectId, ref: Cats.name }) cats: Cats[] & Document;` allows mongoose helper functions but now TS complains anytime we try to use direct assignment for subdocs like `owner.cats = [...listOfCats ]`. The latter is sometimes useful for editing a document instance in place. How can we satisfy both former and the latter to make full use of mongoose in Nestjs?\n- Its a bit cumbersome but I've resolved it. Setup requires casting the subdocs where using the instance as in `const lineItems = order.lineItems as Document & OrderLineItem[]; const item = lineItems.id(itemId);` Extra work because you have to create an extra variable to type the subdocs but this allows the use of the query helpers as well as keeping the Class ref on the prop types of the parent class.\n- Do you know why we should use `SchemaFactory.createForClass`? Should not it work just out of the box?","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":71,"totalLines":651,"estimatedTokens":3345}}41{"id":"stack-63208308","source":"stackoverflow","questionId":63208308,"title":"How to fix AXIOS_INSTANCE_TOKEN at index [0] is available in the Module context","tags":["node.js","axios","httprequest","nestjs","httpservice"],"text":"Title: How to fix AXIOS_INSTANCE_TOKEN at index [0] is available in the Module context\nTags: node.js, axios, httprequest, nestjs, httpservice\nSource: Stack Overflow\n\nQuestion:\nI am using Axios in my project to call some third-party endpoints. I don't seem to understand the\nerror\n\n```\nNest can't resolve dependencies of the HttpService (?). Please make sure that the argument \nAXIOS_INSTANCE_TOKEN at index [0] is available in the TimeModule context.\n\nPotential solutions:\n- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current TimeModule?\n- If AXIOS_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within TimeModule?\n @Module({\n imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]\n })\n```\n\nThis is the module\n\n```\n@Module({\n imports: [TerminalModule,],\n providers: [TimeService, HttpService],\n controllers: [TimeController]\n})\nexport class TimeModule { }\n```\n\nThis is the service\n\n```\n@Injectable()\nexport class TimeService {\n constructor(private httpService: HttpService,\n @InjectModel('PayMobileAirtime') private time: Model, \n @Inject(REQUEST) private request: any,\n\n ) { }\n```\n\nThis is an example of one of my **get** and **post** methods\n\n```\nasync PrimeAirtimeProductList(telcotime: string) {\n let auth = await this.TimeAuth()\n const productList = await this.httpService.get(`https://clients.time.com/api/top/info/${telcotime}`,\n {\n headers: {\n 'Authorization': `Bearer ${auth.token}`\n }\n }\n ).toPromise();\n\n return productList.data\n }\n```\n\nPost\n\n```\nconst dataToken = await this.manageTimeAuth()\n const url = `https://clients.time.com/api/dataup/exec/${number}`\n\n const BuyTelcoData = await this.httpService.post(url, {\n \"product_id\": product_id,\n \"denomination\": amount,\n \"customer_reference\": reference_id\n }, {\n headers: {\n 'Authorization': `Bearer ${dataToken.token}`\n }\n }).toPromise();\n\n const data = BuyTelcoData.data;\n```\n\n========================================\n\nTop Answer:\nDon't pass HttpService in the providers. Import only HttpModule.\n\n========================================\n\nCode:\n```text\nNest can't resolve dependencies of the HttpService (?). Please make sure that the argument \nAXIOS_INSTANCE_TOKEN at index [0] is available in the TimeModule context.\n\nPotential solutions:\n- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current TimeModule?\n- If AXIOS_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within TimeModule?\n  @Module({\n    imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]\n  })\n```\n\n```text\n@Module({\n  imports: [TerminalModule,],\n  providers: [TimeService, HttpService],\n  controllers: [TimeController]\n})\nexport class TimeModule { }\n```\n\n```text\n@Injectable()\nexport class TimeService {\n    constructor(private httpService: HttpService,\n        @InjectModel('PayMobileAirtime') private time: Model<Time>,       \n        @Inject(REQUEST) private request: any,\n\n    ) { }\n```\n\n```text\nasync PrimeAirtimeProductList(telcotime: string) {\n        let auth = await this.TimeAuth()\n        const productList = await this.httpService.get(`https://clients.time.com/api/top/info/${telcotime}`,\n            {\n                headers: {\n                    'Authorization': `Bearer ${auth.token}`\n                }\n            }\n        ).toPromise();\n\n        return productList.data\n    }\n```\n\n```text\nconst dataToken = await this.manageTimeAuth()\n        const url = `https://clients.time.com/api/dataup/exec/${number}`\n\n        const BuyTelcoData = await this.httpService.post(url, {\n            \"product_id\": product_id,\n            \"denomination\": amount,\n            \"customer_reference\": reference_id\n        }, {\n            headers: {\n                'Authorization': `Bearer ${dataToken.token}`\n            }\n        }).toPromise();\n\n        const data = BuyTelcoData.data;\n```\n\n```text\nimport { HttpModule } from '@nestjs/common';\n...\n\n@Module({\n    imports: [TerminalModule, HttpModule],\n    providers: [TimeService],\n    ...\n})\n```\n\n```text\nimport { HttpService } from '@nestjs/common';\n```\n\n```text\nimport { Observable } from 'rxjs';\nimport { AxiosResponse } from 'axios';\n```\n\n```text\nHttpModule\n```\n\n```text\n@nestjs/common\n```\n\n```text\nTimeModule\n```\n\n```text\nimports\n```\n\n```text\nHttpService\n```\n\n```text\nproviders\n```\n\n```text\nTimeModule\n```\n\n```text\nTimeService\n```\n\n```text\nObservable\n```\n\n```text\nAxiosResponse\n```\n\n```text\nTimeService\n```\n\n```text\nimport { HttpModule} from '@nestjs/axios';\n```\n\n========================================\n\nComments:\n- Please provide code for HttpService as well. Also, what exactly AXIOS_INSTANCE_TOKEN is and where is it defined?\n- My code has been updated\n- Try adding \"HttpModule\" in the \"imports\" arrary in \"TimeModule\" module. Make sure to import it first in the module.\n- See this docs.nestjs.com/techniques/http-module\n- FYI: This solution also works for the new `import { HttpModule} from '@nestjs&#47;axios';`\n- Thanks. It worked. But can you explain why it worked ?\n- Because `imports` takes the list of modules that export the providers. By default the providers are encapsulated. Providers can be directly used in the services. Meaning HttpService can be directly used in the TimeService. Have a look at the documentation here Nest Modules *This means that it's impossible to inject providers that are neither directly part of the current module nor exported from the imported modules. Thus, you may consider the exported providers from a module as the module's public interface, or API.*","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":228,"estimatedTokens":1372}}42{"id":"stack-74830166","source":"stackoverflow","questionId":74830166,"title":"Unable to import ESM module in Nestjs","tags":["javascript","node.js","typescript","nestjs","es6-modules"],"text":"Title: Unable to import ESM module in Nestjs\nTags: javascript, node.js, typescript, nestjs, es6-modules\nSource: Stack Overflow\n\nQuestion:\nI am having a problem with importing ESM modules in my project based on Nest.js. As far as I understand, this problem is relevant not just to Nest.js but typescript as well.\n\nI have tried various things and combinations of Node.js & typescript versions, adding `\"type\":\"module\"` to `package.json` & changes in the settings of my `tsconfig.json` file, so it has the following view, which is far from *default* values:\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\"ES2020\"],\n \"esModuleInterop\": true,\n \"module\": \"NodeNext\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"moduleResolution\": \"Node\",\n \"target\": \"esnext\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"skipLibCheck\": true,\n \"strictNullChecks\": false,\n \"noImplicitAny\": false,\n \"strictBindCallApply\": false,\n \"forceConsistentCasingInFileNames\": false,\n \"noFallthroughCasesInSwitch\": false,\n }\n}\n```\n\nMy full environment is:\n\n- Node.js (19.2.1 LTS) managed via nvm\n\n- Typescript (4.9.4, but I also tried 4.3.5)\n\n- @nestjs/common: 9.2.1\n\n- @nestjs/core: 9.2.1\n\n- ts-loader: \"9.4.2\",\n\n- ts-node: \"10.9.1\",\n\n- tsconfig-paths: \"4.1.0\",\n\nBut it still gives me an error when I am trying to import any ESM module in any of my services. For example:\n\n```\nimport random from `random`;\n\nexport class AppService implements OnApplicationBootstrap {\n async test() {\n const r = random.int(1, 5);\n console.log(r);\n }\n}\n```\n\nDoes anyone have a clue how to fix it?\n\n========================================\n\nTop Answer:\nWith Node v22 you can use `--experimental-require-module` flag\n\nThe `package.json` will look something similar to this:\n\n```\n{\n \"scripts\": {\n \"start\": \"nest start -e 'node --experimental-require-module'\",\n \"start:dev\": \"nest start --watch -e 'node --experimental-require-module'\",\n \"start:prod\": \"node --experimental-require-module dist/main\"\n }\n}\n```\n\n========================================\n\nCode:\n```json\n{\n  \"compilerOptions\": {\n    \"lib\": [\"ES2020\"],\n    \"esModuleInterop\": true,\n    \"module\": \"NodeNext\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"moduleResolution\": \"Node\",\n    \"target\": \"esnext\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": false,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false,\n  }\n}\n```\n\n```text\nimport random from `random`;\n\nexport class AppService implements OnApplicationBootstrap {\n  async test() {\n     const r = random.int(1, 5);\n     console.log(r);\n  }\n}\n```\n\n```text\n\"type\":\"module\"\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig.json\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n  async getHello(): Promise<string> {\n    const random = (await import('random')).default;\n    return 'Hello World! ' + random.int(1, 10);\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { type Random } from 'random';\n\nasync function getRandom(): Promise<Random> {\n  const module = await (eval(`import('random')`) as Promise<any>);\n  return module.default;\n}\n\n@Injectable()\nexport class AppService {\n  async getHello(): Promise<string> {\n    return 'Hello World! ' + (await getRandom()).int(1, 10);\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { type Random } from 'random';\n\nlet random: Random;\neval(`import('random')`).then((module) => {\n  random = module.default;\n});\n\n\n@Injectable()\nexport class AppService {\n  async getHello(): Promise<string> {\n    return 'Hello World! ' + random.int(1, 10);\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport random from 'random';\n\n@Injectable()\nexport class AppService {\n  async getHello(): Promise<string> {\n    return 'Hello World! ' + random.int(1, 10);\n  }\n}\n```\n\n```text\nimport()\n```\n\n```text\nimport()\n```\n\n```text\nimport()\n```\n\n```text\nrequire()\n```\n\n```text\nmoduleResolution\n```\n\n```text\nnodenext\n```\n\n```text\nnode16\n```\n\n```text\ntsconfig.json\n```\n\n```text\neval\n```\n\n```text\nawait import()\n```\n\n```text\n\"moduleResolution\": \"nodenext\"\n```\n\n```text\n\"moduleResolution\": \"node16\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\nawait import()\n```\n\n```text\nasync\n```\n\n```text\nrequire\n```\n\n```text\nasync\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\nmodule\n```\n\n```text\nNodeNext\n```\n\n```text\ntsconfig.json\n```\n\n```text\n.js\n```\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"nest start -e 'node --experimental-require-module'\",\n    \"start:dev\": \"nest start --watch -e 'node --experimental-require-module'\",\n    \"start:prod\": \"node --experimental-require-module dist/main\"\n  }\n}\n```\n\n```text\n--experimental-require-module\n```\n\n```text\npackage.json\n```\n\n```text\nnode-options=--experimental-require-module\n```\n\n```text\nnode\n```\n\n```text\n22.4.0\n```\n\n```text\n.npmrc\n```\n\n```text\nimport {DataTransformerOptions} from \"@trpc/server\";\n\nconst dynamicImport = async (packageName: string) =>\n    new Function(`return import('${packageName}')`)();\n\n\nlet superjson: DataTransformerOptions;\n\nexport async function initDynamicImports() {\n    if (!superjson) {\n        superjson = (await dynamicImport('superjson')).default;\n    }\n}\n\nexport let getSuperJson = () => superjson;\n```\n\n```text\nimport {NestFactory} from '@nestjs/core';\nimport {AppModule} from './app.module';\nimport {FastifyAdapter, NestFastifyApplication} from \"@nestjs/platform-fastify\";\nimport {ConfigService} from \"@nestjs/config\";\nimport {initDynamicImports} from \"@server/utils\";\n\n\nasync function bootstrap() {\n\n    await initDynamicImports()\n    const app = await NestFactory.create<NestFastifyApplication>(\n        AppModule,\n        new FastifyAdapter(),\n    );\n    app.enableCors();\n    const configService = app.get(ConfigService);\n    const PORT = configService.get<number>('PORT') || 4000;\n    await app.listen(PORT, '0.0.0.0');\n}\n\nbootstrap();\n```\n\n========================================\n\nComments:\n- nodejs.org/api/esm.html#import-expressions\n- @MicaelLevi I have seen this docs before, but I have no idea how to implement this in a code above, so `nest start dev` should actually work, instead of giving me `ESM` error, could you please explain it a bit more for me, in a format of an answer?\n- have you tried `const random = await import('random')`?\n- no, but I'll try it with currect settings\n- @AlexZeDim Were you able to find a solution, I have exactly the same problem. export const grpcClientOptions: GrpcOptions is not working also, when it exports as follows: export class AppModule {}\n- @schizofreindly tbh, I haven't tested it yet\n- This comment from the creator suggests the use of a bundler : github.com/nestjs/nest/issues/7021#issuecomment-831799620 Any idea if it's a viable third alternative and how it would work ?\n- If you are in charge of the package you need to import from (as CJS) and still want/need to keep its default as ESM, you can use a dual build strategy, according to this great article: sensedeep.com/blog/posts/2021/&hellip;\n- if by a chance someone is importing a premise, it can be done as: const signBuilder = (await import('@dashlane/pqc-sign-dilithium5-node') ).default; const sign = await signBuilder();\n- For some reason, the solution #1 does not work with the package \"ora\".\n- The current file is a CommonJS module and cannot use 'await' at the top level.\n- Variant 1 will not work, when you set `moduleResolution` to any of the values suggested, TypeScript will complain that `module` should also be set to that same option. So this essentially becomes the not recommended variant.\n- For some reason I am getting node: --experimental-require-module is not allowed in NODE_OPTIONS running nodejs version v21.4.0\n- @Normal You need to be on the version **22.4.0**","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":381,"estimatedTokens":2029}}43{"id":"stack-58670553","source":"stackoverflow","questionId":58670553,"title":"NESTJS Gateway / Websocket - how to send jwt access_token through socket.emit","tags":["websocket","socket.io","nestjs"],"text":"Title: NESTJS Gateway / Websocket - how to send jwt access_token through socket.emit\nTags: websocket, socket.io, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using the default passport jwt AuthGuard for my project. That works for my post & get routes fine when setting the authentication header.\n\nNow I want to use Nestjs Gateways as well with socket.io on the client-side, but I don't know how to send the access_token to the gateway?\n\nThat is basically my Gateway:\n\n```\n@WebSocketGateway()\nexport class UserGateway {\n\n entityManager = getManager();\n\n @UseGuards(AuthGuard('jwt'))\n @SubscribeMessage('getUserList')\n async handleMessage(client: any, payload: any) {\n const results = await this.entityManager.find(UserEntity);\n console.log(results);\n return this.entityToClientUser(results);\n }\n```\n\nAnd on the client I'm sending like this:\n\n```\nthis.socket.emit('getUserList', users => {\n console.log(users);\n this.userListSub.next(users);\n});\n```\n\nHow and where do I add the jwt access_token? The documentation of nestjs misses that point completely for Websockets. All they say is, that the Guards work exactly the same for websockets as they do for post / get etc. See here\n\n========================================\n\nTop Answer:\nWhile the question is answered, I want to point out the Guard is not usable to prevent unauthorized users from establishing a connection.\n\nIt's only usable to guard specific events.\n\nThe `handleConnection` method of a class annotated with `@WebSocketGateway` is called before `canActivate` of your Guard.\n\nI end up using something like this in my Gateway class:\n\n```\nasync handleConnection(client: Socket) {\n const payload = this.authService.verify(\n client.handshake.headers.authorization,\n );\n const user = await this.usersService.findOne(payload.userId);\n \n !user && client.disconnect();\n }\n```\n\n========================================\n\nCode:\n```js\n@WebSocketGateway()\nexport class UserGateway {\n\n  entityManager = getManager();\n\n  @UseGuards(AuthGuard('jwt'))\n  @SubscribeMessage('getUserList')\n  async handleMessage(client: any, payload: any) {\n    const results = await this.entityManager.find(UserEntity);\n    console.log(results);\n    return this.entityToClientUser(results);\n  }\n```\n\n```js\nthis.socket.emit('getUserList', users => {\n    console.log(users);\n    this.userListSub.next(users);\n});\n```\n\n```js\n@UseGuards(WsGuard)\n@SubscribeMessage('yourRoute')\nasync saveUser(socket: Socket, data: any) {\n    let auth_token = socket.handshake.headers.authorization;\n    // get the token itself without \"Bearer\"\n    auth_token = auth_token.split(' ')[1];\n}\n```\n\n```js\nthis.socketOptions = {\n    transportOptions: {\n        polling: {\n            extraHeaders: {\n                Authorization: 'your token', // 'Bearer h93t4293t49jt34j9rferek...'\n            }\n        }\n    }\n};\n// ...\nthis.socket = io.connect('http://localhost:4200/', this.socketOptions);\n// ...\n```\n\n```js\n@Injectable()\nexport class WsGuard implements CanActivate {\n\n    constructor(private userService: UserService) {\n    }\n\n    canActivate(\n        context: any,\n    ): boolean | any | Promise<boolean | any> | Observable<boolean | any> {\n        const bearerToken = context.args[0].handshake.headers.authorization.split(' ')[1];\n        try {\n            const decoded = jwt.verify(bearerToken, jwtConstants.secret) as any;\n            return new Promise((resolve, reject) => {\n                return this.userService.findByUsername(decoded.username).then(user => {\n                    if (user) {\n                        resolve(user);\n                    } else {\n                        reject(false);\n                    }\n                });\n\n             });\n        } catch (ex) {\n            console.log(ex);\n            return false;\n        }\n    }\n}\n```\n\n```text\nWsGuard\n```\n\n```js\nimport { CanActivate, ExecutionContext, Injectable, Logger } from '@nestjs/common';\nimport { WsException } from '@nestjs/websockets';\nimport { Socket } from 'socket.io';\nimport { AuthService } from '../auth/auth.service';\nimport { User } from '../auth/entity/user.entity';\n\n@Injectable()\nexport class WsJwtGuard implements CanActivate {\n    private logger: Logger = new Logger(WsJwtGuard.name);\n\n    constructor(private authService: AuthService) { }\n\n    async canActivate(context: ExecutionContext): Promise<boolean> {\n\n        try {\n            const client: Socket = context.switchToWs().getClient<Socket>();\n            const authToken: string = client.handshake?.query?.token;\n            const user: User = await this.authService.verifyUser(authToken);\n            client.join(`house_${user?.house?.id}`);\n            context.switchToHttp().getRequest().user = user\n    \n            return Boolean(user);\n        } catch (err) {\n            throw new WsException(err.message);\n        }\n    }\n}\n```\n\n```js\nasync handleConnection(client: Socket) {\n    const payload = this.authService.verify(\n      client.handshake.headers.authorization,\n    );\n    const user = await this.usersService.findOne(payload.userId);\n    \n    !user && client.disconnect();\n  }\n```\n\n```text\nhandleConnection\n```\n\n```text\n@WebSocketGateway\n```\n\n```text\ncanActivate\n```\n\n```text\nasync canActivate(context: ExecutionContext): Promise<boolean> {\n\n    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n\n    const request = context.switchToHttp().getRequest();\n    //access the request handshake to get the header \n    const token = request?.handshake?.headers?.authorization?.split('Bearer ')[1]\n\n    if (isPublic) return true;\n\n    if (!token) throw new UnauthorizedException('no token provided');\n\n    try {\n      const user = (await this.jwtService.decode(\n        token,\n      )) as JwtAuthResponseInterface;\n      request.user = user;\n      return true;\n    } catch (err) {\n      throw new UnauthorizedException(err);\n    }\n  }\n```\n\n```text\nafterInit(server: Server) {\n  server.use((socket: Socket, next) => {\n    socket.handshake.headers.authorization\n    const [type, token] = socket.handshake.headers.authorization?.split(' ') ?? [];\n    const bearerToken = type === 'Bearer' ? token : undefined;\n\n    if (bearerToken) { // handle token validation\n      next()\n    } else {\n      next(new Error(\"Empty Token!\"));\n    }\n  })\n}\n```\n\n```text\nafterInit()\n```\n\n========================================\n\nComments:\n- Hi, i'm having the same issue, can you please add some more code?\n- You have to add the token to the socket connection on the client side when you initialize the socket itself. There you can set headers. I edited my answer for the client side.\n- Thanks! I'm having trouble with the guard now, did you implement the WsGuard yourself?\n- Hi, no problem! The `WsGuard` is my implementation with `CanActivate`. I Add my implementation of the guard in the answer aswell :)\n- If the token is decoded correctly, it means it has been signed by the server already. Isn't it overkill to re-check if the user is actually in the DB ? Since the server signed it in the first place.\n- @YohjiNakamoto I don't think it is overkill because user could have been deleted in the meantime\n- The code says `polling`. I think if it's polling then it's not actual web-sockets but their emulation through polling. Am I wrong?\n- just a reminder: `socket.io`'s client SDK do not support `extra_headers` in browser. `extra_headers` is only available in nodejs and react native environment.\n- Isn't it terrible to pass the token in the query string (= the URL) ? This is very likely to leak.\n- @YohjiNakamoto Where would it be better to pass it otherwise ?\n- I think handling authorization and disconnection client is guard is much cleaner and comply to Nest-js recommendation.\n- Also, this line `context.switchToHttp().getRequest().user = user` which is used for switching to `httpRequest` to attach `user` data is redundant and not necessary. You can directly add user data to socket variable by modifying socket type as `Socket & { [ k:string ]: any}`\n- I will just add that if you only verify token on handleConnection, if the token is invalid there is a short amount of time the client is connected and able to send other events before failed verification disconnects him.\n- You can implement `OnGatewayConnection` to force yourself to implement `handleConnection` method.\n- @TGPerson, either way the client would be able to connect before it will get rejected. If you're going with the other implementation, having a Guard service implementing `canActivate`, you'll have to put that guard on specific event messages, which means the user will be able to connect, anyway.\n- Just to add to this, the `afterInit` method is inside `IGatewayInit` interface that can be implemented by the gateway","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":264,"estimatedTokens":2189}}44{"id":"stack-53650528","source":"stackoverflow","questionId":53650528,"title":"validate nested objects using class-validator in nest.js controller","tags":["node.js","typescript","validation","nestjs","class-validator"],"text":"Title: validate nested objects using class-validator in nest.js controller\nTags: node.js, typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI want to validate body payload using class-validator in a nest.js controller. My `currency.dto.ts` file is like this:\n\n\r\n\r\n\n```\nimport {\r\n IsNotEmpty,\r\n IsString,\r\n ValidateNested,\r\n IsNumber,\r\n IsDefined,\r\n} from 'class-validator';\r\n\r\nclass Data {\r\n\r\n @IsNotEmpty()\r\n @IsString()\r\n type: string;\r\n\r\n @IsNotEmpty()\r\n @IsNumber()\r\n id: number;\r\n}\r\n\r\nexport class CurrencyDTO {\r\n @ValidateNested({ each: true })\r\n @IsDefined()\r\n data: Data[];\r\n}\n```\n\n\r\n\r\n\r\n\nand in my nest.js controller, I use it like this.\n\n\r\n\r\n\n```\n@Post()\r\n @UseGuards(new AuthTokenGuard())\r\n @UsePipes(new ValidationPipe())\r\n addNewCurrency(@Req() req, @Body() data: CurrencyDTO) {\r\n console.log('data', data);\r\n }\n```\n\n\r\n\r\n\r\n\nmy validation pipe class is like this:\n\n\r\n\r\n\n```\nimport {\r\n PipeTransform,\r\n Injectable,\r\n ArgumentMetadata,\r\n BadRequestException,\r\n HttpException,\r\n HttpStatus,\r\n} from '@nestjs/common';\r\nimport { validate, IsInstance } from 'class-validator';\r\nimport { plainToClass, Exclude } from 'class-transformer';\r\n\r\n@Injectable()\r\nexport class ValidationPipe implements PipeTransform {\r\n async transform(value: any, metadata: ArgumentMetadata) {\r\n if (value instanceof Object && this.isEmpty(value)) {\r\n throw new HttpException(\r\n `Validation failed: No Body provided`,\r\n HttpStatus.BAD_REQUEST,\r\n );\r\n }\r\n const { metatype } = metadata;\r\n if (!metatype || !this.toValidate(metatype)) {\r\n return value;\r\n }\r\n const object = plainToClass(metatype, value);\r\n const errorsList = await validate(object);\r\n if (errorsList.length > 0) {\r\n const errors = [];\r\n for (const error of errorsList) {\r\n const errorsObject = error.constraints;\r\n const { isNotEmpty } = errorsObject;\r\n if (isNotEmpty) {\r\n const parameter = isNotEmpty.split(' ')[0];\r\n errors.push({\r\n title: `The ${parameter} parameter is required.`,\r\n parameter: `${parameter}`,\r\n });\r\n }\r\n }\r\n if (errors.length > 0) {\r\n throw new HttpException({ errors }, HttpStatus.BAD_REQUEST);\r\n }\r\n }\r\n return value;\r\n }\r\n\r\n private toValidate(metatype): boolean {\r\n const types = [String, Boolean, Number, Array, Object];\r\n return !types.find(type => metatype === type);\r\n }\r\n private isEmpty(value: any) {\r\n if (Object.keys(value).length > 0) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nThis validation pipe works fine for all except for nested objects. Any idea what am I doing wrong here?\nMy body payload is like this:\n\n```\n{\n\"data\": [{\n \"id\": 1,\n \"type\": \"a\"\n}]\n}\n```\n\n========================================\n\nTop Answer:\nAt least in my case, the accepted answer needed some more info. As is, the validation will not run if the key `data` does not exist on the request. To get full validation try:\n\n```\n@IsDefined()\n@IsNotEmptyObject()\n@ValidateNested()\n@Type(() => CreateOrganizationDto)\n@ApiProperty()\norganization: CreateOrganizationDto;\n```\n\n========================================\n\nCode:\n```js\nimport {\n  IsNotEmpty,\n  IsString,\n  ValidateNested,\n  IsNumber,\n  IsDefined,\n} from 'class-validator';\n\nclass Data {\n\n  @IsNotEmpty()\n  @IsString()\n  type: string;\n\n  @IsNotEmpty()\n  @IsNumber()\n  id: number;\n}\n\nexport class CurrencyDTO {\n  @ValidateNested({ each: true })\n  @IsDefined()\n  data: Data[];\n}\n```\n\n```js\n@Post()\n  @UseGuards(new AuthTokenGuard())\n  @UsePipes(new ValidationPipe())\n  addNewCurrency(@Req() req, @Body() data: CurrencyDTO) {\n    console.log('data', data);\n  }\n```\n\n```js\nimport {\n  PipeTransform,\n  Injectable,\n  ArgumentMetadata,\n  BadRequestException,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\nimport { validate, IsInstance } from 'class-validator';\nimport { plainToClass, Exclude } from 'class-transformer';\n\n@Injectable()\nexport class ValidationPipe implements PipeTransform<any> {\n  async transform(value: any, metadata: ArgumentMetadata) {\n    if (value instanceof Object && this.isEmpty(value)) {\n      throw new HttpException(\n        `Validation failed: No Body provided`,\n        HttpStatus.BAD_REQUEST,\n      );\n    }\n    const { metatype } = metadata;\n    if (!metatype || !this.toValidate(metatype)) {\n      return value;\n    }\n    const object = plainToClass(metatype, value);\n    const errorsList = await validate(object);\n    if (errorsList.length > 0) {\n      const errors = [];\n      for (const error of errorsList) {\n        const errorsObject = error.constraints;\n        const { isNotEmpty } = errorsObject;\n        if (isNotEmpty) {\n          const parameter = isNotEmpty.split(' ')[0];\n          errors.push({\n            title: `The ${parameter} parameter is required.`,\n            parameter: `${parameter}`,\n          });\n        }\n      }\n      if (errors.length > 0) {\n        throw new HttpException({ errors }, HttpStatus.BAD_REQUEST);\n      }\n    }\n    return value;\n  }\n\n  private toValidate(metatype): boolean {\n    const types = [String, Boolean, Number, Array, Object];\n    return !types.find(type => metatype === type);\n  }\n  private isEmpty(value: any) {\n    if (Object.keys(value).length > 0) {\n      return false;\n    }\n    return true;\n  }\n}\n```\n\n```text\n{\n\"data\": [{\n    \"id\": 1,\n    \"type\": \"a\"\n}]\n}\n```\n\n```text\ncurrency.dto.ts\n```\n\n```text\nimport { Type } from 'class-transformer';\n\nexport class CurrencyDTO {\n  @ValidateNested({ each: true })\n  @Type(() => Data)\n  data: Data[];\n}\n```\n\n```text\n@Type\n```\n\n```text\n@Type\n```\n\n```text\nplainToClass\n```\n\n```text\nVaildationPipe\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\n@IsDefined()\n@IsNotEmptyObject()\n@ValidateNested()\n@Type(() => CreateOrganizationDto)\n@ApiProperty()\norganization: CreateOrganizationDto;\n```\n\n```text\ndata\n```\n\n```text\nexport function ValidateNestedType(type: () => any) {\n  return function (target: object, propertyName: string) {\n    ValidateNested({ each: true })(target, propertyName);\n    Type(type)(target, propertyName);\n  };\n}\n```\n\n```text\n@InputType()\nexport class CreateProductInput {\n  @ValidateNestedType(() => ProductDetailsInput)\n  product: ProductDetailsInput;\n  \n  ...\n}\n```\n\n========================================\n\nComments:\n- For any reason this solution isn't working for me. I did what you said and it didn't work.\n- I have tried it and it works for me. :-/ Without more specific information, I can't help you. Maybe open a new question and add your code?! I'll have a look at it.\n- I just opened a new post, I will appreciate it if you can give it a look.\n- I would add. That class-validator does not require this \\@Type annotation. It's just how nestjs works. It always uses class-transformer on your DTO and class-transformer requires that \\@Type annotation.\n- @LeonardoEmilioDominguez try to put both the classes in the same file and make sure nested class appears first(should be at the top), order matters. As you can see Data appears before DataDTO in the question.\n- I'm using NestJS, the key parts for me were the `@ValidateNested` and `@Type` decorators, which are both shown in this answer. Thank you! (Note: using a global `ValidationPipe({transform: true}` pipe didn't work, I had to use `@Type`.)\n- How i can put multiple type of data like Data | number. eg if i receive object it should be data other wise it should be number\n- Thanks, this worked for me. Since I'm using `whitelist: true` on validator pipe.\n- This worked for me, cheers","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":344,"estimatedTokens":1845}}45{"id":"stack-56173298","source":"stackoverflow","questionId":56173298,"title":"Optional authentication in Nest.js with @nestjs/passport","tags":["javascript","node.js","typescript","passport.js","nestjs"],"text":"Title: Optional authentication in Nest.js with @nestjs/passport\nTags: javascript, node.js, typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a route that needs to be used by authenticated and unauthenticated users. I use `@UseGuards(AuthGuard('jwt'))` to enable authentication but it prevents any unauthenticated user to access the route (normal).\n\nHow can I allow unauthenticated users to also access the route ?\n\nIt seems that there's no options that I can pass to `AuthGuard` in order to retrieve them in my passport strategy.\n\n========================================\n\nCode:\n```text\n@UseGuards(AuthGuard('jwt'))\n```\n\n```text\nAuthGuard\n```\n\n```text\nexport class OptionalJwtAuthGuard extends AuthGuard('jwt') {\n\n  // Override handleRequest so it never throws an error\n  handleRequest(err, user, info, context) {\n    return user;\n  }\n\n}\n```\n\n```text\n@UseGuards(OptionalJwtAuthGuard)\n```\n\n```text\nAuthGuard\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.400Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":40,"estimatedTokens":234}}46{"id":"stack-59000552","source":"stackoverflow","questionId":59000552,"title":"How to print stack trace with reference to typescript source in Nest.js","tags":["stack-trace","nestjs","console.log"],"text":"Title: How to print stack trace with reference to typescript source in Nest.js\nTags: stack-trace, nestjs, console.log\nSource: Stack Overflow\n\nQuestion:\nI am developing a Nest.js server and would like to be able to print useful stack trace in console (e.g. console.log). By default, it returns a reference to the line number in the compiled sources (.js). This is not useful for debugging as it's missing the reference to the line number in the original source files (.ts)\n\nHere is my tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"_baseUrl\": \"./\",\n \"incremental\": true\n },\n \"exclude\": [\"node_modules\", \"dist\"]\n}\n```\n\nThe .map files are generated in the dist folder as well, though it seems to be of no use when checking stack traces in the console.\n\n========================================\n\nTop Answer:\nI was only able to get this working if I also added a\n\nwebpack.config.js\n\nfile into the root directory of the NestJS project with following content:\n\n```\n// webpack.config.js\nmodule.exports = function(options) {\n return {\n ...options,\n devtool: 'inline-source-map',\n }\n}\n```\n\nWith this file in place it is possible to configure Webpack to your needs when transpilling your NestJS sources to main.js.\n\nIn main.ts I added following lines as described in answer above:\n\n```\nimport * as sourceMapSupport from 'source-map-support';\nsourceMapSupport.install();\n```\n\nVoila its working and exact Typescript files plus line numbers are displayed in console stack trace.\n\n========================================\n\nCode:\n```json\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"_baseUrl\": \"./\",\n    \"incremental\": true\n  },\n  \"exclude\": [\"node_modules\", \"dist\"]\n}\n```\n\n```js\nimport * as sourceMapSupport from 'source-map-support';\nsourceMapSupport.install();\n```\n\n```js\nimport { install } from 'source-map-support';\ninstall();\n```\n\n```js\nimport 'source-map-support/register';\n```\n\n```text\nnode -r source-map-support/register fileToRun.js\n```\n\n```text\n// webpack.config.js\nmodule.exports = function(options) {\n  return {\n    ...options,\n    devtool: 'inline-source-map',\n  }\n}\n```\n\n```text\nimport * as sourceMapSupport from 'source-map-support';\nsourceMapSupport.install();\n```\n\n```js\nconst nodeExternals = require('webpack-node-externals');\nconst { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');\n\nmodule.exports = function (options, webpack) {\n  return {\n    ...options,\n    entry: ['webpack/hot/poll?100', options.entry],\n    externals: [\n      nodeExternals({\n        allowlist: ['webpack/hot/poll?100'],\n      }),\n    ],\n    plugins: [\n      ...options.plugins,\n      new webpack.HotModuleReplacementPlugin(),\n      new webpack.WatchIgnorePlugin({\n        paths: [/\\.js$/, /\\.d\\.ts$/],\n      }),\n      new RunScriptWebpackPlugin({\n        name: options.output.filename,\n        autoRestart: false,\n      }),\n    ],\n    devtool: 'inline-source-map',\n  };\n};\n```\n\n```text\nnpm i source-map-support\n```\n\n```text\nnpm i -D @types/source-map-support\n```\n\n```text\nimport \"source-map-support/register\"\n```\n\n```text\nmain.ts\n```\n\n```text\ndevtool: 'inline-source-map'\n```\n\n```text\nwebpack-hmr.config.js\n```\n\n```text\nwebpack-hmr.config.js\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nwebpack-hmr.config.js\n```\n\n========================================\n\nComments:\n- Do you have source maps enabled in your tsconfig?\n- Yes, I have updated my question with the tsconfig content\n- So, after testing in my own server, I only get one line to say `ts` and that's because the server is webpacked via the `ng` compiler. Everything is in `js` files as expected cause you're running JavaScript. This is the default behavior, but it looks like this comment shows a way to get ts lines in the stack trace instead\n- Thank you! It works, just by adding `source-map-support` to the project, now it outputs the line number from the `ts` file\n- Do I have to add this to every file separately? Or is there a way to do this globally for my whole NestJS project?\n- You should just need to add it to your `main.ts` Or to the command line as mentioned.\n- in typescript dont forget to `npm i --save-dev @types&#47;source-map-support`\n- Could you provide some context about the configuration (e.g., package.json, tsconfig.json) that you are using?\n- Nothing special there: Just add \"sourceMap\": true to tsconfig.json. package.json remains the same.\n- Nice! Will definetely give it a try. Didn't know that HMR is also available for Nest.js projects. I thought its more a thing for frontend development. I configured HMR for Angular once and it was kind of pain.","metadata":{"transformedAt":"2026-08-18T18:33:02.401Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":191,"estimatedTokens":1233}}47{"id":"stack-49709429","source":"stackoverflow","questionId":49709429,"title":"Decorator to return a 404 in a Nest controller","tags":["javascript","node.js","nestjs"],"text":"Title: Decorator to return a 404 in a Nest controller\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm working on a backend using NestJS, (which is amazing btw). I have a 'standard get a single instance of an entity situation' similar to this example below.\n\n```\n@Controller('user')\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n ..\n ..\n ..\n @Get(':id')\n async findOneById(@Param() params): Promise {\n return userService.findOneById(params.id);\n }\n```\n\nThis is incredibly simple and works - however, if the user does not exist, the service returns undefined and the controller returns a 200 status code and an empty response.\n\nIn order to make the controller return a 404, I came up with the following:\n\n```\n@Get(':id')\n async findOneById(@Res() res, @Param() params): Promise {\n const user: User = await this.userService.findOneById(params.id);\n if (user === undefined) {\n res.status(HttpStatus.NOT_FOUND).send();\n }\n else {\n res.status(HttpStatus.OK).json(user).send();\n }\n }\n ..\n ..\n```\n\nThis works, but is a lot more code-y (yes it can be refactored).\n\nThis could really use a decorator to handle this situation:\n\n```\n@Get(':id')\n @OnUndefined(404)\n async findOneById(@Param() params): Promise {\n return userService.findOneById(params.id);\n }\n```\n\nAnyone aware of a decorator that does this, or a better solution than the one above?\n\n========================================\n\nTop Answer:\nThere is no built-in decorator for this, but you can create an interceptor that checks the return value and throws a `NotFoundException` on `undefined`:\n\n### Interceptor\n\n```\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n return next.handle()\n .pipe(tap(data => {\n if (data === undefined) throw new NotFoundException();\n }));\n }\n}\n```\n\nThen you can use the `Interceptor` by adding it to either a single endpoint:\n\n```\n@Get(':id')\n@UseInterceptors(NotFoundInterceptor)\nfindUserById(@Param() params): Promise {\n return this.userService.findOneById(params.id);\n}\n```\n\nor all endpoints of your `Controller`:\n\n```\n@Controller('user')\n@UseInterceptors(NotFoundInterceptor)\nexport class UserController {\n```\n\n### Dynamic Interceptor\n\nYou can also pass values to your interceptor to customize its behavior per endpoint.\n\nPass the parameters in the constructor:\n\n```\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n constructor(private errorMessage: string) {}\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n intercept(context: ExecutionContext, stream$: Observable): Observable {\n return stream$\n .pipe(tap(data => {\n if (data === undefined) throw new NotFoundException(this.errorMessage);\n ^^^^^^^^^^^^^^^^^\n }));\n }\n}\n```\n\nand then create the interceptor with `new`:\n\n```\n@Get(':id')\n@UseInterceptors(new NotFoundInterceptor('No user found for given userId'))\nfindUserById(@Param() params): Promise {\n return this.userService.findOneById(params.id);\n}\n```\n\n========================================\n\nCode:\n```text\n@Controller('user')\nexport class UserController {\n    constructor(private readonly userService: UserService) {}\n    ..\n    ..\n    ..\n    @Get(':id')\n    async findOneById(@Param() params): Promise<User> {\n        return userService.findOneById(params.id);\n    }\n```\n\n```text\n@Get(':id')\n    async findOneById(@Res() res, @Param() params): Promise<User> {\n        const user: User = await this.userService.findOneById(params.id);\n        if (user === undefined) {\n            res.status(HttpStatus.NOT_FOUND).send();\n        }\n        else {\n            res.status(HttpStatus.OK).json(user).send();\n        }\n    }\n    ..\n    ..\n```\n\n```text\n@Get(':id')\n    @OnUndefined(404)\n    async findOneById(@Param() params): Promise<User> {\n        return userService.findOneById(params.id);\n    }\n```\n\n```text\n@Get(':id')\nasync findOneById(@Param() params): Promise<User> {\n    const user: User = await this.userService.findOneById(params.id);\n    if (user === undefined) {\n        throw new NotFoundException('Invalid user');\n    }\n    return user;\n}\n```\n\n```text\nimport { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint } from 'class-validator';\nimport { createQueryBuilder } from 'typeorm';\n\n@ValidatorConstraint({ async: true })\nexport class IsValidIdConstraint {\n\n    validate(id: number, args: ValidationArguments) {\n        const tableName = args.constraints[0];\n        return createQueryBuilder(tableName)\n            .where({ id })\n            .getOne()\n            .then(record => {\n                return record ? true : false;\n            });\n    }\n}\n\nexport function IsValidId(tableName: string, validationOptions?: ValidationOptions) {\n    return (object, propertyName: string) => {\n        registerDecorator({\n            target: object.constructor,\n            propertyName,\n            options: validationOptions,\n            constraints: [tableName],\n            validator: IsValidIdConstraint,\n        });\n    };\n}\n```\n\n```text\nexport class GetUserParams {\n    @IsValidId('user', { message: 'Invalid User' })\n    id: number;\n}\n```\n\n```text\nNotFoundException\n```\n\n```text\n@nestjs/common\n```\n\n```text\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next.handle()\n      .pipe(tap(data => {\n        if (data === undefined) throw new NotFoundException();\n      }));\n  }\n}\n```\n\n```text\n@Get(':id')\n@UseInterceptors(NotFoundInterceptor)\nfindUserById(@Param() params): Promise<User> {\n    return this.userService.findOneById(params.id);\n}\n```\n\n```text\n@Controller('user')\n@UseInterceptors(NotFoundInterceptor)\nexport class UserController {\n```\n\n```text\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n  constructor(private errorMessage: string) {}\n              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n  intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {\n    return stream$\n      .pipe(tap(data => {\n        if (data === undefined) throw new NotFoundException(this.errorMessage);\n                                                            ^^^^^^^^^^^^^^^^^\n      }));\n  }\n}\n```\n\n```text\n@Get(':id')\n@UseInterceptors(new NotFoundInterceptor('No user found for given userId'))\nfindUserById(@Param() params): Promise<User> {\n    return this.userService.findOneById(params.id);\n}\n```\n\n```text\nNotFoundException\n```\n\n```text\nundefined\n```\n\n```text\nInterceptor\n```\n\n```text\nController\n```\n\n```text\nnew\n```\n\n```text\nimport {NotFoundException} from '@nestjs/common'\n...\n@Get(':id')\nasync findOneById(@Param() params): Promise<User> {\n    const user: User = await this.userService.findOneById(params.id)\n    if (!user) throw new NotFoundException('User Not Found')\n    return user\n}\n```\n\n```js\nimport { Injectable, NestInterceptor, ExecutionContext, NotFoundException, CallHandler } from '@nestjs/common';\nimport { Observable, pipe } from 'rxjs';\nimport { tap } from 'rxjs/operators';\n\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n  constructor(private errorMessage: string) { }\n\n  intercept(context: ExecutionContext, stream$: CallHandler): Observable<any> {\n    return stream$\n      .handle()\n      .pipe(tap(data => {\n        if (data === undefined) { throw new NotFoundException(this.errorMessage); }\n      }));\n  }\n}\n```\n\n```text\nthis.whateverService.getYourEntity(\n  params.id\n)\n.then(result => {\n  return res.status(HttpStatus.OK).json(result)\n})\n.catch(err => {\n  return res.status(HttpStatus.NOT_FOUND).json(err)\n})\n```\n\n```text\nconst entity = await this.otherService\n  .getEntityById(id)\n\nif (!entity) {\n  return Promise.reject({\n    statusCode: 404,\n    message: 'Entity not found'\n  })\n} \n\nreturn Promise.resolve(entity)\n```\n\n```text\nexport const OnUndefined = (\n  Error: new () => HttpException = NotFoundException,\n) => {\n  return (\n    _target: unknown,\n    _propKey: string,\n    descriptor: PropertyDescriptor,\n  ) => {\n    const original = descriptor.value;\n    const mayThrow = (r: unknown) => {\n      if (undefined === r) throw new Error();\n      return r;\n    };\n    descriptor.value = function (...args: unknown[]) {\n      const r = Reflect.apply(original, this, args);\n      if ('function' === typeof r?.then) return r.then(mayThrow);\n      return mayThrow(r);\n    };\n  };\n};\n```\n\n```text\n@Get(':id')\n@OnUndefined()\nasync findOneById(@Param() params): Promise<User> {\n    return userService.findOneById(params.id);\n}\n```\n\n```text\nfindOneById(id): Promise<User> {\n  return new Promise<User>((resolve, reject) => {\n    const user: User = await this.userService.findOneById(id);\n    user ? \n      resolve(user) :\n      reject(new NotFoundException())        \n    }\n}\n```\n\n========================================\n\nComments:\n- docs.nestjs.com/exception-filters this should be what you're looking for\n- it's definitely is point for such decorator, because it's quite routine code, and it is good practice to be less repetitive. furthermore it is much readable with decorator.\n- You can also throw just `BadRequestException`.\n- Why is everyone throwing `BadRequestException` when this is clearly `NotFoundException`? Bad request is for malformed request object. If you need to check the database, it's not a bad request issue.\n- I believe this (and the addition by Maxime lower down) is a much more elegant solution to the accepted answer\n- Why you throw a 404?? This is for missing web server resources (Broken links). Read the documentation. developer.mozilla.org/en-US/docs/Web/HTTP/Status/404\n- @teteArg This is incorrect. The HTTP spec is very broad and does not define what a resource is. When you call `&#47;users&#47;49` and there is no user (resource) with the requested id 49, it is appropriate to respond with a 404 - the resource was not found. However, it is up to your API design, an empty 200 response might also make sense. Also see this thread: stackoverflow.com/a/9946520/4694994\n- Could you provide more explanation on what the code does and how it will help the OP?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":398,"estimatedTokens":2596}}48{"id":"stack-53426486","source":"stackoverflow","questionId":53426486,"title":"Best practice to use config service in NestJS Module","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Best practice to use config service in NestJS Module\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use environment variables to configure the `HttpModule` per module, from the docs I can use the configuration like this:\n\n```\n@Module({\n imports: [HttpModule.register({\n timeout: 5000,\n maxRedirects: 5,\n })],\n})\n```\n\nBut I don't know what is the best practice to inclue a baseURL from environment vairable (or a config service), for example like this:\n\n```\n@Module({\nimports: [HttpModule.register({\n baseURL: this.config.get('API_BASE_URL'),\n timeout: 5000,\n maxRedirects: 5,\n})],\n```\n\nThe `this.config` is `undefined` here cause it's out of class.\n\nWhat is the best practice to set baseURL from environment variables (or config service)?\n\n========================================\n\nTop Answer:\nAlthough the top rated answer to this question is technically correct for most implementations, users of the `@nestjs/typeorm` package, and the `TypeOrmModule` should use an implementation that looks more like the below.\n\n```\n// NestJS expects database types to match a type listed in TypeOrmModuleOptions\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm/dist/interfaces/typeorm-options.interface';\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n load: [mySettingsFactory],\n }),\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n type: configService.get('database.type', {\n infer: true, // We also need to infer the type of the database.type variable to make userFactory happy\n }),\n database: configService.get('database.host'),\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n logging: true,\n }),\n inject: [ConfigService],\n }),\n ],\n controllers: [],\n})\nexport class AppRoot {\n constructor(private connection: Connection) {}\n}\n```\n\nThe major thing this code is doing is retrieving the correct typings from TypeORM (see the import) and using them to hint the return value configService.get() method. If you don't use the correct TypeORM typings, Typescript would get mad.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [HttpModule.register({\n    timeout: 5000,\n    maxRedirects: 5,\n  })],\n})\n```\n\n```text\n@Module({\nimports: [HttpModule.register({\n    baseURL:  this.config.get('API_BASE_URL'),\n    timeout: 5000,\n    maxRedirects: 5,\n})],\n```\n\n```text\nHttpModule\n```\n\n```text\nthis.config\n```\n\n```text\nundefined\n```\n\n```text\nHttpModule.registerAsync({\n  imports:[ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    baseURL:  configService.get('API_BASE_URL'),\n    timeout: 5000,\n    maxRedirects: 5,\n  }),\n  inject: [ConfigService]\n}),\n```\n\n```text\nTypeOrmModule.forRootAsync({\n  imports:[ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    type: configService.getDatabase()\n  }),\n  inject: [ConfigService]\n}),\n```\n\n```text\nHttpModule.registerAsync()\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nMongooseModule\n```\n\n```text\nuseFactory\n```\n\n```text\nHttpModule\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\n// NestJS expects database types to match a type listed in TypeOrmModuleOptions\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm/dist/interfaces/typeorm-options.interface';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n      load: [mySettingsFactory],\n    }),\n    TypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        type: configService.get<TypeOrmModuleOptions>('database.type', {\n          infer: true, // We also need to infer the type of the database.type variable to make userFactory happy\n        }),\n        database: configService.get<string>('database.host'),\n        entities: [__dirname + '/**/*.entity{.ts,.js}'],\n        synchronize: true,\n        logging: true,\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n  controllers: [],\n})\nexport class AppRoot {\n  constructor(private connection: Connection) {}\n}\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { MikroOrmModule } from '@mikro-orm/nestjs';\n\nimport { AppService } from './users.service';\nimport { AppController } from './users.controller';\nimport { get_db_config } from './config/database.config';\n\n@Module({\n    imports:     [\n        ConfigModule.forRoot({ \n            isGlobal:        true, \n            expandVariables: true,\n        }),\n\n        MikroOrmModule.forRootAsync( get_db_config() ),\n    ],\n    controllers: [AppController],\n    providers:   [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport { MikroOrmModuleAsyncOptions } from \"@mikro-orm/nestjs\";\nimport { ConfigService } from \"@nestjs/config\";\n\n\nexport function get_db_config(): MikroOrmModuleAsyncOptions\n{\n    return {\n        useFactory: (configService: ConfigService) => \n        ({\n            dbName:          'driver',\n            type:            'postgresql',\n            host:             configService.get('DB_HOST'),\n            port:             configService.get('DB_PORT'),\n            user:             configService.get('DB_USERNAME'),\n            password:         configService.get('DB_PASSWORD'),\n            autoLoadEntities: true\n        }),\n        inject: [ConfigService]\n    }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { JwtModule } from '@nestjs/jwt';\n\nimport jwtConfig from './jwt.config';\n\n\n@Module({\n    imports: [\n        ConfigModule.forFeature( jwtConfig ),\n        JwtModule.registerAsync( jwtConfig.asProvider() ),\n    ]\n})\nexport class AuthModule {}\n```\n\n```text\nimport { registerAs } from \"@nestjs/config\"\n\n\nexport default registerAs('jwt', () => {\n    return {\n        secret:         process.env.JWT_SECRET,\n        issuer:         process.env.JWT_TOKEN_ISSUER,\n        accessTokenTtl: parseInt(process.env.JWT_TOKEN_TTL)\n    };\n});\n```\n\n```text\nConfigService\n```\n\n```text\nyou can move configuration logic into a separate file\n```\n\n```text\napp.module.ts\n```\n\n```text\nconfig/database.config.ts\n```\n\n```text\nauth.module.ts\n```\n\n```text\njwt.config.ts\n```\n\n```ts\nimport databaseConfig from './config/database.config';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRootAsync(databaseConfig.asProvider()),\n  ],\n})\n```\n\n```ts\n// Return value of the .asProvider() method\n{\n  imports: [ConfigModule.forFeature(databaseConfig)],\n  useFactory: (configuration: ConfigType<typeof databaseConfig>) => configuration,\n  inject: [databaseConfig.KEY]\n}\n```\n\n========================================\n\nComments:\n- support for `registerAsync` has been added, see my edit. :-)\n- Your medium article breaks both my (and a colleague's) firefox and chrome browser. Very high CPU utilization and unresponsiveness.\n- What does `mySettingsFactory` do and how is it implemented?\n- @JendorskiLabs, mySettingsFactory is a generic Javascript factory (see: this link for an example of the basic pattern. In my case, mySettingsFactory is a function that produces an object (in this case, it parses a yml file and spits out the config)\n- @JendorskiLabs Actually, now that I look at it, nest's docs have an example of how the load key works and how mySettingsFactory gets pulled into the stack. See this link","metadata":{"transformedAt":"2026-08-18T18:33:02.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":319,"estimatedTokens":1853}}49{"id":"stack-54308318","source":"stackoverflow","questionId":54308318,"title":"How to get the configurations from within a module import in NestJS?","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: How to get the configurations from within a module import in NestJS?\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nLet's say I have my module defined as below:\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n // Use ConfigService here\n secretOrPrivateKey: 'secretKey',\n signOptions: {\n expiresIn: 3600,\n },\n }),\n PrismaModule,\n ],\n providers: [AuthResolver, AuthService, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\nNow how can I get the `secretKey` from the `ConfigService` in here?\n\n========================================\n\nTop Answer:\nOr there is another solution, create an JwtStrategy class, something like this:\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: config.session.secret,\n issuer: config.uuid,\n audience: config.session.domain\n });\n }\n\n async validate(payload: JwtPayload) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\nThere you are able to pass `ConfigService` as a parameter to the constructor, but I'm using config just from plain file. \n\nThen, don't forget to place it in array of providers in module.\n\nRegards.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.register({\n      // Use ConfigService here\n      secretOrPrivateKey: 'secretKey',\n      signOptions: {\n        expiresIn: 3600,\n      },\n    }),\n    PrismaModule,\n  ],\n  providers: [AuthResolver, AuthService, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\n```text\nsecretKey\n```\n\n```text\nConfigService\n```\n\n```text\nJwtModule.registerAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    secretOrPrivateKey: configService.getString('SECRET_KEY'),\n    signOptions: {\n        expiresIn: 3600,\n    },\n  }),\n  inject: [ConfigService],\n}),\n```\n\n```text\nregisterAsync\n```\n\n```text\nConfigService\n```\n\n```ts\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor(private readonly authService: AuthService) {\n        super({\n            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n            secretOrKey: config.session.secret,\n            issuer: config.uuid,\n            audience: config.session.domain\n        });\n    }\n\n    async validate(payload: JwtPayload) {\n        const user = await this.authService.validateUser(payload);\n        if (!user) {\n            throw new UnauthorizedException();\n        }\n        return user;\n    }\n}\n```\n\n```text\nConfigService\n```\n\n========================================\n\nComments:\n- Also, you don't need to import ConfigModule if you have already imported it globally in your app module .i.e ConfigModule.forRoot({ isGlobal: true, expandVariables: true, }),\n- @SegunKess that's a pretty nice hint!\n- wiwth \"expiresIn: 3600\", I wasn't able to authorize. Adding the \"s\" to get \"expiresIn: 3600s\" solved the problem - such small one ...\n- From the docs: \"A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (\"120\" is equal to \"120ms\").\" As this is quite confusing, I'd always prefer the expressive variant as string including the time unit.\n- Also, if intended to use it globally, the `global` property needs to be set at the same level as of `useFactory()`, rather than in the object returned by the factory method. See here. Confirmed with `@nestjs&#47;jwt` v10.2.0.\n- you can't pass the `ConfigService` here, because the use of `this` is not allowed in `super()`\n- que? [10 more to go]\n- if you pass the `ConfigService` in the constructor, you can't access it in the `super()` function. stackoverflow.com/questions/51896505/&hellip;\n- and why would you need to access it by this there?\n- i was just replying to what you said... You're using a static config file. I'm just telling it won't work with the ConfigService, that's all\n- But even if you pass the ConfigService here you are able to use it without this, just by name of the argument.\n- It worked for me and I was able to access the configService from the constructor: constructor(private readonly configService: ConfigService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: configService.get('jwt.secret'), }); }","metadata":{"transformedAt":"2026-08-18T18:33:02.403Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":151,"estimatedTokens":1158}}50{"id":"stack-50355670","source":"stackoverflow","questionId":50355670,"title":"NestJS returning the result of an HTTP request","tags":["node.js","typescript","rxjs","axios","nestjs"],"text":"Title: NestJS returning the result of an HTTP request\nTags: node.js, typescript, rxjs, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my NestJS application I want to return the result of an http call.\n\nFollowing the example of the NestJS HTTP module, what I'm doing is simply:\n\n```\nimport { Controller, HttpService, Post } from '@nestjs/common';\nimport { AxiosResponse } from '@nestjs/common/http/interfaces/axios.interfaces';\nimport { Observable } from 'rxjs/internal/Observable';\n\n@Controller('authenticate')\nexport class AuthController {\n\n constructor(private readonly httpService: HttpService) {}\n\n @Post()\n authenticate(): Observable> {\n return this.httpService.post(...);\n }\n}\n```\n\nHowever from the client I'm getting 500 and the server console is saying:\n\n TypeError: Converting circular structure to JSON\n at JSON.stringify ()\n at stringify (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/express/lib/response.js:1119:12)\n at ServerResponse.json (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/express/lib/response.js:260:14)\n at ExpressAdapter.reply (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/@nestjs/core/adapters/express-adapter.js:41:52)\n at RouterResponseController.apply (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/@nestjs/core/router/router-response-controller.js:11:36)\n at \n at process._tickCallback (internal/process/next_tick.js:182:7)\n\n========================================\n\nTop Answer:\nThe problem seems to stem from the fact that we are trying to return a Response object directly, and that is circular by nature. I'm not sure of the correct way to implement this, but I was able to get around it by using axios directly, unwrapping the promise and returning just the data.\n\n```\n@Post('login')\n async authenticateUser(@Body() LoginDto) {\n const params = JSON.stringify(LoginDto);\n\n return await axios.post('https://api.example.com/authenticate_user',\n params,\n {\n headers: {\n 'Content-Type': 'application/json',\n },\n }).then((res) => {\n return res.data;\n });\n}\n```\n\n**UPDATE**\n\nI realized I could just do the same thing to the Observable being returned from the `httpService` using the new rxjs pipe method, so that's probably the better way to do it.\n\n```\n@Post('login')\nasync authenticateUser(@Body() LoginDto) {\n const params = JSON.stringify(LoginDto);\n\n return this.httpService.post('https://api.example.com/authenticate_user',\n params,\n {\n headers: {\n 'Content-Type': 'application/json',\n },\n }).pipe(map((res) => {\n return res.data;\n }));\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Controller, HttpService, Post } from '@nestjs/common';\nimport { AxiosResponse } from '@nestjs/common/http/interfaces/axios.interfaces';\nimport { Observable } from 'rxjs/internal/Observable';\n\n@Controller('authenticate')\nexport class AuthController {\n\n  constructor(private readonly httpService: HttpService) {}\n\n  @Post()\n  authenticate(): Observable<AxiosResponse<any>> {\n    return this.httpService.post(...);\n  }\n}\n```\n\n```text\nreturn this.httpService.post(...)\n  .pipe(\n    map(response => response.data),\n  );\n```\n\n```text\ndata\n```\n\n```text\n@Post('login')\n  async authenticateUser(@Body() LoginDto) {\n    const params = JSON.stringify(LoginDto);\n\n    return await axios.post('https://api.example.com/authenticate_user',\n      params,\n      {\n        headers: {\n          'Content-Type': 'application/json',\n        },\n      }).then((res) => {\n          return res.data;\n    });\n}\n```\n\n```text\n@Post('login')\nasync authenticateUser(@Body() LoginDto) {\n    const params = JSON.stringify(LoginDto);\n\n    return this.httpService.post('https://api.example.com/authenticate_user',\n      params,\n      {\n        headers: {\n          'Content-Type': 'application/json',\n        },\n      }).pipe(map((res) => {\n    return res.data;\n  }));\n}\n```\n\n```text\nhttpService\n```\n\n```text\nconst responseData = await firstValueFrom(\n        this.httpService.post(url, data, config).pipe(map((response) => [response.data, response.status])),\n      );\n```\n\n```text\n@Injectable()\nexport class HttpService {\n constructor(private readonly http: HttpService){}\n\n fetch(url, params) {\n  return this.http.axiosRef.get(url, params)\n  }\n\n}\n```\n\n```js\nconst response = await this.httpService.post(...);\nreturn response.data\n```\n\n========================================\n\nComments:\n- Maybe httpService return some non-valid JSON, and NestJS (Express) throw the error because cannot convert. Try call something simple with httpService, maybe simple test GET.\n- from what is my understanding, NestJS should automatically convert to json.. am I right?\n- Yes, it should convert automatically by default.\n- As I'm experiencing the same exact thing, I tried testing with another source that I'm 100% positive is returning valid json and it's still giving the same error. Same result when using GET.\n- @andyrune. Sorry , I just wanted to point out that async await doesn't work with Observables. It works only with promises. I believe you have to convert your observable to a promise and then use async/await.\n- @andyrune, why controller here, make api call and hit another api instead of directly return data from database?\n- @MuhammedMoussa In my case the authentication api is on a different server.\n- This works, but is really ugly imo. Why is making http request implemented in such a weird way?\n- I am not getting any response, when I tried to console.log the response\n- So I had to learn this on my on. But now I want to push the original HTTP Status code in the case of an error. Any tips?\n- Thanks a lot, this isn't fixed as of today\n- HttpService class is imported from @nestjs/axios\n- Your answer could be improved by providing an example of the solution and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":188,"estimatedTokens":1453}}51{"id":"stack-56044471","source":"stackoverflow","questionId":56044471,"title":"testing private methods in typescript with jest","tags":["typescript","jestjs","nestjs"],"text":"Title: testing private methods in typescript with jest\nTags: typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn the below code my test case was passed as expected but i am using stryker for mutation testing , handleError function is survived in mutation testing , so i want to kill the mutant by testing the handleError function is being called or not. need to help to test the private function.\n\ni tried spyOn but didn't work \n\n```\nconst orderBuilderSpy = jest.spyOn(orderBuilder, 'build')\nconst handleError = jest.fn()\nexpect(rderBuilderSpy).toHaveBeenCalledWith(handleError)\n```\n\n\r\n\r\n\n```\n// code written in nestJS/typescript\r\n\r\nexport class OrderBuilder {\r\n private amount: number\r\n\r\n public withAmount(amount: number): BuyOrderBuilder {\r\n this.amount = amount\r\n return this\r\n }\r\n\r\n\r\n public build(): TransactionRequest {\r\n this.handleError()\r\n return {\r\n amount: this.amount,\r\n acceptedWarningRules: [\r\n {\r\n ruleNumber: 4464\r\n }\r\n ]\r\n }\r\n }\r\n private handleError() {\r\n const errors: string[] = []\r\n const dynamicFields: string[] = [\r\n 'amount',\r\n ]\r\n dynamicFields.forEach((field: string) => {\r\n if (!this[field]) {\r\n errors.push(field)\r\n }\r\n })\r\n if (errors.length > 0) {\r\n const errorMessage = errors.join()\r\n throw new Error(`missing ${errorMessage} field in order`)\r\n }\r\n }\r\n\r\n}\r\n\r\n\r\n// test\r\ndescribe('Order Builder', () => {\r\n it('should test the handleError', () => {\r\n const orderBuilder = new OrderBuilder()\r\n const errorMessage = new Error(\r\n `missing amount field in order`\r\n )\r\n try {\r\n orderBuilder.build()\r\n } catch (error) {\r\n expect(error).toEqual(errorMessage)\r\n }\r\n });\r\n});\n```\n\n========================================\n\nTop Answer:\nHere you go\n\n```\nconst handleErrorSpy = jest.spyOn(OrderBuilder.prototype as unknown as keyof typeof OrderBuilder, 'handleError');\n```\n\n========================================\n\nCode:\n```text\nconst orderBuilderSpy = jest.spyOn(orderBuilder, 'build')\nconst handleError = jest.fn()\nexpect(rderBuilderSpy).toHaveBeenCalledWith(handleError)\n```\n\n```js\n// code written in nestJS/typescript\n\nexport class OrderBuilder {\n  private amount: number\n\n  public withAmount(amount: number): BuyOrderBuilder {\n    this.amount = amount\n    return this\n  }\n\n\n  public build(): TransactionRequest {\n    this.handleError()\n    return {\n      amount: this.amount,\n      acceptedWarningRules: [\n        {\n          ruleNumber: 4464\n        }\n      ]\n    }\n  }\n  private handleError() {\n    const errors: string[] = []\n    const dynamicFields: string[] = [\n      'amount',\n    ]\n    dynamicFields.forEach((field: string) => {\n      if (!this[field]) {\n        errors.push(field)\n      }\n    })\n    if (errors.length > 0) {\n      const errorMessage = errors.join()\n      throw new Error(`missing ${errorMessage} field in order`)\n    }\n  }\n\n}\n\n\n// test\ndescribe('Order Builder', () => {\n  it('should test the handleError', () => {\n    const orderBuilder = new OrderBuilder()\n    const errorMessage = new Error(\n      `missing amount field in order`\n    )\n    try {\n      orderBuilder.build()\n    } catch (error) {\n      expect(error).toEqual(errorMessage)\n    }\n  });\n});\n```\n\n```text\nclass OrderBuilder {\n  public build() {\n    this.handleError()\n  }\n  private handleError() {\n    throw new Error('missing ... field in order')\n  }\n}\n\ndescribe('Order Builder', () => {\n  it('should test the handleError', () => {\n    const handleErrorSpy = jest.spyOn(OrderBuilder.prototype as any, 'handleError');\n    const orderBuilder = new OrderBuilder()\n    expect(() => orderBuilder.build()).toThrow('missing ... field in order');  // Success!\n    expect(handleErrorSpy).toHaveBeenCalled();  // Success!\n  });\n});\n```\n\n```text\nhandleError\n```\n\n```text\nbuild\n```\n\n```text\nany\n```\n\n```text\nconst handleErrorSpy = jest.spyOn(OrderBuilder.prototype  as unknown as keyof typeof OrderBuilder, 'handleError');\n```\n\n```text\n// @ts-expect-error(TS2769)\ncons spy = jest.spyOn(OrderBuilder, 'handleError');\n```\n\n========================================\n\nComments:\n- This one is really nice example for mocking out private methods in a javascript class. I have been trying out different ways jest.fn(), jest.spyOn() but couldn't make it work earlier. But now I do.\n- Is there a way to do this if the `handleError` is an arrow function and thus a property of the object?\n- This worked for me even without the `as any`","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":199,"estimatedTokens":1085}}52{"id":"stack-56660312","source":"stackoverflow","questionId":56660312,"title":"cannot connect an SSL secured database to typeorm","tags":["postgresql","ssl","nestjs","typeorm"],"text":"Title: cannot connect an SSL secured database to typeorm\nTags: postgresql, ssl, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThis is my first time using NestJS and I am having trouble connecting my Postgres database which is hosted on Digitalocean to NestJS.\n\nI searched online for solutions and tried adding `\"ssl\": \"true\" or \"extra\": { \"ssl\": \"true\" }`\n\nHeres my ormconfig.json\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"host\",\n \"port\": \"port\",\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"database\",\n \"extra\": {\n \"ssl\": \"true\"\n },\n \"synchronize\": \"true\",\n \"logging\": \"true\",\n \"entities\": [\"src/**/*.entity.ts\", \"dist/**/*.entity.js\"]\n}\n```\n\nI expect it to connect to the server. The error I'm getting is `[TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host \"\", user \"\", database \"\", SSL off`\n\n========================================\n\nTop Answer:\nThis works if you are connecting to postgres database on heroku from localhost using typeorm.\n\n`ormconfig.json`\n\n```\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"url\": \"postgres://username:password@host:port/database\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"],\n \"ssl\": true,\n \"extra\": {\n \"ssl\": {\n \"rejectUnauthorized\": false\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n  \"type\": \"postgres\",\n  \"host\": \"host\",\n  \"port\": \"port\",\n  \"username\": \"username\",\n  \"password\": \"password\",\n  \"database\": \"database\",\n  \"extra\": {\n    \"ssl\": \"true\"\n  },\n  \"synchronize\": \"true\",\n  \"logging\": \"true\",\n  \"entities\": [\"src/**/*.entity.ts\", \"dist/**/*.entity.js\"]\n}\n```\n\n```text\n\"ssl\": \"true\" or \"extra\": { \"ssl\": \"true\" }\n```\n\n```text\n[TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host \"\", user \"\", database \"\", SSL off\n```\n\n```text\nmodule.exports = {\n  name: 'default',\n  type: 'postgres',\n  host: 'host',\n  port: port,\n  username: 'username',\n  password: 'password',\n  database: 'database',\n  synchronize: true,\n  dropSchema: false,\n  logging: true,\n  ssl: {\n    ca: process.env.SSL_CERT,\n  },\n  entities: ['src/**/*.entity.ts', 'dist/**/*.entity.js'],\n};\n```\n\n```text\nssl: {\n    rejectUnauthorized: false,\n    ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),\n    key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),\n    cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),\n  },\n```\n\n```text\n{\n  \"name\": \"default\",\n  \"type\": \"postgres\",\n  \"url\": \"postgres://username:password@host:port/database\",\n  \"synchronize\": true,\n  \"logging\": true,\n  \"entities\": [\"src/entity/*.*\"],\n  \"ssl\": true,\n  \"extra\": {\n    \"ssl\": {\n      \"rejectUnauthorized\": false\n    }\n  }\n}\n```\n\n```text\normconfig.json\n```\n\n```js\nTypeOrmModule.forRoot({\n  type: 'postgres',\n  url: process.env.DATABASE_URL,\n  autoLoadEntities: true,\n  ssl:\n    process.env.NODE_ENV === 'production'\n      ? { rejectUnauthorized: false }\n      : false,\n}),\n```\n\n```text\nPQSSLMODE\n```\n\n```text\nrequire\n```\n\n```text\nlibpq\n```\n\n```text\noptions: { encrypt: false }\n```\n\n```text\nTypeOrmModule.forRoot({\n  type: 'mssql',\n  host: 'your_db_server_address',\n  port: 1433,\n  username: 'user',\n  password: 'pwd',\n  database: 'your_db_name_here',\n  entities: [Subscription],\n  options: { encrypt: false }\n  \n})\n```\n\n```js\nssl: {\n        ca: readFileSync(join(__dirname, 'assets', 'RDS.us-east-1.ca-bundle.pem')).toString()\n      },\n```\n\n```text\nurl\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nlogging\n```\n\n```js\nimport { DataSourceOptions } from 'typeorm';\n\nconst config: DataSourceOptions = {\n    type: \"mssql\",\n    host: \"dev\",\n    database: \"dev\",\n    username: \"\",\n    password: \"\",\n    synchronize: false,\n    logging: false,\n    entities: [\n        \"src/entity/**/*.ts\"\n    ],\n    migrations: [\n        \"src/migration/**/*.ts\"\n    ],\n    subscribers: [\n        \"src/subscriber/**/*.ts\"\n    ],\n    extra: {\n        trustServerCertificate: true,\n    }\n};\n\nexport default config;\n```\n\n```text\ntype: \"mssql\"\n```\n\n```text\nextra\n```\n\n```text\ntrustServerCertificate\n```\n\n```text\nnew DataSource({\n    ... current configuration,\n    ssl: true,\n    extra: {\n      ssl: {\n        rejectUnauthorized: false,\n      },\n    },\n   })\n```\n\n```text\nsslmode=require\n```\n\n```text\nDataSource\n```\n\n========================================\n\nComments:\n- Hello, I have the same issue. But I don't have any ssl cerificate. Do you any advice or sujestion? or is it mandatory to get a ssl certificate?. Could you helpme with this question stackoverflow.com/questions/65136834/&hellip; please.\n- If you have hosted database you want to connect to you need to download SSL certificate from that platform, you can use that certificate then. it's probably something like `ca_certificate.crt` and you can find more about it in your cloud hosting provider documentation.\n- I had a similar issue on Digitalocean. But I was using the url parameter in the typeorm config, and the url from DO contains sslmode=require at the end. It turns out that the sslmode parmeter in the url overwrites the ssl-parameter in config, s o the ca parameter was never set. See: node-postgres.com/features/ssl\n- But what's actually stored in that SSL_CERT environment variable??\n- @Musilix the contents of the .crt file you get from Digital Ocean (or whomever), with the newlines removed so it's all on one line\n- For anyone wondering where the certificate and other variables are coming from: only the DATABASE_URL environment variable will be set by default. You have to configure the other ones by yourself, see docs.digitalocean.com/products/app-platform/how-to/&hellip; There is currently an open issue when using the url property. I got it working by not using the url property and by defining each setting (e.g. host, username, ...) separately\n- It's not the greatest answer, but this does answer the actual question, the link is correct\n- on azure, you're going to need the cert as well- stackoverflow.com/a/63043606/228369","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":266,"estimatedTokens":1498}}53{"id":"stack-61431679","source":"stackoverflow","questionId":61431679,"title":"How to manage different config environments in nestjs","tags":["nestjs"],"text":"Title: How to manage different config environments in nestjs\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'd like to have a few environments, let's say `development`, `production`, `test`. These environments should be independent and use their own set of config parameters, e.g. for DB, SERVER_PORT, USER etc.\nThey should not be in the code base, so I think they should be different .env files. That's to say, I should be able to load different .env files depending on what environment is active. Also, it's not clear where I have to set that env switcher.\n\nMaybe it should be a single .env file that has the NODE_ENV parameter, that param can be set to any of the above-mentioned values, be that development, production or test. And depending on the value of this parameter a necessary set of config parameters gets automatically loaded.\n\nI've read the documentation, it seems a little confusing to me at the moment. \n\nSeems like there should be some config factory.\n\n========================================\n\nTop Answer:\nYou can use the config library as mentioned in the official documentation.\nOtherwise you can use the npm library dotenv.\n\nIn either way what really matters is how you organise your .env files. Env files are supposed to contain database credentials, encryption secret and many confidential data, so its not really a good idea to put them in version control. Instead you should store the .env file in the system. Production server will have .env file with production secrets, developer server can have .env file with local secrets. Flag .env to be ignored by git. In this way you won't have to change according to environment, it will automatically take the right configuration based on which server you are deploying.\n\n========================================\n\nCode:\n```text\ndevelopment\n```\n\n```text\nproduction\n```\n\n```text\ntest\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config';\n\nconst ENV = process.env.NODE_ENV;\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      envFilePath: !ENV ? '.env' : `.env.${ENV}`,\n    }),\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```text\nenv.development\n```\n\n```text\nenv.staging\n```\n\n```text\nenv.test\n```\n\n```text\napp.module.ts\n```\n\n```text\nConfigModule.forRoot({envFilePath: '.development.env'});\n```\n\n```text\nexport default () => ({\n  port: parseInt(process.env.PORT, 10) || 3000,\n  database: {\n    host: process.env.DATABASE_HOST,\n    port: parseInt(process.env.DATABASE_PORT, 10) || 5432\n  }\n});\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      load: [configuration],\n    }),\n  ],\n})\n```\n\n```text\n.prod.env\n```\n\n```text\n.development.env\n```\n\n```text\n.test.env\n```\n\n```text\n// Grab the system env variable\nconst ENV = process.env.NODE_ENV;\n\n// Set custom filepath in ConfigModule properties based on NODE_ENV\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n    envFilePath: !ENV ? '.env.dev' : `.env.${ENV}`\n    })\n  ]\n})\n```\n\n```text\n\"scripts\": {\n  \"start:dev\": \"NODE_ENV=dev nest start --watch\",\n  \"start:prod\": \"NODE_ENV=prod node dist/main\"\n}\n```\n\n```text\n- /config\n  - config.default.ts\n  - config.dev.ts\n  - config.production.ts\n  - configuration.ts\n```\n\n```text\nexport default {\n  // nodemailer config\n  mailer: {\n    host: 'xxx',\n    port: 80,\n    auth: {\n      user: 'xxx',\n      pass: 'xxx',\n    },\n    secure: false, // or true using 443\n  },\n  // jwt sign secret\n  jwt: {\n    secret: process.env.JWT_SECRET || '123456',\n  }\n}\n```\n\n```text\nimport { merge } from 'lodash';\nimport DefaultConfig from './config.default';\n\n\n\nexport default () => {\n  let envConfig = {};\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-var-requires\n    envConfig = require(`./config.${process.env.NODE_ENV}`).default;\n  } catch (e) {\n\n  }\n  \n  return merge(DefaultConfig, envConfig);\n};\n```\n\n```text\nimport configuration from './config/Configuration';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      load: [configuration],\n    }),\n  ],\n})\n```\n\n```text\nconfig\n```\n\n```text\nconfig.ENV.ts\n```\n\n```text\nconfiguration.ts\n```\n\n```text\nconfiguration.ts\n```\n\n```text\napp.module.ts\n```\n\n========================================\n\nComments:\n- FYI: According to the docs nest-js uses dotenv under the hood\n- I like this approach better over all other. But where do you set process.env.NODE_ENV. In Package.json?\n- @KrishnanSriram \"start:dev\": \"NODE_ENV=development nest start --watch\" is one approach.\n- @ChristianGroleau Using cross-env will ensure that the env variable is set for all OS (windows, linux).\n- console.log('ENV', ENV); = ENV undefined\n- This answer is incomplete. It has to be accompanied with how one will specifiy the NODE_ENV. Because that is the 2nd biggest part of this problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":213,"estimatedTokens":1181}}54{"id":"stack-70858113","source":"stackoverflow","questionId":70858113,"title":"Module '\"buffer\"' has no exported member 'Blob'","tags":["nestjs","buffer","cicd"],"text":"Title: Module '\"buffer\"' has no exported member 'Blob'\nTags: nestjs, buffer, cicd\nSource: Stack Overflow\n\nQuestion:\nHave anyone been in this situation before ?\nI run my code with CI/CD\nafter nest build, it gives me error :\n`node_modules/@types/superagent/index.d.ts:23:10 - error TS2305: Module '\"buffer\"' has no exported member 'Blob'. 23 import { Blob } from \"buffer\";`\n\nI don't know why? Please if you got a solution for this one.\n\n========================================\n\nTop Answer:\nUpgrading **@types/node** to `^14.18.10` and **typescript** to `^3.9.10` worked for me.\n\n```\n\"devDependencies\": {\n \"@types/node\": \"^14.18.10\",\n \"typescript\": \"^3.9.10\"\n},\n```\n\nFound on this discussion from Github\n\n========================================\n\nCode:\n```text\nnode_modules/@types/superagent/index.d.ts:23:10 - error TS2305: Module '\"buffer\"' has no exported member 'Blob'. 23 import { Blob } from \"buffer\";\n```\n\n```json\n...\n    \"devDependencies\": {\n        ...\n        \"@types/node\": \"14.18.2\",\n        \"@types/superagent\": \"4.1.10\",\n        \"@types/supertest\": \"^2.0.11\",\n        ...\n```\n\n```text\n\"supertest\"\n```\n\n```text\n\"nestjs/testing\"\n```\n\n```text\n\"@types/supertest\"\n```\n\n```text\n\"@types/superagent\": \"*\"\n```\n\n```text\n\"@types/node\": \"*\"\n```\n\n```text\nnestjs/testing -> supertest -> @types/supertest -> @types/superagent -> @types/node >= 16.X.X\n```\n\n```text\n\"@types/node\": \"\">=12.0.0 <16.0.0\"\n```\n\n```text\n\"@types/node\": \"*\"\n```\n\n```text\nnpm install\n```\n\n```text\nnpm ci\n```\n\n```text\n\"@types/node\": \"^16.0.0\",\n```\n\n```text\nnpm ci\n```\n\n```text\nnpm install\n```\n\n```text\n\"devDependencies\": {\n  \"@types/node\": \"^14.18.10\",\n  \"typescript\": \"^3.9.10\"\n},\n```\n\n```text\n^14.18.10\n```\n\n```text\n^3.9.10\n```\n\n```text\nnpm view @types/node\n```\n\n========================================\n\nComments:\n- looks like this is related with the version of your `@types&#47;node` or something like that\n- It is so weird because yesterday everything is still fine to me :( . I still use the same node version with it.\n- have you versioned the lock file and ran `npm ci`?\n- I will try it now. But when I run in local , it is still good? only when I push it to gitlab and run CI/CD , it gives me this error. Have you ever got something like this before ?\n- I haven't. I've been using GitHub Actions in TS projects without worries so far. Maybe the version that your CI/CD end up having isn't the same as the local one due to the lack of the lock file and `npm ci`\n- Yes, I got your point. But it seems like the answer from @vfrank66 is the answer I need.\n- Thank you @MicaelLevi . Your comments are so helpful\n- Thank you for the solution. I will try it and let you know soon.\n- Thank you. To me, your first option works.\n- For me the problem was a mismatch of my running node version and `@types&#47;node`. So after updating types to match node major version it works.\n- 14.8.2 doesn't seem to exist. Hugo's answer worked for me.\n- @Samantha it does exist: npmjs.com/package/@types/node/v/14.18.2\n- You can actually use node 14 without specifying `@types&#47;superagent` with the latest versions. The following work: - node: 14.21.1 - @types/node: 14.18.34 - @types/supertest: 2.0.12","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":130,"estimatedTokens":790}}55{"id":"stack-60114023","source":"stackoverflow","questionId":60114023,"title":"How to add summary and body manually in swagger nestjs","tags":["swagger","swagger-ui","nestjs","nestjs-swagger"],"text":"Title: How to add summary and body manually in swagger nestjs\nTags: swagger, swagger-ui, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI am trying to add summary in my swagger documentation routes but I am not able to find the appropriate decorator for defining the summary.\n\nThere are some routes in which I have not specified any DTO's. So, I would like to manually add request body for that endpoint.\n\n**user.controller.ts**\n\n```\n@Controller('users')\n@ApiTags('User')\n@ApiBearerAuth()\nexport class UsersController {\n\n constructor(private readonly service: UsersService) {}\n\n @Get()\n async findAll() {\n const data = await this.service.findAll();\n\n return {\n statusCode: 200,\n message: 'Users retrieved successfully',\n data,\n };\n }\n}\n```\n\nhttps://i.sstatic.net/cWMBD.png\n\n**auth.controller.ts**\n\n```\n@UseGuards(AuthGuard('local'))\n @Post('login')\n @ApiParam({\n name: 'email',\n type: 'string'\n })\n @ApiParam({\n name: 'password',\n type: 'string'\n })\n\n async login(@Request() req) {\n return this.authService.login(req.user);\n }\n```\n\n========================================\n\nTop Answer:\nI guess this can be seen more as a reference as this post comes up when looking for instructions for Swagger/OpenAPI.\n\nI have set up an example repo which shows the basic usage.\nYou can find it here: https://gitlab.com/WaldemarLehner/nestjs-swagger-example\n\n### Missing Summary\n\nUse the `@ApiOperation`-Decorator to define a Endpoint-Description.\n\n```\n@ApiOperation({description: \"This is the main Description of an Endpoint.\"})\n```\n\n### Want to manually add request schema\n\nFirst of all, note that you have a GET-Endpoint. As a result any request towards that endpoint **cannot have a request body**.\n\nSo.. assuming you use a HTTP Method that allows for a Request-Body (like POST), you can use the `@ApiBody`-Decorator.\n\nHere you can define the Body-Summary, a Schema (using an OpenAPI-Schema Object), or a Type (Schema is inferred from the Class and its Decorators).\n\n```\n@ApiBody({\n type: PostHelloBodyDTO,\n description: \"The Description for the Post Body. Please look into the DTO. You will see the @ApiOptionalProperty used to define the Schema.\",\n examples: {\n a: {\n summary: \"Empty Body\",\n description: \"Description for when an empty body is used\",\n value: {} as PostHelloBodyDTO\n },\n b: {\n summary: \"Hello Body\",\n description: \"Hello is used as the greeting\",\n value: {greeting: \"Hello\"} as PostHelloBodyDTO\n }\n }\n})\n```\n\n### Further Reference\n\nUsing the following Decorations will result in a Swagger-Document as shown below.\n\n```\n@ApiOperation({description: \"This is the main Description of an Endpoint.\"})\n/// Request Documentation\n@ApiParam({\n name: \"name\",\n description: \"This Decorator specifies the documentation for a specific Parameter, in this case the **name** Param.\",\n allowEmptyValue: false,\n examples: {\n a: {\n summary: \"Name is Pete\",\n description: \"Pete can be provided as a name. See how it becomes a selectable option in the dropdown\",\n value: \"Pete\"\n },\n b: {\n summary: \"Name is Joe\",\n value: \"Joe\"\n }\n }\n})\n@ApiQuery({\n name: \"useExclamation\",\n description: \"This is the description of a query argument. In this instance, we have a boolean value.\",\n type: Boolean,\n required: false // This value is optional\n})\n@ApiBody({\n type: PostHelloBodyDTO,\n description: \"The Description for the Post Body. Please look into the DTO. You will see the @ApiOptionalProperty used to define the Schema.\",\n examples: {\n a: {\n summary: \"Empty Body\",\n description: \"Description for when an empty body is used\",\n value: {} as PostHelloBodyDTO\n },\n b: {\n summary: \"Hello Body\",\n description: \"Hello is used as the greeting\",\n value: {greeting: \"Hello\"} as PostHelloBodyDTO\n }\n }\n\n})\n/// Response Documentation\n@ApiOkResponse({\n description: \"This description defines when a 200 (OK) is returned. For @Get-Annotated Endpoints this is always present. When, for example, using a @Post-Endpoint, a 201 Created is always present\",\n schema: {\n type: \"string\",\n example: \"Hello, Pete!\"\n // For instructions on how to set a Schema, please refer to https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object-examples\n }\n})\n@ApiBadRequestResponse({\n description: \"This description is for a 400 response. It is returned when additional query params are passed, or when the **useExclamation**-Argument could not be parsed as a boolean.\"\n})\n@ApiResponse({\n status: 417,\n description: \"One can also provided a Status-Code directly, as seen here\"\n})\n@Post(\":name\")\npublic postHello(...){...}\n```\n\n### Result\n\nhttps://i.sstatic.net/eGY7P.png\n\n========================================\n\nCode:\n```text\n@Controller('users')\n@ApiTags('User')\n@ApiBearerAuth()\nexport class UsersController {\n\n  constructor(private readonly service: UsersService) {}\n\n  @Get()\n  async findAll() {\n    const data = await this.service.findAll();\n\n    return {\n      statusCode: 200,\n      message: 'Users retrieved successfully',\n      data,\n    };\n  }\n}\n```\n\n```text\n@UseGuards(AuthGuard('local'))\n  @Post('login')\n  @ApiParam({\n    name: 'email',\n    type: 'string'\n  })\n  @ApiParam({\n    name: 'password',\n    type: 'string'\n  })\n\n  async login(@Request() req) {\n    return this.authService.login(req.user);\n  }\n```\n\n```js\n@Get()\n@ApiOperation({ summary: 'summary goes here' })\n@ApiResponse({ status: 200, description: 'description goes here', schema: { ...define schema here... } })\nasync findAll() {}\n```\n\n```text\n@ApiOperation()\n```\n\n```text\n@ApiResponse()\n```\n\n```js\nimport { ApiProperty } from '@nestjs/swagger';\n\n    export class ExampleRedditDTO {\n        @ApiProperty({\n            type: String,\n            description: \"The target subreddit\"\n        })\n        targetSub!: string;\n\n        @ApiProperty({\n            type: Number,\n            description: \"The number of top posts you want back\"\n        })\n        postCount!: number;\n    }\n```\n\n```text\n@ApiOperation({description: \"This is the main Description of an Endpoint.\"})\n```\n\n```js\n@ApiBody({\n    type: PostHelloBodyDTO,\n    description: \"The Description for the Post Body. Please look into the DTO. You will see the @ApiOptionalProperty used to define the Schema.\",\n    examples: {\n        a: {\n            summary: \"Empty Body\",\n            description: \"Description for when an empty body is used\",\n            value: {} as PostHelloBodyDTO\n        },\n        b: {\n            summary: \"Hello Body\",\n            description: \"Hello is used as the greeting\",\n            value: {greeting: \"Hello\"} as PostHelloBodyDTO\n        }\n    }\n})\n```\n\n```js\n@ApiOperation({description: \"This is the main Description of an Endpoint.\"})\n/// Request Documentation\n@ApiParam({\n    name: \"name\",\n    description: \"This Decorator specifies the documentation for a specific Parameter, in this case the <b>name</b> Param.\",\n    allowEmptyValue: false,\n    examples: {\n        a: {\n            summary: \"Name is Pete\",\n            description: \"Pete can be provided as a name. See how it becomes a selectable option in the dropdown\",\n            value: \"Pete\"\n        },\n        b: {\n            summary: \"Name is Joe\",\n            value: \"Joe\"\n        }\n    }\n})\n@ApiQuery({\n    name: \"useExclamation\",\n    description: \"This is the description of a query argument. In this instance, we have a boolean value.\",\n    type: Boolean,\n    required: false // This value is optional\n})\n@ApiBody({\n    type: PostHelloBodyDTO,\n    description: \"The Description for the Post Body. Please look into the DTO. You will see the @ApiOptionalProperty used to define the Schema.\",\n    examples: {\n        a: {\n            summary: \"Empty Body\",\n            description: \"Description for when an empty body is used\",\n            value: {} as PostHelloBodyDTO\n        },\n        b: {\n            summary: \"Hello Body\",\n            description: \"Hello is used as the greeting\",\n            value: {greeting: \"Hello\"} as PostHelloBodyDTO\n        }\n    }\n\n})\n/// Response Documentation\n@ApiOkResponse({\n    description: \"This description defines when a 200 (OK) is returned. For @Get-Annotated Endpoints this is always present. When, for example, using a @Post-Endpoint, a 201 Created is always present\",\n    schema: {\n        type: \"string\",\n        example: \"Hello, Pete!\"\n        // For instructions on how to set a Schema, please refer to https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object-examples\n    }\n})\n@ApiBadRequestResponse({\n    description: \"This description is for a 400 response. It is returned when additional query params are passed, or when the <b>useExclamation</b>-Argument could not be parsed as a boolean.\"\n})\n@ApiResponse({\n    status: 417,\n    description: \"One can also provided a Status-Code directly, as seen here\"\n})\n@Post(\":name\")\npublic postHello(...){...}\n```\n\n```text\n@ApiOperation\n```\n\n```text\n@ApiBody\n```\n\n```text\n@RequestBody(content = @Content(\n            examples = {@ExampleObject(name = \"Testing Name\", value = \"{'name':'Abc', 'age':23}\", description = \"Testing Description\")}))\n```\n\n```text\n@Operation(summary = \"Testing GitHub File Reader\")\n```\n\n```text\nimport org.eclipse.microprofile.openapi.annotations.Operation;\nimport org.eclipse.microprofile.openapi.annotations.media.Content;\nimport org.eclipse.microprofile.openapi.annotations.media.ExampleObject;\nimport org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;\n\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport java.util.Map;\n\n@Path(\"/api\")\npublic class RestControllerResponse {\n\n    @Path(\"/generate\")\n    @POST\n    @Operation(summary = \"Testing GitHub File Reader\")\n    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})\n    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})\n    @RequestBody(content = @Content(\n            examples = {@ExampleObject(name = \"Testing Name\", value = \"{'name':'Abc', 'age':23}\", description = \"Testing Description\")}))\n    public String generator(final Map<String, Object> input) throws Exception {\n        return \"Hello From Generator Method\";\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":370,"estimatedTokens":2525}}56{"id":"stack-62762492","source":"stackoverflow","questionId":62762492,"title":"NestJS - How to create nested schema with decorators","tags":["mongoose","schema","nestjs","mongoose-schema"],"text":"Title: NestJS - How to create nested schema with decorators\nTags: mongoose, schema, nestjs, mongoose-schema\nSource: Stack Overflow\n\nQuestion:\nLet's say I want to build the below schema with mongoose:\n\n```\nconst userSchema = new Schema({\n name: {\n firstName: String,\n lastName: String\n }\n})\n```\n\nHow can I do it with NestJS decorators (`@Schema()` & `@Prop()`)?\n\nI try this method, but no luck:\n\n```\n@Schema()\nclass Name {\n @Prop()\n firstName: string;\n\n @Prop()\n lastName: string;\n}\n\n@Schema()\nclass User extends Document {\n @Prop({ type: Name })\n name: Name;\n}\n```\n\nI also don't want to use the `raw()` method.\n\n========================================\n\nTop Answer:\nI haven't found this part of NestJS to be flexible enough. A working solution (tested) for me is the following:\n\n```\n@Schema({_id: false}) // _id:false is optional\nclass Name {\n @Prop() // any options will be evaluated\n firstName: string; // data type will be checked\n\n @Prop()\n lastName: string;\n}\n\n@Schema()\nclass User {\n @Prop({type: Name}) // {type: Name} can be omitted\n name: Name;\n}\n```\n\nDefining your schemas this way will keep everything (class decorators, passed options, data types verification, NestJS functionalities, etc.) working as expected. The only \"issue\" is that `_id` properties will be created for each `@Schema` and you might not want that, like in your case. You can avoid that by adding `{_id: false}` as an options object to your `@Schema()`. Keep in mind, that any further nested schemas won't be prevented from creating `_id` properties, e.g.\n\nThis:\n\n```\n@Schema() // will create _id filed\nclass Father {\n age: number;\n name: string;\n}\n\n@Schema({_id: false}) // won't create _id field\nclass Parents {\n @Prop()\n father: Father;\n\n @Prop()\n mother: string;\n}\n\n@Schema()\nclass Person {\n @Prop()\n parents: Parents;\n}\n```\n\nwill produce this:\n\n```\n{\n _id: ObjectId('someIdThatMongoGenerated'),\n parents: {\n father: {\n _id: ObjectId('someIdThatMongoGenerated'),\n age: 40,\n name: Jon Doe\n },\n mother: Jane Doe\n }\n}\n```\n\nThe other workaround is to use native mongoose for creating your schemas in NestJS, like so:\n\n```\nconst UserSchema = new mongoose.Schema({\n name: {\n firstName: {\n type: String, // note uppercase\n required: true // optional\n },\n lastName: {\n type: String,\n required: true\n }\n }\n});\n```\n\n========================================\n\nCode:\n```js\nconst userSchema = new Schema({\n  name: {\n    firstName: String,\n    lastName: String\n  }\n})\n```\n\n```js\n@Schema()\nclass Name {\n  @Prop()\n  firstName: string;\n\n  @Prop()\n  lastName: string;\n}\n\n@Schema()\nclass User extends Document {\n  @Prop({ type: Name })\n  name: Name;\n}\n```\n\n```text\n@Schema()\n```\n\n```text\n@Prop()\n```\n\n```text\nraw()\n```\n\n```js\n// Nested Schema\n@Schema()\nexport class BodyApi extends Document {\n  @Prop({ required: true })\n  type: string;\n\n  @Prop()\n  content: string;\n}\nexport const BodySchema = SchemaFactory.createForClass(BodyApi);\n\n// Parent Schema\n@Schema()\nexport class ChaptersApi extends Document {\n  // Array example\n  @Prop({ type: [BodySchema], default: [] })\n  body: BodyApi[];\n\n  // Single example\n  @Prop({ type: BodySchema })\n  body: BodyApi;\n}\nexport const ChaptersSchema = SchemaFactory.createForClass(ChaptersApi);\n```\n\n```text\nexport const UserSchema = new mongoose.Schema(\n  {\n    name: [UserNameSchema],\n  },\n  {\n    timestamps: true,\n  },\n);\n```\n\n```text\n@Prop(raw({\n  firstName: { type: String },\n  lastName: { type: String }\n}))\ndetails: Record<string, any>;\n```\n\n```js\nimport { Prop, Schema, SchemaFactory, } from '@nestjs/mongoose';\n    import { Document  } from 'mongoose';\n        \n    class Name {\n      @Prop()\n      firstName: string;\n    \n      @Prop()\n      lastName: string;\n    }\n    \n    @Schema()\n    class User extends Document {\n      @Prop({ type: Name })\n      name: Name;\n    }\n    export const userSchema = SchemaFactory.createForClass(user);\n```\n\n```text\nimport { Document } from 'mongoose';\n\n@Schema()\nexport class User extends Document {\n  @Prop({ type: Name })\n  name: Name;\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n```text\nimport { Document } from 'mongoose';\n\nexport class Name extends Document {\n  @Prop({ default: \" \" })\n  firstName: string;\n\n  @Prop({ default: \" \" })\n  lastName: string;\n}\n```\n\n```text\n@Schema\n```\n\n```text\nDocument\n```\n\n```text\n'mongoose'\n```\n\n```text\nuser.schema.ts\n```\n\n```text\nname.schema.ts\n```\n\n```js\n@Schema()\n    class User extends Document {\n      @Prop({ type:  { firstName: String, lastName: String })\n      name: Name;\n    }\n```\n\n```js\n@Schema({_id: false}) // _id:false is optional\nclass Name {\n  @Prop() // any options will be evaluated\n  firstName: string; // data type will be checked\n\n  @Prop()\n  lastName: string;\n}\n\n@Schema()\nclass User {\n  @Prop({type: Name}) // {type: Name} can be omitted\n  name: Name;\n}\n```\n\n```js\n@Schema() // will create _id filed\nclass Father {\n  age: number;\n  name: string;\n}\n\n@Schema({_id: false}) // won't create _id field\nclass Parents {\n  @Prop()\n  father: Father;\n\n  @Prop()\n  mother: string;\n}\n\n@Schema()\nclass Person {\n  @Prop()\n  parents: Parents;\n}\n```\n\n```js\n{\n  _id: ObjectId('someIdThatMongoGenerated'),\n  parents: {\n    father: {\n      _id: ObjectId('someIdThatMongoGenerated'),\n      age: 40,\n      name: Jon Doe\n    },\n    mother: Jane Doe\n  }\n}\n```\n\n```js\nconst UserSchema = new mongoose.Schema({\n  name: {\n    firstName: {\n      type: String, // note uppercase\n      required: true // optional\n    },\n    lastName: {\n      type: String,\n      required: true\n    }\n  }\n});\n```\n\n```text\n_id\n```\n\n```text\n@Schema\n```\n\n```text\n{_id: false}\n```\n\n```text\n@Schema()\n```\n\n```text\n_id\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { HydratedDocument } from 'mongoose';\nimport { FanNotification } from './notification.schema';\n\nexport type FanDocument = HydratedDocument<Fan>;\n\n@Schema()\nexport class Fan {\n\n  @Prop({ type: FanNotification, default: () => ({}) })\n  notifications: FanNotification;\n\n}\n\nexport const FanSchema = SchemaFactory.createForClass(Fan);\n```\n\n```js\nimport { Prop, Schema } from '@nestjs/mongoose';\nimport { AllMethod } from 'common/types';\nimport { Schema as MongooseSchema } from 'mongoose';\n\n@Schema({ _id: false })\nexport class FanNotification {\n  @Prop({\n    type: MongooseSchema.Types.Mixed,\n    default: { sms: true, email: true },\n  })\n  chat: AllMethod;\n\n}\n```\n\n```text\ndefault: () => ({})\n```\n\n```text\n@Prop()\n```\n\n```text\n{ _id: false }\n```\n\n========================================\n\nComments:\n- why not `raw()`?\n- I want to use my typescript model both in frontend and backend and I save this model in a shared folder. With this approach, I can't do this anymore!\n- Totally, It should not. Because the schemas and model are different. You should define interface files as well. The return data should be compatibility with interface. Then the interface to frontend. Using OpenAPI generator.\n- the question clearly states using Nest decorators.\n- What is the problem? Are you getting any error messages? I just did that structure in my project and it is working fine\n- I don't know, I don't get any error, it just doesn't work. Try to put a default value on a nested property like 'firstName', the default value won't set, showing there's a problem.\n- discordapp.com/channels/520622812742811698/60612538081791182&zwnj;&#8203;8/&hellip;\n- Will it work for unique: true for a property inside an array of sub document?\n- This solution will correctly create a nested object (user.name.firstName) but the type (:string) validation will not work. You will be allowed to write a number or another type into the firstName field. It's not a working solution.\n- I'm following the same the but my defaults are not being set on the nested object.\n- Hmmm, looks promising. Gonna try it out soon ๐Ÿ‘\n- will it create 2 separate collections? I want a single collection.\n- @AnkitTanna No, only the schema you pass to `MongooseModule.forFeature` in the module will get created.\n- Is BodyContentInterface supposed to be the same as BodyApi? Its not defined anywhere\n- If we do not pass the subdocument schema into `MongooseModule`, then how should we use and populate subdocument inside the corresponding `service.ts`\n- @AlexanderK1987, you don't need to pass it to the MongooseModule tho, I was making the same mistake and once I removed them, those collections never came back. I guess you'd have to stick to using those models inside of their own modules and that's a good practice.\n- This solution creates a collection for the sub document on the fly. To create an embedded document without creating the collection, read my answer below\n- @austinthedeveloper what is BodyContentInterface please? class annotated with @Schema()? Why in your example classes annotated with @Scehma() needs to extend Document? At least in nestjs docs, i cant find example where they extends from Document any schema.\n- @austinthedeveloper or maybe it is HydratedDocument? Something like: export type BodyContentInterface = HydratedDocument?\n- Yes, BodyContentInterface should be BodyApi, probably the code was copied from somewhere, I've edited it. Based on this: stackoverflow.com/a/68745009/1806628\n- This solution work perfectly for me, including prop args like `default`, `get`/`set` and so on. Hope I know this method earlier\n- You should use `markModified()` for the sub-document when anything has changed on that path.","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":439,"estimatedTokens":2344}}57{"id":"stack-56311203","source":"stackoverflow","questionId":56311203,"title":"Can I map entity field names to alias column names in TypeORM?","tags":["nestjs","typeorm"],"text":"Title: Can I map entity field names to alias column names in TypeORM?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am in the process of migrating from Rails to NestJs with TypeORM.\nFor historical reasons, table names and column names in Rails are `snaked_cased` - I don't want to copy this nuisance to our NestJs/React side.\n\nCan I create entity fields in NestJS (typeorm) called `firstName` but are mapped to a column named `first_name` in my DB?\n\nMy table\n\n```\n+-------------+--------------+----------------------------+\n| system_users |\n+-------------+--------------+----------------------------+\n| id | int(11) | PRIMARY KEY AUTO_INCREMENT |\n| first_name | varchar(100) | |\n| last_name | varcahr(100) | |\n+-------------+--------------+----------------------------+\n```\n\nMy User Entity Class\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'system_users' })\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 255 })\n first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)\n\n @Column({ length: 255 })\n last_name: string; // <-- I WANT THIS TO BE lastName (camelCased)\n}\n```\n\n========================================\n\nTop Answer:\nIf anyone else comes across this issue, know that TypeORM supports naming strategies.\n\nAnd there is even a package for a snake case naming strategy\n\n========================================\n\nCode:\n```sql\n+-------------+--------------+----------------------------+\n|                      system_users                       |\n+-------------+--------------+----------------------------+\n| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |\n| first_name  | varchar(100) |                            |\n| last_name   | varcahr(100) |                            |\n+-------------+--------------+----------------------------+\n```\n\n```js\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'system_users' })\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ length: 255 })\n  first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)\n\n  @Column({ length: 255 })\n  last_name: string;  // <-- I WANT THIS TO BE lastName (camelCased)\n}\n```\n\n```text\nsnaked_cased\n```\n\n```text\nfirstName\n```\n\n```text\nfirst_name\n```\n\n```js\n@Entity({ name: 'system_users' })\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ length: 255, name: \"first_name\" })\n  firstName: string; \n\n  @Column({ length: 255, name: \"last_name\" })\n  lastName: string; \n}\n```\n\n```text\n@Column\n```\n\n```text\nname\n```\n\n========================================\n\nComments:\n- This was 100% identical to what I was looking as well. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":675}}58{"id":"stack-51537780","source":"stackoverflow","questionId":51537780,"title":"TypeORM: Joining when we have one to many and many to one relationship","tags":["nestjs","typeorm"],"text":"Title: TypeORM: Joining when we have one to many and many to one relationship\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\n@Entity()\nexport class User {\n @PrimaryColumn()\n id: string;\n\n @Column({unique: true})\n username: string;\n\n @Column({unique: true})\n email: string;\n\n @OneToMany(type => Post, post => post.id)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(type => User, user => user.posts)\n @JoinColumn({name: 'user_id'})\n user: User;\n\n @OneToMany(type => Image, image => image.id)\n images: Image[];\n}\n \n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(type => Post, post => post.images)\n @JoinColumn({name : 'post_id'})\n post: Post;\n}\n```\n\nI have these 3 entities and I want to make a query to have all the posts from a user and for that post to get all the images. I am trying to do this using the following code:\n\n```\nreturn await this.postRepository.createQueryBuilder(\"post\")\n .innerJoinAndSelect(\"post.images\", \"image\")\n .where(\"user_id = :userId\", {userId: id})\n .getMany();\n```\n\nAnd I get the following error:\n\n```\nCannot read property 'joinColumns' of undefined\n```\n\nI also tried this instead of the `.innerJoin` from above:\n\n```\n.innerJoinAndSelect(Image, \"image\", \"image.post_id = post.id\")\n```\n\nThis way I don't get that error anymore, but as a result I get only the post and I don't get the images from it\n\n========================================\n\nTop Answer:\n```\n@Entity()\nexport class User {\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n user_id: number;\n\n @ManyToOne(type => User)\n @JoinColumn({name: 'user_id', referencedColumnName: 'id'})\n user: User;\n\n @OneToMany(type => Image, image => image.post)\n images: Image[];\n}\n\n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n post_id: number;\n\n @ManyToOne(type => Post)\n @JoinColumn({name : 'post_id', referencedColumnName: 'id'})\n post: Post;\n}\n```\n\nTry this\n\n========================================\n\nCode:\n```ts\n@Entity()\nexport class User {\n  @PrimaryColumn()\n  id: string;\n\n  @Column({unique: true})\n  username: string;\n\n  @Column({unique: true})\n  email: string;\n\n  @OneToMany(type => Post, post => post.id)\n  posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @ManyToOne(type => User, user => user.posts)\n  @JoinColumn({name: 'user_id'})\n  user: User;\n\n  @OneToMany(type => Image, image => image.id)\n  images: Image[];\n}\n \n@Entity()\nexport class Image {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @ManyToOne(type => Post, post => post.images)\n  @JoinColumn({name : 'post_id'})\n  post: Post;\n}\n```\n\n```ts\nreturn await this.postRepository.createQueryBuilder(\"post\")\n  .innerJoinAndSelect(\"post.images\", \"image\")\n  .where(\"user_id = :userId\", {userId: id})\n  .getMany();\n```\n\n```text\nCannot read property 'joinColumns' of undefined\n```\n\n```text\n.innerJoinAndSelect(Image, \"image\", \"image.post_id = post.id\")\n```\n\n```text\n.innerJoin\n```\n\n```js\n@OneToMany(type => Image, image => image.id)\nimages: Image[];\n```\n\n```js\n@OneToMany(type => Image, image => image.post)\nimages: Image[];\n```\n\n```js\n@OneToMany(type => Post, post => post.id)\nposts: Post[];\n```\n\n```js\n@OneToMany(type => Post, post => post.user)\nposts: Post[];\n```\n\n```js\nreturn await this.postRepository.find({\n  relations: ['images', 'user'],\n  where: { user: { id: id } },\n});\n```\n\n```text\nimage.id\n```\n\n```text\nimage.post\n```\n\n```text\npost.id\n```\n\n```text\npost.user\n```\n\n```text\n@JoinColumn()\n```\n\n```text\n@JoinColumn\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@OneToMany\n```\n\n```text\n@OneToMany\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@OneToMany\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@Entity()\nexport class User {\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n user_id: number;\n\n @ManyToOne(type => User)\n @JoinColumn({name: 'user_id', referencedColumnName: 'id'})\n user: User;\n\n @OneToMany(type => Image, image => image.post)\n images: Image[];\n}\n\n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n post_id: number;\n\n @ManyToOne(type => Post)\n @JoinColumn({name : 'post_id', referencedColumnName: 'id'})\n post: Post;\n}\n```\n\n========================================\n\nComments:\n- How is it going? did you solve the probelm?\n- This worked. A column with the foreign key was to be added. Thanks a lot\n- Using this I get : \"'type' is declared but its value is never read.\"\n- referencedColumnName: 'id' works for me!\n- If `@OneToMany` and `@ManyToOne` are matched, no extra parameter is needed. `@JoinColumn({name: 'user_id', referencedColumnName: 'id'})` `@JoinColumn()` // auto join\n- Using this method I get an error: 'type' is declared but its value is never read.\n- You should be able to sort that out by replacing 'type' with either () or _ (Empty parentheses or underscore) to let the typescript compiler know you do not want to use it. You may find more info in this answer here stackoverflow.com/a/41086381/10952954\n- The problem with the TypeORM documentation is that it assumes you're using the sync feature, so the library *creates* the join column so it knows which one is it. But it doesn't explain clearly how to deal with non-synced already existing tables.","metadata":{"transformedAt":"2026-08-18T18:33:02.404Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":305,"estimatedTokens":1361}}59{"id":"stack-62046413","source":"stackoverflow","questionId":62046413,"title":"Is it possible to pass a parameter to a nestjs guard?","tags":["nestjs"],"text":"Title: Is it possible to pass a parameter to a nestjs guard?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to come up with a somewhat reusable guard and it looks like I need to pass a string param to a guard. Is it achievable in nestjs?\n\n========================================\n\nTop Answer:\nIt seems impossible to use mixin in Guard in NestJs. It will throw Exported variable 'RoleGuard' has or is using private name 'RoleGuardMixin'.\n\nActually, you may use setMetadata to pass in the parameters one by one, then get it from the Guard using reflector from from '@nestjs/core'.\n\n```\n@Injectable()\n export class RoleGuard implements CanActivate {\n constructor(\n private reflector: Reflector,\n ) {}\n\n canActivate(context: ExecutionContext) {\n const roleName = this.reflector.get('roleName', context.getHandler());\n return true;\n }\n }\n```\n\n```\n@Get()\n @UseGuards(RoleGuard)\n @SetMetadata('roleName', 'developer')\n async testRoleGuard() {\n return true;\n }\n```\n\nOr you may define a decorator to pass the parameter in.\n\n```\nexport const RoleName = (roleName: string) => SetMetadata('roleName', roleName);\n```\n\n```\n@Get()\n @UseGuards(RoleGuard)\n @RoleName('developer')\n async testRoleGuard() {\n return true;\n }\n```\n\n*`UseGuards` is imported from `@nestjs/common`.*\n\n========================================\n\nCode:\n```js\nexport const RoleGuard = (role: string) => {\n  class RoleGuardMixin implements CanActivate {\n    canActivate(context: ExecutionContext) {\n      // do something with context and role\n      return true;\n    }\n  }\n\n  const guard = mixin(RoleGuardMixin);\n  return guard;\n}\n```\n\n```text\nmixin\n```\n\n```text\nmixin\n```\n\n```text\n@nestjs/common\n```\n\n```text\n@Injectable()\n```\n\n```text\n@UseGuards(RoleGuard('admin'))\n```\n\n```js\n@Injectable()\n    export class RoleGuard implements CanActivate {\n        constructor(\n            private reflector: Reflector,\n        ) {}\n\n        canActivate(context: ExecutionContext) {\n          const roleName = this.reflector.get<string>('roleName', context.getHandler());\n          return true;\n        }\n    }\n```\n\n```js\n@Get()\n    @UseGuards(RoleGuard)\n    @SetMetadata('roleName', 'developer')\n    async testRoleGuard() {\n      return true;\n    }\n```\n\n```js\nexport const RoleName = (roleName: string) => SetMetadata('roleName', roleName);\n```\n\n```js\n@Get()\n    @UseGuards(RoleGuard)\n    @RoleName('developer')\n    async testRoleGuard() {\n      return true;\n    }\n```\n\n```text\nUseGuards\n```\n\n```text\n@nestjs/common\n```\n\n```js\n@UseGuards(new AuthorizeGuard('read', 'users'))\n```\n\n```js\n@Injectable()\nexport class AuthorizeGuard implements CanActivate {\n\n  constructor(private action, private subject) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    //you can use this.action and this.subject\n  }\n}\n```\n\n```js\ndescribe('PaymentGuard', () => {\n  let guard: CanActivate;\n  beforeEach(async () => {\n    const guardProvider = PaymentGuard(PaymentGuardHandlerToken.EXPECT_PLATFORM_ENABLED);\n    const module = await Test.createTestingModule({\n      providers: [\n        guardProvider,\n        {\n          provide: PaymentService,\n          useValue: MOCK_PAYMENT_SERVICE,\n        },\n        {\n          provide: EntityManager,\n          useValue: MOCK_ENTITY_MANAGER,\n        }\n      ],\n    }).compile();\n    guard = module.get(guardProvider);\n  });\n});\n```\n\n```text\nguard.canActivate\n```\n\n```text\nexport const RoleGuard = (role: string) => {\n  @Injectable() // => Here\n  class RoleGuardMixin implements CanActivate {\n    canActivate(context: ExecutionContext) {\n      // do something with context and role\n      return true;\n    }\n  }\n\n  const guard = mixin(RoleGuardMixin);\n  return guard;\n}\n```\n\n========================================\n\nComments:\n- @SimonSch&#252;rg seeing what code you have would be necessary to determine the problem. I've used this pattern several times without fail.\n- @JayMcDoniel I have figured out the exception problem in my nest js code. To my suprise it had not to do with the mixin guard pattern. The reason was that I used a guard in one controller wrong. So sorry for the not related comment. I deleted it to avoid confusion.\n- @JayMcDoniel but if without mixin or with @UseGuards(new PermissionsGuard2('test'))\n- @Michael if you have a new question, it may be best to create a new post. From your comment, I can't tell what's being asked here\n- Just a heads up for people running into TS errors with this solution, it can be easily resolved by changing the return type of `RoleGuard` (ie. `export const RoleGuard = (role: string): Type ...`. Otherwise the return type is a private class, which will fail.\n- Error : Exported variable 'RoleGuard' has or is using private name 'RoleGuardMixin'\n- I get a runtime error: metatype is not a constructor\n- @TruMan1 what are you passing to `@UseGuards()`?\n- \"metatype is not a constructor\" means you are not calling the mixin function itself. `@UseGuards(UploadGuard)` -> `@UseGuards(UploadGuard(params))`\n- You saved my day :-)\n- A mixin is not a function that returns a class. This isn't mixin. Mixins are entirely different things.\n- @Gherman In NestJS, we call functions that return class references (that can be `new`ed) a mixin. Whether that matches the wikipedia definition is not something I was concerned with while answering how to do what OP asked\n- @JayMcDoniel Can you post a link to NestJS docs with a definition of mixin in the context? I did not learn what mixin is from Wikipedia but from a number of books and docs.\n- also appears, RoleGuardMixin, cannot have any private methods\n- How do I register such a Guard in providers?\n- @Michaล‚J.Gฤ…sior Why are you wanting a guard in the provider? You can do a global provider with `{ provide: APP_GUARD, useClass: RoleGuard(role)}`, but otherwise guards don't *normaly* go in the providers array\n- If iam use this, how do i inject some service ?\n- Bad approach, creates new guard instances for every controller","metadata":{"transformedAt":"2026-08-18T18:33:02.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":214,"estimatedTokens":1477}}60{"id":"stack-69139950","source":"stackoverflow","questionId":69139950,"title":"How to use axios HttpService from Nest.js to make a POST request","tags":["nestjs"],"text":"Title: How to use axios HttpService from Nest.js to make a POST request\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a POST request using `@nestjs/axios` and then access the response.\n\nThis is my code so far:\n\n```\nverifyResponse(captcha_response: String): Observable> {\n\n return this.httpService.post('some url', {\n captcha_response\n });\n}\n```\n\nHowever, I am unsure how to access the response data. If I use `console.log()` to view the response I get this:\n\n```\nObservable { _subscribe: [Function (anonymous)] }\n```\n\nI'm new to both Nest.js and the concept of an Observable. I would be grateful for an example to make a HTTP request and access the response data.\n\n========================================\n\nTop Answer:\n`AxiosResponse` should be imported from `axios`:\n\n```\nimport { AxiosResponse } from 'axios'\n```\n\nYou can make use of import suggestions by pressing `ctrl`+`space` (or `options` + `esc` on mac) or by using `ctrl`+`.`\n\n========================================\n\nCode:\n```js\nverifyResponse(captcha_response: String): Observable<AxiosResponse<any>> {\n\n    return this.httpService.post('some url', {\n        captcha_response\n    });\n}\n```\n\n```text\nObservable { _subscribe: [Function (anonymous)] }\n```\n\n```text\n@nestjs/axios\n```\n\n```text\nconsole.log()\n```\n\n```js\nthis.httpService.post(url, data, options).pipe(\n  tap((resp) => console.log(resp)),\n  map((resp) => resp.data),\n  tap((data) =>  console.log(data)),\n);\n```\n\n```js\nconst data = await lastValueFrom(\n  this.httpService.post(url, data, options).pipe(\n    map(resp => res.data)\n  )\n);\n```\n\n```js\nconst requestConfig: AxiosRequestConfig = {\n  headers: {\n    'Content-Type': 'YOUR_CONTENT_TYPE_HEADER',\n  },\n  params: {\n    param1: 'YOUR_VALUE_HERE'\n  },\n};\n\nconst responseData = await lastValueFrom(\n  this.httpService.post(requestUrl, null, requestConfig).pipe(\n    map((response) => {\n      return response.data;\n    }),\n  ),\n);\n```\n\n```text\nHttpService\n```\n\n```text\nlastValueFrom\n```\n\n```text\nthis.httpService.post()\n```\n\n```text\nawait\n```\n\n```text\nmap((resp) => resp.data)\n```\n\n```text\nconsole.log()\n```\n\n```text\ntap\n```\n\n```text\nmap\n```\n\n```text\ntap\n```\n\n```text\nmap\n```\n\n```text\nawait\n```\n\n```text\nAxiosRequestConfig\n```\n\n```js\nimport { AxiosResponse } from 'axios'\n```\n\n```text\nAxiosResponse\n```\n\n```text\naxios\n```\n\n```text\nctrl\n```\n\n```text\nspace\n```\n\n```text\noptions\n```\n\n```text\nesc\n```\n\n```text\nctrl\n```\n\n```text\n.\n```\n\n```text\nconst config: AxiosRequestConfig = {\n  url,\n  method,\n  params,\n  headers,\n  data,\n};\n\ntry {\n  const response = await this.httpService.axiosRef.request(config);\n  return response.data;\n} catch (error) {\n  console.log(error);\n}\n```\n\n```text\ntry {\n  const url = `some url`;\n  const data = {};\n  return await this.httpService.axiosRef.post(url, data);\n} catch (error) {\n  console.log(error);\n}\n```\n\n```text\nverifyResponse(captcha_response: string): Observable<any> {\n  return this.httpService.post('some url', { captcha_response }).pipe(\n    map(response => response.data)\n  );\n}\n```\n\n```text\nverifyResponse(captcha_response: string): void {\n  this.verifyResponse(captcha_response).subscribe(\n    data => {\n        // Handle the response data here\n        console.log(data);\n    },\n    error => {\n        // Handle errors if any\n        console.error(error);\n    }\n  );\n}\n```\n\n========================================\n\nComments:\n- I am getting this error - Cannot find name 'map'. Did you mean 'Map'?ts(2552) lib.es2015.collection.d.ts(56, 13): 'Map' is declared here.\n- `map` is an RxJS operator, imported as `import { map } from 'rxjs'`","metadata":{"transformedAt":"2026-08-18T18:33:02.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":235,"estimatedTokens":892}}61{"id":"stack-55269777","source":"stackoverflow","questionId":55269777,"title":"NestJS Get current user in GraphQL resolver authenticated with JWT","tags":["node.js","jwt","graphql","nestjs"],"text":"Title: NestJS Get current user in GraphQL resolver authenticated with JWT\nTags: node.js, jwt, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am currently implementing JWT authentication with Passport.js into a NestJS application. \n\nIn some of my GraphQL resolvers I need to access the currently authenticated user. I know that passport will attach the authenticated user to the request object (at least I hope that this is correct), but I do not know how to access the request object inside a resolver. \n\nI followed the issue https://github.com/nestjs/nest/issues/1326 and the mentioned link https://github.com/ForetagInc/fullstack-boilerplate/tree/master/apps/api/src/app/auth inside the issue. I saw some code that uses `@Res() res: Request` as a method parameter in the GraphQL resolver methods, but I always get `undefined` for `res`. \n\nThese are the current implementations I have:\n\n**GQLAuth**\n\n```\nimport { Injectable, ExecutionContext } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\nimport { AuthenticationError } from 'apollo-server-core';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n console.log(req);\n\n return super.canActivate(new ExecutionContextHost([req]));\n }\n\n handleRequest(err: any, user: any) {\n if (err || !user) {\n throw err || new AuthenticationError('GqlAuthGuard');\n }\n return user;\n }\n}\n```\n\n**Resolver that needs to access the current user**\n\n```\nimport { UseGuards, Req } from '@nestjs/common';\nimport { Resolver, Query, Args, Mutation, Context } from '@nestjs/graphql';\nimport { Request } from 'express';\n\nimport { UserService } from './user.service';\nimport { User } from './models/user.entity';\nimport { GqlAuthGuard } from '../auth/guards/gql-auth.guard';\n\n@Resolver(of => User)\nexport class UserResolver {\n constructor(private userService: UserService) {}\n\n @Query(returns => User)\n @UseGuards(GqlAuthGuard)\n whoami(@Req() req: Request) {\n console.log(req);\n return this.userService.findByUsername('aw');\n }\n}\n```\n\n**JWT Strategy**\n\n```\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.SECRET,\n });\n }\n\n async validate(payload: JwtPayload) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\nAuthorization and creating JWT tokens works fine. GraphQL guard also works fine for methods that do not need to access the user. But for methods that need access to the currently authenticated user, I see no way of getting it. \n\nIs there a way to accomplish something like this ?\n\n========================================\n\nTop Answer:\nIn order to use an AuthGuard with GraphQL, extend the built-in AuthGuard class and override the `getRequest()` method.\nCreate a file called `gql.guard.ts` (Naming your wish)\n\n```\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n}\n```\n\nTo get the current authenticated user in your graphql resolver, you can define a `@CurrentUser()` decorator (create a file called `user.decorator.graphql.ts`)\n\n```\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n (data: unknown, context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req.user;\n },\n);\n```\n\nTo use above decorator in your resolver, be sure to include it as a parameter of your query or mutation\n\n```\n@Query(returns => User)\n@UseGuards(GqlAuthGuard)\nwhoAmI(@CurrentUser() user: User) {\n return this.usersService.findById(user.id);\n}\n```\n\nRead More : https://docs.nestjs.com/security/authentication#graphql\n\n========================================\n\nCode:\n```text\nimport { Injectable, ExecutionContext } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\nimport { AuthenticationError } from 'apollo-server-core';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n  canActivate(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    const { req } = ctx.getContext();\n    console.log(req);\n\n    return super.canActivate(new ExecutionContextHost([req]));\n  }\n\n  handleRequest(err: any, user: any) {\n    if (err || !user) {\n      throw err || new AuthenticationError('GqlAuthGuard');\n    }\n    return user;\n  }\n}\n```\n\n```text\nimport { UseGuards, Req } from '@nestjs/common';\nimport { Resolver, Query, Args, Mutation, Context } from '@nestjs/graphql';\nimport { Request } from 'express';\n\nimport { UserService } from './user.service';\nimport { User } from './models/user.entity';\nimport { GqlAuthGuard } from '../auth/guards/gql-auth.guard';\n\n@Resolver(of => User)\nexport class UserResolver {\n  constructor(private userService: UserService) {}\n\n  @Query(returns => User)\n  @UseGuards(GqlAuthGuard)\n  whoami(@Req() req: Request) {\n    console.log(req);\n    return this.userService.findByUsername('aw');\n  }\n}\n```\n\n```text\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: process.env.SECRET,\n    });\n  }\n\n  async validate(payload: JwtPayload) {\n    const user = await this.authService.validateUser(payload);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\n```text\n@Res() res: Request\n```\n\n```text\nundefined\n```\n\n```text\nres\n```\n\n```text\n// user.decorator.ts\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n  (data, req) => req.user,\n);\n```\n\n```text\nimport { User as CurrentUser } from './user.decorator';\n\n @Query(returns => User)\n  @UseGuards(GqlAuthGuard)\n  whoami(@CurrentUser() user: User) {\n    console.log(user);\n    return this.userService.findByUsername(user.username);\n  }\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\n\nexport const GetUser = createParamDecorator((data, context: ExecutionContext)  => {\n const ctx = GqlExecutionContext.create(context).getContext();\nreturn ctx.user\n});\n```\n\n```text\nget-user.decorator.ts\n```\n\n```text\n// get-user.decorator.ts\n\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nimport { User } from '../../user/entity/user.entity';\n\nexport const GetAuthenticatedUser = createParamDecorator((data, ctx: ExecutionContext): User => {\n  const req = ctx.switchToHttp().getRequest();\n  return req.user;\n});\n```\n\n```text\n// auth.controller.ts\n\nimport { GetAuthenticatedUser } from './decarator/get-user.decorator';\n\n...\n\n@Controller('api/v1/auth')\nexport class AuthController {\n  constructor(private authService: AuthService) {\n    //\n  }\n\n  ...\n\n  /**\n   * Get the currently authenticated user.\n   *\n   * @param user\n   */\n   @Post('/user')\n   @UseGuards(AuthGuard())\n   async getAuthenticatedUser(@GetAuthenticatedUser() user: User) {\n     console.log('user', user);\n   }\n```\n\n```text\n// console.log output:\n\nuser User {\n  id: 1,\n  email: 'email@test.com',\n  ...\n}\n```\n\n```text\nauth.controller\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n  (data, context: ExecutionContext) => {\n    const ctx = GqlExecutionContext.create(context).getContext();\n    return ctx.req.user;\n  },\n);\n```\n\n```text\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n  getRequest(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    return ctx.getContext().req;\n  }\n}\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n  (data: unknown, context: ExecutionContext) => {\n    const ctx = GqlExecutionContext.create(context);\n    return ctx.getContext().req.user;\n  },\n);\n```\n\n```text\n@Query(returns => User)\n@UseGuards(GqlAuthGuard)\nwhoAmI(@CurrentUser() user: User) {\n  return this.usersService.findById(user.id);\n}\n```\n\n```text\ngetRequest()\n```\n\n```text\ngql.guard.ts\n```\n\n```text\n@CurrentUser()\n```\n\n```text\nuser.decorator.graphql.ts\n```\n\n```text\nexport const CurrentUser = createParamDecorator(\n  (data, context: ExecutionContextHost) => {\n    return GqlExecutionContext.create(context).getContext().req.user;\n  },\n);\n```\n\n========================================\n\nComments:\n- Instead of implement your own `canActivate` method in your `GqlAuthGuard` you should create a `getRequest` method and return `GqlExecutionContext.create(context).getContext().req;`. This is a better approach in my opinion.\n- Would you a link to your GitHub repo? I'm new to Nest.js, I'm also using GraphQL and I'm stuck with the authentication implementation. Thanks!\n- This really needs to be part of the framework and in the default docs, something like this missing makes me think if people are actually using it, lol\n- Thank you! Also, as this is a working answer you should accept it even if it's your own. Thanks again, I searched for a solution for at least an hour before finding this and it worked perfectly.\n- In v7 of Nest createParamDecorator has change. Retrieving the user is done through the GraphQL context. See here: docs.nestjs.com/graphql/other-features#custom-decorators\n- Note that this will only work for REST services. When using GraphQL you will need to make use of the context associated with GraphQL `GqlExecutionContext.create(context).getContext()` and not `ctx.switchToHttp().getRequest()`\n- This worked for me on August, 2022","metadata":{"transformedAt":"2026-08-18T18:33:02.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":393,"estimatedTokens":2742}}62{"id":"stack-51994541","source":"stackoverflow","questionId":51994541,"title":"NestJS + TypeORM: Use two or more databases?","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: NestJS + TypeORM: Use two or more databases?\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying since 2 days to solve this, perhaps I'm simply missing the point here.\n\nMy goal was to write a NestJS app (with TypeORM included) which serves a RestAPI for 2 or 3 of my little projects, instead of writing a NestJS-App for every single one of them.\n\nSo far so good, the app is ready, works well with the single projects (which resides in subfolders with their entities, controllers, services, modules), but I can't get it to run with all of them.\n\nThe point seems to be the configuration, I'm using `ormconfig.json`:\n\n```\n[ {\n \"name\": \"Project1\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"\",\n \"password\": \"\",\n \"database\": \"\",\n \"synchronize\": false,\n \"entities\": [\"project1/*.entity.ts\"],\n \"subscribers\": [\"project1/*.subscriber.ts\"],\n \"migrations\": [\"project1/migrations/*.ts\"],\n \"cli\": { \"migrationsDir\": \"project1/migrations\" }\n}, {\n \"name\": \"project2\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"\",\n \"password\": \"\",\n \"database\": \"\",\n \"synchronize\": false,\n \"entities\": [\"project2/*.entity.ts\"],\n \"subscribers\": [\"project2/*.subscriber.ts\"],\n \"migrations\": [\"project2/migrations/*.ts\"],\n \"cli\": { \"migrationsDir\": \"project2/migrations\"\n } ]\n```\n\nThe error message says:\n\n [ExceptionHandler] Cannot find connection default because its not defined in any orm configuration files\n\nOf course \"default\" couldn't be found, because I'm providing two configs with unique names different to \"default\".\n\nIn **ApplicationModule** I could provide the name of the connection, like this:\n\n```\nTypeOrmModule.forRoot( { name: \"project1\" } ),\n```\n\nbut then it would work only for one project.\n\nI could mix all in one config, but then I would have everything in one database, same user for all and perhaps mix up the entities...\n\nCan someone give me a hint how to solve this?\nPerhaps with `getConnection()` in every module, but how to start the ApplicationModule then?\n\nKind regards,\n\nsagerobert\n\n========================================\n\nTop Answer:\nYou need to explicitly pass the connection name at the same level inside **TypeOrmModule.forRoot({ name: 'db1Connection' })** incase you are using multiple database connections.\n\n```\nTypeOrmModule.forRootAsync({\n name: DB1_CONNECTION,\n imports: [ConfigModule],\n useClass: TypeormDb1ConfigService,\n}),\n\nTypeOrmModule.forRootAsync({\n name: DB2_CONNECTION,\n imports: [ConfigModule],\n useClass: TypeormDb2ConfigService,\n})\n```\n\n========================================\n\nCode:\n```text\n[ {\n    \"name\": \"Project1\",\n    \"type\": \"mysql\",\n    \"host\": \"localhost\",\n    \"port\": 3306,\n    \"username\": \"<username>\",\n    \"password\": \"<pwd>\",\n    \"database\": \"<database>\",\n    \"synchronize\": false,\n    \"entities\": [\"project1/*.entity.ts\"],\n    \"subscribers\": [\"project1/*.subscriber.ts\"],\n    \"migrations\": [\"project1/migrations/*.ts\"],\n    \"cli\": { \"migrationsDir\": \"project1/migrations\" }\n}, {\n    \"name\": \"project2\",\n    \"type\": \"mysql\",\n    \"host\": \"localhost\",\n    \"port\": 3306,\n    \"username\": \"<another-username>\",\n    \"password\": \"<another-pwd>\",\n    \"database\": \"<another-database>\",\n    \"synchronize\": false,\n    \"entities\": [\"project2/*.entity.ts\"],\n    \"subscribers\": [\"project2/*.subscriber.ts\"],\n    \"migrations\": [\"project2/migrations/*.ts\"],\n    \"cli\": { \"migrationsDir\": \"project2/migrations\"\n    } ]\n```\n\n```text\nTypeOrmModule.forRoot( { name: \"project1\" } ),\n```\n\n```text\normconfig.json\n```\n\n```text\ngetConnection(<name>)\n```\n\n```text\nimports: [\n  ...,\n  TypeOrmModule.forRoot({\n    name: 'Project1',\n    type: 'mysql',\n    host: 'localhost',\n    port: 3306,\n    username: '<username>',\n    password: '<pwd>',\n    database: '<database>',\n    synchronize: false,\n    entities: ['project1/*.entity.ts'],\n    subscribers: ['project1/*.subscriber.ts'],\n    migrations: ['project1/migrations/*.ts'],\n    cli: { migrationsDir: 'project1/migrations' },\n  }),\n  TypeOrmModule.forRoot({\n    name: 'project2',\n    type: 'mysql',\n    host: 'localhost',\n    port: 3306,\n    username: '<another-username>',\n    password: '<another-pwd>',\n    database: '<another-database>',\n    synchronize: false,\n    entities: ['project2/*.entity.ts'],\n    subscribers: ['project2/*.subscriber.ts'],\n    migrations: ['project2/migrations/*.ts'],\n    cli: { migrationsDir: 'project2/migrations' },\n  })\n]\n```\n\n```text\normconfig.json\n```\n\n```text\ndefault\n```\n\n```text\napp.module.ts\n```\n\n```text\normconfig.json\n```\n\n```text\nTypeOrmModule.forRootAsync({\n  name: DB1_CONNECTION,\n  imports: [ConfigModule],\n  useClass: TypeormDb1ConfigService,\n}),\n\nTypeOrmModule.forRootAsync({\n  name: DB2_CONNECTION,\n  imports: [ConfigModule],\n  useClass: TypeormDb2ConfigService,\n})\n```\n\n```js\n@Module({\n    imports: [TypeOrmModule.forFeature([Entity1, Entity2]), //This will use default connection\n    TypeOrmModule.forRoot({name: 'con1'}), // This will register globaly con1\n    TypeOrmModule.forRoot({name: 'con2'}), // This will register globaly con2\n    controllers: [...],\n    providers: [...],\n    exports: [...]\n})\n```\n\n```text\n\"name\":\"default\"\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.json\n```\n\n```js\nimport parseBoolean from '@eturino/ts-parse-boolean';\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport * as dotenv from 'dotenv';\nimport { join } from 'path';\n\ndotenv.config();\n\nexport = [\n  {\n    //name: 'default',\n    type: 'mssql',\n    host: process.env.DEFAULT_DB_HOST,\n    username: process.env.DEFAULT_DB_USERNAME,\n    password: process.env.DEFAULT_DB_PASSWORD,\n    database: process.env.DEFAULT_DB_NAME,\n    options: {\n      instanceName: process.env.DEFAULT_DB_INSTANCE,\n      enableArithAbort: false,\n    },\n    logging: parseBoolean(process.env.DEFAULT_DB_LOGGING),\n    dropSchema: false,\n    synchronize: false,\n    migrationsRun: parseBoolean(process.env.DEFAULT_DB_RUN_MIGRATIONS),\n    migrations: [join(__dirname, '..', 'model/migration/*.{ts,js}')],\n    cli: {\n      migrationsDir: 'src/model/migration',\n    },\n    entities: [\n      join(__dirname, '..', 'model/entity/default/**/*.entity.{ts,js}'),\n    ],\n  } as TypeOrmModuleOptions,\n  {\n    name: 'other',\n    type: 'mssql',\n    host: process.env.OTHER_DB_HOST,\n    username: process.env.OTHER_DB_USERNAME,\n    password: process.env.OTHER_DB_PASSWORD,\n    database: process.env.OTHER_DB_NAME,\n    options: {\n      instanceName: process.env.OTHER_DB_INSTANCE,\n      enableArithAbort: false,\n    },\n    logging: parseBoolean(process.env.OTHER_DB_LOGGING),\n    dropSchema: false,\n    synchronize: false,\n    migrationsRun: false,\n    entities: [],\n  } as TypeOrmModuleOptions,\n];\n```\n\n```js\nimport configuration from '@config/configuration';\nimport validationSchema from '@config/validation';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { LoggerService } from '@shared/logger/logger.service';\nimport { UsersModule } from '@user/user.module';\nimport { AppController } from './app.controller';\nimport ormconfig = require('./config/ormconfig'); //path mapping doesn't work here\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      cache: true,\n      isGlobal: true,\n      validationSchema: validationSchema,\n      load: [configuration],\n    }),\n    TypeOrmModule.forRoot(ormconfig[0]), //default\n    TypeOrmModule.forRoot(ormconfig[1]), //other db\n    LoggerService,\n    UsersModule,\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```json\n\"scripts\": {\n    ...\n    \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./src/config/ormconfig.ts\",\n    \"typeorm:migration:generate\": \"npm run typeorm -- migration:generate -n\",\n    \"typeorm:migration:run\": \"npm run typeorm -- migration:run\"\n  },\n```\n\n```text\nsrc/\nโ”œโ”€โ”€ app.controller.ts\nโ”œโ”€โ”€ app.module.ts\nโ”œโ”€โ”€ config\nโ”‚   โ”œโ”€โ”€ configuration.ts\nโ”‚   โ”œโ”€โ”€ ormconfig.ts\nโ”‚   โ””โ”€โ”€ validation.ts\nโ”œโ”€โ”€ main.ts\nโ”œโ”€โ”€ model\nโ”‚   โ”œโ”€โ”€ entity\nโ”‚   โ”œโ”€โ”€ migration\nโ”‚   โ””โ”€โ”€ repository\nโ”œโ”€โ”€ route\nโ”‚   โ””โ”€โ”€ user\nโ””โ”€โ”€ shared\n    โ””โ”€โ”€ logger\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n      load: [\n        database,\n        databaseAllo #<= my second database\n      ]\n    }),\n    TypeOrmModule.forRootAsync({\n      useFactory: (configs: ConfigService) => configs.get(\"db_config\"),\n      inject: [ConfigService],\n    }),\n    TypeOrmModule.forRootAsync({\n      name:\"db_allo\", #<= create connection to my second db\n      useFactory: (configs: ConfigService) => configs.get(\"db_config_allo\"),\n      inject: [ConfigService],\n    }),\n    AuthModule,\n    JwtAuthModule\n  ],\n  controllers: []\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([AlloMpcTable], \"db_allo\" #<= call connection again),\n  ],\n  providers: [\n    AlloRepository\n  ],\n  exports: [AlloRepository],\n  controllers: [],\n})\nexport class AlloModule {}\n```\n\n```text\n@Injectable()\nexport class AlloRepository extends BaseRepository<AlloMpcTable> {\n  constructor(\n    @InjectRepository(AlloMpcTable, \"db_allo\") #<= you need to call connection again\n    private readonly allo: Repository<AlloMpcTable>,\n  ) {\n    super(allo)\n  }\n\n  public async Find(id: number): Promise<AlloMpcTable> {\n    return await this.allo.findOne(id)\n  }\n\n}\n```\n\n```text\nexport const DB_CONNECTION_1 = 'conn1';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRootAsync({\n      name: DB_CONNECTION_1,\n      ...\n    })\n  ],\n  ...\n)\nexport class AppModule {}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forFeature(\n      [MyRepo],\n      DB_CONNECTION_1,\n    ),\n  ],\n  providers: [MyRepo],\n})\n```\n\n```text\n@Injectable()\nexport class MyRepo {\n  constructor(\n    @InjectRepository(MyOrmEntity, DB_CONNECTION_1)\n    private readonly repo: Repository<MyOrmEntity>,\n  ) {}\n}\n```\n\n```text\napp.module.ts\n```\n\n```text\nconstants.ts\n```\n\n```text\nNo repository found for\n```\n\n```text\nwas found. Looks like this entity is not registered in current \"default\" connection.\n```\n\n```text\nexport const DB_CONNECTION_1 = 'conn1';\n```\n\n```text\napp.module.ts\n```\n\n```text\nconstants.ts\n```\n\n========================================\n\nComments:\n- Thanks a lot, that seems to solve this issue! Just one another question: before this block, in the `...,` section, do you import the Modules for each 'project' (like `Project1Module, Project2Module`) or additionally something else?\n- Sorry, missed your comment. No, I couldn't think of any special import.\n- Out of interest ... How did you run the migrations?\n- By defining as you said, I didn't get any error. But the program always run by default database. Have any idea what else should be checked?\n- @SorayaAnvari When you use the `forFeature` import, are you also passing the `name` of the connection: `TypeOrmModule.forFeature([Album], 'albumsConnection')`?\n- I wrote TypeOrmModule.forRoot with both databases in app.module. Then added TypeOrmModule.forFeature(Entities, 'connectionname') in each.separated module. My program has the same host with different databases. I created a module to handle each database request. I don't know what is missing.\n- @SorayaAnvari, Have you been able to solve the issue. I have also similar situation. Thank you!\n- You just saved my day sir. `TypeOrmModule.forRootAsync` has the worst API interface I have ever witnessed.\n- @PubuduDodangoda I think that the problem is not the api, is that the docs has only one small phrase mentioning this that only clicked when I read Frozenex reply. It makes sense how they do it, but it should be clearer in the docs","metadata":{"transformedAt":"2026-08-18T18:33:02.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":461,"estimatedTokens":2899}}63{"id":"stack-72549668","source":"stackoverflow","questionId":72549668,"title":"How to do custom repository using TypeORM (MongoDB) in NestJS?","tags":["typescript","mongodb","nestjs","typeorm"],"text":"Title: How to do custom repository using TypeORM (MongoDB) in NestJS?\nTags: typescript, mongodb, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a question. With `@EntityRepository` decorator being marked as deprecated in `typeorm@^0.3.6`, what is now the recommended or TypeScript-friendly way to create a custom repository for an entity in NestJS? A custom repository before would look like this:\n\n```\n// users.repository.ts\nimport { EntityRepository, Repository } from 'typeorm';\nimport { User } from './user.entity';\n\n@EntityRepository(User)\nexport class UsersRepository extends Repository {\n async createUser(firstName: string, lastName: string): Promise {\n const user = this.create({\n firstName,\n lastName,\n });\n\n await this.save(user);\n\n return user;\n }\n}\n```\n\nAnd since NestJS is by default configured with TypeScript support, I will be able to call `usersRepository.createUser()` without an issue in a service like this:\n\n```\n// users.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(UsersRepository)\n private readonly usersRepository: UsersRepository,\n ) {}\n\n async createUser(firstName: string, lastName: string): Promise {\n return this.usersRepository.createUser(firstName, lastName);\n }\n}\n```\n\nThis is how the modules would import the custom repository:\n\n```\n// users.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([UsersRepository])],\n controllers: [UsersController],\n providers: [UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\nAlso the reason why I mentioned MongoDB here is because I tried using `typeorm@0.2` where `@EntityRepository` is still supported but I receive an error when I tried to import it in the module stating `Repository not found` or something. Do note, if I chose `postgresql` as my database in TypeORM with the same changes above, I don't have this issue. Hence I went to check the latest only to find out it is already deprecated, I also didn't find any example in NestJS documentation.\n\n========================================\n\nTop Answer:\nThe way you can create a custom repository for mongo in `TypeORM` it with the following way:\n\n**users.repository.ts**\n\nHere instead of using `@EntityRepository` you will use the `@Injectable` decorator, and for inject, the `schema` will use MongoRepository\n\n```\n// users.repository.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { User } from './user.entity';\n@Injectable()\nexport class UsersRepository {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: MongoRepository,\n ) {}\n\n async createUser(firstName: string, lastName: string): Promise {\n const user = new User({\n firstName,\n lastName,\n });\n\n await this.usersRepository.save(user);\n\n return user;\n }\n \n\n //write other helpful methods here(find, delete, etc...)\n\n}\n```\n\n**users.service.ts**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(private readonly usersRepository: UsersRepository) {}\n\n async createUser(firstName: string, lastName: string): Promise {\n return this.usersRepository.createUser(firstName, lastName);\n }\n}\n```\n\n**users.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\nimport { User } from './user.entity';\nimport { UsersRepository } from './database/repository/UsersRepository';\n@Module({\n imports: [TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [UsersRepository, UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n========================================\n\nCode:\n```text\n// users.repository.ts\nimport { EntityRepository, Repository } from 'typeorm';\nimport { User } from './user.entity';\n\n@EntityRepository(User)\nexport class UsersRepository extends Repository<User> {\n  async createUser(firstName: string, lastName: string): Promise<User> {\n    const user = this.create({\n      firstName,\n      lastName,\n    });\n\n    await this.save(user);\n\n    return user;\n  }\n}\n```\n\n```text\n// users.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(UsersRepository)\n    private readonly usersRepository: UsersRepository,\n  ) {}\n\n  async createUser(firstName: string, lastName: string): Promise<User> {\n    return this.usersRepository.createUser(firstName, lastName);\n  }\n}\n```\n\n```text\n// users.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([UsersRepository])],\n  controllers: [UsersController],\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\n@EntityRepository\n```\n\n```text\ntypeorm@^0.3.6\n```\n\n```text\nusersRepository.createUser()\n```\n\n```text\ntypeorm@0.2\n```\n\n```text\n@EntityRepository\n```\n\n```text\nRepository not found\n```\n\n```text\npostgresql\n```\n\n```text\nimport {DataSource, Repository} from 'typeorm';\nimport {Injectable} from '@nestjs/common';\nimport {Team} from '@Domain/Team/Models/team.entity';\n\n@Injectable()\nexport class TeamRepository extends Repository<Team>\n{\n    constructor(private dataSource: DataSource)\n    {\n        super(Team, dataSource.createEntityManager());\n    }\n\n    /**\n     * Add a basic where clause to the query and return the first result.\n     */\n    async firstWhere(column: string, value: string | number, operator = '='): Promise<Team | undefined>\n    {\n        return await this.createQueryBuilder()\n                         .where(`Team.${column} ${operator} :value`, {value: value})\n                         .getOne();\n    }\n}\n```\n\n```text\nimport {Injectable} from '@nestjs/common';\nimport {Team} from '@Domain/Team/Models/team.entity';\nimport {TeamRepository} from '@Domain/Team/Repositories/team.repository';\n\n@Injectable()\nexport class TeamService\n{\n    constructor(\n        private teamRepository: TeamRepository,\n    )\n    {\n    }\n\n    async create(): Promise<Team>\n    {\n        const team: Team = await this.teamRepository.firstWhere('id', 1);\n\n        return this.teamRepository.save(team);\n    }\n}\n```\n\n```text\nimport {Module} from '@nestjs/common';\nimport {TeamService} from '@Domain/Team/Services/team.service';\nimport {TypeOrmModule} from '@nestjs/typeorm';\nimport {Team} from '@Domain/Team/Models/team.entity';\nimport {TeamRepository} from '@Domain/Team/Repositories/team.repository';\n\n@Module({\n            imports:   [TypeOrmModule.forFeature([Team])],\n            exports:   [TeamService],\n            providers: [TeamService, TeamRepository],\n        })\nexport class TeamModule\n{\n}\n```\n\n```text\n// users.repository.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { User } from './user.entity';\n@Injectable()\nexport class UsersRepository {\n  constructor(\n    @InjectRepository(User)\n    private readonly usersRepository: MongoRepository<User>,\n  ) {}\n\n  async createUser(firstName: string, lastName: string): Promise<User> {\n    const user = new User({\n      firstName,\n      lastName,\n    });\n\n    await this.usersRepository.save(user);\n\n    return user;\n  }\n  \n\n   //write other helpful methods here(find, delete, etc...)\n\n\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n  constructor(private readonly usersRepository: UsersRepository) {}\n\n  async createUser(firstName: string, lastName: string): Promise<User> {\n    return this.usersRepository.createUser(firstName, lastName);\n  }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\nimport { User } from './user.entity';\nimport { UsersRepository } from './database/repository/UsersRepository';\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  controllers: [UsersController],\n  providers: [UsersRepository, UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\nTypeORM\n```\n\n```text\n@EntityRepository\n```\n\n```text\n@Injectable\n```\n\n```text\nschema\n```\n\n```text\n// task.entity.ts\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Task {\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column()\n  title: string;\n\n  @Column()\n  description: string;\n}\n```\n\n```text\n// tasks.repository.ts\nimport { Injectable } from '@nestjs/common';\nimport { DataSource, Repository } from 'typeorm';\nimport { Task } from './tast.entity';\n\n@Injectable()\nexport class TasksRepository extends Repository<Task> {\n  constructor(dataSource: DataSource) {\n    super(Task, dataSource.createEntityManager());\n  }\n}\n```\n\n```text\n//tasks.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { TasksController } from './tasks.controller';\nimport { TasksService } from './tasks.service';\nimport { Task } from './tast.entity';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Task])], // NOTICE: HERE\n  controllers: [TasksController], // NOTICE: HERE\n  providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\n@Injectable()\nexport class TasksService {\n  constructor(\n    @InjectRepository(Task) // NOTICE: here\n    private readonly tasksRepository: TasksRepository,\n  ) {}\n\n  async getTaskById(id: string): Promise<Task> {\n    const task = this.tasksRepository.findOne({\n      where: {\n        id,\n      },\n    });\n\n    if (!task) {\n      throw new NotFoundException(`Task with id ${id} not found`);\n    }\n\n    return task;\n  }\n}\n```\n\n```text\n// users.repository.ts\nimport { Repository } from 'typeorm';\nimport { EntityRepository } from 'nestjs-typeorm-custom-repository';\n\nimport { User } from './user.entity';\n\n@EntityRepository(User)\nexport class UsersRepository extends Repository<User> {}\n```\n\n```text\n// users.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    private readonly usersRepository: UsersRepository,\n  ) {}\n  ...\n  }\n}\n```\n\n```text\n// users.module.ts\nimport { Module } from '@nestjs/common';\nimport { CustomRepositoryModule } from 'nestjs-typeorm-custom-repository';\n\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\n\n@Module({\n  imports: [CustomRepositoryModule.forFeature([UsersRepository])],\n  controllers: [UsersController],\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\nexport const UserRepository = dataSource.getRepository(User).extend({\n    findByName(firstName: string, lastName: string) {\n        return this.createQueryBuilder(\"user\")\n            .where(\"user.firstName = :firstName\", { firstName })\n            .andWhere(\"user.lastName = :lastName\", { lastName })\n            .getMany()\n    },\n})\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { PlaygroundEntity } from 'src/entities/playground.entity';\nimport { Repository } from 'typeorm';\n\n@Injectable()\nexport class PlaygroundRepository {\n  constructor(\n    @InjectRepository(PlaygroundEntity)\n    private readonly _repository: Repository<PlaygroundEntity>,\n  ) {}\n\n  public get _() {\n    return this._repository;\n  }\n\n  async findWithCriteria() {\n    return this._.find({ where: { datecolumn: new Date() } });\n  }\n}\n```\n\n```js\nimport { Inject, Injectable } from '@nestjs/common';\nimport { PlaygroundRepository } from './repositories/pg.repository';\n\n@Injectable()\nexport class AppService {\n  constructor(\n    @Inject(PlaygroundRepository)\n    private pgRepository: PlaygroundRepository,\n  ) {}\n\n  async start() {\n    const customMethod = await this.pgRepository.findWithCriteria();\n\n    const defaultMethod = await this.pgRepository._.find();\n  }\n}\n```\n\n========================================\n\nComments:\n- Hey, thanks for this. I think it's almost there to what I was looking for! But there's one issue with this, it seems like it will only expose one function from `UsersRepository` which is the `createUser()` I created. But I can't use common functions of a repository like `.find()`, `.updateOne()`, etc with the custom `UsersRepository` in the `UsersService`, how to make it such that it would be an extension of a repository?\n- @unspeakable29 the best way to do that it creating an abstract class base repository, in this base repository implement all that you need(find(), findById(), findOne(), etc..), and in UsersRepository just extend the BaseRepository.\n- I see. I guess that's the best way huh. It used to be easier with `EntityRepository` but oh well. Thanks for the help! ๐Ÿ™๐Ÿป\n- Thanks Nick, this is what I was looking for! It works on MongoDB too.\n- Thank you @Nick This was so helpful! It does work with mongo too, obviously just swapping out the extension in the repository to extend from MongoRepository instead of a regular one. I was struggling with this for like a week thank you for posting!\n- Thank you Nick, got this working. Seems much simpler than an alternative approach outlined here - gist.github.com/anchan828/9e569f076e7bc18daf21c652f7c3d012\n- Great job on figuring this out. Really appreciate it :).\n- How can we write unit test for the repository with this? I need to provide dependency for data source\n- @IshikaJain did you managed to find a proper solution? I saw this solution for unit tests (docs.nestjs.com/techniques/database#testing), but I'm struggling with e2e tests.\n- I 'm also really struggling to find a way to test team.repository.ts with jest as others have. I keep getting error like: Nest can't resolve dependencies of the XYZRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context. If anyone has managed to do it, please .\n- I meant, I'm trying to test a service that uses the team.repository.ts\n- Inside tests using jest, dataSource will be undefined\n- Hi, was there any solution for testing with this method ?\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.405Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":567,"estimatedTokens":4030}}64{"id":"stack-70230659","source":"stackoverflow","questionId":70230659,"title":"Run NestJS worker in a separate process","tags":["nestjs","worker"],"text":"Title: Run NestJS worker in a separate process\nTags: nestjs, worker\nSource: Stack Overflow\n\nQuestion:\nI am implementing NestJS worker, queues, using Bull.\n\nAccording to the documentation, both the worker and the server (will) run in a same \"process\", but I want to run the worker in a separate process, so as to **not** block the main event loop.\n\nI think it's called \"running a task in a separate binary\" or something else.\n\nAnyway, I tried googling it, went through the documentation of NestJS, but couldn't find something similar.\n\n++\nIn other words:\n\nI have a main project (my current), and I want to create the worker in a separate process (standalone application) and want to connect both my current main project and worker. And I can't really find it in the documentation.\n\nIn which module should I instantiate my Bull's instance? I am assuming I'll keep my `producer` in my main module and `consumer` in my worker module.\n\nHow can I do so?\n\nPlease note, by \"separate process\", I do not mean running a specific task in a separate process, as defined in Bull's documentation.\nI want to deploy the whole worker module in a separate process or whatever the term should be used.\n\n++\n[Extra, if possible]\n\nBefore running my server and worker, I also want to check whether my worker (bull instance) is successfully connected to my Redis server. I couldn't find anything on the Bull's documentation... do you think there is a good workaround for that?\n\n========================================\n\nTop Answer:\nYou *can* use that documentation to implement the entire worker. If you **use Nest.js in standalone mode** you can just have Processor(s) and Process(es).\n\nThis is documented here. โ€œSeparate binaryโ€ isnโ€™t a question either. A binary is the product of compilation, Node.js isnโ€™t compiled so youโ€™ll need a separate **application**.\n\nYou donโ€™t need a workaround for anything, this is literally the nature of Bull and optionally Nest.js.\n\nSometimes youโ€™ll need to adapt examples in docs to fit your needs, this can take some time to learn.\n\n### Terminology\n\nI think there's some confusion with terminology so in this post assume that:\n\n- A `process` is what your `application` runs inside (if you look in your OS process manager it should be `node`).\n\n- A `application` is **one** Node.js project that runs in a separate `process`.\n\n- A `worker` is an `application` that is **only focused with processing Queue jobs**.\n\n- `Queue` and `Job` is terminology of Bull.\n\n- `Processor` and `Process` is terminology of Nest.js `@nestjs/bull`\n\n### Solution\n\nHere is how you create an **application** with a **worker** running in separate processes. After following these instructions, you should see two processes running your process manager.\n\nCreate a new Nest.js application that we'll use for your `worker`:\n\n```\nnest new my-worker\n```\n\nOpen `src/main.ts` and replace everything in `bootstrap` function with:\n\n```\nconst app = await NestFactory.createApplicationContext(AppModule);\n```\n\nInstall `Bull` and the Nest.js implementation with:\n\n```\nyarn add @nestjs/bull bull\n```\n\nOpen `src/app.module.ts` and remove `AppController` from `controllers`, and add `BullModule.registerQueue` to imports (from `@nestjs/bull`.\n\nYour `src/app.module.ts` should now look like:\n\n```\n// app.module.ts\n// ... imports\n@Module({\n imports: [\n BullModule.registerQueue({\n name: 'my-queue',\n redis: {\n host: 'localhost',\n port: 6379,\n },\n }),\n ],\n})\nexport class AppModule {}\n```\n\nCreate a new file: `app.processor.ts` in `src` directory:\n\n```\n// app.processor.ts\n// ... imports\n@Processor('my-queue')\nexport class AppConsumer {\n @Process('namedjob')\n async processNamedJob(job: Job): Promise {\n // do something with job and job.data\n }\n}\n```\n\nAnd you're done for the `worker` side of things. Now all you need to do is in your `application` (main project), update your `AppModule` to include `BullModule.registerQueue` (like above) and inject it:\n\n```\nexport class MyService {\n constructor(@InjectQueue('my-queue') private queue: Queue) {}\n}\n```\n\nAnd then use `this.queue.add('namedJob', data);`\n\nTry above and if you get stuck, create a repository on Github and I'll get you on the right track.\n\n### Reference\n\n- https://github.com/OptimalBits/bull#separate-processes\n\n- https://docs.nestjs.com/standalone-applications\n\n========================================\n\nCode:\n```text\nproducer\n```\n\n```text\nconsumer\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';\nimport { WorkerModule } from './worker/worker.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(WorkerModule);\n  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));\n  process.env.WORKER_HTTP_PORT = process.env.WORKER_HTTP_PORT ?? '4001';\n  await app.listen(process.env.WORKER_HTTP_PORT);\n  console.debug(`Worker is running on ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"entryFile\": \"main\",\n  \"compilerOptions\": {\n    \"assets\": [\"**/*.graphql\"],\n    \"watchAssets\": true\n  }\n}\n```\n\n```text\n{\n    \"collection\": \"@nestjs/schematics\",\n    \"sourceRoot\": \"src\",\n    \"entryFile\": \"worker\",\n    \"compilerOptions\": {\n        \"watchAssets\": true\n    }\n}\n```\n\n```text\n\"start:dev\": \"yarn nest start --watch -e 'node -r dotenv/config -r source-map-support/register'\"\n```\n\n```text\n\"start:prod\": \"node -r dotenv/config -r ./tsconfig-paths-bootstrap.js dist/src/main.js\"\n```\n\n```text\n\"worker:start:dev\": \"yarn nest start --config nest-cli-worker.json --watch -e 'node -r dotenv/config -r source-map-support/register'\"\n```\n\n```text\n\"worker:start:prod\": \"node -r dotenv/config -r ./tsconfig-paths-bootstrap.js dist/src/worker.js\"\n```\n\n```text\nversion: '3.8'\n\nservices:\n  main:\n    container_name: my-server\n    image: xxx.amazonaws.com/xx/xxx:${CONTAINER_IMAGE_TAG:-latest}\n    ports:\n      - 80:80\n    command: node -r dotenv/config -r ./tsconfig-paths-bootstrap.js dist/src/main.js #My `prod` command for main server\n    volumes:\n      - xxx\n    links:\n      - xxx\n    environment:\n      xxx\n    # .env is generated by Elastic Beanstalk, don't provide one\n    env_file:\n      - .env\n  worker:\n    container_name: worker-server #YOUR WORER\n    image: xxx.us-west-2.amazonaws.com/xxx:${CONTAINER_IMAGE_TAG:-latest}\n    ports:\n      - 90:90\n    links:\n      - xxx\n    command: node -r dotenv/config -r ./tsconfig-paths-bootstrap.js dist/src/worker.js  #prod command for Worker\n    volumes:\n      - xxx\n    environment:\n      xxx\n    # .env is generated by Elastic Beanstalk, don't provide one\n    env_file:\n      - .env\n```\n\n```text\nindex.ts\n```\n\n```text\nmain.ts\n```\n\n```text\nworker.ts\n```\n\n```text\nworker.module.ts\n```\n\n```text\nworker.module.ts\n```\n\n```text\nBullModule.forRoot({})\n```\n\n```text\nproviders\n```\n\n```text\nconsumers\n```\n\n```text\nworker.ts\n```\n\n```text\nnest-cli.json\n```\n\n```text\nnest-cli-worker.json\n```\n\n```text\nyarn\n```\n\n```text\npackage.json\n```\n\n```text\nstart\n```\n\n```text\nserver\n```\n\n```text\nstart\n```\n\n```text\nworker\n```\n\n```text\ndotenv/config\n```\n\n```text\ndocker\n```\n\n```text\ndocker-compose.yaml\n```\n\n```sh\nnest new my-worker\n```\n\n```text\nconst app = await NestFactory.createApplicationContext(AppModule);\n```\n\n```sh\nyarn add @nestjs/bull bull\n```\n\n```js\n// app.module.ts\n// ... imports\n@Module({\n  imports: [\n    BullModule.registerQueue({\n      name: 'my-queue',\n      redis: {\n        host: 'localhost',\n        port: 6379,\n      },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```js\n// app.processor.ts\n// ... imports\n@Processor('my-queue')\nexport class AppConsumer {\n    @Process('namedjob')\n    async processNamedJob(job: Job<any>): Promise<any> {\n        // do something with job and job.data\n    }\n}\n```\n\n```js\nexport class MyService {\n  constructor(@InjectQueue('my-queue') private queue: Queue) {}\n}\n```\n\n```text\nprocess\n```\n\n```text\napplication\n```\n\n```text\nnode\n```\n\n```text\napplication\n```\n\n```text\nprocess\n```\n\n```text\nworker\n```\n\n```text\napplication\n```\n\n```text\nQueue\n```\n\n```text\nJob\n```\n\n```text\nProcessor\n```\n\n```text\nProcess\n```\n\n```text\n@nestjs/bull\n```\n\n```text\nworker\n```\n\n```text\nsrc/main.ts\n```\n\n```text\nbootstrap\n```\n\n```text\nBull\n```\n\n```text\nsrc/app.module.ts\n```\n\n```text\nAppController\n```\n\n```text\ncontrollers\n```\n\n```text\nBullModule.registerQueue\n```\n\n```text\n@nestjs/bull\n```\n\n```text\nsrc/app.module.ts\n```\n\n```text\napp.processor.ts\n```\n\n```text\nsrc\n```\n\n```text\nworker\n```\n\n```text\napplication\n```\n\n```text\nAppModule\n```\n\n```text\nBullModule.registerQueue\n```\n\n```text\nthis.queue.add('namedJob', data);\n```\n\n```text\nimport { NestFactory } from '@nestjs/core'\nimport { ConfigModule, ConfigService } from '@nestjs/config'\nimport { WorkersModule } from './services/queue/workers-email/workers.module'\n\nasync function bootstrap() {\n    const app = await NestFactory.createApplicationContext(WorkersModule)\n    const config = app.get(ConfigService)\n    ConfigModule.forRoot({ isGlobal: true })\n\n    app.useLogger(\n        config.get<string>('NODE_ENV') === 'development'\n            ? ['log', 'debug', 'error', 'verbose', 'warn']\n            : ['log', 'error', 'warn'],\n    )\n}\n\nbootstrap()\n```\n\n```text\nimport { BullModule } from '@nestjs/bullmq'\nimport { Module } from '@nestjs/common'\nimport { ConfigModule, ConfigService } from '@nestjs/config'\nimport { redisFactory } from '../../../factories/redis.factory'\nimport { workerProcessor } from './workers.processor'\n   \n@Module({\n    imports: [\n        BullModule.forRootAsync({\n            imports: [ConfigModule],\n            useFactory: redisFactory,\n            inject: [ConfigService],\n        }),\n        BullModule.registerQueueAsync({ name: 'queue-name' }),\n    \n    ],\n    providers: [\n        ConfigService,\n        workerProcessor,\n    ],\n})\nexport class WorkersModule {}\n```\n\n```text\nimport { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq'\nimport { Logger } from '@nestjs/common'\nimport { ConfigService } from '@nestjs/config'\nimport { Job } from 'bullmq'\n\n@Processor('queue-name')\nexport class workerProcessor extends WorkerHost {\n    private logger = new Logger('processor')\n\n    constructor(private config: ConfigService) {\n        super()\n    }\n\n    async process(job: Job<any, any, string>): Promise<any> {\n        ... process here ...\n    }\n\n    @OnWorkerEvent('completed')\n    onCompleted(job: Job<anu, any, string>) {\n        this.logger.log(`Job ${job.id} ${job.name.toUpperCase()} Completed`)\n    }\n\n    @OnWorkerEvent('failed')\n    onFailed(job: Job<any, any, string>) {\n        this.logger.error(`Job ${job.id} ${job.name.toUpperCase()} Failed`)\n    }\n\n\n}\n```\n\n========================================\n\nComments:\n- You could always separate your worker in a stand-alone app, I think thatโ€™s what you mean by โ€œseparate binaryโ€ in this context.\n- โ€œ I couldn't find anything on the Bull's documentation...โ€, are you sure? What about github.com/OptimalBits/bull#separate-processes\n- check my answer, itโ€™s the same thing the example shown just isnโ€™t the best.\n- Yeah, I saw this, but couldn't figure out how can I use it in my project. I have a main project ( my current), and I want to create the worker in a separate process (standlone application) and want to connect both my current main project and worker. And I can't really find it in the documentation.\n- And in which module should I instantiate my Bull's instance? I am assuming I'll keep my `producer` in my main module and `consumer` in my worker module.\n- @DakshGargas I updated my answer. You shouldn't have separate modules, you should have two separate projects/apps. Take a look and let me know if I can help any further but hopefully that should cover it.\n- I'm doing the same thing, but this won't spawn my worker as a separate `application`. But maybe I am off on one step... when you asked me to do `nest new my-worker`... is this a whole new project? If so, how should I connect it with my current project? Also, my `consumer` will be using multiple modules from my current project.\n- @DarshGargas yes an entirely new projects. The problem with this is youโ€™ll need to either consume those modules through an API or some other means, or duplicate them from your main project into your worker. However, with this approach you gain a cleaner separation plus achieve the separate process. You need not worry about connecting the two as this happens over Redis providing you connect both projects to the same Redis.\n- why would we need a standalone application for this? And if the dependencies are included in app.processor.ts we wouldn't have to create a new project , right?\n- @juztcode You really wouldn't need a standalone application. I found that when using Bull (built on top of Redis), my workflow worked best when I separated processes and had both running in isolated containers using Bull to communicate work. Really comes down to what works best for your application.\n- Hi ! Are you happy with this approach ? Using Bull / Redis and your worker ? Have you tried running multiple instances of your app AND your worker ?\n- Hey, so far it's getting the job done... but haven't tried running *multiple* instances of runner. I think I'll just have to spawn it in another port and it should be fine. Been running my worker on Staging like this for 15 days and no complaints till now!\n- So are you already running multiple of the app?\n- \"Multiple of the app?\" I don't ...\n- Thank you!!! This is the way. Especially if you want to horizontally scale your processes by adding more Docker containers as needed.\n- when running multiple instances of the runner I assume you'll need some sort of load balancer for this?\n- Yeah... we used AWS Elastic Beanstalk to horizontally scale the instances and used AWS Load Balancer to take care of it. @Christian\n- so the main app would expose one port and the worker app would expose another port, and to prevent user from requesting to the worker port, you'd have to somehow be able to disable access to that port?\n- Yep, restrict that port. @juztcode\n- while this works, I find it let's say quite discussable that we running CLI worker as an HTTP application. Can we run the worker as CLI application, without exposing all the app's routes/endpoints?\n- @borN_free, Good question! Not sure, I haven't tried it. Pls drop an answer here once you come up with something. Good luck!","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":68,"totalLines":576,"estimatedTokens":3599}}65{"id":"stack-52266348","source":"stackoverflow","questionId":52266348,"title":"How to split Nest.js microservices into separate projects?","tags":["node.js","typescript","microservices","nestjs"],"text":"Title: How to split Nest.js microservices into separate projects?\nTags: node.js, typescript, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nLet's say I want to create a simplistic cinema-management platform. It needs few microservices: `movies`, `cinemas`, `payments`, etc.\n\nHow would you go about doing it in Nest.js? I don't want them in the same big folder as that feels like making a monolith. I want them to be separate Nest.js projects with their own git repositories so I can orchestrate them with Kubernetes later on.\n\nHow? How to connect from service `cinemas` to service `movies` if they are two separate projects and only , let's say, Redis?\n\nEdit:\nThis is not a question about microservices in general. This is a question Nest.js specific. I read the documentation, I know there are decorators like `@Client` for connecting to the transport layer. I just want to know where to use that decorator and maybe see a short snippet of code on \"having two separate Nest.js repositories how to connect them together so they can talk to each other\".\n\nI don't care about the transport layer, that thing I can figure out myself. I just need some advice on the framework itself as I believe the documentation is lacking.\n\n========================================\n\nCode:\n```text\nmovies\n```\n\n```text\ncinemas\n```\n\n```text\npayments\n```\n\n```text\ncinemas\n```\n\n```text\nmovies\n```\n\n```text\n@Client\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Transport } from '@nestjs/common/enums/transport.enum';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice(AppModule, {\n    transport: Transport.REDIS,\n    options: {\n      url: 'redis://localhost:6379',\n    },\n  });\n  await app.listen(() => console.log('MoviesService is running.'));\n}\nbootstrap();\n```\n\n```text\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @MessagePattern({ cmd: 'LIST_MOVIES' })\n  listMovies(): string[] {\n    return ['Pulp Fiction', 'Blade Runner', 'Hatred'];\n  }\n}\n```\n\n```text\n@Controller()\nexport class AppController {\n  private readonly client: ClientProxy;\n\n  constructor(private readonly appService: AppService) {\n    this.client = ClientProxyFactory.create({\n      transport: Transport.REDIS,\n      options: {\n        url: 'redis://localhost:6379',\n      },\n    });\n  }\n\n  @Get()\n  listMovies() {\n    const pattern = { cmd: 'LIST_MOVIES' };\n\n    return this.client.send<string[]>(pattern, []);\n  }\n}\n```\n\n```text\ncreateMicroservice\n```\n\n```text\nmain.ts\n```\n\n```text\n@MessagePattern\n```\n\n```text\nmain.ts\n```\n\n```text\n@nestjs/cli\n```\n\n```text\nclient\n```\n\n```text\n@MessagePattern\n```\n\n```text\nthis.client\n```\n\n========================================\n\nComments:\n- the microservices should not any database and should communicate only using the network (HTTP, messaging etc)\n- @JesseCarter \"let's say Redis\" is pointing to a specific transport layer. \"Did you even read the docs\" - please don't insult me. Of course I did. I still think the documentation is lacking in example on how to take one microservice and use `@Client` (or something) to connect to different one. The sample in GitHub (`3-microservices`) is using only one project and is a hybrid app. That's why I posted here.\n- @ConstantinGalbenu yes, they shouldn't a database. That's why I want them as seperate as they can be. Nest.js supports multiple different transport layers including `Transport.REDIS`. That was just an example.\n- I can't give you an answer because I don't use Nest.js but I could with you some thoughts. So, the microservices should communicate only using the network, using a protocol that hides the technologies that are used by the other. So, if a microservice uses Nest.js (or another framework) it should not assume that the other microservice uses also Nest.js. And also, when a microservice processes a request, it should not ask for data from another microservice during that request *if you want resilience*; in other words, it should have all the data already gathered from other microservice.\n- @ConstantinGalbenu I know how microservices work. I need to use Nest.js for microservices though and I don't grasp how to utilize their decorators. This is a Nest.js specific question (hence the tag). It's not the architecture I'm asking for but an example of two Nest.js microservices that can talk to one another but are in separate two Nest.js projects.\n- I understand now, +1 from me\n- I can see that the actual microservices example doesn't show multiple services.This is definitely still outside the scope of a StackOverflow question though. If you put a bounty on it I'll put together a git repo that you can use as reference material\n- Good stuff! Glad you figured out how to put things together. After you asked this I decided to put together an example repo anyways. It's pretty barebones at the moment but provides a GraphQL client application that communicates with another microservice over Redis. Set up with all kinds of docker and docker-compose goodness so that people can reference a working example: github.com/WonderPanda/nestjs-microservice-architecture\n- You might want to consider using Nats instead of Redis so that you can continue to use pub/sub with multiple nodes/instances of the same service (i.e. you only want one of them to handle a given message. think user login, or data manipulation). Nats allows you to add the same services/modules to their own queue so only one instance of a given service picks up a message.","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":139,"estimatedTokens":1390}}66{"id":"stack-61697771","source":"stackoverflow","questionId":61697771,"title":"How can I set a header field in a response with NestJS?","tags":["typescript","nestjs","fastify"],"text":"Title: How can I set a header field in a response with NestJS?\nTags: typescript, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm trying:\n\n```\n@Post('login')\n async login(@Body() body: AuthDto, @Res() res: Response) {\n const loginResponse = await this.authService.login(body);\n console.log('loginResponse', loginResponse)\n res.headers.set('x-access-token', loginResponse.access_token)\n return loginResponse\n }\n```\n\nbut no dice. I get an error:\n\n```\nTypeError: Cannot read property 'set' of undefined\n```\n\n========================================\n\nTop Answer:\nTo specify a custom response header, you can either use a @Header() decorator or a library-specific response object (and call res.header() directly).\n\nImport Header from the `@nestjs/common package`.\n\n```\n@Post()\n@Header('Cache-Control', 'none')\ncreate() {\n return 'This action adds a new cat';\n}\n```\n\n========================================\n\nCode:\n```text\n@Post('login')\n    async login(@Body() body: AuthDto, @Res() res: Response) {\n        const loginResponse = await this.authService.login(body);\n        console.log('loginResponse', loginResponse)\n        res.headers.set('x-access-token', loginResponse.access_token)\n        return loginResponse\n    }\n```\n\n```text\nTypeError: Cannot read property 'set' of undefined\n```\n\n```js\nimport { Controller, Get, Response } from '@nestjs/common';\nimport { Response as Res } from 'express';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getHello(@Response() res: Res): Res {\n    return res.set({ 'x-access-token': 1 }).json({ hello: 'world' });\n  }\n\n  @Get()\n  getHelloAlt(@Response() res: Res): Res {\n    return res.set({ 'x-access-token': 1 }).json({ hello: 'world' });\n  }\n}\n```\n\n```text\nreturn res.set({ 'x-access-token': loginResponse.access_token }).json(loginResponse);\n```\n\n```js\n@Post()\n@Header('Cache-Control', 'none')\ncreate() {\n  return 'This action adds a new cat';\n}\n```\n\n```text\n@nestjs/common package\n```\n\n```text\nimport { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\nimport { Response as ExpressResponse } from 'express';\n\n@Injectable()\nexport class ResponseAddAccessTokenToHeaderInterceptor implements NestInterceptor {\n    intercept(context:ExecutionContext, next:CallHandler): Observable<any> {\n\n        const ResponseObj:ExpressResponse = context.switchToHttp().getResponse();\n        ResponseObj.setHeader('x-access-token', 'Your Data' );\n        return next.handle();\n    }\n}\n```\n\n```text\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    app.useGlobalInterceptors(new ResponseAddAccessTokenToHeaderInterceptor());\n    await app.listen(8080);\n}\nbootstrap();\n```\n\n```text\n@Post('login')\nasync login(@Body() body: AuthDto, @Res() res: Response) {\n    const loginResponse = await this.authService.login(body);\n    res.header('x-access-token', loginResponse.access_token).json(loginResponse);\n}\n```\n\n```text\n@Post('login')\nasync login(@Body() body: AuthDto, @Res({ passthrough: true }) res: Response) {\n    const loginResponse = await this.authService.login(body);\n    res.header('x-access-token', loginResponse.access_token);\n    return loginResponse;\n}\n```\n\n```text\npassthrough\n```\n\n========================================\n\nComments:\n- Same: `Property 'set' does not exist on type 'Response'`\n- Is that error at compile-time or run-time? If compile-time, where are you importing Response from? Native, or Express? Be aware there's a global Response type also. I've updated my original answer for you, let me know how that works.\n- It's at compile time. I'm importing from `nest.js`\n- `async login(@Req() req: Request, @Response() res) {` - that did it\n- If you want to keep type-safety, use the Express.js Response interface, it won't affect run-time though as the Express Response is used internally.\n- Why won't the nest type work? And if you update your answer to reflect my comment, I can accept\n- Because the type you're importing isn't a type, it's a decorator so it doesn't have a collection of properties. Depending on your code editor (I use VS Code), you can view where the import is declared, this looks like: `export declare const Response: () => ParameterDecorator;` A little confusing I must admit. I'll edit your comment into the answer though!\n- This is a super-simple way to fix CORS errors when debugging your UI locally. Just add `Access-Control-Allow-Origin: http:&#47;&#47;localhost:4200` (or similar) to your endpoints.","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":150,"estimatedTokens":1149}}67{"id":"stack-60062318","source":"stackoverflow","questionId":60062318,"title":"How to inject service to validator constraint interface in nestjs using class-validator?","tags":["typescript","nestjs","class-validator"],"text":"Title: How to inject service to validator constraint interface in nestjs using class-validator?\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to inject my users service into my validator constraint interface but it doesn't seem to work:\n\n```\nimport { ValidatorConstraintInterface, ValidatorConstraint, ValidationArguments, registerDecorator, ValidationOptions } from \"class-validator\";\nimport { UsersService } from './users.service';\n\n@ValidatorConstraint({ async: true })\nexport class IsEmailAlreadyInUseConstraint implements ValidatorConstraintInterface {\n constructor(private usersService: UsersService) {\n console.log(this.usersService);\n }\n validate(email: any, args: ValidationArguments) {\n return this.usersService.findUserByEmail(email).then(user => {\n if (user) return false;\n return true;\n });\n return false;\n }\n\n}\n```\n\nBut, as usersService is logged null, I can't access its methods.\n\nAny insight on this matter?\n\n========================================\n\nTop Answer:\nBy the way, this doesn't work in e2e test. This is the way how I get it running.\n\n```\nbeforeAll(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n app = moduleFixture.createNestApplication();\n\n app.useGlobalPipes(GetValidationPipe());\n useContainer(app.select(AppModule), { fallbackOnErrors: true });\n await app.init();\n});\n```\n\n========================================\n\nCode:\n```text\nimport { ValidatorConstraintInterface, ValidatorConstraint, ValidationArguments, registerDecorator, ValidationOptions } from \"class-validator\";\nimport { UsersService } from './users.service';\n\n@ValidatorConstraint({ async: true })\nexport class IsEmailAlreadyInUseConstraint implements ValidatorConstraintInterface {\n    constructor(private usersService: UsersService) {\n        console.log(this.usersService);\n    }\n    validate(email: any, args: ValidationArguments) {\n        return this.usersService.findUserByEmail(email).then(user => {\n             if (user) return false;\n             return true;\n        });\n        return false;\n    }\n\n}\n```\n\n```text\nimport {useContainer, Validator} from \"class-validator\";\n\n// do this somewhere in the global application level:\nuseContainer(Container);\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  useContainer(app.select(AppModule), { fallbackOnErrors: true });\n...}\n```\n\n```text\nimport {ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';\nimport {UsersService} from './user.service';\nimport {Injectable} from '@nestjs/common';\n\n@ValidatorConstraint({ name: 'isUserAlreadyExist', async: true })\n@Injectable() // this is needed in order to the class be injected into the module\nexport class IsUserAlreadyExist implements ValidatorConstraintInterface {\n    constructor(protected readonly usersService: UsersService) {}\n\n    async validate(text: string) {\n        const user = await this.usersService.findOne({\n            email: text\n        });\n        return !user;\n    }\n}\n```\n\n```text\nimport {Module} from '@nestjs/common';\nimport { UsersController } from './user.controller';\nimport { UsersService } from './user.service';\nimport { IsUserAlreadyExist } from './user.validator';\n\n@Module({\n    controllers: [UsersController],\n    providers: [IsUserAlreadyExist, UsersService],\n    imports: [],\n    exports: []\n})\nexport class UserModule {\n}\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(ApplicationModule);\n  useContainer(app, { fallback: true });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nclass-validator\n```\n\n```text\n@Injectable()\n```\n\n```text\nbeforeAll(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n        imports: [AppModule],\n    }).compile();\n    app = moduleFixture.createNestApplication();\n\n    app.useGlobalPipes(GetValidationPipe());\n    useContainer(app.select(AppModule), { fallbackOnErrors: true });\n    await app.init();\n});\n```\n\n```text\nimport { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';\nimport isURL from 'validator/es/lib/isURL'; // Import for URL validation\n\n@ValidatorConstraint({ name: 'isEmptyOrUrl' })\nexport class IsEmptyOrUrl implements ValidatorConstraintInterface {\n  validate(value: string, validationArguments: ValidationArguments): boolean {\n    // Check if the value is empty or a valid URL\n    return value === '' || this.validateUrl(value);\n  }\n\n  private validateUrl(value: string): boolean {\n    try {\n      return isURL(value, { protocols: ['https'], require_protocol: true });\n    } catch (error) {\n      return false; // Invalid URL if an error occurs\n    }\n  }\n}\n```\n\n```text\nimport { IsEmptyOrUrl, IsOptional } from './path/to/validators'; // \n// Replace with actual path\n\nexport class MyDto {\n  @IsOptional()\n  @Validate(IsEmptyOrUrl)\n  readonly facebook?: string;\n}\n```\n\n========================================\n\nComments:\n- thanks for sharing. `useContainer(app, { fallback: true });` what is its task?\n- can we use useContainer on the AppModule?\n- @kadiro not to my knowledge, because we need to pass `app`, the configured application, to the `useContainer` method\n- This is a great anwer, however, I would love to see how you would inject the container inside app.module.ts instead of main.ts, since when running tests main.ts does not get triggered.\n- I couldn't figure out step 3 - you answer just saved me a whole lot of nerves :)\n- @FooBar you can inject ModuleRef into the module(`constructor(private moduleRef: ModuleRef) {}`) and then call useContainer in onModuleInit(`onModuleInit() { useContainer(this.moduleRef, { fallbackOnErrors: true }); }`)\n- When using the repository pattern injecting the repository would work the same way, refer to this article\n- @juraj Unfortunately, this does not work for me\n- this helped me solved the issue i was dealing with for almost 48 hrs :( Thanks!\n- Not injecting any service which is the point of the question","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":196,"estimatedTokens":1511}}68{"id":"stack-54737166","source":"stackoverflow","questionId":54737166,"title":"How to generate a production build of an API done with NESTJS","tags":["node.js","typescript","production","nestjs"],"text":"Title: How to generate a production build of an API done with NESTJS\nTags: node.js, typescript, production, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am generating the production version of an API I made using the NESTJS framework and would like to know which files I should upload to the server. When I run the \"npm run start: prod\" compile it generates the \"dist\" folder but I tried to run only with it but it is not enough to run my application. Do I need to upload all files to the server? I did several tests removing the folders I used during development but only managed to run in production mode when I was all the same in dev mode.\n\nI looked in the documentation for something about this but found nothing. can anybody help me?\n\nThank you\n\n========================================\n\nTop Answer:\nFor me this approach worked and all you need is the `dist` folder for this:\n\n- Create a prod build of your application using `npm run start:prod`, this would create a `dist` folder within your application source\n\n- Copy the `dist` folder to your server.\n\n- For getting all the `node_modules` dependencies on your server just copy your `package.json` file into the `dist` folder (that you have copied onto the server) and then run `npm install` from there.\n\n- If you are using `pm2` to run your node applications just run `pm2 start main.js` from within the `dist` folder\n\n========================================\n\nCode:\n```sh\ngit clone git@github.com:myuser/myrepo.git /var/www/\ncd /var/www/\nnode -v && \\\nyarn && \\\nyarn build && \\\nyarn start:prod\n```\n\n```text\nnode dist/main.js\n```\n\n```text\nyarn start:prod\n```\n\n```text\nyarn start\n```\n\n```text\nyarn start:dev\n```\n\n```text\nyarn start:prod\n```\n\n```text\nts-node\n```\n\n```text\nstart:dev\n```\n\n```text\nts-node\n```\n\n```text\nstart:prod\n```\n\n```text\nnode dist/main.js\n```\n\n```text\nprestart:prod\n```\n\n```text\nrm -rf dist && tsc\n```\n\n```text\nnode_modules\n```\n\n```text\nbcrypt\n```\n\n```text\nnpm run start:prod\n```\n\n```text\nnpm install\n```\n\n```text\ndist/\n```\n\n```text\nnode_modules\n```\n\n```text\npackage.json\n```\n\n```text\nnpm rebuild bcrypt --update-binary\n```\n\n```text\ndist\n```\n\n```text\nnpm run start:prod\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\nnode_modules\n```\n\n```text\npackage.json\n```\n\n```text\ndist\n```\n\n```text\nnpm install\n```\n\n```text\npm2\n```\n\n```text\npm2 start main.js\n```\n\n```text\ndist\n```\n\n```text\nnest build\n```\n\n```text\nproduction=true pm2 start dist/main.js\n```\n\n```text\nasync function bootstrap() {\nlet appConfig = {}\nif (process.env.production) {\n    console.log('process env production: ', process.env.production)\n    const httpsOptions = {\n        key: fs.readFileSync('/etc/certs/letsencrypt/live/testtest.de/privkey.pem'),\n        cert: fs.readFileSync('/etc/certs/letsencrypt/live/testtest.de/fullchain.pem'),\n    }\n    \n    // prod config\n    appConfig = {\n        httpsOptions,\n    }\n}\n\nconst app = await NestFactory.create<NestExpressApplication>(\n    AppModule,\n    appConfig,\n)\n\napp.enableCors()\napp.setGlobalPrefix('v1')\n\nawait app.listen(3300)\n}\nbootstrap()\n```\n\n```text\nnpx nx build <project>\n```\n\n```text\ndist/apps/<project>\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- omg. After 6 hours I saw your \"machine specific\" phrase. I wish I knew that. Thanks!\n- A drawback of building on the server is that it takes tons and tons of memory for Webpack to finish the Typescript type checking. For example Node.js runs fine on a AWS t2.micro with 1GB ram, but when building a node app even a 2gb ram server crashes. You could use `transpileOnly: true` in webpack config. Then the app builds in seconds but you haven o type checking. The best option might be to build the javascript before deployment but run npm/yarn install on the server?\n- Another drawback of building on the server is that it takes tons and tons of memory for Webpack to finish the Typescript type checking. For example Node.js runs fine on a AWS t2.micro with 1GB ram, but when building a node app even a 2gb ram server crashes. You could use `transpileOnly: true` in webpack config. Then the app builds in seconds but you haven o type checking.\n- This seems smarter. You don't want the production build to end up with slightly different modules after the build passed on CI. Production builds should be EXACTLY what was built in CI, with no code downloaded from the internet to production.\n- @MarkStosberg isn't it a problem that the code has been built in a different environment than the one it'll run in?\n- Why do you need to copy the package json into the dist folder? You can run npm install from root and run your app in the dist folder from root, too.\n- Hi @Mick of-course you are correct, your approach works if you don't mind having your source code also on the server. But in situations where you need bundle only the `dist` files onto your servers the approach you mentioned might not be a viable solution. Thats why you need to have the `package.json` install your node_modules for you to run your application using your `dist` files. I hope that helps.\n- I believe, `dist` folder doesn't contain machine specific code, Correct?\n- `pm2` + `dist` is clean\n- The caution with `npm install` is it doesn't actually install exactly the version defined in the `package.json` unless you pin versions. It's always better to run `npm ci --production` and copy the node_modules into the image - this will guarantee consistent versions. `npm install` where you have `\"lib\": \"^1.0.0\"` will upgrade `\"lib\"` to `v1.0.1` and i've had mongoose introduce breaking changes on patch versions.","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":222,"estimatedTokens":1391}}69{"id":"stack-51732236","source":"stackoverflow","questionId":51732236,"title":"Generate Swagger documentation as JSON/YAML in NestJS","tags":["javascript","node.js","swagger","nestjs"],"text":"Title: Generate Swagger documentation as JSON/YAML in NestJS\nTags: javascript, node.js, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've followed the instructions to create a Swagger documentation, and my documentation is now available using Swagger UI. I'd like to also generate the documentation as JSON or YAML so it's easy to import in e.g. Postman, but I can't find any suitable methods in the `SwaggerModule`, nor does the Swagger UI have any export button.\n\n========================================\n\nTop Answer:\nTested in **Nestjs v9**\n\nSuppose the docs path is as follows\n\n```\nhttp://localhost:3000/docs\n```\n\nGet JSON\n\n```\nhttp://localhost:3000/docs-json\n```\n\nGet YAML\n\n```\nhttp://localhost:3000/docs-yaml\n```\n\n========================================\n\nCode:\n```text\nSwaggerModule\n```\n\n```text\nconst app = await NestFactory.create(ApplicationModule);\nconst options = new DocumentBuilder()\n    .setTitle(\"Title\")\n    .setDescription(\"description\")\n    .setVersion(\"1.0\")\n    .build();\nconst document = SwaggerModule.createDocument(app, options);\n\nfs.writeFileSync(\"./swagger-spec.json\", JSON.stringify(document));\nSwaggerModule.setup(\"/api\", app, document);\n\nawait app.listen(80);\n```\n\n```text\ndocument\n```\n\n```text\n/api/json\n```\n\n```text\n/api-json\n```\n\n```text\nswagger-ui-express\n```\n\n```text\nfastify\n```\n\n```text\n/api\n```\n\n```text\nswagger-ui-express\n```\n\n```text\nhttp://localhost:3000/docs\n```\n\n```text\nhttp://localhost:3000/docs-json\n```\n\n```text\nhttp://localhost:3000/docs-yaml\n```\n\n```text\nGET http://{host}:{port}/docs\n```\n\n```text\nGET http://{host}:{port}/docs/json\n```\n\n```text\nGET http://{host}:{port}/api-docs\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport fs from 'fs/promises';\nimport { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';\nimport { AppModule } from './app/app.module';\n    \nasync function bootstrap() {\n   const app = await NestFactory.create(\n      AppModule,\n      { preview: true, abortOnError: false } // <-- This parameters prevent for instantiate controllers but its not necessary for SwaggerModule\n   );\n    \n    const prefix = 'api/v1';\n    const corsOrigin = '*';\n    \n    app.enableCors({ origin: corsOrigin });\n    app.setGlobalPrefix(prefix);\n    \n    const config = new DocumentBuilder().setTitle('Title').setDescription('Description').setVersion('1.0').addBearerAuth().build();\n    const document = SwaggerModule.createDocument(app, config);\n    \n    await fs.writeFile('path/to/create/swagger.json', JSON.stringify(document));\n    process.exit();\n}\n    \nbootstrap();\n```\n\n```text\nconst config = new DocumentBuilder()\n    .setTitle('App')\n    .build();\nconst document = SwaggerModule.createDocument(app, config);     \nSwaggerModule.setup('swagger', app, document, {\n        jsonDocumentUrl: 'swagger.json',\n      });\n```\n\n```text\nGET http://{host}:{port}/swagger\n```\n\n```text\nGET http://{host}:{port}/swagger.json\n```\n\n```js\nimport { writeFileSync } from 'fs';\nimport * as yaml from 'js-yaml';\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\n\nasync function generate(): Promise<void> {\n    const app = await NestFactory.create(ApiModule);\n    app.enableVersioning();\n\n    const options = new DocumentBuilder()\n      .setTitle('Your Application API')\n      .setDescription('Your Application API')\n      .setVersion('1.0.0')\n      .addBearerAuth({ type: 'http', bearerFormat: 'JWT' })\n      .build();\n\n    const document = SwaggerModule.createDocument(app, options);\n    const yamlDocument = yaml.dump(document);\n\n    writeFileSync('swagger.yaml', yamlDocument);\n    console.log('โœ… OpenAPI YAML file generated as swagger.yaml.');\n}\n\ngenerate();\n```\n\n```text\njs-yaml\n```\n\n```text\ntags\n```\n\n========================================\n\nComments:\n- Yeah I've been wondering about this too, NestJS can be a bit obfuse\n- This worked very well for me, I added an if condition to save that file only on development environment: `if (process.env.NODE_ENV === 'development')`\n- Is there a way to import this to Postmann as an Collection ?\n- A note on importing fs/path module(s) if you get an error try importing like this. import * as fs from fs import * as path from path\n- This works - but if all you want to do is export the file as a cli task, without starting the server, my workaround is to create a new nest config, and use the `--config` flag of `nest start` and specify the `entryFile` parameter to be a new `swagger-main.ts` where you don't specify `app.listen`. Alternatively you can try `nest-commander` package.\n- in my case I use `SwaggerModule.setup('docs', app, document)`, so I download json file from *localhost:3000/docs-json*\n- Are you sure about that? It seems the linked webpage references `&#47;api-json`.\n- above comment is incorrect, directly from the linked doc as of April, 2023: To generate and download a Swagger JSON file, navigate to `http:&#47;&#47;localhost:3000&#47;api-json` (assuming that your Swagger documentation is available under `http:&#47;&#47;localhost:3000&#47;api`).\n- localhost:3000/docs-json works ok. localhost:3000/docs-yaml not found.\n- I just tried and both routes worked for me. Make sure you are using the latest version of Nestjs (10 for core and 7 for swagger)\n- Works perfectly with `nest start --entryFile main-generate-swagger`\n- I spent two days hunting for this, this is exactly what I needed. Thank you!!","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":200,"estimatedTokens":1348}}70{"id":"stack-59289699","source":"stackoverflow","questionId":59289699,"title":"NestJS: How to transform an array in a @Query object","tags":["nestjs","class-validator","class-transformer"],"text":"Title: NestJS: How to transform an array in a @Query object\nTags: nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS and I am trying to fill a filter DTO from query Parameters.\n\nHere is what I have:\n\nQuery:\n\nlocalhost:3000/api/checklists?stations=114630,114666,114667,114668\n\nController\n\n```\n@Get()\npublic async getChecklists(@Query(ValidationPipe) filter: ChecklistFilter): Promise {\n // ...\n}\n```\n\nDTO\n\n```\nexport class ChecklistFilter {\n\n @IsOptional()\n @IsArray()\n @IsString({ each: true })\n @Type(() => String)\n @Transform((value: string) => value.split(','))\n stations?: string[];\n\n // ...\n}\n```\n\nWith this, the class validator does not complain, however, in the filter object stations is not actually an array but still a single string.\n\nI want to transform it into an array within the validation pipe. How can I achieve that?\n\n========================================\n\nTop Answer:\nThis can be handled without a separate DTO class using the `ParseArrayPipe`:\n\n```\n@Get()\nfindByIds(\n @Query('ids', new ParseArrayPipe({ items: Number, separator: ',' }))\n ids: number[],\n) {\n console.log(ids);\n console.log(Array.isArray(ids)); //returns true\n return 'This action returns users by ids';\n}\n```\n\nref: https://docs.nestjs.com/techniques/validation#parsing-and-validating-arrays\n\n========================================\n\nCode:\n```text\n@Get()\npublic async getChecklists(@Query(ValidationPipe) filter: ChecklistFilter): Promise<ChecklistDto[]> {\n    // ...\n}\n```\n\n```text\nexport class ChecklistFilter {\n\n    @IsOptional()\n    @IsArray()\n    @IsString({ each: true })\n    @Type(() => String)\n    @Transform((value: string) => value.split(','))\n    stations?: string[];\n\n    // ...\n}\n```\n\n```js\n@Get()\npublic async getChecklists(@Query(new ValidationPipe({ transform: true })) filter: ChecklistFilter): Promise<ChecklistDto[]> {\n    // ...\n}\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nexport class ChecklistFilter {\n    \n            @IsOptional()\n            @IsArray()\n            @IsString({ each: true })\n            @Type(() => String)\n            @Transform(({ value }) => value.split(','))\n            stations?: string[];\n        \n            // ...\n        }\n```\n\n```text\n@Get()\n     public async getChecklists(@Query() filter: ChecklistFilter): Promise<ChecklistDto[]> {\n                // ...\n            }\n```\n\n```text\n@Get()\nfindByIds(\n  @Query('ids', new ParseArrayPipe({ items: Number, separator: ',' }))\n  ids: number[],\n) {\n  console.log(ids);\n  console.log(Array.isArray(ids)); //returns true\n  return 'This action returns users by ids';\n}\n```\n\n```text\nParseArrayPipe\n```\n\n```text\nlocalhost:3000/api/checklists?stations[]=114630&stations[]=114666&stations[]=114667&stations[]=114668\n```\n\n```text\n@Get()\npublic async getChecklists(@Query('stations') filter: string[]): Promise<ChecklistDto[]> {\n    // ...\n}\n```\n\n```text\nexport class ChecklistFilter {\n\n        @IsOptional()\n        @Transform((params) => params.value.split(',').map(Number))\n        @IsInt({ each: true })\n        stations?: number[]\n    \n        // ...\n    }\n```\n\n```js\nexport class ChecklistFilter {\n  @ApiProperty({ type: [Number] })\n  @IsOptional()\n  @IsArray()\n  @Transform((item) => item.value.map((v) => parseInt(v, 10)))\n  stations?: number[];\n  //...\n}\n```\n\n```text\n\"class-transformer\": \"^0.5.1\",\n\"class-validator\": \"^0.14.1\",\n```\n\n```text\n@IsOptional()\n  @IsArray()\n  @IsUUID('4', { each: true })\n  @Type(() => String)\n  @Transform((params) => params.value.split(','))\n  readonly ids?: string[];\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      transform: true,\n    }),\n```\n\n```text\nexport class RequestTransformer{\n    static Date(){\n        return Type(()=>Date)\n    }\n\n    static StringArray(){\n        return Transform(({value})=>value.split(\",\"));\n    }\n\n    static NumerArray(){\n        return Transform(({value})=>value.split(\",\").map((e)=>Number(e)));\n    }\n}\n```\n\n```text\nexport class QueryParamsRequest{\n\n    @RequestTransformer.NumerArray()\n    ids:number[];\n    @RequestTransformer.Date()\n    date:Date;\n\n}\n```\n\n```text\n@Get(\"/query-params\")\n  async testeQueryParams(@Query() params:QueryParamsRequest){\n    return params;\n  }\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      transform: true\n    }),\n  );\n```\n\n```text\n@Transform(({ value }) => String(value).split(','))\n```\n\n```text\n\"class-transformer\": \"^0.5.1\",\n```\n\n```text\nvalue.split\n```\n\n========================================\n\nComments:\n- Btw. it should be: @Transform(({value}) => value.split(','))\n- Hi, any idea on how to achieve this for an array of numbers in a query param? imagine im trying to validate [www.url.com/path?ids=1,2,3] , where [ids] should be an array of numbers, and nothing else. tried converting your answer, but with no success so far.\n- `@IsArray() @IsInt({ each: true }) @Transform(({ value }) => value.trim().split(',').map(id=>Number(id))) @ApiProperty({ type: [Number], format: 'form' }) ids?: number[];` **/path?ids=1,2,3,4**\n- this was almost exactly what i needed, thank you! only exception is i needed array of strings instead of numbers but that was easy enough to figure out :)\n- But this doesn't validate the query parameters\n- I believe it's supposed to at least - github.com/nestjs/nest/issues/5467","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":263,"estimatedTokens":1340}}71{"id":"stack-52862644","source":"stackoverflow","questionId":52862644,"title":"Inject service into guard in Nest.JS","tags":["node.js","express","nestjs"],"text":"Title: Inject service into guard in Nest.JS\nTags: node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have KeysModule, which can be used to add or remove API keys. I need these keys to protect some routes from unauthorized access. \nTo protect these routes I have created ApiGuard:\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ApiGuard implements CanActivate {\n\nasync canActivate(\n context: ExecutionContext,\n ): Promise {\n const request = context.switchToHttp().getRequest();\n return request.headers.api_key;\n }\n}\n```\n\nAnd then I use it in route:\n\n```\n@Get('/protected')\n @UseGuards(ApiGuard)\n async protected(@Headers() headers: Api) {\n const key = await this.ks.findKey({ key: headers.api_key });\n if (!key || !key.active) return 'Invalid Key';\n return 'Your API key works';\n }\n```\n\nWhere ks is KeyService used to check if key is correct or not.\nThis solution works, but is stupid. I have to copy and paste some lines of code everywhere I want to use this guard (I mean lines in route).\n\nI have tried to to move all logic to ApiGuard, but there I have got error, that KeyService cannot be injected to ApiGuard class. To explain, I have KeyService in providers in KeysModule, but ApiGuard is globally used.\n\nDo you have any idea how to do it?\n\n========================================\n\nTop Answer:\nAs of NestJS v8 it seems injecting the service as answered by zsoca in the accepted answer doesn't work anymore.\n\nThe working solution for NestJS 8 is by providing a class reference instead of a string:\n\n```\nconstructor(@Inject(KeyService) private keyService: KeyService) {}\n```\n\n========================================\n\nCode:\n```text\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ApiGuard implements CanActivate {\n\nasync canActivate(\n    context: ExecutionContext,\n  ): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n    return request.headers.api_key;\n  }\n}\n```\n\n```text\n@Get('/protected')\n @UseGuards(ApiGuard)\n async protected(@Headers() headers: Api) {\n   const key = await this.ks.findKey({ key: headers.api_key });\n   if (!key || !key.active) return 'Invalid Key';\n   return 'Your API key works';\n }\n```\n\n```text\n// ApiModule\nimport {Module,Global} from '@nestjs/common';\nimport {KeyService} from '../';\n\n@Global()\n@Module({\n    providers: [ KeyService ],\n    exports: [KeyService]\n})\nexport class ApiModule {}\n```\n\n```text\n// guard\nexport class ApiGuard implements CanActivate {\nconstructor(@Inject('KeyService') private readonly KeyService) {}\n}\n async canActivate(context: ExecutionContext) {\n    // your code\n    throw new ForbiddenException();\n  }\n```\n\n```text\n// app.module.js\nimport { Module } from '@nestjs/common';\nimport { APP_GUARD } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_GUARD,\n      useClass: RolesGuard,\n    },\n  ],\n})\nexport class ApplicationModule {}\n```\n\n```text\nInjectable\n```\n\n```text\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ApiGuard implements CanActivate {\n\nconstructor(\n@Inject('KeyService')\nprivate readonly ks\n) {}\n\nconst key = await this.ks.findKey();\n\n\"YOUR_CODE_HERE...\"\n\n}\n```\n\n```js\nconstructor(@Inject(KeyService) private keyService: KeyService) {}\n```\n\n```text\n// auth.module.ts\n@Module({\n  // Mark it as a provider of auth module\n  providers: [TokenService]\n})\nclass AuthModule {}\n\n// guard.ts\n@Injectable()\nclass AuthGuard implements CanActive {\n  // Use TokenService of AuthModule\n  constructor(private tokenServie: TokenService) {}\n\n  canActive() {\n     return this.tokenServie.hasAccessToken();\n  }\n}\n\n// user.controller.ts\n@Controller('/users')\nclass UserController {\n    constructor(private userService: UserService) {}\n\n    @UseGuards(AuthGuard) // <- Use AuthGuard in UserModule, we need to inject TokenService which comes from AuthModule so that we need to import it\n    getUsers() {\n      return this.userService.getUsers();\n    }\n}\n\n// user.module.ts\n@Module({\n   // AuthGuard uses TokenService and TokenService persisting in AuthModule. And we always need to import AuthModule wherever we use AuthGuard\n  imports: [AuthModule], \n  controllers: [UserController]\n})\nclass AuthModule {}\n```\n\n```text\n// stategy-storage.ts\nconst StragegyStorage = new Map();\n\n// auth.strategy.ts\n// Bundle injection at compile time\n@Injectable()    \nclass AuthStrategy {\n    constructor(private tokenServie: TokenService) {\n        StragegyStorage.set(AuthStrategy.name, this);\n    }\n    verify(userId: string): Promise<boolean> {\n      return this.tokenService.verify(userId);\n    }\n}\n\n// guard.ts\n@Injectable()\nclass AuthGuard implements CanActive {\n  constructor() {}\n\n  canActive() {\n     const userId = ...\n     // Get instance of strategy at runtime \n     return StragegyStorage.get(AuthStrategy.name).verify(userId);\n  }\n}\n\n@Module({\n  providers: [TokenService, AuthStrategy]\n})\nclass AuthModule {}\n\n// user.controller.ts\n@Controller('/users')\nclass UserController {\n    constructor(private userService: UserService) {}\n\n    @UseGuards(AuthGuard)\n    getUsers() {\n      return this.userService.getUsers();\n    }\n}\n\n// user.module.ts\n@Module({\n  // No need to import AuthModule anymore\n  controllers: [UserController]\n})\n```\n\n```text\nโ”œโ”€โ”€ app\nโ”‚   โ””โ”€โ”€ app.module.ts        # main application module\nโ”œโ”€โ”€ status\nโ”‚   โ”œโ”€โ”€ status.module.ts\nโ”‚   โ””โ”€โ”€ status.service.ts    # status service (which is to be injected)\nโ”œโ”€โ”€ hodor\nโ”‚   โ”œโ”€โ”€ hodor.decorators.ts  # avoid using @UseGuards(HodorGuard) => use @NotDangerousNow() instead\nโ”‚   โ””โ”€โ”€ hodor.guard.ts       # the guard using StatusService\nโ””โ”€โ”€ door\n    โ”œโ”€โ”€ door.module.ts\n    โ””โ”€โ”€ door.controller.ts   # the controller guarded by @NoDanger()\n```\n\n```js\nimport { Module } from '@nestjs/common'\nimport { APP_GUARD } from '@nestjs/core'\nimport { DoorModule } from '../door/door.module'\nimport { HodorGuard } from '../hodor/hodor.guard'\nimport { StatusModule } from '../status/status.module'\n\n@Module({\n  imports: [\n    HodorModule,\n    DoorModule,\n    StatusModule\n  ],\n  providers: [\n    { provide: APP_GUARD, useClass: HodorGuard } // makes the guard used everywhere\n  ]\n})\nexport class AppModule {}\n```\n\n```js\nimport { Module } from '@nestjs/common'\nimport { StatusService } from './status.service'\n\n@Module({\n    providers: [StatusService],\n    exports: [StatusService]\n})\nexport class StatusModule {}\n```\n\n```js\nimport { Injectable } from '@nestjs/common'\n\n@Injectable()\nexport class StatusService {\n    /**\n     * Returns whether Hodor thinks it's dangerous at the given time.\n     * Just async because in general there is a db call there.\n     */\n    async isDangerousAt(date: Date): Promise<boolean> {\n        return date.getHours() > 22\n    }\n}\n```\n\n```js\nimport { SetMetadata } from '@nestjs/common'\n\nexport const DANGER_KEY = 'danger'\n\n// 403 if Hodor thinks it's dangerous at the given date/time\n// usage: @NotDangerous(date) => that's right I see no possible usage for that one, it's for the example\nexport const NotDangerous = (date: Date) => SetMetadata(DANGER_KEY, { date })\n\n// 403 if Hodor thinks it's dangerous right now\n// usage: @NotDangerousNow()\nexport const NotDangerousNow = () => SetMetadata(DANGER_KEY, { date: new Date() })\n```\n\n```js\nimport { Injectable, CanActivate, ForbiddenException } from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport { DANGER_KEY } from './hodor.decorator'\nimport { StatusService } from '../status/status.service'\n\ntype HodorMetadata = {\n    status: PlatformHodor\n    expected: boolean\n}\n\n@Injectable()\nexport class HodorGuard implements CanActivate {\n    constructor(\n        private reflector: Reflector,\n        private readonly statusService: StatusService // Do not use @Inject (or nest won't be able to inject it)\n    ) {}\n\n    /**\n     * Rely on status service to check if Hodor thinks it is dangerous at the given date/time.\n     * @throws ForbiddenException if Hodor thinks it's dangerous at the given date/time => 403\n     */\n    async canActivate(context: any): Promise<boolean> {\n        // METADATA DANGER_KEY is the magic link between NotDangerous decorator and the guard\n        const metadata = this.reflector.getAllAndOverride<HodorMetadata>(\n            DANGER_KEY,\n            [context.getHandler(), context.getClass()]\n        )\n\n        // because we inject the guard in the whole app\n        // => it must let pass in routes with no decorator\n        if (!metadata) return true\n\n        // 403 if dangerous\n        const isDangerous = await this.statusService.isDangerousAt(metadata.date)\n        if (isDangerous) {\n            throw new ForbiddenException(`Hodor thinks it's dangerous on ${metadata.date}`)\n        }\n        \n        // let pass otherwise\n        return true\n    }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common'\nimport { DoorController } from './door.controller'\n\n@Module({\n    controllers: [DoorController],\n    providers: [DoorService],\n})\nexport class DoorModule {}\n```\n\n```js\nimport { Controller, HttpCode, Post } from '@nestjs/common'\nimport { NotDangerousNow } from '../hodor/hodor.decorator'\n\n@Controller('door')\nexport class DoorController {\n    @NotDangerousNow()\n    @Post()\n    open(): Promise<string> {\n        return 'please, come in'\n    }\n}\n```\n\n```text\n@Global\n```\n\n```text\n@Inject\n```\n\n========================================\n\nComments:\n- do you know a way to set guard on a module but on a particular controller\n- You can add the @UseGuards(GuardName) decorator to a specific route in the controller. That will only apply the guard to that method.\n- You best!๐Ÿš€ Save my life)\n- Thanks, I wasted so much time on this!\n- Thanks for the answer! It really helped tie everything together after some experimentation and googling.","metadata":{"transformedAt":"2026-08-18T18:33:02.406Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":397,"estimatedTokens":2447}}72{"id":"stack-57099863","source":"stackoverflow","questionId":57099863,"title":"SpyOn TypeORM repository to change the return value for unit testing NestJS","tags":["nestjs","typeorm"],"text":"Title: SpyOn TypeORM repository to change the return value for unit testing NestJS\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to unittest corner cases for my TypeORM database calls. I have already mocked all my TypeORM repositories with valid data. But I would like to SpyOn the repository and change the return value form TypeORM. How do I do that?\n\n```\nimport {INestApplication} from '@nestjs/common';\nimport {Test} from '@nestjs/testing';\nimport {CommonModule} from '@src/common/common.module';\nimport {AuthService} from './auth.service';\nimport {Repository} from 'typeorm';\nimport {V3User} from '@src/database/entity/user.v3entity';\n \ndescribe('AuthService', () => {\n let service: AuthService;\n let app: INestApplication;\n \n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [CommonModule.forRoot(`${process.env.DEV_ENV}`)],\n providers: [\n AuthService, \n {provide: 'V3USER_REPOSITORY', useValue: mockRepositoryV3User()},\n ],\n }).compile();\n \n app = module.createNestApplication();\n await app.init();\n \n service = module.get(AuthService);\n });\n \n\n \n it('test auth service - with non existing user in v3 db', async () => {\n \n jest.spyOn(?????? , 'findOne').mockImplementation(() => undefined);\n \n const res = await service.loginUser(\"bad token\");\n \n await expect(service.tokenBasedAuth('example bad token'))\n .rejects.toThrow('bad token exception');\n });\n});\n```\n\nI mock the database like this for normal test cases:\n\n```\nexport const mockRepositoryV3User = () => ({\n metadata: {\n columns: [],\n relations: [],\n },\n findOne: async () =>\n Promise.resolve({\n id: 3,\n email: 'email@example.com',\n first_name: 'david',\n last_name: 'david',\n last_login: '2019-07-15',\n date_joined: '2019-07-15',\n }),\n});\n```\n\n========================================\n\nCode:\n```js\nimport {INestApplication} from '@nestjs/common';\nimport {Test} from '@nestjs/testing';\nimport {CommonModule} from '@src/common/common.module';\nimport {AuthService} from './auth.service';\nimport {Repository} from 'typeorm';\nimport {V3User} from '@src/database/entity/user.v3entity';\n    \ndescribe('AuthService', () => {\n    let service: AuthService;\n    let app: INestApplication;\n        \n    beforeEach(async () => {\n        const module = await Test.createTestingModule({\n            imports: [CommonModule.forRoot(`${process.env.DEV_ENV}`)],\n            providers: [\n                AuthService,     \n                {provide: 'V3USER_REPOSITORY', useValue: mockRepositoryV3User()},\n            ],\n        }).compile();\n    \n        app = module.createNestApplication();\n        await app.init();\n    \n        service = module.get<AuthService>(AuthService);\n    });\n    \n\n    \n    it('test auth service - with non existing user in v3 db', async () => {\n                \n        jest.spyOn(?????? , 'findOne').mockImplementation(() => undefined);\n    \n        const res = await service.loginUser(\"bad token\");\n    \n        await expect(service.tokenBasedAuth('example bad token'))\n            .rejects.toThrow('bad token exception');\n    });\n});\n```\n\n```js\nexport const mockRepositoryV3User = () => ({\n    metadata: {\n        columns: [],\n        relations: [],\n    },\n    findOne: async () =>\n        Promise.resolve({\n            id: 3,\n            email: 'email@example.com',\n            first_name: 'david',\n            last_name: 'david',\n            last_login: '2019-07-15',\n            date_joined: '2019-07-15',\n        }),\n});\n```\n\n```js\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Photo {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ length: 500 })\n  name: string;\n\n  @Column('text')\n  description: string;\n\n  @Column()\n  filename: string;\n\n  @Column('int')\n  views: number;\n\n  @Column()\n  isPublished: boolean;\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { Photo } from './photo.entity';\n\n@Injectable()\nexport class PhotoService {\n  constructor(\n    @InjectRepository(Photo)\n    private readonly photoRepository: Repository<Photo>,\n  ) {}\n\n  async findAll(): Promise<Photo[]> {\n    return await this.photoRepository.find();\n  }\n}\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { PhotoService } from './photo.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { Photo } from './photo.entity';\nimport { Repository } from 'typeorm';\n\ndescribe('PhotoService', () => {\n  let service: PhotoService;\n  // declaring the repo variable for easy access later\n  let repo: Repository<Photo>;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        PhotoService,\n        {\n          // how you provide the injection token in a test instance\n          provide: getRepositoryToken(Photo),\n          // as a class value, Repository needs no generics\n          useClass: Repository,\n        },\n      ],\n    }).compile();\n\n    service = module.get<PhotoService>(PhotoService);\n    // Save the instance of the repository and set the correct generics\n    repo = module.get<Repository<Photo>>(getRepositoryToken(Photo));\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n\n  it('should return for findAll', async () => {\n    // mock file for reuse\n    const testPhoto: Photo =  {\n      id: 'a47ecdc2-77d6-462f-9045-c440c5e4616f',\n      name: 'hello',\n      description: 'the description',\n      isPublished: true,\n      filename: 'testFile.png',\n      views: 5,\n    };\n    // notice we are pulling the repo variable and using jest.spyOn with no issues\n    jest.spyOn(repo, 'find').mockResolvedValueOnce([testPhoto]);\n    expect(await service.findAll()).toEqual([testPhoto]);\n  });\n});\n```\n\n```sh\nโ–ถ npm run test -- photo.service\n\n> nestjs-playground@0.0.1 test ~/Documents/code/nestjs-playground\n> jest \"photo.service\"\n\n PASS  src/photo/photo.service.spec.ts\n  PhotoService\n    โœ“ should be defined (17ms)\n    โœ“ should return for findAll (4ms)  < -- test passes with no problem\n\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        3.372s, estimated 4s\nRan all test suites matching /photo.service/i.\n```\n\n```text\nPhotoEntity\n```\n\n```text\nPhotoService\n```\n\n```text\nuseClass: Repository\n```\n\n========================================\n\nComments:\n- Excellent. Works flawlessly.\n- How to test if the query was like .createQueryBuilder('image').offset(pagination.offset).limit&zwnj;&#8203;(pagination.limit).g&zwnj;&#8203;etManyAndCount();\n- For something like that, you'd need a lot of `mockReturnThis()` kind of jest functions with a final one with `mockresolvedValue()`. You'll probably end up having several mocks or spies, one for each that is chained minus the final on, so a `jest.spyOn(repo, 'createQueryBuilder')`, a `jest.spyOn(repo, 'offset'), etc, and your repo should probably set up an initial`createQueryBuilder` method. To go more in depth, this question should really be asked as a separate question\n- I'm following your approach but on line `.mockResolvedValueOnce([testPhoto])` I keep getting `Type MyEntity is not assignable to type never` - did you have that issue?\n- @asus as discussed on Discord, you were trying to use `mockResolvedValueOnce` on a synchronous function. Instead, you should use `mockReturnValueOnce`.\n- @JayMcDoniel for some reason I am getting this error `Error: Cannot spy the find property because it is not a function; undefined given instead` I am sure I followed your steps\n- @MFarahat make a reproducing repository on GitHub, or a Gist. It's not gonna be possible to trouble shoot it in the comments. Terrible formatting\n- @JayMcDoniel heres the repo github.com/mfarahat/backend-demo/tree/feature/customer/src/&hellip;\n- @JayMcDoniel Thank you very much for the solution, banged my head around this issue for 3 days straight before stumbling across your answer :)\n- @JayMcDoniel Thank you very much. I was getting mad about this issue and Corona LockDown. You saved me.\n- @JayMcDoniel i got the msg of TypeError: Right-hand side of 'instanceof' is not an object, i guess is module resolve issue, would you mind to ur repo to me\n- THANK YOU. I was beating my head against the wall trying to do this with `automock`, but this way *works*.","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":270,"estimatedTokens":2085}}73{"id":"stack-52570212","source":"stackoverflow","questionId":52570212,"title":"NestJS Using ConfigService with TypeOrmModule","tags":["typescript","nestjs"],"text":"Title: NestJS Using ConfigService with TypeOrmModule\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI set up a ConfigService as described in docs https://docs.nestjs.com/techniques/configuration \n\nHow can I use this service with the the TypeOrmModule? \n\n```\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'root',\n database: 'test',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n}),\n```\n\n========================================\n\nTop Answer:\nIn **NestJS 10.0.0** a superclean way of doing this is as follows:\n\n### Step 1. Create a `.env` file.\n\n```\n# DATABASE\nDB_HOST=localhost\nDB_PORT=5432\nDB_NAME=demo-db\nDB_USERNAME=postgres\nDB_PASSWORD=example\n```\n\n### Step 2. Register your database config using `registerAs`.\n\n```\n// config/database.config.ts\n\nimport { registerAs } from '@nestjs/config';\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport default registerAs(\n 'database',\n (): TypeOrmModuleOptions => ({\n type: 'postgres',\n host: process.env.DB_HOST,\n port: +process.env.DB_PORT,\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_NAME,\n autoLoadEntities: true,\n synchronize: true,\n }),\n);\n```\n\n### Step 3: Then load this `databaseConfig` into the main `app.module.ts` as follows:\n\n```\n// app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConfigModule } from '@nestjs/config';\nimport databaseConfig from './config/database.config';\n\n@Module({\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRoot(databaseConfig()),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n\nexport class AppModule {}\n```\n\n### That's All!\n\nAdditionally, If you wish to access this `database` configuration in one of your module services, you can do it as below:\n\n```\n// app.module.ts\n\n@Module({\n imports: [\n ConfigModule.forRoot({ load: [databaseConfig] }),\n TypeOrmModule.forRoot(databaseConfig()),\n ...\n ],\n ...\n})\nexport class AppModule {}\n```\n\n```\n// [feature].module.ts\n\n@Module({\n imports: [ConfigModule],\n controllers: [FeatureController],\n providers: [FeatureService],\n})\nexport class FeatureModule {}\n```\n\n```\n// feature.service.ts\n\n@Injectable()\nexport class FeatureService {\n constructor(private configService: ConfigService) {}\n\n printConfiguration() {\n console.log(this.configService.get('database'));\n }\n}\n```\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRoot({\n  type: 'mysql',\n  host: 'localhost',\n  port: 3306,\n  username: 'root',\n  password: 'root',\n  database: 'test',\n  entities: [__dirname + '/**/*.entity{.ts,.js}'],\n  synchronize: true,\n}),\n```\n\n```js\nimport { ConfigService } from './config.service'\nimport { Module } from '@nestjs/common'\nimport { TypeOrmModule } from '@nestjs/typeorm'\n\n@Module({\n  imports: [\n    TypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: (config: ConfigService) => config.get('database'),\n      inject: [ConfigService],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```env\n# DATABASE\nDB_HOST=localhost\nDB_PORT=5432\nDB_NAME=demo-db\nDB_USERNAME=postgres\nDB_PASSWORD=example\n```\n\n```ts\n// config/database.config.ts\n\nimport { registerAs } from '@nestjs/config';\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport default registerAs(\n  'database',\n  (): TypeOrmModuleOptions => ({\n    type: 'postgres',\n    host: process.env.DB_HOST,\n    port: +process.env.DB_PORT,\n    username: process.env.DB_USERNAME,\n    password: process.env.DB_PASSWORD,\n    database: process.env.DB_NAME,\n    autoLoadEntities: true,\n    synchronize: true,\n  }),\n);\n```\n\n```ts\n// app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConfigModule } from '@nestjs/config';\nimport databaseConfig from './config/database.config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    TypeOrmModule.forRoot(databaseConfig()),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n\nexport class AppModule {}\n```\n\n```ts\n// app.module.ts\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({ load: [databaseConfig] }),\n    TypeOrmModule.forRoot(databaseConfig()),\n    ...\n  ],\n  ...\n})\nexport class AppModule {}\n```\n\n```ts\n// [feature].module.ts\n\n@Module({\n  imports: [ConfigModule],\n  controllers: [FeatureController],\n  providers: [FeatureService],\n})\nexport class FeatureModule {}\n```\n\n```ts\n// feature.service.ts\n\n@Injectable()\nexport class FeatureService {\n  constructor(private configService: ConfigService) {}\n\n  printConfiguration() {\n    console.log(this.configService.get('database'));\n  }\n}\n```\n\n```text\n.env\n```\n\n```text\nregisterAs\n```\n\n```text\ndatabaseConfig\n```\n\n```text\napp.module.ts\n```\n\n```text\ndatabase\n```\n\n```js\nimport {Injectable} from '@nestjs/common'\nimport {ConfigService} from '@nestjs/config'\nimport {TypeOrmModuleOptions, TypeOrmOptionsFactory} from '@nestjs/typeorm'\n\n@Injectable()\nexport class TypeOrmConfigService implements TypeOrmOptionsFactory {\n    constructor(protected readonly configService: ConfigService) {}\n    createTypeOrmOptions(): TypeOrmModuleOptions {\n        const {configService} = this\n        return {\n            type: 'postgres',\n            host: configService.getOrThrow('POSTGRES_HOST'),\n            port: configService.getOrThrow('POSTGRES_PORT'),\n            username: configService.getOrThrow('POSTGRES_USER'),\n            password: configService.getOrThrow('POSTGRES_PASSWORD'),\n            database: configService.getOrThrow('POSTGRES_DB'),\n            autoLoadEntities: true,\n            synchronize: !configService.get('PRODUCTION')\n        }\n    }\n}\n```\n\n```text\n@Module({imports:[typeormmodule.forroot(config)]]})\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';\n\n@Injectable()\nexport class TypeOrmConfigService implements TypeOrmOptionsFactory {\n  constructor(private configService: ConfigService) {}\n\n  createTypeOrmOptions(): TypeOrmModuleOptions {\n\n    return {\n      type: 'postgres',\n      host: this.configService.get<string>('DATABASE_HOST'),\n      port: +this.configService.get<string>('DATABASE_PORT'),\n      username: this.configService.get<string>('DATABASE_USER'),\n      password: this.configService.get<string>('DATABASE_PASSWORD'),\n      database: this.configService.get<string>('DATABASE_NAME'),\n      entities: [],\n      migrations: ['dist/migrations/*.js'],\n      synchronize: false,\n    };\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    TypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      useClass: TypeOrmConfigService,\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- Few changes were needed to get it to work for me at least: 1. import { ConfigModule, ConfigService } from '@nestjs/config'; 2. imports: [ConfigModule.forRoot()],\n- @Kevin Exactly!\n- Downvoted because it isn't using the `ConfigService`\n- The method above is an alternative to directly using configService. It is officially supported and mentioned in the NestJS documentation. Benefit of following namespaced configuration is that, it allows you to break the large configuration file into multiple smaller config files which in turn increases maintainability. Also, it prevents the possibility of key collisions by human error as the keys are separated by unique namespaces.\n- Your answer could be improved with additional supporting information. Please edit to add details, so that others can confirm that your answer is correct.","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":346,"estimatedTokens":1971}}74{"id":"stack-62879810","source":"stackoverflow","questionId":62879810,"title":"EntityMetadataNotFound: No metadata for \"Task\" was found - NestJS","tags":["javascript","node.js","orm","nestjs","typeorm"],"text":"Title: EntityMetadataNotFound: No metadata for \"Task\" was found - NestJS\nTags: javascript, node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am learning the NestJS course from Udemy https://www.udemy.com/course/nestjs-zero-to-hero.\n\nAnd I am stuck with a strange issue and I have tried many things but nothing seems to be working. Here is the issue and complete code that I have.\n\n**Error that I am getting**\n\nhttps://i.sstatic.net/sW23F.png\n\n**My ORM configuration file:**\n\nhttps://i.sstatic.net/Zl7z2.png\n\n**Task Entity File: **\nhttps://i.sstatic.net/uWoKC.png\n\n**Finally I am importing the configuration file in tasks.module.ts file**\nhttps://i.sstatic.net/GPgG6.png\n\nPeople facing there issue have resolved it with different fixes,\n\n- Some said that we might be adding misspelled file name or path in configuration that might have caused this issue.\n\n- Some said that changing from npm to yarn has fixed the issue.\n\n- And few also said that the issue is with ORM itself.\n\nI have tried all possible solutions that are available over the internet but was not able to fix this. Its been quite few days now and I am looking for a helping hand or savior on stack overflow.\n\nMeanwhile, I will try to see a few more possibilities that could help but if you have faced this issue do let me know the possible solutions.\n\n========================================\n\nTop Answer:\n```\nentities: [__dirname + '/../**/*.entity.ts']\n```\n\nto\n\n```\nentities: [__dirname + '/../**/*.entity.js']\n```\n\nin **typeorm.config.ts**\n\nit works on me\n\n========================================\n\nCode:\n```text\n@Entity()\n```\n\n```text\nTask\n```\n\n```text\n// base.entity.ts\nimport { PrimaryGeneratedColumn, Column, UpdateDateColumn, CreateDateColumn } from 'typeorm';\n\nexport abstract class BaseEntity {\n@PrimaryGeneratedColumn('uuid')\nid: string;\n\n@Column({ type: 'boolean', default: true })\nisActive: boolean;\n\n@Column({ type: 'boolean', default: false })\nisArchived: boolean;\n\n@CreateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })\ncreateDateTime: Date;\n\n@Column({ type: 'varchar', length: 300 })\ncreatedBy: string;\n\n@UpdateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })\nlastChangedDateTime: Date;\n\n@Column({ type: 'varchar', length: 300 })\nlastChangedBy: string;\n\n@Column({ type: 'varchar', length: 300, nullable: true })\n   internalComment: string | null;\n}\n```\n\n```text\nentities: [__dirname + '/../**/*.entity.ts']\n```\n\n```text\nentities: [__dirname + '/../**/*.entity.js']\n```\n\n```text\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const TypeORMConfig: TypeOrmModuleOptions = {\n  type: 'postgres',\n  url: process.env.DATABASE_URL,\n  synchronize: true,\n  entities: [__dirname + '/../**/*.entity.ts'],\n  migrationsTableName: 'Migrations_History',\n};\n```\n\n```text\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const TypeORMConfig: TypeOrmModuleOptions = {\n  type: 'postgres',\n  url: process.env.DATABASE_URL,\n  synchronize: true,\n  entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n  migrationsTableName: 'Migrations_History',\n};\n```\n\n```text\n.js\n```\n\n```text\n.ts\n```\n\n```text\ntypeorm.config.ts\n```\n\n```text\nentities: [__dirname + '../**/*.entity{.ts,.js}']\n```\n\n```js\n@Module({\n  imports: [\n    TasksModule,\n    TypeOrmModule.forRoot({\n      type: 'postgres',\n      host: 'localhost',\n      port: 5432,\n      username: 'postgres',\n      password: 'postgres',\n      database: 'userdata',\n      autoLoadEntities: true,\n      synchronize: true,\n\n    }),\n  ],\n  \n})\nexport class AppModule { }\n```\n\n```text\nautoLoadEntities: true,\n```\n\n```text\nentities: ['dist/src/**/*.entity{.ts,.js}'],\n```\n\n```text\nimport { Device } from \"@core/entities/device\";\nimport { User } from \"@core/entities/user\";\n\nexport const AppDataSource = new DataSource({\n    type: \"postgres\",\n    url: process.env.POSTGRES_URL_NON_POOLING,\n    entities: [Device, User], // <-------- \n    logging: true,\n});\n```\n\n========================================\n\nComments:\n- In the future, please post actual code snippets and not screenshots. Please take a look at this link.\n- @JayMcDoniel sure. Will make sure to add code's. I added screenshot as i knew that something small might be an issue and I had my code on github . just in case if someone wanted to debug I would have given the github link. But will make sure that i add code\n- You didn't add code.\n- Hi Jay. Thank you it helped. Sometimes I feel like an idiot. Not sure how I missed it.\n- didnt work for me even tho i have @Entity. same issue, No metadata was found\n- Hi Sunny. Thank you for your answer. Not sure how did I miss that.\n- set typeOrmCOnfig entities: [`dist&#47;**&#47;**&#47;*.entity{.ts,.js}`], // try this\n- we can do the ORM configurations in **app.module** file and Try with the above approach. For me, it works fine","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":194,"estimatedTokens":1207}}75{"id":"stack-52859515","source":"stackoverflow","questionId":52859515,"title":"Nestjs using axios","tags":["javascript","node.js","axios","nestjs"],"text":"Title: Nestjs using axios\nTags: javascript, node.js, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nThis simple demo has an error\n *https://docs.nestjs.com/techniques/http-module*\n\n```\nimport { Get, Controller, HttpService } from '@nestjs/common';\nimport { AxiosResponse } from 'axios'\nimport { Observable } from 'rxjs'\n@Controller()\nexport class AppController {\n constructor(private readonly http: HttpService) {}\n @Get()\n root(): Observable> {\n return this.http.get('https://api.github.com/users/januwA');\n }\n}\n```\n\nWhat should I do?\n\n```\n[Nest] 7356 - 2018-10-18 00:08:59 [ExceptionsHandler] Converting circular structure to JSON +9852ms\nTypeError: Converting circular structure to JSON\n at JSON.stringify ()\n```\n\n```\nnest i\ncommon version : 5.1.0\ncore version : 5.1.0\n```\n\n========================================\n\nTop Answer:\nYou have to make sure to handle your responses as a JSON you can return it as a promise and get the data, use one of both or HttpService or axios\n\n```\nimport { Get, Controller, HttpService } from '@nestjs/common';\n@Controller()\nexport class AppController {\n constructor(private readonly http: HttpService) {}\n @Get()\n root(): {\n return this.http.get('https://api.github.com/users/quen2404')\n .toPromise()\n .then(res => res.data)\n .catch(err => /*handle error*/)\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Get, Controller, HttpService } from '@nestjs/common';\nimport { AxiosResponse } from 'axios'\nimport { Observable } from 'rxjs'\n@Controller()\nexport class AppController {\n  constructor(private readonly http: HttpService) {}\n  @Get()\n  root(): Observable<AxiosResponse<any>>  {\n    return this.http.get('https://api.github.com/users/januwA');\n  }\n}\n```\n\n```text\n[Nest] 7356   - 2018-10-18 00:08:59   [ExceptionsHandler] Converting circular structure to JSON +9852ms\nTypeError: Converting circular structure to JSON\n    at JSON.stringify (<anonymous>)\n```\n\n```text\nnest i\ncommon version : 5.1.0\ncore version   : 5.1.0\n```\n\n```text\n@Get()\nroot() {\n  return this.http.get('https://api.github.com/users/januwA').pipe(\n    map(response => response.data)\n  );\n}\n```\n\n```text\n@Get()\nasync root() {\n  const response = await this.http.get('https://api.github.com/users/januwA').toPromise();\n  return response.data;\n}\n```\n\n```text\nAxiosResponse\n```\n\n```text\ndata\n```\n\n```text\nPromises\n```\n\n```text\nimport { Get, Controller, HttpService } from '@nestjs/common';\nimport { AxiosResponse } from 'axios'\nimport { Observable } from 'rxjs'\n@Controller()\nexport class AppController {\n  constructor(private readonly http: HttpService) {}\n  @Get()\n  root(): Observable<any>{\n    return this.httpClient.get('https://api.github.com/users/quen2404')\n      .pipe(map(response => response.data));\n  }\n}\n```\n\n```text\nget\n```\n\n```text\nAxiosResponse<>\n```\n\n```text\nhttps://api.github.com/users/januwA\n```\n\n```text\nAxiosResponse.data\n```\n\n```text\nimport { Get, Controller, HttpService } from '@nestjs/common';\n@Controller()\nexport class AppController {\n  constructor(private readonly http: HttpService) {}\n  @Get()\n      root(): {\n        return this.http.get('https://api.github.com/users/quen2404')\n        .toPromise()\n        .then(res => res.data)\n        .catch(err => /*handle error*/)\n      }\n}\n```\n\n```js\nimport { firstValueFrom } from 'rxjs';\nimport { HttpService } from '@nestjs/axios';\n...\nconst response = await firstValueFrom(this.httpService.get('/api'));\nreturn response.data;\n}\n```\n\n```text\ntoPromise()\n```\n\n========================================\n\nComments:\n- toPromise is going to be deprecated, refer to documentation rxjs.dev/deprecations/to-promise\n- to handle errors from the http services use `catchError` function after the map.","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":178,"estimatedTokens":923}}76{"id":"stack-66605192","source":"stackoverflow","questionId":66605192,"title":"File uploading along with other data in Swagger NestJs","tags":["nestjs","nestjs-swagger"],"text":"Title: File uploading along with other data in Swagger NestJs\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI want to send file along with JSON\n\n```\n{\n \"comment\" : \"string\",\n \"outletId\" : 1\n}\n```\n\nThe help I got from Documentation is\n\n```\nrequestBody:\n content:\n multipart/form-data:\n schema:\n type: object\n properties:\n orderId:\n type: integer\n userId:\n type: integer\n fileName:\n type: string\n format: binary\n```\n\nI don't know where to put this schema. I have tried putting it inside `@ApiProperty()` in DTO as well as in `@ApiOperations` but could not resolve the issue.\n\nBelow is the function I want to capture file content in.\n\n```\n@Post('/punchin')\n@ApiConsumes('multipart/form-data')\n@ApiOperation({ summary: 'Attendance Punch In' })\n@UseInterceptors(CrudRequestInterceptor, ClassSerializerInterceptor, FileInterceptor('file'))\n@ApiImplicitFile({ name: 'file' })\nasync punchInAttendance( @Body() body: PunchInDto, @UploadedFile() file: Express.Multer.File ): Promise {\n const imageUrl = await this.s3FileUploadService.upload(file)\n console.log(body, imageUrl)\n return await this.service.punchInAttendance({\n comment: body.punchInComment,\n outletId: body.outletId,\n imgUrl: imageUrl,\n })\n }\n```\n\n========================================\n\nTop Answer:\nThe solution that works for me was to create a class containing the API references I will be using and to set one of those fields as the `File`.\n\n*storage-object.dto.ts*\n\n```\nexport class StorageObjectDto {\n @ApiProperty({ required: false })\n @IsString()\n comment?: string\n\n @ApiProperty({ type: 'string', format: 'number', required: false })\n @IsNumber()\n outletId?: number\n\n @ApiProperty({ type: 'string', format: 'binary', required: true })\n file: Express.Multer.File\n}\n```\n\nUsing the implementation suggested on the nestJs docs, I can extract the file based on the associated key within the object.\nIn this case, the key is `file`\n\n*object.controller.ts*\n\n```\n@Version('1')\n@Post('upload')\n@ApiConsumes('multipart/form-data')\n@UseInterceptors(FileInterceptor('file'))\nuploadFile(@Body() data: StorageObjectDto, @UploadedFile() file: Express.Multer.File): void {\n console.log({ data, file })\n}\n```\n\nOnce you call the endpoint you should see the following output in your console log\n\n```\n{\n data: FileDataDto {\n comment: 'This is a test comment',\n outletID: 123\n },\n file: {\n fieldname: 'file',\n originalname: 'placeholder.png',\n encoding: '7bit',\n mimetype: 'image/png',\n buffer: ,\n size: 1119\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n    \"comment\" : \"string\",\n    \"outletId\" : 1\n}\n```\n\n```text\nrequestBody:\n    content:\n      multipart/form-data:\n        schema:\n          type: object\n          properties:\n            orderId:\n              type: integer\n            userId:\n              type: integer\n            fileName:\n              type: string\n              format: binary\n```\n\n```text\n@Post('/punchin')\n@ApiConsumes('multipart/form-data')\n@ApiOperation({ summary: 'Attendance Punch In' })\n@UseInterceptors(CrudRequestInterceptor, ClassSerializerInterceptor, FileInterceptor('file'))\n@ApiImplicitFile({ name: 'file' })\nasync punchInAttendance( @Body() body: PunchInDto, @UploadedFile() file: Express.Multer.File ): Promise<Attendance> {\n    const imageUrl = await this.s3FileUploadService.upload(file)\n    console.log(body, imageUrl)\n    return await this.service.punchInAttendance({\n      comment: body.punchInComment,\n      outletId: body.outletId,\n      imgUrl: imageUrl,\n    })\n  }\n```\n\n```text\n@ApiProperty()\n```\n\n```text\n@ApiOperations\n```\n\n```ts\n@Post('upload')\n  @ApiConsumes('multipart/form-data')\n  @ApiBody({\n    schema: {\n      type: 'object',\n      properties: {\n        comment: { type: 'string' },\n        outletId: { type: 'integer' },\n        file: {\n          type: 'string',\n          format: 'binary',\n        },\n      },\n    },\n  })\n  @UseInterceptors(FileExtender)\n  @UseInterceptors(FileInterceptor('file'))\n  uploadFile2(@UploadedFile('file') file) {\n    console.log(file);\n  }\n```\n\n```ts\n{\n  fieldname: 'file',\n  originalname: 'dart.txt',\n  encoding: '7bit',\n  mimetype: 'text/plain',\n  buffer: <Buffer 20 0a 69 6d  ... 401 more bytes>,\n  size: 451,\n  comment: 'some comment',\n  outletId: 123456\n}\n```\n\n```ts\n@Injectable()\nexport class FileExtender implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const req = context.switchToHttp().getRequest();\n    req.file['comment'] = req.body.comment;\n    req.file['outletId'] = Number(req.body.outletId);\n    return next.handle();\n  }\n}\n```\n\n```text\n@ApiBody\n```\n\n```text\nFileInterceptor\n```\n\n```text\nFileExtender\n```\n\n```text\ncomment\n```\n\n```text\noutletId\n```\n\n```ts\nexport class StorageObjectDto {\n    @ApiProperty({ required: false })\n    @IsString()\n    comment?: string\n\n    @ApiProperty({ type: 'string', format: 'number', required: false })\n    @IsNumber()\n    outletId?: number\n\n    @ApiProperty({ type: 'string', format: 'binary', required: true })\n    file: Express.Multer.File\n}\n```\n\n```ts\n@Version('1')\n@Post('upload')\n@ApiConsumes('multipart/form-data')\n@UseInterceptors(FileInterceptor('file'))\nuploadFile(@Body() data: StorageObjectDto, @UploadedFile() file: Express.Multer.File): void {\n    console.log({ data, file })\n}\n```\n\n```js\n{\n  data: FileDataDto {\n    comment: 'This is a test comment',\n    outletID: 123\n  },\n  file: {\n    fieldname: 'file',\n    originalname: 'placeholder.png',\n    encoding: '7bit',\n    mimetype: 'image/png',\n    buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 f4 00 00 01 f4 04 03 00 00 00 39 f8 c2 b9 00 00 00 1b 50 4c 54 45 cc cc cc 96 96 96 9c 9c 9c ... 1069 more bytes>,\n    size: 1119\n  }\n}\n```\n\n```text\nFile\n```\n\n```text\nfile\n```\n\n```js\n@ApiProperty({\n  type: 'array',\n  items: {\n    type: 'string',\n    format: 'binary',\n  },\n  required: false,\n})\nfile: Express.Multer.File;\n```\n\n```text\nimport { ApiImplicitFile } from '@nestjs/swagger/dist/decorators/api-implicit-file.decorator';\n\n@ApiImplicitFile({ name: 'avatar', required: true, description: 'Avatar' })\n```\n\n```js\n@ApiConsumes('multipart/form-data')\n@ApiBody({\n  schema: {\n    type: 'object',\n    properties: {\n      media: {\n        type: 'string',\n        format: 'binary',\n      },\n    },\n  },\n})\n```\n\n```text\nexport class ReqBodyDto {\n  @ApiProperty({ required: true })\n  @IsNotEmpty()\n  MACode: string;\n\n  @ApiProperty({ required: true })\n  @IsNotEmpty()\n  chunkSize: string;\n}\n```\n\n```text\n@UseGuards(StrictAuthGuard)\n  @Post(\"/v1/upload\")\n  @UseInterceptors(FileInterceptor('file', multerOptions))\n  async upload(@UploadedFile() file, @Body() body: ReqBodyDto) {\n    console.log(`body : ${JSON.stringify(body)}`);\n    if (body?.MACode !== MACode) {\n      return \"MACode is invalid. Please provide the correct MACode\";\n    }\n    if (!file) {\n      throw new HttpException(\n        `Please provide correct file name`,\n        400\n      );\n    }\n    console.log(`Migration file: ${JSON.stringify(file)}`);\n    return this.migrations(file, body);\n  }\n```\n\n========================================\n\nComments:\n- giving error at comment and outletId that `Type 'string is not assignable to type 'SchemaObject | ReferenceObject'.`\n- try to change it from `'string'` to `String` - js object\n- doing this does not solve the issue... I assigned empty object `{ }` just for the sake of test.. error goes away but new one came saying `error TS2688: cannot find type definition file for 'loash'.`\n- does it work if you remove both `comment : 'string', outletId : 'integer'` ?\n- removing comment and outlet id makes field as fileupload in swagger UI. now tell me how to include comment and outlet id too.\n- Instead of putting Body properties like this, is there a way to define file properties along with Request Body DTO?\n- @SanchitBhatnagar can you describe more specifically what you are looking for? I'm not sure there are other ways, although I don't deny it\n- @DaniilLoban `properties: { comment: { type: 'string' }, outletId: { type: 'integer' }, file: { type: 'string', format: 'binary', }, },` Here body properties are explicitly defined here only, Can somehow map a DTO class here for the body instead of defining it here manually?\n- Maybe I don't know something, but I have a bad idea how you will interact with a swagger if the file is a field in a DTO object showed as JSON in the swagger interface except in base64.\n- @DaniilLoban what if we have a nested object of files, please do you have any idea of how to render that?\n- @IsraelObanijesu working with an array of files is also possible, but I think it would be better to put this in a separate question where you can give a full-fledged example of the necessary structure, you can add a link to your question here\n- how can i set swagger key param file for multi value .\n- @lakshmankashyap write a little more about what you mean by multivalue\n- Just in case, no need for a class, you can use a plain TypeScript interface here as well\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Worked for me. Thanks a lot! Note that the \"media\" is a property name which you can set to whatever name you want.","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":362,"estimatedTokens":2332}}77{"id":"stack-57459643","source":"stackoverflow","questionId":57459643,"title":"TypeORM: Dynamically set database schema for EntityManager (or repositories) at runtime?","tags":["postgresql","orm","multi-tenant","nestjs","typeorm"],"text":"Title: TypeORM: Dynamically set database schema for EntityManager (or repositories) at runtime?\nTags: postgresql, orm, multi-tenant, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n**Situation:**\n\nFor our SaaS API we use schema-based multitenancy, which means every customer (~tenant) has its own separate schema within the same (postgres) database, without interfering with other customers. Each schema consists of the same underlying entity-model. \n\nEverytime a new customer is registered to the system, a new isolated schema is automatically created within the db. This means, the schema is created at runtime and not known in advance. The customer's schema is named according to the customer's domain.\n\nFor every request that arrives at our API, we extract the user's tenancy-affiliation from the JWT and determine which db-schema to use to perform the requested db-operations for this tenant.\n\n**Problem**\n\nAfter having established a connection to a (postgres) database via TypeORM (e.g. using createConnection), our only chance to set the schema for a db-operation is to resort to the `createQueryBuilder`:\n\n```\nconst orders = await this.entityManager\n .createQueryBuilder()\n .select()\n .from(`${tenantId}.orders`, 'order') // This means, we are forced to use the `QueryBuilder` as it does not seem to be possible to set the schema when working with the EntityManager API (or the Repository API).\n\nHowever, we want/need to use these APIs, because they are much simpler to write, require less code and are also less error-prone, since they do not rely on writing queries \"manually\" employing a string-based syntax.\n\n**Question**\n\nIn case of TypeORM, is it possible to somehow set the db-schema when working with the `EntityManager` or repositories?\n\nSomething like this?\n\n```\n// set schema when instantiating manager\nconst manager = connection.createEntityManager({ schema: tenantDomain });\n\n// should find all matching \"order\" entities within schema\nconst orders = manager.find(Order, { priority: 4 })\n\n// should find a matching \"item\" entity within schema using same manager\nconst item = manager.findOne(Item, { id: 321 })\n```\n\n**Notes:**\n\n- The db-schema needs to be set in a request-scoped way to avoid setting the schema for other requests, which may belong to other customers. Setting the schema for the whole connection is not an option.\n\n- We are aware that one could create a whole new connection and set the schema for this connection, but we want to reuse the existing connection. So simply creating a new connection to set the schema is not an option.\n\n========================================\n\nTop Answer:\nHere is a global overview of the issues with schema-based multitenancy along with a complete walkthrough a Github repo for it.\n\nMost of the time, you may want to use Postgres Row Security Policy instead. It gives most of the benefits of schema-based multitenancy (especially on developer experience), without the issues related to the multiplication of connections.\n\n========================================\n\nCode:\n```js\nconst orders = await this.entityManager\n  .createQueryBuilder()\n  .select()\n  .from(`${tenantId}.orders`, 'order') // <--- setting schema-prefix here\n  .where(\"order.priority = 4\")\n  .getMany();\n```\n\n```js\n// set schema when instantiating manager\nconst manager = connection.createEntityManager({ schema: tenantDomain });\n\n// should find all matching \"order\" entities within schema\nconst orders = manager.find(Order, { priority: 4 })\n\n// should find a matching \"item\" entity within schema using same manager\nconst item = manager.findOne(Item, { id: 321 })\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nQueryBuilder\n```\n\n```text\nEntityManager\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nquery()\n```\n\n```text\nthis.photoRepository.useSchema('customer1').find()\n```\n\n```text\ngetConnection().changeDefaultSchema('myschema')\n```\n\n```text\nTypeOrmModule.forRootAsync(dynamicCreatedDbConfig)\n```\n\n========================================\n\nComments:\n- I'm having the exact same setup in my project, each tenant has its own schema, each schema looks the same and the connection needs to be request-scoped. Iโ€™m going the way which you donโ€™t want to, meaning creating a new connection for each customer. What is your intention not to do it that way? Performance might be a reason, but currently Iโ€™m not running into any problems with to many database connections. Data security shouldnโ€™t be an issue, doing it your way doesnโ€™t differ from the way I do it: const manager = ConnectionUtils.createConnection(schema).createEntityManager&zwnj;&#8203;();\n- Would you just use a Model Driven solution, with one entity class per tenant that you generate at each tenant change? Keeping business code in an abstract class and specifying the schema in the entity decorator in subclasses?\n- Hi @JudgeFudge many thanks for your feedback! May I ask, how many requests does your backend receive per minute, and how many concurrent connections are usually kept open simultaneously? Also, at which point do you close the db-connection? Do you keep them idle or do you close them once the response is sent to the client via a middleware? The reason I don't want to open new connections is to avoid unnecessary resource usage (memory/CPU), moreover, I do not see the point in reestablishing a connection if โ€“ theoretically speaking โ€“ we can set a different schema with TypeORM... really annoying :(\n- @zenbeni Unfortunately \"specifying the schema in the entity decorator in subclasses\" is not possible. As I mentioned, the schema is created at runtime and I cannot create an entity per tenant and set decorators at compile time, since the tenants are not known in advance.\n- @B12Toaster I looked through the TypeORM sources to find a way to set the schema dynamically, but there seems to be no easy way (the way you find is the less dirty way I guess). I have about 50 tenants und the number of requests is not that high (around 50 requests per tenant per hour), so I canโ€™t tell you much about scaling. So I think we have two options: Create a change request (maybe do it on your own) or find more about the performance while having many connections. Since Iโ€™m also very interested in this topic, I might try some test scenarios in my app. I will keep you up to date.\n- HI @B12Toaster have you get the answer somehow? I had exactly the same questions and TypeORM team aren't responding... Just wondering if you found any nice solution.\n- @WinterTime nope not yet. I saw your Issue at github, thanks for opening it, will link it in the OP if that is okay for you? Currently, I am creating one connection per tenant and we will try to keep the tenant number per server below 100. But still experimenting with this. Here is an interesting article that provides some information about how many connections are possible with postgres and how much memory is consumed: citusdata.com/blog/2017/05/10/scaling-connections-in-postgre&zwnj;&#8203;s\n- @B12Toaster after creating schema how do you run initial migration. I want to implement your method but stuck got stuck there.\n- @FelixK. Not directly related to your question but how do you create tables for new schema? I mean when a new tenant is registered you must be creating new schema for it through code. How do you then replicate all tables for new schema?\n- sorry, but this does not answer my question.\n- Wondering if there is any update on Typeorm supporting multi tenancy for a single DB?\n- i wonder why typeorm doesn't have a clean method for something so common\n- Is there any updates on this topic? Does TypeORM still cannot switch schema at runtime?\n- getConnection() is deprecated\n- @Felix K. , isn't the link provided(first one) in this answer the solution appropriate? It the connection in the pool exists , then it's not supposed to be recreated right?\n- isn't the link provided in this answer (the first one) the solution appropriate? It the connection in the pool exists , then it's not supposed to be recreated right?","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":129,"estimatedTokens":1999}}78{"id":"stack-58255000","source":"stackoverflow","questionId":58255000,"title":"How can I get all the routes (from all the modules and controllers available on each module) in Nestjs?","tags":["node.js","typescript","express","nestjs"],"text":"Title: How can I get all the routes (from all the modules and controllers available on each module) in Nestjs?\nTags: node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nUsing Nestjs I'd like to get a list of all the available routes (controller methods) with http verbs, like this:\n\n```\nAPI:\n POST /api/v1/user\n GET /api/v1/user\n PUT /api/v1/user\n```\n\nIt seems that access to express router is required, but I haven found a way to do this in Nestjs. For express there are some libraries like \"express-list-routes\" or \"express-list-endpoints\".\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nI just found that Nestjs app has a \"getHttpServer()\" method, with this I was able to access the \"router stack\", here's the solution:\n\n```\n// main.ts\n\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as expressListRoutes from 'express-list-routes';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.enableCors();\n await app.listen(3000);\n\n const server = app.getHttpServer();\n const router = server._events.request._router;\n console.log(expressListRoutes({}, 'API:', router));\n\n}\nbootstrap();\n```\n\nhttps://i.sstatic.net/4CoF1.png\n\n========================================\n\nCode:\n```text\nAPI:\n      POST   /api/v1/user\n      GET    /api/v1/user\n      PUT    /api/v1/user\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n  const server = app.getHttpAdapter().getInstance();\n  const router = server.router;\n\n  const availableRoutes: [] = router.stack\n    .map(layer => {\n      if (layer.route) {\n        return {\n          route: {\n            path: layer.route?.path,\n            method: layer.route?.stack[0].method,\n          },\n        };\n      }\n    })\n    .filter(item => item !== undefined);\n  console.log(availableRoutes);\n}\nbootstrap();\n```\n\n```text\n// main.ts\n\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as expressListRoutes from 'express-list-routes';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.enableCors();\n  await app.listen(3000);\n\n\n  const server = app.getHttpServer();\n  const router = server._events.request._router;\n  console.log(expressListRoutes({}, 'API:', router));\n\n}\nbootstrap();\n```\n\n```text\n// main.ts\n\napp\n    .getHttpAdapter()\n    .getInstance()\n    .addHook('onRoute', opts => {\n      console.log(opts.url)\n    })\n```\n\n```text\nFastify\n```\n\n```text\nimport { Controller, Get, Request } from \"@nestjs/common\";\nimport { Request as ExpressRequest, Router } from \"express\";\n\n...\n\n@Get()\nroot(@Request() req: ExpressRequest) {\n    const router = req.app._router as Router;\n    return {\n        routes: router.stack\n            .map(layer => {\n                if(layer.route) {\n                    const path = layer.route?.path;\n                    const method = layer.route?.stack[0].method;\n                    return `${method.toUpperCase()} ${path}`\n                }\n            })\n            .filter(item => item !== undefined)\n    }\n}\n\n...\n```\n\n```json\n{\n    \"routes\": [\n        \"GET /\",\n        \"GET /users\",\n        \"POST /users\",\n        \"GET /users/:id\",\n        \"PUT /users/:id\",\n        \"DELETE /users/:id\",\n    ]\n}\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as expressListRoutes from 'express-list-routes';\n\nasync function getApp() {\n  const app = await NestFactory.create(AppModule);\n\n  await app.listen(3000);\n\n  expressListRoutes(app.getHttpServer()._events.request._router);\n\n  return app;\n}\n\ngetApp();\n```\n\n```text\n[Nest] 11619  - 10/03/2022 19:53:56     LOG [NestApplication] Nest application successfully started +3ms\nGET      /ui\nGET      /ui-json\nGET      /\nGET      /api/v1/auth\n```\n\n```text\nconstructor(\nprivate readonly _discoveryService: DiscoveryService,\nprivate readonly _reflector: Reflector){}\n\nprivate async getAllEndpoints(): Promise<void> {\nconst getRoutes = [];\nconst controllers = this._discoveryService.getControllers();\ncontrollers.forEach(wrappper => {\n  const { instance } = wrappper;\n  if (instance) {\n    const controllerPath = this._reflector.get<string>(PATH_METADATA, instance.constructor);\n    const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(instance));\n    methods.forEach(methodName => {\n      const methodHandler = instance[methodName];\n      const methodPath = this._reflector.get<string>(PATH_METADATA, methodHandler);\n      const requestMethod = this._reflector.get<RequestMethod>(METHOD_METADATA, methodHandler);\n      const baseUri = `${controllerPath}  `;\n      const method = RequestMethod[requestMethod];\n      if (method) {\n        getRoutes.push({\n          path: methodPath == '/' ? baseUri : `${baseUri}/${methodPath}`,\n          method: method,\n        });\n      }\n    });\n  }\n});\n}\n```\n\n```text\n[  \n   { path: 'auth/login', method: 'POST' },\n   { path: 'auth/password/change', method: 'PATCH' }\n]\n```\n\n========================================\n\nComments:\n- see this link, its gitHub `express-list-routes` and `index.js` file. look at this and re-write this code for yourself : github.com/labithiotis/express-list-routes/blob/master/index&zwnj;&#8203;.js. All it takes is a few lines of code\n- @mohammadjavadahmadi The problem is that I don't know wether there's a way to access the \"route stack\" (I see that's what the \"express-list-routes\" receives).\n- This answer seems to be outdated, I installed `express-list-routes` and followed the same steps, it doesn't work. Using `console.log('API:', server._events.request);`, I get `[Function]`. Are you still using the same method?\n- It works with Nestjs, without any other package. Are you using express directly instead of Nestjs? That could be the reason why it's not working. @Adham Sabry\n- @mr-d-mx I am using express afaik, what do you mean by are you suing express directly instead of nestjs? Also, ``` await app.listen(3000); const server = app.getHttpServer(); // is this line reachable with the await above? const router = server._events.request._router; console.log(expressListRoutes({}, 'API:', router)); ```\n- @mr-d-mx: ``` console.log(router, expressListRoutes); console.log(expressListRoutes({}, 'API:', router)); ``` I get the following: ``` undefined { default: [Function] } (node:5006) UnhandledPromiseRejectionWarning: TypeError: expressListRoutes is not a function at bootstrap (main.js:44:17) ```\n- i am using the default nestjs server which i assume express by default.\n- Is this specific to express? If so is there an equivalent command for fastify?\n- This works great but is it possible to get the Guards information with every endpoint?\n- `const router = server._events.request._router;` seems to be outdated. The `_events` prop isn't there\n- The `_events` property exists for me on the latest NestJS using express, but the `_router` property doesn't exist.\n- `addHook` doesn't exist on `getInstance()`\n- I use Fastify, the code above works, even though you don't get code completion for the instance. However, you need to place it before the app.listen() statement because the hooks are triggered when the routes are added to the app.\n- This worked for me but the output had some duplicates in it, so be sure to check for those.\n- Works for NestJS 9","metadata":{"transformedAt":"2026-08-18T18:33:02.407Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":235,"estimatedTokens":1843}}79{"id":"stack-60363353","source":"stackoverflow","questionId":60363353,"title":"TypeORM OneToMany causes \"ReferenceError: Cannot access '' before initialization\"","tags":["typescript","nestjs","typeorm","nrwl-nx"],"text":"Title: TypeORM OneToMany causes \"ReferenceError: Cannot access '' before initialization\"\nTags: typescript, nestjs, typeorm, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nI have two entities: **User** and **Habit**. \nA user can create multiple Habits, thus I use a **OneToMany** relation on the User (and **ManyToOne** on the Habit, respectively).\n\n### User Entity\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, BeforeUpdate, OneToMany} from \"typeorm\";\nimport * as bcrypt from \"bcryptjs\";\nimport { Habit } from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column()\n email: string;\n\n @Column()\n password: string;\n\n @OneToMany(type => Habit, habit => habit.author)\n habits: Habit[];\n\n @CreateDateColumn()\n dateCreated: Date;\n\n @UpdateDateColumn()\n dateUpdated: Date;\n\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise {\n this.password = await bcrypt.hash(this.password,10);\n }\n\n async comparePassword(password: string): Promise {\n return bcrypt.compare(password, this.password);\n }\n\n constructor(props: any) {\n Object.assign(this, props);\n }\n}\n```\n\n### Habit Entity\n\n```\nimport {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, ManyToOne} from \"typeorm\";\nimport { User } from \"../users/users.entity\";\n\n@Entity()\nexport class Habit {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column({ nullable: true})\n description?: string;\n\n @ManyToOne(type => User, user => user.habits)\n author: User;\n\n @CreateDateColumn()\n dateCreated: Date;\n\n @UpdateDateColumn()\n dateUpdated: Date;\n\n constructor(props: Partial) {\n Object.assign(this, props);\n }\n}\n```\n\n### Problem\n\nWhen setting up the above relation I receive the following error\n\n```\nWARNING in Circular dependency detected:\napps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts\n\nWARNING in Circular dependency detected:\napps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts\n\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"User\", function() { return User; });\n ^\nReferenceError: Cannot access 'User' before initialization\n at Module.User (...\\dist\\apps\\api\\main.js:1782:96)\n at Module../apps/api/src/habits/habits.entity.ts (...\\dist\\apps\\api\\webpack:\\apps\\api\\src\\habits\\habits.entity.ts:42:13)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/users/users.entity.ts (...\\dist\\apps\\api\\main.js:1790:79)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/config/db-config.service.ts (...\\dist\\apps\\api\\main.js:1038:77)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/config/config.module.ts (...\\dist\\apps\\api\\main.js:978:76)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/app/app.module.ts (...\\dist\\apps\\api\\main.js:147:79)\n```\n\n### Note\n\nI use **Nx** and have created a **NestJS** app.\nThe TypeOrm version is **\"^0.2.22\"** and the @nestjs/typeorm version is **\"^6.2.0\"**\n\nMy **tsconfig** is as follows:\n\n```\n{\n \"compileOnSave\": false,\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"sourceMap\": true,\n \"declaration\": false,\n \"moduleResolution\": \"node\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"importHelpers\": true,\n \"target\": \"es2015\",\n \"module\": \"esnext\",\n \"typeRoots\": [\"node_modules/@types\"],\n \"lib\": [\"es2018\", \"dom\"],\n \"skipLibCheck\": true,\n \"skipDefaultLibCheck\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"@awhile/contracts\": [\"libs/contracts/src/index.ts\"],\n \"@awhile/ui\": [\"libs/ui/src/index.ts\"]\n }\n },\n \"exclude\": [\"node_modules\", \"tmp\"]\n}\n```\n\nI have tried to use a **ManyToMany** relation and it worked. Also, on a separate NestJS app (without Nx) I cannot reproduce this reference error.\nChanging the ECMAScript **target** version in the **tsconfig.json** also did not work.\n\nBoth entities are only used in their services and are not instantiated anywhere else.\n\nI appreciate any help. Thank you in advance.\n\n========================================\n\nTop Answer:\nUse the `Relation` type wrapper to avoid circular dependency issues, as described here.\n\nFor example:\n\n```\nimport {Entity, OneToMany, Relation} from \"typeorm\";\nimport {Habit} from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n ...\n\n @OneToMany(type => Habit, habit => habit.author)\n habits: Relation[];\n\n ...\n}\n```\n\n========================================\n\nCode:\n```ts\nimport {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, BeforeUpdate, OneToMany} from \"typeorm\";\nimport * as bcrypt from \"bcryptjs\";\nimport { Habit } from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn(\"uuid\")\n    id: string;\n\n    @Column()\n    name: string;\n\n    @Column()\n    email: string;\n\n    @Column()\n    password: string;\n\n    @OneToMany(type => Habit, habit => habit.author)\n    habits: Habit[];\n\n    @CreateDateColumn()\n    dateCreated: Date;\n\n    @UpdateDateColumn()\n    dateUpdated: Date;\n\n    @BeforeInsert()\n    @BeforeUpdate()\n    async hashPassword(): Promise<void> {\n        this.password = await bcrypt.hash(this.password,10);\n    }\n\n    async comparePassword(password: string): Promise<boolean> {\n        return bcrypt.compare(password, this.password);\n    }\n\n    constructor(props: any) {\n        Object.assign(this, props);\n    }\n}\n```\n\n```ts\nimport {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, ManyToOne} from \"typeorm\";\nimport { User } from \"../users/users.entity\";\n\n@Entity()\nexport class Habit {\n    @PrimaryGeneratedColumn(\"uuid\")\n    id: string;\n\n    @Column()\n    name: string;\n\n    @Column({ nullable: true})\n    description?: string;\n\n    @ManyToOne(type => User, user => user.habits)\n    author: User;\n\n    @CreateDateColumn()\n    dateCreated: Date;\n\n    @UpdateDateColumn()\n    dateUpdated: Date;\n\n    constructor(props: Partial<Habit>) {\n        Object.assign(this, props);\n    }\n}\n```\n\n```bash\nWARNING in Circular dependency detected:\napps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts\n\nWARNING in Circular dependency detected:\napps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts\n\n\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"User\", function() { return User; });\n                                                                                               ^\nReferenceError: Cannot access 'User' before initialization\n    at Module.User (...\\dist\\apps\\api\\main.js:1782:96)\n    at Module../apps/api/src/habits/habits.entity.ts (...\\dist\\apps\\api\\webpack:\\apps\\api\\src\\habits\\habits.entity.ts:42:13)\n    at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n    at Module../apps/api/src/users/users.entity.ts (...\\dist\\apps\\api\\main.js:1790:79)\n    at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n    at Module../apps/api/src/config/db-config.service.ts (...\\dist\\apps\\api\\main.js:1038:77)\n    at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n    at Module../apps/api/src/config/config.module.ts (...\\dist\\apps\\api\\main.js:978:76)\n    at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n    at Module../apps/api/src/app/app.module.ts (...\\dist\\apps\\api\\main.js:147:79)\n```\n\n```json\n{\n  \"compileOnSave\": false,\n  \"compilerOptions\": {\n    \"rootDir\": \".\",\n    \"sourceMap\": true,\n    \"declaration\": false,\n    \"moduleResolution\": \"node\",\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"importHelpers\": true,\n    \"target\": \"es2015\",\n    \"module\": \"esnext\",\n    \"typeRoots\": [\"node_modules/@types\"],\n    \"lib\": [\"es2018\", \"dom\"],\n    \"skipLibCheck\": true,\n    \"skipDefaultLibCheck\": true,\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@awhile/contracts\": [\"libs/contracts/src/index.ts\"],\n      \"@awhile/ui\": [\"libs/ui/src/index.ts\"]\n    }\n  },\n  \"exclude\": [\"node_modules\", \"tmp\"]\n}\n```\n\n```text\n{\n  \"extends\": \"../../tsconfig.json\",\n  \"compilerOptions\": {\n    \"types\": [\"node\", \"jest\"],\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"module\": \"commonjs\",\n    \"target\": \"esnext\"\n  },\n  \"include\": [\"**/*.ts\"]\n}\n```\n\n```text\n\"paths\": {\n   \"@entities\":[\"app/src/entities/index.ts\"]\n}\n```\n\n```text\nexport * from './user.entity';\nexport * from './habit.entity';\n```\n\n```text\nimport { User, Habit } from '@entities';\n```\n\n```text\ncompilerOptions\n```\n\n```js\nimport {Entity, OneToMany, Relation} from \"typeorm\";\nimport {Habit} from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n    ...\n\n    @OneToMany(type => Habit, habit => habit.author)\n    habits: Relation<Habit>[];\n\n    ...\n}\n```\n\n```text\nRelation\n```\n\n```text\nexport class CreateUser {\n  @IsNotEmpty()\n  userName: string\n  @IsNotEmpty()\n  photoURL: string\n  @IsNotEmpty()\n  displayName: string\n  ...\n  @IsDefined()\n  @IsNotEmptyObject()\n  @ValidateNested()\n  @Type(() => CreateStreakConfig)\n  streakConfig: CreateStreakConfig\n}\n\nexport class CreateStreakConfig {\n  @IsNotEmpty()\n  minimumDistance: number\n  @IsNotEmpty()\n  unitOfDistanceType: typeof STREAK_CONFIG_UNIT_OF_DISTANCE_MILES | typeof STREAK_CONFIG_UNIT_OF_DISTANCE_KILOMETERS\n}\n```\n\n```text\nexport class CreateStreakConfig {\n  @IsNotEmpty()\n  minimumDistance: number\n  @IsNotEmpty()\n  unitOfDistanceType: typeof STREAK_CONFIG_UNIT_OF_DISTANCE_MILES | typeof STREAK_CONFIG_UNIT_OF_DISTANCE_KILOMETERS\n}\n\nexport class CreateUser {\n  @IsNotEmpty()\n  userName: string\n  @IsNotEmpty()\n  photoURL: string\n  @IsNotEmpty()\n  displayName: string\n  ...\n  @IsDefined()\n  @IsNotEmptyObject()\n  @ValidateNested()\n  @Type(() => CreateStreakConfig)\n  streakConfig: CreateStreakConfig\n}\n```\n\n```json\n{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"deleteOutDir\": true,\n    \"webpack\": true\n  }\n}\n```\n\n```text\nimport {\n    Entity,\n    Column,\n    PrimaryGeneratedColumn,\n    OneToOne,\n    JoinColumn,\n    Relation,\n} from \"typeorm\"\nimport { Photo } from \"./Photo\"\n\n@Entity()\nexport class PhotoMetadata {\n    /* ... other columns */\n\n    @OneToOne(() => Photo, (photo) => photo.metadata)\n    @JoinColumn()\n    photo: Relation<Photo>\n}\n```\n\n```text\n@ManyToOne(() => EntityName, (ett) => ett.property)\nval: typeof EntityName;\n```\n\n```text\n@OneToMany('Habit', 'author')\nhabits: Habit[];\n```\n\n========================================\n\nComments:\n- This is indeed the case, after reordering my classes error disappeared. This is wrong, it shouldn't depend on the order, as with any javascript code where hoisting works.\n- I tried to get a vue electron app to work with typeorm. Error was: ReferenceError, can not use variable before declaration on an entity. That did the trick for me. Thanks!\n- Using this on an auto generated schema. Lots of hand work, but much less than creating the schema from scratch;\n- How do you make `paths` work with `ts-loader`?\n- This ended up working for my use case.\n- Adding `Relation` helped when I moved the project to use ESM modules.\n- It works with `OneToOne` as well. Greate!\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review\n- A lot of thx!!!","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":457,"estimatedTokens":2922}}80{"id":"stack-62050741","source":"stackoverflow","questionId":62050741,"title":"Request body not showing in Nest.js + Swagger","tags":["swagger","swagger-ui","nestjs","nestjs-swagger","nestjs-config"],"text":"Title: Request body not showing in Nest.js + Swagger\nTags: swagger, swagger-ui, nestjs, nestjs-swagger, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nMy controller code is something like this. \n\n```\n@Controller('customer')\nexport class CustomerController{\n\n constructor(private readonly customerService: CustomerService){}\n\n @Post('lookup')\n async someMethod(@Body() body:any){\n\n console.log(\"BEGIN -- CustomerController.someMethod\");\n```\n\nI am expecting to see in Swagger a place where I can input some text as a request body but instead I see this\n\nhttps://i.sstatic.net/xf3k7.png\n\n========================================\n\nTop Answer:\nAdd @ApiProperty()\n\n```\nexport class User{\n\n @ApiProperty()\n name:string\n \n}\n```\n\n========================================\n\nCode:\n```text\n@Controller('customer')\nexport class CustomerController{\n\n    constructor(private readonly customerService: CustomerService){}\n\n    @Post('lookup')\n    async someMethod(@Body() body:any){\n\n        console.log(\"BEGIN -- CustomerController.someMethod\");\n```\n\n```text\nany\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\n@Body()\n```\n\n```text\nany\n```\n\n```text\n@Body() data: Map<string, any>\n```\n\n```text\nexport class User{\n\n @ApiProperty()\n  name:string\n \n}\n```\n\n```text\n@ApiBody({description: \"body:any someMethod\"})\n@Post('lookup')\nasync someMethod(@Body() body:any){\nconsole.log(\"BEGIN -- CustomerController.someMethod\");\n}\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class CreateCatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\n```text\n@Post()\nasync create(@Body() createCatDto: CreateCatDto) {\n  //Do Stuff.\n}\n```\n\n```text\n@Post()\n@ApiBody({ type: CreateCatDto })\nasync create(@Body() createCatDto: CreateCatDto) {\n  //Do Stuff.\n}\n```\n\n```text\n@ApiProperty\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"@nestjs/swagger\",\n        \"options\": {\n          \"introspectComments\": true\n        }\n      }\n    ]\n  }\n}\n```\n\n```text\n*.dto.ts\n```\n\n```text\ncompilerOptions\n```\n\n========================================\n\nComments:\n- Are you using the Swagger Plugin?\n- in my package.json I have \"@nestjs/swagger\": \"^4.4.0\",\n- In your `nest-cli.json` are you using the swagger plugin?\n- I am not really sure what plugin means here but this is what's in my nest-cli.json\n- { \"collection\": \"@nestjs/schematics\", \"sourceRoot\": \"src\" }\n- @p0tta yes, you'll have to install package\n- Do I need to install the Swagger plugin or does it come out of the box if I have this in my package.json? \"@nestjs/swagger\": \"^4.4.0\"\n- The link to the docs in my answer clearly explains how to set up the plugin to work.\n- I tried with setting body type to an interface, still it did not work. Finally, replacing the interface as class worked. Thanks...\n- Interfaces don't exist at runtime, so there's no metadata to reflect about them.\n- I was looking for a solution to having a Request body example value in swagger ui and this was it thanks !\n- Actually - the *.dto.ts is a subtle nuance that I wasn't expecting. This helped me - I went from no success with .request-body-dto.ts to success with .request-body.dto.ts","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":161,"estimatedTokens":795}}81{"id":"stack-71557301","source":"stackoverflow","questionId":71557301,"title":"How to workraound this TypeORM error, \"EntityRepository is deprecated , use Repository.extend function instead\"?","tags":["nestjs","typeorm"],"text":"Title: How to workraound this TypeORM error, \"EntityRepository is deprecated , use Repository.extend function instead\"?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHowever, I can't find any Repository.extend method in Repository class and there's nothing about it in the documentation. How to solve this?\n\ntypeorm version: \"^0.3.0\"\n\nI'm using nest js and trying to create a custom repository.\n\n========================================\n\nTop Answer:\nWith the current version of TypeORM, it's possible to implement a custom repository in the following way utilizing DataSource.\n\n```\n// user.repository.ts\n@Injectable()\nexport class UsersRepository extends Repository {\n constructor(private dataSource: DataSource) {\n super(UsersEntity, dataSource.createEntityManager());\n }\n\n async getById(id: string) {\n return this.findOne({ where: { id } });\n }\n // ...\n}\n```\n\nThe repository is then injected into the service.\n\n```\n// user.service.ts\nexport class UserService {\n constructor(private readonly userRepository: UserRepository) {}\n\n async getById(id: string): Promise {\n return this.userRepository.getById(id);\n }\n // ...\n}\n```\n\nand the module has imports for the feature and the repository as a provider.\n\n```\n// user.module.ts\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity])],\n // ...\n ],\n providers: [UserService, UserRepository],\n // ...\n})\nexport class UserModule {}\n```\n\n========================================\n\nCode:\n```text\nnpm install @nestjs/typeorm@next\n```\n\n```text\n// typeorm-ex.decorator.ts\n\nimport { SetMetadata } from \"@nestjs/common\";\n\nexport const TYPEORM_EX_CUSTOM_REPOSITORY = \"TYPEORM_EX_CUSTOM_REPOSITORY\";\n\nexport function CustomRepository(entity: Function): ClassDecorator {\n  return SetMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, entity);\n}\n```\n\n```text\n// typeorm-ex.module.ts\n\nimport { DynamicModule, Provider } from \"@nestjs/common\";\nimport { getDataSourceToken } from \"@nestjs/typeorm\";\nimport { DataSource } from \"typeorm\";\nimport { TYPEORM_EX_CUSTOM_REPOSITORY } from \"./typeorm-ex.decorator\";\n\nexport class TypeOrmExModule {\n  public static forCustomRepository<T extends new (...args: any[]) => any>(repositories: T[]): DynamicModule {\n    const providers: Provider[] = [];\n\n    for (const repository of repositories) {\n      const entity = Reflect.getMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, repository);\n\n      if (!entity) {\n        continue;\n      }\n\n      providers.push({\n        inject: [getDataSourceToken()],\n        provide: repository,\n        useFactory: (dataSource: DataSource): typeof repository => {\n          const baseRepository = dataSource.getRepository<any>(entity);\n          return new repository(baseRepository.target, baseRepository.manager, baseRepository.queryRunner);\n        },\n      });\n    }\n\n    return {\n      exports: providers,\n      module: TypeOrmExModule,\n      providers,\n    };\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mssql',\n      ...\n      entities: [Photo],\n    }),\n    TypeOrmExModule.forCustomRepository([PhotoRepository]),\n    ...\n  ],\n  controllers: [AppController],\n  providers: [\n    AppService\n  ],\n})\nexport class AppModule { }\n```\n\n```text\n@CustomRepository(Photo)\nexport class PhotoRepository extends Repository<Photo> {\n    public async getAllPhoto() {\n        const query = this.createQueryBuilder('photo')\n            .where('photo.isPublished = :isPublished', { isPublished: true })\n        const photos = await query.getMany()\n        return photos\n    }\n}\n```\n\n```text\n9.0.0-next.2\n```\n\n```text\n0.3.6\n```\n\n```text\nexport const UserRepository = dataSource.getRepository(User).extend({...})\n```\n\n```text\nyarn add @nestjs/typeorm@next\n```\n\n```js\n@EntityRepository(Person)\n  export class PersonRepository extends Repository<Person> {...}\n```\n\n```js\n@Injectable()\n  export class PersonRepository {\n    constructor(private dataSource: DataSource) { }\n\n    exampleQueryBuilder() {\n      return this.dataSource\n          .getRepository(Person)\n          .createQueryBuilder() ...\n    }\n```\n\n```js\n@Injectable()\n  export class PersonService {\n    constructor(\n      @Inject(PersonRepository)\n      private readonly personRepository: PersonRepository,\n    ) {}\n```\n\n```text\nimport { DataSource } from 'typeorm';\nrequire('dotenv').config();\n\nexport const AppDataSource = new DataSource({\n  type: 'mongodb',\n  url: process.env.MONGO_URI,\n  useNewUrlParser: true,\n  synchronize: true,\n  logging: true,\n  database: process.env.DB_DATABASE,\n  entities: ['dist/entities/*.js'],\n  useUnifiedTopology: true,\n});\n\nAppDataSource.initialize()\n  .then(() => {\n    console.log('Data Source has been initialized!');\n  })\n  .catch((err) => {\n    console.error('Error during Data Source initialization', err);\n  });\n```\n\n```text\nimport { AppDataSource } from '@CustomDataSource';\nimport { Product } from '@Entities';\nimport { CreateProductDto, UpdateProductDto } from '@Products';\n\nconst dataSource = AppDataSource;\nexport const ProductRepository = \ndataSource.getMongoRepository(Product).extend({\nasync findOneById(id: number): Promise<Product> {\n    const product = await ProductRepository.findOne({ where: { id }});\n    return product;\n  },\nasync findMany(): Promise<Product[]> {\n    const products = await ProductRepository.find();\n    return products;\n  },\n});\n```\n\n```text\ndatasource.ts\n```\n\n```text\normconfig.js\n```\n\n```text\nTypeORMModule.forFeature([])\n```\n\n```text\nthis\n```\n\n```text\nProductRepository\n```\n\n```text\nimport { Provider, Type } from '@nestjs/common';\nimport { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';\nimport { DataSource, DataSourceOptions, Repository } from 'typeorm';\n\nexport function provideCustomRepository<T>(\n  entity: Type<T>,\n  repository: Type<Repository<T>>,\n  dataSource?: DataSource | DataSourceOptions | string\n): Provider {\n  return {\n    provide: getRepositoryToken(entity),\n    inject: [getDataSourceToken(dataSource)],\n    useFactory(dataSource: DataSource) {\n      const baseRepository = dataSource.getRepository(entity);\n      return new repository(\n        baseRepository.target,\n        baseRepository.manager,\n        baseRepository.queryRunner\n      );\n    },\n  };\n}\n```\n\n```html\n<script src=\"https://gist.github.com/rhutchison/a530d89c37f1978a48dcee4bf2418cb7.js\"></script>\n```\n\n```text\nprovideCustomRepository\n```\n\n```js\n// user.repository.ts\n@Injectable()\nexport class UsersRepository extends Repository<UsersEntity> {\n  constructor(private dataSource: DataSource) {\n    super(UsersEntity, dataSource.createEntityManager());\n  }\n\n  async getById(id: string) {\n    return this.findOne({ where: { id } });\n  }\n  // ...\n}\n```\n\n```js\n// user.service.ts\nexport class UserService {\n  constructor(private readonly userRepository: UserRepository) {}\n\n  async getById(id: string): Promise<User> {\n    return this.userRepository.getById(id);\n  }\n  // ...\n}\n```\n\n```js\n// user.module.ts\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([UserEntity])],\n    // ...\n  ],\n  providers: [UserService, UserRepository],\n  // ...\n})\nexport class UserModule {}\n```\n\n```text\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { Task } from './task.entity';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\n\n@Injectable()\nexport class TasksService {\n constructor(\n  @InjectRepository(Task)\n  private taskRepository: Repository<Task>\n ) {}\n\n async getTasksById(id: number): Promise<Task> {\n   const found = await this.taskRepository.findOne({ where: { id: id \n   }});\n }\n}\n```\n\n```text\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Task {\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column()\n  title: string;\n}\n```\n\n```text\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { DataSource, Repository } from 'typeorm';\nimport { Task } from './task.entity';\n\n@Injectable()\nexport class TasksRepository extends Repository<Task> {\n  constructor(private dataSource: DataSource) {\n    super(Task, dataSource.createEntityManager());\n  }\n\n  async getById(id: string): Promise<Task> {\n    const found = await this.findOneBy({ id });\n\n    if (!found) {\n      throw new NotFoundException(`Task with ID \"${id}\" not found`);\n    }\n\n    return found;\n  }\n}\n```\n\n```text\nimport {\n  Controller,\n  Get,\n  Param,\n} from '@nestjs/common';\nimport { TasksService } from './tasks.service';\nimport { Task } from './task.entity';\n\n@Controller('tasks')\nexport class TasksController {\n  constructor(private tasksService: TasksService) {}\n\n  @Get('/:id')\n  getTaskById(@Param('id') id: string): Promise<Task> {\n    return this.tasksService.getTaskById(id);\n  }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Task } from './task.entity';\nimport { TasksController } from './tasks.controller';\nimport { TasksRepository } from './tasks.repository';\nimport { TasksService } from './tasks.service';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Task])],\n  controllers: [TasksController],\n  providers: [TasksService, TasksRepository],\n})\nexport class TasksModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TasksModule } from './tasks/tasks.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n    TasksModule,\n    TypeOrmModule.forRoot({\n      type: 'postgres',\n      host: 'localhost',\n      port: 5432,\n      username: 'postgres',\n      password: 'postgres',\n      database: 'task-management',\n      autoLoadEntities: true,\n      synchronize: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```js\n// some-entity.repository.ts\nimport { EntityRepository, Repository } from 'typeorm';\nimport { SomeEntity } from './entities/some-entity.entity'; // Adjust path as necessary\nimport { Injectable } from '@nestjs/common';\nimport { DataSource } from 'typeorm';\n\n@Injectable()\nexport class SomeEntityRepository extends Repository<SomeEntity> {\n  constructor(private dataSource: DataSource) {\n    super();\n    this.manager = dataSource.createEntityManager();\n  }\n\n  // You can add custom repository methods here if needed\n}\n```\n\n```js\n// some-entity.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { SomeEntityController } from './controllers/some-entity.controller'; // Adjust path as necessary\nimport { SomeEntityService } from './services/some-entity.service'; // Adjust path as necessary\nimport { SomeEntityRepository } from './repositories/some-entity.repository'; // Adjust path as necessary\nimport { SomeEntity } from './entities/some-entity.entity'; // Adjust path as necessary\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([SomeEntity, SomeEntityRepository]),\n    // Other modules or imports\n  ],\n  controllers: [SomeEntityController],\n  providers: [SomeEntityService, SomeEntityRepository], // Include SomeEntityRepository as a provider if needed\n  exports: [SomeEntityRepository], // Export SomeEntityRepository if needed\n})\nexport class SomeEntityModule {}\n```\n\n```js\n// some-entity.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { SomeEntity } from './entities/some-entity.entity'; // Adjust path as necessary\nimport { SomeEntityRepository } from './repositories/some-entity.repository'; // Adjust path as necessary\n\n@Injectable()\nexport class SomeEntityService {\n  constructor(\n    @InjectRepository(SomeEntityRepository)\n    private someEntityRepository: SomeEntityRepository,\n  ) {}\n\n  // Implement service methods using someEntityRepository\n}\n```\n\n```text\nSomeEntity\n```\n\n```text\nEntityRepository\n```\n\n```text\nSomeEntity\n```\n\n```text\nRepository<SomeEntity>\n```\n\n```text\nSomeEntityRepository\n```\n\n```text\nSomeEntityRepository\n```\n\n```text\nSomeEntityService\n```\n\n```js\n@Injectable()\nexport class TaskRepository extends Repository<Task> {\n  constructor(private dataSource: DataSource) {\n    super(Task, dataSource.createEntityManager());\n  }\n\n  async createTask(createTaskDto: CreateTaskDto): Promise<Task> {\n    const { title, description } = createTaskDto;\n    const task = this.create({\n      title,\n      description,\n      status: TaskStatus.OPEN,\n    });\n    await this.save(task);\n    return task;\n  }\n}\n```\n\n```js\nexport class TasksService {\n  private tasks: Task[] = [];\n\n  constructor(@Inject(TaskRepository) private readonly taskRepository: TaskRepository) {}\n\n  async createTask(createTaskDto: CreateTaskDto): Promise<Task> {\n    return this.taskRepository.createTask(createTaskDto);\n  }\n}\n```\n\n```js\nimport { Module } from \"@nestjs/common\";\nimport { TasksController } from \"./tasks.controller\";\nimport { TasksService } from \"./tasks.service\";\nimport { TypeOrmModule } from \"@nestjs/typeorm\";\nimport { TaskRepository } from \"./dto/task.repository\";\nimport { Task } from \"./dto/task.entity\";\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Task])],\n  controllers: [TasksController],\n  providers: [TasksService, TaskRepository],\n})\nexport class TasksModule {}\n```\n\n```text\n\"@nestjs/typeorm\": \"^10.0.2\"\n```\n\n```text\n\"typeorm\": \"^0.3.20\"\n```\n\n========================================\n\nComments:\n- I guess it's better to use `typeorm@0.2` for now. Also, see this PR: github.com/nestjs/typeorm/pull/384\n- doesnt help the old implementation of extending repositories suing @Entityrepository decorator\n- To those arriving here from Google: this certainly works, but is much more complicated than this solution\n- This approach is much simpler and cleaner. It also works for those who were extending from the `AbstractRepository` in earlier versions of TypeORM.\n- Just tried this with nestjs v10.2.7, nestjs/typeorm v10.0.0 and typeorm v0.3.17 and it works. Cleanest solution to this that I've seen yet.\n- In `user.service.ts`, the constructor is missing to define the @Inject(UserRepository). It should be like this: `constructor(@Inject(UserRepository) private readonly userRepository: UserRepository) {}` Before that, I had tried following the code snippet, but it did not work until I added `@Inject(UserRepository)` by following the comment below of Zoltan Rakottyai","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":593,"estimatedTokens":3538}}82{"id":"stack-51910908","source":"stackoverflow","questionId":51910908,"title":"NestJs async httpService call","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: NestJs async httpService call\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow can I use Async/Await on `HttpService` using NestJs?\nThe below code doesn`t works:\n\n```\nasync create(data) {\n return await this.httpService.post(url, data);\n}\n```\n\n========================================\n\nTop Answer:\nAs `toPromise()` is being deprecated, you can replace it with `firstValueFrom` or `lastValueFrom`\n\nFor example:\n\n```\nconst resp = await firstValueFrom(this.http.post(`http://localhost:3000/myApi`)\n```\n\nhttps://rxjs.dev/deprecations/to-promise\n\n========================================\n\nCode:\n```text\nasync create(data) {\n    return await this.httpService.post(url, data);\n}\n```\n\n```text\nHttpService\n```\n\n```text\ncreate(data): Promise<AxiosResponse> {\n    return this.httpService.post(url, data).toPromise();\n                                           ^^^^^^^^^^^^^\n}\n```\n\n```text\nimport { firstValueFrom } from 'rxjs';\n\n// ...\n\nreturn firstValueFrom(this.httpService.post(url, data))\n```\n\n```text\nHttpModule\n```\n\n```text\nObservable\n```\n\n```text\nPromise\n```\n\n```text\nHttpService\n```\n\n```text\nObservable<AxiosResponse<T>>\n```\n\n```text\nPromise\n```\n\n```text\nObservable\n```\n\n```text\nreturn await\n```\n\n```text\ntoPromise\n```\n\n```text\nfirstValueFrom\n```\n\n```text\nobservablSource.subscribe(\n   data => { ... },\n   failure => { ... },\n   compelete => { ... }\n)\n```\n\n```text\nconst data: Observable<any>;\ndata.from([\n   {\n      id: 1,\n      name: 'mahdi'\n   }, \n   {\n      id: 2,\n      name: 'reza'\n   },\n ])\n```\n\n```text\ndata.toPromise();\n```\n\n```text\nasync userList( URL: string | URLPattern ) {\n    const userList = await this.http.get<any>( URL ).toPromise();\n    ...\n }\n```\n\n```text\nasync getAuthToken() {\n    const payload = {\n      \"SCOPE\": this.configService.get<string>('SCOPE'),\n      \"EMAIL_ID\": this.configService.get<string>('EMAIL_ID'),\n      \"PASSWORD\": this.configService.get<string>('PASSWORD'),\n    };\n    const url = this.configService.get<string>('AUTHTOKEN_URL')\n    const response = await this.httpService.post(\n      url,\n      payload\n    ).toPromise();\n    console.log(response.data);\n    return response.data;\n  }\n```\n\n```js\nconst resp = await firstValueFrom(this.http.post(`http://localhost:3000/myApi`)\n```\n\n```text\ntoPromise()\n```\n\n```text\nfirstValueFrom\n```\n\n```text\nlastValueFrom\n```\n\n========================================\n\nComments:\n- Doesn't work anymore, toPromise is deprecated\n- Thanks for your help Mahdi! That was what I did!\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review\n- Changed the answer to include the main parts here :)","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":168,"estimatedTokens":693}}83{"id":"stack-58780119","source":"stackoverflow","questionId":58780119,"title":"Why I am getting the error \"cannot determine GraphQL output type\"?","tags":["node.js","typescript","graphql","nestjs"],"text":"Title: Why I am getting the error \"cannot determine GraphQL output type\"?\nTags: node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to create simple appliaction with **Nest.js**, **GraphQL** and **MongoDB**. I wnated to use **TypeORM** and **TypeGraphql** to generate my schema and make a connection with localhost databasebut but i can not run my server with `nest start` becouse I am getting this error:\n\n UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for getArticles\n\nI have no idea why i am getting this error. My class `ArticleEntity` does't has any not primary types, so there should not be any problem. I tried to remove `() => ID` from `@Field()` decorator of filed `_id` of `ArticleEntity` class but it didn't helped\n\n**ArticleResolver**\n\n```\n@Resolver(() => ArticleEntity)\nexport class ArticlesResolver {\n constructor(\n private readonly articlesService: ArticlesService) {}\n\n @Query(() => String)\n async hello(): Promise {\n return 'Hello world';\n }\n\n @Query(() => [ArticleEntity])\n async getArticles(): Promise {\n return await this.articlesService.findAll();\n }\n\n}\n```\n\n**ArticleService**\n\n```\n@Injectable()\nexport class ArticlesService {\n constructor(\n @InjectRepository(ArticleEntity)\n private readonly articleRepository: MongoRepository,\n ) {}\n\n async findAll(): Promise {\n return await this.articleRepository.find();\n }\n}\n```\n\n**ArticleEntity**\n\n```\n@Entity()\nexport class ArticleEntity {\n @Field(() => ID)\n @ObjectIdColumn()\n _id: string;\n\n @Field()\n @Column()\n title: string;\n\n @Field()\n @Column()\n description: string;\n}\n```\n\n**ArticleDTO**\n\n```\n@InputType()\nexport class CreateArticleDTO {\n @Field()\n readonly title: string;\n\n @Field()\n readonly description: string;\n}\n```\n\nIf you need anything else comment\n\n========================================\n\nTop Answer:\nFor anyone who gets this error and uses enums, you may be missing a call to `registerEnumType`.\n\n========================================\n\nCode:\n```js\n@Resolver(() => ArticleEntity)\nexport class ArticlesResolver {\n  constructor(\n    private readonly articlesService: ArticlesService) {}\n\n  @Query(() => String)\n  async hello(): Promise<string> {\n    return 'Hello world';\n  }\n\n  @Query(() => [ArticleEntity])\n  async getArticles(): Promise<ArticleEntity[]> {\n    return await this.articlesService.findAll();\n  }\n\n}\n```\n\n```js\n@Injectable()\nexport class ArticlesService {\n  constructor(\n    @InjectRepository(ArticleEntity)\n    private readonly articleRepository: MongoRepository<ArticleEntity>,\n  ) {}\n\n  async findAll(): Promise<ArticleEntity[]> {\n    return await this.articleRepository.find();\n  }\n}\n```\n\n```js\n@Entity()\nexport class ArticleEntity {\n  @Field(() => ID)\n  @ObjectIdColumn()\n  _id: string;\n\n  @Field()\n  @Column()\n  title: string;\n\n  @Field()\n  @Column()\n  description: string;\n}\n```\n\n```js\n@InputType()\nexport class CreateArticleDTO {\n  @Field()\n  readonly title: string;\n\n  @Field()\n  readonly description: string;\n}\n```\n\n```text\nnest start\n```\n\n```text\nArticleEntity\n```\n\n```text\n() => ID\n```\n\n```text\n@Field()\n```\n\n```text\n_id\n```\n\n```text\nArticleEntity\n```\n\n```text\n@Entity()\n@ObjectType()\nexport class ArticleEntity {\n  ...\n}\n```\n\n```text\nArticleEntity\n```\n\n```text\n@ObjectType\n```\n\n```js\n@ObjectType()\n@Schema({ versionKey: `version` })\nexport class User {\n    @Field()\n    _id: string\n\n    @Prop({ required: true })\n    @Field()\n    email: string\n\n    @Prop({ required: true })\n    password: string\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User)\n```\n\n```js\n@Query((returns) => User)\nasync user(): Promise<UserDocument> {\n    const newUser = new this.userModel({\n        id: ``,\n        email: `test@test.com`,\n        password: `abcdefg`,\n    })\n    return await newUser.save()\n}\n```\n\n```text\nQuery\n```\n\n```text\n@Query((returns) => UserSchema)\n```\n\n```text\n@Query((returns) => User)\n```\n\n```js\nimport { ObjectType } from '@nestjs/graphql';\n```\n\n```text\n@ObjectType\n```\n\n```text\ntype-graphql\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\nregisterEnumType\n```\n\n```text\nexport class A{\nid: number;\nname:string;\nchildProperty: B\n. . . . .\n}\n\n\nexport class B{\n prop1:string;\n prop2:string;\n}\n```\n\n```text\nObjectType()\nexport class User {\n```\n\n```text\n@ObjectType()\nexport class User {\n```\n\n```text\n@\n```\n\n```text\nObjectType\n```\n\n```text\ntype-graphql\n```\n\n========================================\n\nComments:\n- Yes i forgot about this decorator, such a small thing, such a big mistake. Thank you mate\n- Excellent insight; this is what I was missing!","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":295,"estimatedTokens":1131}}84{"id":"stack-49429241","source":"stackoverflow","questionId":49429241,"title":"Nest.js: Global AuthGuard but with exceptions","tags":["nestjs"],"text":"Title: Nest.js: Global AuthGuard but with exceptions\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to register my AuthenticationGuard, which checks for Authentication, globally on my application, so that by default all routes require authentication.\n\n```\nconst authGuard = app\n .select(AuthModule)\n .get(AuthGuard);\napp.useGlobalGuards(authGuard);\n```\n\nWhat is the best/nest.js way to add route exceptions, so that anonymous routes can also be implemented?\n\n========================================\n\nTop Answer:\nYou can actually set metadata for the global `AuthGuard` so it can determine if it should allow an unauthorized request.\n\ne.g.\n\nSet Global Auth Guard\n\n```\nimport { Module } from '@nestjs/common';\n import { APP_GUARD } from '@nestjs/core';\n import { AuthGuard } from './auth.guard';\n \n @Module({\n providers: [\n {\n provide: APP_GUARD,\n useClass: AuthGuard,\n },\n ],\n })\n export class AppModule {}\n```\n\nUse `SetMetadata` to pass in data to the `AuthGuard`\n\n```\nimport { SetMetadata } from '@nestjs/common';\n // Convienience Function\n const AllowUnauthorizedRequest = () => SetMetadata('allowUnauthorizedRequest', true);\n @Controller()\n export class AppController {\n \n @Get('my-unauthorized-path')\n @AllowUnauthorizedRequest()\n myHandler () {\n return { unauthorized: true };\n }\n \n }\n```\n\nUse data passed in from `SetMetadata` to determine if unauthorized request is allowed.\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\n import { Reflector } from '@nestjs/core';\n import { validateRequest } from './validateRequest' // your custom implementation\n \n @Injectable()\n export class AuthGuard implements CanActivate {\n \n constructor(private reflector: Reflector) {}\n canActivate(context: ExecutionContext) {\n const request = context.switchToHttp().getRequest();\n const allowUnauthorizedRequest = this.reflector.get('allowUnauthorizedRequest', context.getHandler());\n return allowUnauthorizedRequest || validateRequest(request);\n }\n \n }\n```\n\n========================================\n\nCode:\n```text\nconst authGuard = app\n    .select(AuthModule)\n    .get(AuthGuard);\napp.useGlobalGuards(authGuard);\n```\n\n```text\nuseGlobalGuards\n```\n\n```text\nAuthGuard\n```\n\n```js\nimport { Module } from '@nestjs/common';\n    import { APP_GUARD } from '@nestjs/core';\n    import { AuthGuard } from './auth.guard';\n    \n    @Module({\n      providers: [\n        {\n          provide: APP_GUARD,\n          useClass: AuthGuard,\n        },\n      ],\n    })\n    export class AppModule {}\n```\n\n```js\nimport { SetMetadata } from '@nestjs/common';\n    // Convienience Function\n    const AllowUnauthorizedRequest = () => SetMetadata('allowUnauthorizedRequest', true);\n    @Controller()\n    export class AppController {\n    \n      @Get('my-unauthorized-path')\n      @AllowUnauthorizedRequest()\n      myHandler () {\n        return { unauthorized: true };\n      }\n    \n    }\n```\n\n```js\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\n    import { Reflector } from '@nestjs/core';\n    import { validateRequest } from './validateRequest' // your custom implementation\n    \n    @Injectable()\n    export class AuthGuard implements CanActivate {\n    \n      constructor(private reflector: Reflector) {}\n      canActivate(context: ExecutionContext) {\n        const request = context.switchToHttp().getRequest();\n        const allowUnauthorizedRequest = this.reflector.get<boolean>('allowUnauthorizedRequest', context.getHandler());\n        return allowUnauthorizedRequest || validateRequest(request);\n      }\n    \n    }\n```\n\n```text\nAuthGuard\n```\n\n```text\nSetMetadata\n```\n\n```text\nAuthGuard\n```\n\n```text\nSetMetadata\n```\n\n========================================\n\nComments:\n- One should probably look at the upvoted answer below (or above) by @jonathan002, instead of mine\n- Just one thing to clarify, you can have the `AllowUnauthorizedRequest` decorator in a separate file (in a shared folder for example). Then, you just import and add `AllowUnauthorizedRequest` to the requests you want to exclude.\n- To make this work when set on controllers use `this.reflector.getAllAndOverride` and specify both `context.getHandler` as well as `context.getClass`; see docs docs.nestjs.com/fundamentals/execution-context","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":169,"estimatedTokens":1061}}85{"id":"stack-62371711","source":"stackoverflow","questionId":62371711,"title":"how to use optional url parameters with NestjS","tags":["node.js","typescript","express","nestjs","fastify"],"text":"Title: how to use optional url parameters with NestjS\nTags: node.js, typescript, express, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm trying to replace our current backend service using Nestjs library, \nhowever, I want to create a route with 2 optional parameters in the URL something like : \n\n`/route/:param1/config/:OptionalParam3?/:OptionalParam3?` \n\nthat means the route should catch : \n\n- `route/aa/config`\n\n- `route/aa/config/bb`\n\n- `route/aa/config/bb/cc`\n\nhow can I achieve that, I have tried to use `?` and `()` but it's not working well.\n\n========================================\n\nTop Answer:\nIf you are looking for how to annotate an optional query parameter, you can do it like so:\n\n```\n@ApiQuery({\n name: \"myParam\",\n type: String,\n description: \"A parameter. Optional\",\n required: false\n})\nasync myEndpoint(\n @Query(\"myParam\") myParam?: string\n): Promise { \n [...] \n}\n```\n\n========================================\n\nCode:\n```text\n/route/:param1/config/:OptionalParam3?/:OptionalParam3?\n```\n\n```text\nroute/aa/config\n```\n\n```text\nroute/aa/config/bb\n```\n\n```text\nroute/aa/config/bb/cc\n```\n\n```text\n?\n```\n\n```text\n()\n```\n\n```text\n/route/:param1/config/:OptionalParam3?/:OptionalParam3?\n```\n\n```text\n/route/:param1/config/:OptionalParam3?/:OptionalParam4?\n```\n\n```text\n@ApiQuery({\n  name: \"myParam\",\n  type: String,\n  description: \"A parameter. Optional\",\n  required: false\n})\nasync myEndpoint(\n  @Query(\"myParam\") myParam?: string\n): Promise<blah> { \n  [...] \n}\n```\n\n```text\n@Get()\nasync getAll(@Query('someParameter') someParameter?: number) {\n  return this.service.getAll(someParameter);\n}\n```\n\n```text\ngetAll(someParameter?: number) {\n  return this.http.get(`apiUrl/controllerAddress?someParameter=${someParameter}`\n  );\n}\n```\n\n```text\n@Query\n```\n\n```text\n@Get()\n  async getExample(\n    @Query('param_name') param_name?: string,\n    @Query('param_name2') param_name2?: string,\n  ): Promise<JSON> {\n    const params = {\n      param_name,\n      param_name2,\n    };\n\n    return this.appService.getExampleService(params);\n  }\n}\n```\n\n```text\n@ApiQuery({\n  name: \"myBoolean\",\n  type: Boolean,\n  description: \"Just an optional boolean\",\n  required: false\n})\nasync hello(\n  @Query(\"myBoolean\", new ParseBoolPipe({ optional: true })) myBoolean?: boolean\n): Promise<HelloDto> { \n  return this.myService.hello(myBoolean);\n}\n```\n\n========================================\n\nComments:\n- `@Vinayak Sarawagi` your approach makes sense. But for the sake of url readability for service users sometimes it worth to keep longer url, but with a short option\n- not working for me.. not sure why getting the 404 Error.. my URL: resource1/:id1/resource2/:id2?\n- figured another way as solution used something like this in NestJS @Delete([ 'resource1/:id1/resource2/:id2', 'resource1/:id1/resource2' ])\n- This approach is correct but doesn't consider the project is using NestJS, which offers a lot more readability\n- @Cppcrusaders - The approach is more readable and easy to understand. Although for multiple optional params I prefer to go with the QueryParams.\n- This worked to me, but I could make it work with a custom path.\n- I tried this way but the api always returned 200 status without any content\n- The only way that worked for me in Swagger.\n- github.com/nestjs/swagger/issues/30#issuecomment-1250550921\n- This will only make the function argument optional.\n- I thought that was the point of the question","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":150,"estimatedTokens":853}}86{"id":"stack-63872093","source":"stackoverflow","questionId":63872093,"title":"Accept form-data in Nest.js","tags":["nestjs","body-parser","req"],"text":"Title: Accept form-data in Nest.js\nTags: nestjs, body-parser, req\nSource: Stack Overflow\n\nQuestion:\nI have written auth routes in Nestjs and wanted to use it with the form-data. I got it working with URL-encoded-form-data, JSON, text, but not receiving anything in the body when I use form-data and really want it to work with form-data as on the front-end I am hitting the route with form-data. I have tried every way I could find on the web, but none of them helped me in this case. so after hours of searching and trying when I didn't get any lead I am posting my question here.\nAny Kind of Help is appreciated.\n\nCode of signup endpoint:\n\n```\n@Post('native/loginWithPhone')\nasync loginWithPhoneNative(@Body() { phone }: LoginWithPhoneDto) {\n return await this.securityCodeService.sendSecurityCodeNative(phone, 'otp');\n}\n\n@Post('signup')\nasync signup(@Request() req, @Body() body) {\n console.log(req)\n console.log(body)\n return await req.body\n // return await this.authService.signupWithEmail({\n // email,\n // password,\n // dob,\n // role: process.env.ROLE_USER,\n // });\n}\n```\n\n`Main.ts` configurations :\n\n```\nimport * as bodyParser from 'body-parser'\nimport * as multer from 'multer';\nglobal. fetch = require('node-fetch');\n\nasync function bootstrap() {\n require('dotenv').config();\n\n const app = await NestFactory.create(AppModule, {\n bodyParser: true,\n});\n\nawait app.init();\napp.enableCors();\n\napp.use(multer)\napp.use(bodyParser.urlencoded({extended: true}))\napp.use(bodyParser.text({type: 'text/html'}))\napp.use(bodyParser.json())\napp.useGlobalPipes(new ValidationPipe());\n```\n\nempty body I am getting on postman\nhttps://i.sstatic.net/rxyDY.png\n\n========================================\n\nTop Answer:\nI recommend the npm package named \"nestjs-form-data\".\n\nYou only need use npm install nestjs-form-data or yarn add nestjs-form-data respectively.\n\nThe code that solve the problem is something like that:\n\nThe module:...\n\n```\n@Module({\n imports: [\n NestjsFormDataModule.config({ storage: MemoryStoredFile }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {\n}\n```\n\nThe controller:...\n\n```\n@Controller()\nexport class NestjsFormDataController {\n\n @Post('load')\n @FormDataRequest({storage: MemoryStoredFile})\n getHello(@Body() testDto: FormDataTestDto): void {\n console.log(testDto);\n }\n}\n```\n\nYou can make validations like that:\n\n```\nimport { FileSystemStoredFile, HasMimeType, IsFile, MaxFileSize } from 'nestjs-form-data';\n\nexport class FormDataTestDto {\n\n @IsFile()\n @MaxFileSize(1e6)\n @HasMimeType(['image/jpeg', 'image/png'])\n avatar: FileSystemStoredFile;\n\n}\n```\n\n========================================\n\nCode:\n```js\n@Post('native/loginWithPhone')\nasync loginWithPhoneNative(@Body() { phone }: LoginWithPhoneDto) {\n    return await this.securityCodeService.sendSecurityCodeNative(phone, 'otp');\n}\n\n@Post('signup')\nasync signup(@Request() req, @Body() body) {\n    console.log(req)\n    console.log(body)\n    return await req.body\n    // return await this.authService.signupWithEmail({\n    //   email,\n    //   password,\n    //   dob,\n    //   role: process.env.ROLE_USER,\n    // });\n}\n```\n\n```js\nimport * as bodyParser from 'body-parser'\nimport * as multer from 'multer';\nglobal. fetch = require('node-fetch');\n\nasync function bootstrap() {\n    require('dotenv').config();\n\n    const app = await NestFactory.create(AppModule, {\n    bodyParser: true,\n});\n\nawait app.init();\napp.enableCors();\n\napp.use(multer)\napp.use(bodyParser.urlencoded({extended: true}))\napp.use(bodyParser.text({type: 'text/html'}))\napp.use(bodyParser.json())\napp.useGlobalPipes(new ValidationPipe());\n```\n\n```text\nMain.ts\n```\n\n```ts\n@Post('signup')\n@UseInterceptors(FileInterceptor('<name of file here - asdasd in your screenshot>'))\nsignup(@UploadedFile() file, @Body() body) {\n  console.log(file);\n  console.log(body);\n}\n```\n\n```text\nmultipart/form-data\n```\n\n```text\nFileInterceptor\n```\n\n```js\n@Module({\n  imports: [\n    NestjsFormDataModule.config({ storage: MemoryStoredFile }),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {\n}\n```\n\n```js\n@Controller()\nexport class NestjsFormDataController {\n\n\n  @Post('load')\n  @FormDataRequest({storage: MemoryStoredFile})\n  getHello(@Body() testDto: FormDataTestDto): void {\n    console.log(testDto);\n  }\n}\n```\n\n```js\nimport { FileSystemStoredFile, HasMimeType, IsFile, MaxFileSize } from 'nestjs-form-data';\n\n\nexport class FormDataTestDto {\n\n  @IsFile()\n  @MaxFileSize(1e6)\n  @HasMimeType(['image/jpeg', 'image/png'])\n  avatar: FileSystemStoredFile;\n\n}\n```\n\n```text\nimport { Controller, Post, UploadedFiles, UseInterceptors, Body, Get } from '@nestjs/common';\nimport { FilesInterceptor } from '@nestjs/platform-express';\n\n@Controller('api/portal/file')\nexport class GCPController {\n  constructor(private gcpService: GCPService) {}\n\n  @Post('/multiple')\n  @UseInterceptors(FilesInterceptor('files'))\n  async uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>, @Body() body: any) {\n    console.log('body :', body);\n    const req: FileDataReq = {\n      files,\n      ...body,\n    };\n    return req;\n  }\n}\n```\n\n```text\n@Post(\"register\")\n@UseInterceptors(NoFilesInterceptor())\nasync register(\n@Body() body: any,\n@Res() res: Response,\n@Req() req: Request\n)\n```\n\n```text\nconst app = await NestFactory.create(AppModule, {\n    rawBody: true,\n    cors: true,\n    bodyParser: true,\n    });\n```\n\n========================================\n\nComments:\n- This question should include the actual code instead of images of code.\n- If I dont need a file name, the FileInterceptor still need a name string. Is it the best practice if put any string name here in FileInterceptor in this case?\n- To accept multipart/form-data but not allow any files to be uploaded, use the NoFilesInterceptor. Learn more from here\n- How could someone go about validating the form data being sent from the User? I can't seem to find a way to set up a validator pipe that can be applied on the file field + the additional fields that may have been included in the body.\n- How do you validate nested dtos?","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":261,"estimatedTokens":1508}}87{"id":"stack-65636980","source":"stackoverflow","questionId":65636980,"title":"How to test a nestjs service by passing in a ConfigService with custom values?","tags":["typescript","dependency-injection","nestjs","launchdarkly"],"text":"Title: How to test a nestjs service by passing in a ConfigService with custom values?\nTags: typescript, dependency-injection, nestjs, launchdarkly\nSource: Stack Overflow\n\nQuestion:\nI've created a service, and the module for it looks like this:\n\n**launchdarkly.module.ts**\n\n```\n@Module({\n providers: [LaunchdarklyService],\n exports: [LaunchdarklyService],\n imports: [ConfigService],\n})\nexport class LaunchdarklyModule {}\n```\n\n(this service/module is to let the application use LaunchDarkly feature-flagging)\n\nI'm happy to show the service-implementation if you'd like, but to keep this question shorter I skipped it. The important point is that this service imports the `ConfigService` (which it uses to grab the LaunchDarkly SDK key).\n\nBut how can I test the `Launchdarkly` service? It reads a key from `ConfigService` so I want to write tests where `ConfigService` has various values, but after hours of trying I can't figure out how to configure `ConfigService` in a test.\n\nHere's the test:\n\n**launchdarkly.service.spec.ts**\n\n```\ndescribe('LaunchdarklyService', () => {\n let service: LaunchdarklyService;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [LaunchdarklyService],\n imports: [ConfigModule],\n }).compile();\n\n service = module.get(LaunchdarklyService);\n });\n\n it(\"should not create a client if there's no key\", async () => {\n // somehow I need ConfigService to have key FOO=undefined for this test\n expect(service.client).toBeUndefined();\n });\n\n it(\"should create a client if an SDK key is specified\", async () => {\n // For this test ConfigService needs to specify FOO=123\n expect(service.client).toBeDefined();\n });\n})\n```\n\nI'm open for any non-hacky suggestions, I just want to feature-flag my application!\n\n========================================\n\nTop Answer:\nYou can get a cleaner syntax using the `forFeature` method provided by ConfigModule.\n\nIt accepts an async function that needs to return an object (in your case, your Env object).\n\nThe advantage of using the `forFeature` method is that you can register a partial object so you won't need to worry about other variables (or doing a lot of ifs).\n\n```\nbeforeEach(async () => {\n const moduleRef = await Test.createTestingModule({\n imports: [\n ConfigModule.forFeature(async () => ({\n ANY_KEY_YOU_WANT: 'Any_Value'\n }))\n ],\n providers: [AnyService]\n }).compile()\n\n service = moduleRef.get(AnyService)\n})\n```\n\n========================================\n\nCode:\n```js\n@Module({\n  providers: [LaunchdarklyService],\n  exports: [LaunchdarklyService],\n  imports: [ConfigService],\n})\nexport class LaunchdarklyModule {}\n```\n\n```js\ndescribe('LaunchdarklyService', () => {\n  let service: LaunchdarklyService;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [LaunchdarklyService],\n      imports: [ConfigModule],\n    }).compile();\n\n    service = module.get<LaunchdarklyService>(LaunchdarklyService);\n  });\n\n  it(\"should not create a client if there's no key\", async () => {\n    // somehow I need ConfigService to have key FOO=undefined for this test\n    expect(service.client).toBeUndefined();\n  });\n\n  it(\"should create a client if an SDK key is specified\", async () => {\n    // For this test ConfigService needs to specify FOO=123\n    expect(service.client).toBeDefined();\n  });\n})\n```\n\n```text\nConfigService\n```\n\n```text\nLaunchdarkly\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```js\ndescribe('LaunchdarklyService', () => {\n  let service: LaunchdarklyService;\n  let config: ConfigService;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [LaunchdarklyService, {\n        provide: ConfigService,\n        useValue: {\n          get: jest.fn((key: string) => {\n            // this is being super extra, in the case that you need multiple keys with the `get` method\n            if (key === 'FOO') {\n              return 123;\n            }\n            return null;\n          })\n        }\n      ],\n    }).compile();\n\n    service = module.get<LaunchdarklyService>(LaunchdarklyService);\n    config = module.get<ConfigService>(ConfigService);\n  });\n\n  it(\"should not create a client if there's no key\", async () => {\n    // somehow I need ConfigService to have key FOO=undefined for this test\n    // we can use jest spies to change the return value of a method\n    jest.spyOn(config, 'get').mockReturnedValueOnce(undefined);\n    expect(service.client).toBeUndefined();\n  });\n\n  it(\"should create a client if an SDK key is specified\", async () => {\n    // For this test ConfigService needs to specify FOO=123\n    // the pre-configured mock takes care of this case\n    expect(service.client).toBeDefined();\n  });\n})\n```\n\n```text\nLaunchdarklyService\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\nCustom Provider\n```\n\n```text\nimports: [CommonModule,ConfigModule.forRoot({\n                ignoreEnvVars: true,\n                ignoreEnvFile: true,\n                load: [() => ({ IntersectionOptions: { number_of_decimal_places: '3' }})],\n            })],\n```\n\n```js\nimport { CONFIGURATION_TOKEN } from '@nestjs/config/dist/config.constants';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\n@Injectable()\nexport class TestConfigService {\n  private initialConfig: Record<string, any>;\n  constructor(\n    @Optional()\n    @Inject(CONFIGURATION_TOKEN)\n    private internalConfig: Record<string, any> = {},\n  ) {\n    this.initialConfig = internalConfig;\n  }\n\n  get(key: string, def: any) {\n    const result = findByPath(this.internalConfig, key);\n    return result || def;\n  }\n\n  set(key: string, val: any) {\n    assignRawDataTo(this.internalConfig, { [key]: val });\n  }\n\n  reset() {\n    this.internalConfig = this.initialConfig;\n  }\n}\n```\n\n```js\nreturn Test.createTestingModule({\n    imports: [\n        ConfigModule.forRoot({\n            load: [\n                 () => import('./test.config').then((module) => module.default),\n             ],\n             isGlobal: true,\n         }),\n      ],\n}).overrideProvider(ConfigService)\n    .useClass(TestConfigService);\n```\n\n```text\nfindByPath\n```\n\n```text\nassignRawDataTo\n```\n\n```text\nbeforeEach(async () => {\n  const moduleRef = await Test.createTestingModule({\n    imports: [\n      ConfigModule.forFeature(async () => ({\n        ANY_KEY_YOU_WANT: 'Any_Value'\n      }))\n    ],\n    providers: [AnyService]\n  }).compile()\n\n  service = moduleRef.get<AnyService>(AnyService)\n})\n```\n\n```text\nforFeature\n```\n\n```text\nforFeature\n```\n\n```text\nconst module = await Test.createTestingModule({\n  imports: [\n    CacheModule.register({ isGlobal: true, ttl: 60000 }),\n    ConfigModule.forRoot({\n      load: Configs, // imported from another file\n      ignoreEnvFile: false,\n      isGlobal: true,\n      cache: true,\n      envFilePath: [\".env\"],\n    }),\n  ],\n  providers: [ConfigService],\n})\n  .overrideProvider(PinoLogger)\n  .useValue({\n    info: jest.fn(() => Promise.resolve(null)),\n  })\n  .compile();\n```\n\n```text\nconst module = await Test.createTestingModule({\n  imports: [CacheModule.register({ isGlobal: true, ttl: 60000 })],\n  providers: [\n    {\n      provide: configService,\n      useValue: {\n        get: jest.fn(() =>\n          Promise.resolve({\n            VARIABLE_NAME: VALUE,\n          })\n        ),\n      },\n    },\n  ],\n})\n  .overrideProvider(PinoLogger)\n  .useValue({\n    info: jest.fn(() => Promise.resolve(null)),\n  })\n  .compile();\n```\n\n========================================\n\nComments:\n- Thanks! The `jest.spyOn(config, 'get').mockReturnValueOnce` results in `Error: Cannot spyOn on a primitive value; undefined given`, but the core `useValue:{get: ...` pattern works.\n- Oh whoops, forgot to add a line in the `beforeEach`. I'll make an edit for that\n- I was just wondering we can't reach the actual ConfigService ?\n- @katmanco you could use the actual `ConfigService`, but I find using mocks more reliable for unit tests\n- This is the cleanest of the solutions because it doesn't break the `ConfigService` contract. The solutions that override `get` will break if/when `getOrThrow` is called.","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":327,"estimatedTokens":2036}}88{"id":"stack-68145372","source":"stackoverflow","questionId":68145372,"title":"Cannot find module '@nestjs/core' or its corresponding type declarations","tags":["nestjs"],"text":"Title: Cannot find module '@nestjs/core' or its corresponding type declarations\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nCouple of weeks ago I installed NestJS globally on my computer.\nNow I'm coming back to that, to start learning.\n\nSo I created new project with comand:\n\n```\nnest new ./\n```\n\nIt generated all the files, but when I try to run this application with command:\n\n```\nnest start\n```\n\nI expected this template project to start but there are errors with importing paths?\nIs this due to version of my installed Nest or something?\n\nErrors on the screen:\nhttps://i.sstatic.net/OLBnT.png\n\nVersion of my Nest:\n`7.5.6`\n\nPackage.json:\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^7.6.13\",\n \"@nestjs/core\": \"^7.6.13\",\n \"@nestjs/platform-express\": \"^7.6.13\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^3.0.2\",\n \"rxjs\": \"^6.6.6\"\n },\n \"devDependencies\": {\n \"@nestjs/cli\": \"^7.5.6\",\n \"@nestjs/schematics\": \"^7.2.7\",\n \"@nestjs/testing\": \"^7.6.13\",\n \"@types/express\": \"^4.17.11\",\n \"@types/jest\": \"^26.0.20\",\n \"@types/node\": \"^14.14.31\",\n \"@types/supertest\": \"^2.0.10\",\n \"@typescript-eslint/eslint-plugin\": \"^4.15.2\",\n \"@typescript-eslint/parser\": \"^4.15.2\",\n \"eslint\": \"^7.20.0\",\n \"eslint-config-prettier\": \"^8.1.0\",\n \"eslint-plugin-prettier\": \"^3.3.1\",\n \"jest\": \"^26.6.3\",\n \"prettier\": \"^2.2.1\",\n \"supertest\": \"^6.1.3\",\n \"ts-jest\": \"^26.5.2\",\n \"ts-loader\": \"^8.0.17\",\n \"ts-node\": \"^9.1.1\",\n \"tsconfig-paths\": \"^3.9.0\",\n \"typescript\": \"^4.1.5\"\n },\n```\n\n========================================\n\nTop Answer:\nRun\n\n```\nnpm i --save @nestjs/config\n```\n\nReference: https://docs.nestjs.com/techniques/configuration\n\n========================================\n\nCode:\n```text\nnest new ./\n```\n\n```text\nnest start\n```\n\n```text\n\"dependencies\": {\n    \"@nestjs/common\": \"^7.6.13\",\n    \"@nestjs/core\": \"^7.6.13\",\n    \"@nestjs/platform-express\": \"^7.6.13\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^6.6.6\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^7.5.6\",\n    \"@nestjs/schematics\": \"^7.2.7\",\n    \"@nestjs/testing\": \"^7.6.13\",\n    \"@types/express\": \"^4.17.11\",\n    \"@types/jest\": \"^26.0.20\",\n    \"@types/node\": \"^14.14.31\",\n    \"@types/supertest\": \"^2.0.10\",\n    \"@typescript-eslint/eslint-plugin\": \"^4.15.2\",\n    \"@typescript-eslint/parser\": \"^4.15.2\",\n    \"eslint\": \"^7.20.0\",\n    \"eslint-config-prettier\": \"^8.1.0\",\n    \"eslint-plugin-prettier\": \"^3.3.1\",\n    \"jest\": \"^26.6.3\",\n    \"prettier\": \"^2.2.1\",\n    \"supertest\": \"^6.1.3\",\n    \"ts-jest\": \"^26.5.2\",\n    \"ts-loader\": \"^8.0.17\",\n    \"ts-node\": \"^9.1.1\",\n    \"tsconfig-paths\": \"^3.9.0\",\n    \"typescript\": \"^4.1.5\"\n  },\n```\n\n```text\n7.5.6\n```\n\n```text\nnpm install @nestjs/common\nnpm install @nestjs/core\n```\n\n```text\nnpm install @nestjs/mapped-types\n```\n\n```text\nCannot find module '@nestjs/mapped-types' or its corresponding type declarations.\n```\n\n```text\nnpm i --save @nestjs/config\n```\n\n```text\ncp package.json build/package.json && cd build && npm install --only=production\n```\n\n```text\nnpm uninstall @nestjs/core @nestjs/common @nestjs/microservices @nestjs/platform-express\n```\n\n```text\nnpm i @nestjs/core@9.1.1 @nestjs/common@9.1.1 @nestjs/microservices@9.1.1 @nestjs/platform-express@9.1.1*\n```\n\n```text\n@nestjs/*\n```\n\n```text\nyarn.lock\n```\n\n```text\nyarn install\n```\n\n```text\nnpm i\n```\n\n```text\nnpm --install\n```\n\n```text\nnpm i\n```\n\n```text\nnpm --install\n```\n\n========================================\n\nComments:\n- `nest new` should install dependencies for you. But just in case, can you run your package manager of choice's install command?\n- same issue but i'm using yarn 3x and want to use Plug 'N play but somehow it still requires me to do this and get the node_module directory before it works :(\n- I installed these packages, but I encountered a problem after installing them. When I cut whole the import line and paste it again from scratch, it worked for me. :D\n- The comment by Mohammad B๐Ÿ‘†๐Ÿผactually worked for me. IDK why tho &#175;\\_(ใƒ„)_/&#175;\n- You're right. And how do you resolve this?\n- This was the only suggestion that really worked, with just some small adjustment to the version, thanks! What worked for me: pnpm i @nestjs/axios@3.0.1 @nestjs/config@3.1.1 @nestjs/swagger@7.1.14 @nestjs/core@9.1.1 @nestjs/common@9.1.1 @nestjs/microservices@9.1.1 @nestjs/platform-express@9.1.1\n- Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answersโ€”including one that has been extensively validated by the community. Are you certain your approach hasnโ€™t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers arenโ€™t sufficient.** Can you kindly edit your answer to offer an explanation?","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":190,"estimatedTokens":1198}}89{"id":"stack-60555003","source":"stackoverflow","questionId":60555003,"title":"Getting an error on dockerising nest.js application","tags":["docker","nestjs"],"text":"Title: Getting an error on dockerising nest.js application\nTags: docker, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am working on a Nest.js application and this is the Dockerfile that we have. When I run this I am getting an error on the `npm run build` step in docker.\nThis is the build task in package.json.\n`\"build\": \"nest build\"`\n\n```\nsh: nest: not found\nnpm ERR! code ELIFECYCLE\nnpm ERR! syscall spawn\nnpm ERR! file sh\nnpm ERR! errno ENOENT\nnpm ERR! atom-qbuilder-api@0.0.1 build: `nest build`\nnpm ERR! spawn ENOENT\nnpm ERR! \nnpm ERR! Failed at the atom-qbuilder-api@0.0.1 build script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\nDockerfile\n\n```\n# Build\nFROM node:8-alpine as builder\n\nCOPY package.json /usr/src/atom/package.json\nCOPY package-lock.json /usr/src/atom/package-lock.json\nWORKDIR /usr/src/atom\n\n# Install dependencies\nRUN npm install --production --loglevel warn\n\nARG APPLICATION\nARG BRANCH\nARG BUILD_NUMBER\nARG SHA\nENV NODE_ENV qa\nENV VERSION 1.0.0\n\n## Copy app directory in container and set workdir\nCOPY . /usr/src/atom\n\n# Build & Test Coverage\nRUN set -x \\\n && npm run build \\\n && echo \"{ \\\"status\\\": \\\"Ok\\\", \\\"result\\\": { \\\"version\\\": \\\"$VERSION\\\", \\\"branchName\\\": \\\"$BRANCH\\\", \\\"SHA\\\": \\\"$SHA\\\", \\\"buildDate\\\": \\\"$(date)\\\", \\\"buildNumber\\\": \\\"$BUILD_NUMBER\\\", \\\"environment\\\": \\\"$NODE_ENV\\\" } }\" > build.json\n\n# Release\nFROM node:8-alpine \n\nENV PORT 3000\n\nCOPY --from=builder /usr/src/atom/node_modules /usr/src/atom/node_modules\nCOPY --from=builder /usr/src/atom/dist /usr/src/atom/dist\nCOPY --from=builder /usr/src/atom/package.json /usr/src/atom/package.json\nCOPY --from=builder /usr/src/atom/build.json /usr/src/atom/build.json\nWORKDIR /usr/src/atom\n\nEXPOSE $PORT\n## Run supervisor as foreground process\nCMD bash -c \"npm run start:prod && /usr/bin/supervisord\"\n```\n\n========================================\n\nCode:\n```text\nsh: nest: not found\nnpm ERR! code ELIFECYCLE\nnpm ERR! syscall spawn\nnpm ERR! file sh\nnpm ERR! errno ENOENT\nnpm ERR! atom-qbuilder-api@0.0.1 build: `nest build`\nnpm ERR! spawn ENOENT\nnpm ERR! \nnpm ERR! Failed at the atom-qbuilder-api@0.0.1 build script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n```\n\n```text\n# Build\nFROM node:8-alpine as builder\n\nCOPY package.json /usr/src/atom/package.json\nCOPY package-lock.json /usr/src/atom/package-lock.json\nWORKDIR /usr/src/atom\n\n# Install dependencies\nRUN npm install --production --loglevel warn\n\nARG APPLICATION\nARG BRANCH\nARG BUILD_NUMBER\nARG SHA\nENV NODE_ENV qa\nENV VERSION 1.0.0\n\n\n## Copy app directory in container and set workdir\nCOPY . /usr/src/atom\n\n# Build & Test Coverage\nRUN set -x \\\n  && npm run build \\\n  && echo \"{ \\\"status\\\": \\\"Ok\\\", \\\"result\\\": { \\\"version\\\": \\\"$VERSION\\\", \\\"branchName\\\": \\\"$BRANCH\\\", \\\"SHA\\\": \\\"$SHA\\\", \\\"buildDate\\\": \\\"$(date)\\\", \\\"buildNumber\\\": \\\"$BUILD_NUMBER\\\", \\\"environment\\\": \\\"$NODE_ENV\\\" } }\" > build.json\n\n# Release\nFROM node:8-alpine \n\nENV PORT 3000\n\nCOPY --from=builder /usr/src/atom/node_modules /usr/src/atom/node_modules\nCOPY --from=builder /usr/src/atom/dist /usr/src/atom/dist\nCOPY --from=builder /usr/src/atom/package.json /usr/src/atom/package.json\nCOPY --from=builder /usr/src/atom/build.json /usr/src/atom/build.json\nWORKDIR /usr/src/atom\n\nEXPOSE $PORT\n## Run supervisor as foreground process\nCMD bash -c \"npm run start:prod && /usr/bin/supervisord\"\n```\n\n```text\nnpm run build\n```\n\n```text\n\"build\": \"nest build\"\n```\n\n```text\n@nestjs/cli\n```\n\n```text\nnest\n```\n\n```text\ndevDependencies\n```\n\n```text\npackage.json\n```\n\n```text\nnpm i --production\n```\n\n```text\n@nestjs/cli\n```\n\n```text\n@nestjs/cli\n```\n\n```text\ndependencies\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.408Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":164,"estimatedTokens":922}}90{"id":"stack-60192912","source":"stackoverflow","questionId":60192912,"title":"How to create a Service that acts as a singleton with NestJS","tags":["dependency-injection","singleton","nestjs"],"text":"Title: How to create a Service that acts as a singleton with NestJS\nTags: dependency-injection, singleton, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a Module that provdies a singleton service. Imagine a `QueueService`, simplest implementation would be a singleton service.\n\nReproducible repository: https://github.com/colthreepv/nestjs-singletons\n\n**WALL OF CODE**\n\napp.module.ts:\n\n```\n@Module({ imports: [FirstConsumerModule, SecondConsumerModule] })\nexport class AppModule {}\n```\n\nfirstconsumer.module.ts **and** secondconsumer.module.ts (they are identical):\n\n```\n@Injectable()\nclass FirstConsumer {\n constructor(private readonly dependency: DependencyService) {}\n}\n\n@Module({\n imports: [DependencyServiceModule],\n providers: [DependencyService, FirstConsumer]\n})\nexport class FirstConsumerModule {\n constructor(private readonly first: FirstConsumer) {}\n}\n```\n\ndependency.module.ts:\n\n```\n@Injectable()\nexport class DependencyService {\n constructor() { console.log(\"Instance created\") }\n}\n\n@Module({ providers: [DependencyService], exports: [DependencyService] })\nexport class DependencyServiceModule {}\n```\n\n**CODE DONE**\n\nWhat I would like to obtain is having console.log `Instance created` just be posted once.\n\nAt the moment:\n\n```\n[NestFactory] Starting Nest application...\nInstance created\nInstance created\nInstance created\n[InstanceLoader] AppModule dependencies initialized +16ms\n[InstanceLoader] DependencyServiceModule dependencies initialized +1ms\n[InstanceLoader] FirstConsumerModule dependencies initialized +1ms\n[InstanceLoader] SecondConsumerModule dependencies initialized +1ms\n[NestApplication] Nest application successfully started +8ms\n```\n\n========================================\n\nCode:\n```js\n@Module({ imports: [FirstConsumerModule, SecondConsumerModule] })\nexport class AppModule {}\n```\n\n```js\n@Injectable()\nclass FirstConsumer {\n  constructor(private readonly dependency: DependencyService) {}\n}\n\n@Module({\n  imports: [DependencyServiceModule],\n  providers: [DependencyService, FirstConsumer]\n})\nexport class FirstConsumerModule {\n  constructor(private readonly first: FirstConsumer) {}\n}\n```\n\n```js\n@Injectable()\nexport class DependencyService {\n  constructor() { console.log(\"Instance created\") }\n}\n\n@Module({ providers: [DependencyService], exports: [DependencyService] })\nexport class DependencyServiceModule {}\n```\n\n```text\n[NestFactory] Starting Nest application...\nInstance created\nInstance created\nInstance created\n[InstanceLoader] AppModule dependencies initialized +16ms\n[InstanceLoader] DependencyServiceModule dependencies initialized +1ms\n[InstanceLoader] FirstConsumerModule dependencies initialized +1ms\n[InstanceLoader] SecondConsumerModule dependencies initialized +1ms\n[NestApplication] Nest application successfully started +8ms\n```\n\n```text\nQueueService\n```\n\n```text\nInstance created\n```\n\n```js\n@Module({\n  providers: [DependencyService],\n  exports: [DependencyService]\n})\nexport class DependencyServiceModule {}\n```\n\n```js\n@Module({\n  imports: [DependencyServiceModule],\n  providers: [FirstConsumer] // notice no DependencyService class\n})\nexport class FirstConsumerModule {}\n```\n\n```js\n@Module({\n  imports: [DependnecyServiceModule, FirstCosnumerModule]\n})\nexport class AppModule {}\n```\n\n```text\nDependencyService\n```\n\n```text\nproviders\n```\n\n```text\nproviders\n```\n\n```text\nDependencyServiceModule\n```\n\n```text\nexports\n```\n\n```text\nDependencyServiceModule\n```\n\n```text\nimports\n```\n\n```text\nFrstConsumerModule\n```\n\n```text\nSecondConsumerModule\n```\n\n```text\nDependencyService\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n========================================\n\nComments:\n- Thanks for the answer. TLDR: services in nestjs are singletons, but **ONLY** regarding a module. So if you want a *ThingService* to be a single instance in all the app, you should create a module that instantiate said *ThingService*, and then exports it. In that way the *ThingService* will only ever have a single instance\n- Excellent answer. For some reason this isn't made very clear in the Nest JS docs regarding modules and how to properly register / use them.\n- This does not seem to work for guards, am I right? I see them being instantiated multiple times, even when it's only added as a provider in a single module and properly exported\n- Correct, guards and other enhancers will be instantiated per use.","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":196,"estimatedTokens":1090}}91{"id":"stack-55601651","source":"stackoverflow","questionId":55601651,"title":"How to rethrow errors of HttpService call with NestJS?","tags":["javascript","typescript","observable","axios","nestjs"],"text":"Title: How to rethrow errors of HttpService call with NestJS?\nTags: javascript, typescript, observable, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS to essentially proxy a request to another api using the `HttpService` (an observable wrapped Axios library). For example: \n\n```\nreturn this.httpService.post(...)\n .pipe(\n map(response => response.data),\n );\n```\n\nThis works properly when the call is successful; however, if there's an error (4xx), how do I properly return the status and error message? \n\nI've figured out how to do it with promises, but if possible I would like to stay within an observable.\n\n========================================\n\nTop Answer:\nWithout using rxjs:\n\n```\nimport { AxiosResponse, isAxiosError } from 'axios';\nimport { lastValueFrom } from 'rxjs';\nimport { HttpService } from '@nestjs/axios';\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nclass YourService {\n constructor(private readonly httpService: HttpService) {}\n\n private async request(body?: B): Promise | null> {\n try {\n const res = await lastValueFrom(this.httpService.post('http://localhost:3000/api', body));\n\n return res;\n } catch (e) {\n // Error handling here...\n if (isAxiosError(e)) {\n console.log(e.response.data);\n } else {\n console.log(e);\n }\n\n return null;\n }\n }\n\n public async sendTest() {\n const res = await this.request();\n\n return res?.data;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nreturn this.httpService.post(...)\n  .pipe(\n    map(response => response.data),\n  );\n```\n\n```text\nHttpService\n```\n\n```text\nimport { catchError } from 'rxjs/operators';\n\nthis.httpService.get(url)\n      .pipe(\n        catchError(e => {\n          throw new HttpException(e.response.data, e.response.status);\n        }),\n      );\n```\n\n```text\ncatchError\n```\n\n```text\nerror.response\n```\n\n```text\nvalidateStatus\n```\n\n```text\nimport { AxiosResponse, isAxiosError } from 'axios';\nimport { lastValueFrom } from 'rxjs';\nimport { HttpService } from '@nestjs/axios';\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nclass YourService {\n    constructor(private readonly httpService: HttpService) {}\n\n    private async request<TRes, B = unknown>(body?: B): Promise<AxiosResponse<TRes> | null> {\n        try {\n            const res = await lastValueFrom(this.httpService.post<TRes>('http://localhost:3000/api', body));\n\n            return res;\n        } catch (e) {\n            // Error handling here...\n            if (isAxiosError(e)) {\n                console.log(e.response.data);\n            } else {\n                console.log(e);\n            }\n\n            return null;\n        }\n    }\n\n    public async sendTest() {\n        const res = await this.request();\n\n        return res?.data;\n    }\n}\n```\n\n========================================\n\nComments:\n- Oddly, I can send an AxiosError with a code of 401 through this pipeline and it never catches. All 400 level errors are considered a \"success\".\n- @JimWharton You should be able to customize this behavior with `validateStatus`, see github.com/axios/axios#handling-errors\n- Looks like that's getting ignored. I've had to put an explicit check for status codes greater than 400 in a map inside the pipe. I throw from there. It's not ideal but, it's what I'd do with a Promise so, it's fine. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":136,"estimatedTokens":825}}92{"id":"stack-60189849","source":"stackoverflow","questionId":60189849,"title":"How to format response before sending in Nest.js?","tags":["javascript","typescript","nestjs"],"text":"Title: How to format response before sending in Nest.js?\nTags: javascript, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI followed the documentation and was able to add an interceptor for response mapping.\n\nI want a consistent json format output for responses.\n\nHow can I achieve this with interceptor or with something else better than this approach.\n\n```\n{\n \"statusCode\": 201,\n \"message\": \"Custom Dynamic Message\"\n \"data\": {\n // properties\n meta: {}\n }\n}\n```\n\n**transform.interceptor.ts**\n\n```\nimport {\n Injectable,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nexport interface Response {\n statusCode: number;\n data: T;\n}\n\n@Injectable()\nexport class TransformInterceptor\n implements NestInterceptor> {\n intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable> {\n return next\n .handle()\n .pipe(\n map((data) => ({\n statusCode: context.switchToHttp().getResponse().statusCode,\n data,\n })),\n );\n }\n}\n```\n\n**app.controller.ts**\n\n```\nexport class AppController {\n @Post('login')\n @UseGuards(AuthGuard('local'))\n @ApiOperation({ summary: 'Login user' })\n @ApiBody({ type: LoginDto })\n @ApiOkResponse({ content: { 'application/json': {} } })\n @UseInterceptors(TransformInterceptor)\n async login(@Request() req) {\n const result = await this.authService.login(req.user);\n return { message: 'Thank you!', result };\n }\n}\n```\n\n========================================\n\nTop Answer:\nInstead of requiring every controller to always include a message property in the response data, I utilized reflectors and `SetMetadata` to extract the message value and set it as metadata on the controller method.\n\n*response_message.decorator.ts*\n\n```\nimport { SetMetadata } from '@nestjs/common';\n\nexport const ResponseMessage = (message: string) =>\n SetMetadata('response_message', message);\n```\n\n*response.interceptor.ts*\n\n```\nimport {\n Injectable,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nexport interface Response {\n statusCode: number;\n message: string;\n data: T;\n}\n\n@Injectable()\nexport class TransformInterceptor\n implements NestInterceptor>\n{\n constructor(private reflector: Reflector) {}\n intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable> {\n return next.handle().pipe(\n map((data) => ({\n statusCode: context.switchToHttp().getResponse().statusCode,\n message:\n this.reflector.get(\n 'response_message',\n context.getHandler(),\n ) || '',\n data,\n })),\n );\n }\n}\n```\n\nusage in controller\n\n*media.controller.ts*\n\n```\n@Get('/stats')\n @ResponseMessage('Fetched Stats Succesfully')\n getUserMediaStats(@GetUser('id') userId: Types.ObjectId) {\n return this.mediaService.getUserMediaStats(userId);\n }\n```\n\nMy Response Structure\n\n```\n{\n \"statusCode\": 200,\n \"message\": \"Fetched Stats Succesfully\",\n \"data\": {\n \"userId\": \"6419cbb6c053f0692ef400ae\",\n \"totalCount\": 8,\n \"totalSizeMB\": 2.079585,\n \"imageCount\": 8,\n \"videoCount\": 0\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n  \"statusCode\": 201,\n  \"message\": \"Custom Dynamic Message\"\n  \"data\": {\n     // properties\n     meta: {}\n  }\n}\n```\n\n```text\nimport {\n  Injectable,\n  NestInterceptor,\n  ExecutionContext,\n  CallHandler,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nexport interface Response<T> {\n  statusCode: number;\n  data: T;\n}\n\n@Injectable()\nexport class TransformInterceptor<T>\n  implements NestInterceptor<T, Response<T>> {\n  intercept(\n    context: ExecutionContext,\n    next: CallHandler,\n  ): Observable<Response<T>> {\n    return next\n      .handle()\n      .pipe(\n        map((data) => ({\n          statusCode: context.switchToHttp().getResponse().statusCode,\n          data,\n        })),\n      );\n  }\n}\n```\n\n```text\nexport class AppController {\n      @Post('login')\n      @UseGuards(AuthGuard('local'))\n      @ApiOperation({ summary: 'Login user' })\n      @ApiBody({ type: LoginDto })\n      @ApiOkResponse({ content: { 'application/json': {} } })\n      @UseInterceptors(TransformInterceptor)\n      async login(@Request() req) {\n        const result = await this.authService.login(req.user);\n        return { message: 'Thank you!', result };\n      }\n}\n```\n\n```js\nimport {\n  Injectable,\n  NestInterceptor,\n  ExecutionContext,\n  CallHandler,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nexport interface Response<T> {\n  statusCode: number;\n  message: string;\n  data: T;\n}\n\n@Injectable()\nexport class TransformInterceptor<T>\n  implements NestInterceptor<T, Response<T>> {\n  intercept(\n    context: ExecutionContext,\n    next: CallHandler,\n  ): Observable<Response<T>> {\n    return next\n      .handle()\n      .pipe(\n        map((data) => ({\n          statusCode: context.switchToHttp().getResponse().statusCode,\n          message: data.message,\n          data: {\n            result: data.result,\n            meta: {} // if this is supposed to be the actual return then replace {} with data.result\n          }\n        })),\n      );\n  }\n}\n```\n\n```text\n{message: 'Custom message', result: result}\n```\n\n```text\nimport { SetMetadata } from '@nestjs/common';\n\nexport const ResponseMessage = (message: string) =>\n      SetMetadata('response_message', message);\n```\n\n```text\nimport {\n  Injectable,\n  NestInterceptor,\n  ExecutionContext,\n  CallHandler,\n} from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nexport interface Response<T> {\n  statusCode: number;\n  message: string;\n  data: T;\n}\n\n@Injectable()\nexport class TransformInterceptor<T>\n  implements NestInterceptor<T, Response<T>>\n{\n  constructor(private reflector: Reflector) {}\n  intercept(\n    context: ExecutionContext,\n    next: CallHandler,\n  ): Observable<Response<T>> {\n    return next.handle().pipe(\n      map((data) => ({\n        statusCode: context.switchToHttp().getResponse().statusCode,\n        message:\n          this.reflector.get<string>(\n            'response_message',\n            context.getHandler(),\n          ) || '',\n        data,\n      })),\n    );\n  }\n}\n```\n\n```text\n@Get('/stats')\n  @ResponseMessage('Fetched Stats Succesfully')\n  getUserMediaStats(@GetUser('id') userId: Types.ObjectId) {\n    return this.mediaService.getUserMediaStats(userId);\n  }\n```\n\n```text\n{\n    \"statusCode\": 200,\n    \"message\": \"Fetched Stats Succesfully\",\n    \"data\": {\n        \"userId\": \"6419cbb6c053f0692ef400ae\",\n        \"totalCount\": 8,\n        \"totalSizeMB\": 2.079585,\n        \"imageCount\": 8,\n        \"videoCount\": 0\n    }\n}\n```\n\n```text\nSetMetadata\n```\n\n```text\nimport { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { map, Observable } from 'rxjs';\nimport { Reflector } from '@nestjs/core';\n\nexport interface Response<T> {\n statusCode: number;\n message: string;\n data: T;\n}\n\n@Injectable()\nexport class TransformationInterceptor<T> implements NestInterceptor<T, \nResponse<T>> {\nconstructor(private reflector: Reflector) {}\nintercept(context: ExecutionContext, next: CallHandler): \nObservable<Response<T>> {\n   return next.handle().pipe(\n   map((data) => ({\n    message: this.reflector.get<string>('response_message', \n      context.getHandler()) || data.message || '',\n    statusCode: context.switchToHttp().getResponse().statusCode,\n    data: data.result || data\n   }))\n   );\n }\n}\n```\n\n```text\n@Get()\n@ResponseMessage('Employees records fetched Succesfully')\nfindAll() {\n  return this.employeesService.findAll();\n}\n```\n\n```text\n{\n   \"message\": \"Employees records fetched Succesfully\",\n   \"statusCode\": 200,\n   \"data\": [\n     {\n       \"id\": 1,\n       \"code\": \"2001\",\n       \"companyCode\": \"01\",\n       \"firstName\": \"Walter\",\n       \"lastName\": \"Mendoza\",\n       \"email\": \"w.dummy@gmail.com\",\n       \"phone\": \"+1214\",\n       \"siteId\": 4,\n       \"roleId\": 5,\n       \"isActive\": 0,\n       \"inviteStatus\": 3,\n       \"shiftId\": null,\n       \"createdAt\": \"2019-08-26T15:21:44.000Z\",\n       \"syncAt\": \"2022-10-09T19:01:40.000Z\",\n       \"modifiedAt\": \"2022-10-09T19:01:40.000Z\"\n     },\n     {\n      \"id\": 2,\n      \"code\": \"2002\",\n      \"companyCode\": \"01\",\n      \"firstName\": \"Hugo\",\n      \"lastName\": \"Rosa\",\n      \"email\": \"dummy@gmail.com\",\n      \"phone\": \"+18324888233\",\n      \"siteId\": 4,\n      \"roleId\": 5,\n      \"isActive\": 1,\n      \"inviteStatus\": 3,\n      \"shiftId\": null,\n      \"createdAt\": \"2019-08-26T15:21:44.000Z\",\n      \"syncAt\": \"2022-10-09T19:01:40.000Z\",\n      \"modifiedAt\": \"2022-10-09T19:01:40.000Z\"\n     }\n    ] \n   }\n\n\n\n @Get(':id')\n async findOne(@Param('id') id: string) {\n     const result = await this.employeesService.findOne(+id);\n     return { message: `Employees ${id} detail fetched Succesfully`, \n     result};\n }\n```\n\n```text\n{\n \"message\": \"Employees 1 detail fetched Succesfully\",\n \"statusCode\": 200,\n \"data\": {\n  \"id\": 1,\n  \"code\": \"2001\",\n  \"companyCode\": \"01\",\n  \"firstName\": \"Walter\",\n  \"lastName\": \"Mendoza\",\n  \"email\": \"dummy@gmail.com\",\n  \"phone\": \"+1214\",\n  \"siteId\": 4,\n  \"roleId\": 5,\n  \"isActive\": 0,\n  \"inviteStatus\": 3,\n  \"shiftId\": null,\n  \"createdAt\": \"2019-08-26T15:21:44.000Z\",\n  \"syncAt\": \"2022-10-09T19:01:40.000Z\",\n  \"modifiedAt\": \"2022-10-09T19:01:40.000Z\"\n }\n}\n```\n\n========================================\n\nComments:\n- What do you mean by \"better than this approach\"? Is there something about the Interceptor approach that you don't like?\n- @JayMcDoniel As I said earlier. How can I add a message key with a custom message in the json response? And what I meant was how can I achieve the desire result that I wanted using the interceptor approach. If we cannot achieve what I wanted using interceptor then is there any other approach for that?\n- Thanks man this works but can you tell me more about the map function we are using here. Because earlier I tried to do something similar like your answer but I was not able to debug or print that iterator \"data\" in map function. Even when I put my breakpoint there it says undefined. Can you please help me on how to debug it?\n- `map` is the rxjs operator. What this does is it takes the observable returned from `next.handle()` which means the value returned from your controller (Nest makes in an observable automatically so you shouldn't need to worry about that), then it should take `data` and map it accordingly to our new format using that arrow function that returns a json. If you'd like to `console.log(data)` you'll need to change it from immediately returning a json to using the word `return` and only using `{}`, not `({})`\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- what if the message is for the failed response? it cant be customized if the message hard coded in the decorator right?","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":462,"estimatedTokens":2771}}93{"id":"stack-52095261","source":"stackoverflow","questionId":52095261,"title":"Overriding providers in NestJS Jest tests","tags":["jestjs","nestjs"],"text":"Title: Overriding providers in NestJS Jest tests\nTags: jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use an in-memory Mongo instance to mock data for testing purposes in my NestJS application. I have a database provider which connects to my production db using mongoose, which is part of my database module, which in turn gets imported into other modules.\n\nI am trying to override the database provider within my Jest tests so I can use the in-memory Mongo instance.\n\nThis is the database module:\n\n```\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n providers: [...databaseProviders],\n exports: [...databaseProviders],\n})\nexport class DatabaseModule { }\n```\n\nand the databaseProvider:\n\n```\nexport const databaseProviders = [\n {\n provide: 'DbConnectionToken',\n useFactory: async (): Promise =>\n await mongoose.connect(PRODUCTION_DATABASE_URL),\n },\n];\n```\n\nI have an Events module which imports and uses the database connection from the database module the Events service is what I am testing - the beforeEach in my events.spec.ts:\n\n```\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [EventsModule],\n providers: [\n EventsService,\n {\n provide: 'EventModelToken',\n useValue: EventSchema\n },\n ],\n }).compile();\n\n eventService = module.get(EventsService);\n });\n```\n\nI tried importing the DatabaseModule into the testing module and then adding my custom provider assuming it would override the database provider, but it doesn't work as I expected so I fear I may misunderstand how overriding providers works in this context.\n\nThis is what I tried:\n\n```\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [EventsModule, DatabaseModule],\n providers: [\n EventsService,\n {\n provide: 'EventModelToken',\n useValue: EventSchema\n },\n {\n provide: 'DbConnectionToken',\n useFactory: async (): Promise =>\n await mongoose.connect(IN_MEMORY_DB_URI),\n },\n ],\n }).compile();\n\n eventService = module.get(EventsService);\n});\n```\n\n========================================\n\nCode:\n```ts\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n  providers: [...databaseProviders],\n  exports: [...databaseProviders],\n})\nexport class DatabaseModule { }\n```\n\n```ts\nexport const databaseProviders = [\n  {\n    provide: 'DbConnectionToken',\n    useFactory: async (): Promise<typeof mongoose> =>\n      await mongoose.connect(PRODUCTION_DATABASE_URL),\n  },\n];\n```\n\n```ts\nbeforeEach(async () => {\n    const module = await Test.createTestingModule({\n      imports: [EventsModule],\n      providers: [\n        EventsService,\n        {\n          provide: 'EventModelToken',\n          useValue: EventSchema\n        },\n      ],\n    }).compile();\n\n    eventService = module.get<EventsService>(EventsService);\n  });\n```\n\n```ts\nbeforeEach(async () => {\n  const module = await Test.createTestingModule({\n    imports: [EventsModule, DatabaseModule],\n    providers: [\n      EventsService,\n      {\n        provide: 'EventModelToken',\n        useValue: EventSchema\n      },\n      {\n        provide: 'DbConnectionToken',\n        useFactory: async (): Promise<typeof mongoose> =>\n          await mongoose.connect(IN_MEMORY_DB_URI),\n      },\n    ],\n  }).compile();\n\n  eventService = module.get<EventsService>(EventsService);\n});\n```\n\n```ts\nbeforeEach(async () => {\n    const module = await Test.createTestingModule({\n        imports: [EventsModule, DatabaseModule],\n        providers: [\n            EventsService,\n        ],\n    }).overrideProvider('DbConnectionToken')\n    .useFactory({\n        factory: async (): Promise<typeof mongoose> =>\n          await mongoose.connect(IN_MEMORY_DB_URI),\n    })\n    .compile();\n\n    eventService = module.get<EventsService>(EventsService);\n});\n```\n\n```ts\n@Module({})\nexport DatabaseModule {\n    public static forRoot(options: DatabaseOptions): DynamicModule {\n        return {\n            providers: [\n                {\n                    provide: 'DB_OPTIONS',\n                    useValue: options,\n                },\n                {\n                    provide: 'DbConnectionToken',\n                    useFactory: async (options): Promise<typeof mongoose> => await mongoose.connect(options),\n                    inject: ['DB_OPTIONS']\n                },\n            ],\n        };\n    }\n}\n```\n\n```ts\nconst module: TestingModule = await Test.createTestingModule({\n    imports: [DatabaseModule.forRoot({ host: 'whatever'})],\n});\n```\n\n========================================\n\nComments:\n- I had tried using the overrideProvider functionality previously but I obviously didn't use it correctly. Works perfectly now, thanks for the help!","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":191,"estimatedTokens":1181}}94{"id":"stack-58843038","source":"stackoverflow","questionId":58843038,"title":"How to manually test input validation with NestJS and class-validator","tags":["validation","testing","dto","nestjs"],"text":"Title: How to manually test input validation with NestJS and class-validator\nTags: validation, testing, dto, nestjs\nSource: Stack Overflow\n\nQuestion:\n**TLNR:** I was trying to test DTO validation in the controller spec instead of in e2e specs, which are precisely crafted for that. McDoniel's answer pointed me to the right direction.\n\nI develop a NestJS entrypoint, looking like that:\n\n```\n@Post()\nasync doStuff(@Body() dto: MyDto): Promise {\n // some code...\n}\n```\n\nI use `class-validator` so that when my API receives a request, the payload is parsed and turned into a MyDto object, and validations present as annotations in MyDto class are performed. Note that MyDto has an array of nested object of class MySubDto. With the @ValidateNested and @Type annotations, the nested objects are also validated correctly.\n\n**This works great.**\n\nNow I want to write tests for the performed validations. In my .spec file, I write:\n\n```\nimport { validate } from 'class-validator';\n// ...\nit('should FAIL on invalid DTO', async () => {\n const dto = {\n //...\n };\n const errors = await validate( dto );\n expect(errors.length).not.toBe(0);\n}\n```\n\nThis fails because the validated dto object is not a MyDto. I can rewrite the test as such:\n\n```\nit('should FAIL on invalid DTO', async () => {\n const dto = new MyDto()\n dto.attribute1 = 1;\n dto.subDto = { 'name':'Vincent' };\n const errors = await validate( dto );\n expect(errors.length).not.toBe(0);\n}\n```\n\nValidations are now properly made on the MyDto object, but not on my nested subDto object, which means I will have to instantiate aaaall objects of my Dto with according classes, which would be much inefficient. Also, instantiating classes means that TypeScript will raise errors if I voluntarily omits some required properties or indicate incorrect values.\n\n**So the question is:**\n\nHow can I use NestJs built-in request body parser in my tests, so that I can write any JSON I want for dto, parse it *as* a MyDto object and validate it with `class-validator` validate function?\n\nAny alternate better-practice ways to tests validations are welcome too!\n\n========================================\n\nTop Answer:\nAlthough, we should test how our validation DTOs work with `ValidationPipe`, that's a form of integration or e2e tests. Unit tests are unit tests, right?! Every unit should be testable independently.\n\nThe DTOs in Nest.js are perfectly *unit-tastable*. It becomes necessary to unit-test the DTOs, when they contain complex regular expressions or sanitation logic.\n\n### Creating an object of the DTO for test\n\nThe request body parser in Nest.js that you are looking for is the `class-transformer` package. It has a function `plainToInstance()` to turn your literal or JSON object into an object of the specified type. In your example the specified type is the type of your DTO:\n\n```\nconst myDtoObject = plainToInstance(MyDto, myBodyObject)\n```\n\nHere, `myBodyObject` is your plain object that you created for test, like:\n\n```\nconst myBodyObject = { attribute1: 1, subDto: { name: 'Vincent' } }\n```\n\nThe `plainToInstance()` function also applies all the transformations that you have in your DTO. If you just want to test the transformations, you can assert after this statement. You don't have to call the `validate()` function to test the transformations.\n\n### Validating the object of the DTO in test\n\nTo the emulate validation of Nest.js, simply pass the `myDtoObject` to the `validate()` function of the `class-validator` package:\n\n```\nconst errors = await validate(myDtoObject)\n```\n\nAlso, if your DTO or SubDTO object is too big or too complex to create, you have the option to skip the remaining properties or subObjects like your `subDto`:\n\n```\nconst errors = await validate(myDtoObject, { skipMissingProperties: true })\n```\n\nNow your test object could be without the `subDto`, like:\n\n```\nconst myBodyObject = { attribute1: 1 }\n```\n\n### Asserting the errors\n\nApart from asserting that the `errors` array is not empty, I also like to specify a custom error message for each validation in the DTO:\n\n```\n@IsPositive({ message: `Attribute1 must be a positive number.` })\nreadonly attribute1: number\n```\n\nOne advantage of a custom error message is that we can write it in a user-friendly way instead of the generic messages created by the library. Another big advantage is that I can assert this error message in my tests. This way I can be sure that the `errors` array is not empty because it contains the error for this particular validation and not something else:\n\n```\nexpect(stringified(errors)).toContain(`Attribute1 must be a positive number.`)\n```\n\nHere, `stringified()` is a simple utility function to convert the errors object to a JSON string, so we can search our error message in it:\n\n```\nexport function stringified(errors: ValidationError[]): string {\n return JSON.stringify(errors)\n}\n```\n\n### Your final test code\n\nInstead of the `controller.spec.ts` file, create a new file specific to your DTO, like `my-dto.spec.ts` for unit tests of your DTO. A DTO can have plenty of unit tests and they should not be mixed with the controller's tests:\n\n```\nit('should fail on invalid DTO', async () => {\n const myBodyObject = { attribute1: -1, subDto: { name: 'Vincent' } }\n const myDtoObject = plainToInstance(MyDto, myBodyObject)\n const errors = await validate(myDtoObject)\n expect(errors.length).not.toBe(0)\n expect(stringified(errors)).toContain(`Attribute1 must be a positive number.`)\n}\n```\n\nNotice how you don't have to assign the values to the properties one by one for creating the `myDtoObject`. In most cases, the properties of your DTOs should be marked `readonly`. So, you can't assign the values one by one. The `plainToInstance()` to the rescue!\n\nThat's it! You were almost there, unit testing your DTO. Good efforts! Hope that helps now.\n\n========================================\n\nCode:\n```text\n@Post()\nasync doStuff(@Body() dto: MyDto): Promise<string> {\n  // some code...\n}\n```\n\n```text\nimport { validate  } from 'class-validator';\n// ...\nit('should FAIL on invalid DTO', async () => {\n  const dto = {\n    //...\n  };\n  const errors = await validate( dto );\n  expect(errors.length).not.toBe(0);\n}\n```\n\n```text\nit('should FAIL on invalid DTO', async () => {\n  const dto = new MyDto()\n  dto.attribute1 = 1;\n  dto.subDto = { 'name':'Vincent' };\n  const errors = await validate( dto );\n  expect(errors.length).not.toBe(0);\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-validator\n```\n\n```text\napp.useGlobalPipes()\n```\n\n```text\nconst myDtoObject = plainToInstance(MyDto, myBodyObject)\n```\n\n```text\nconst myBodyObject = { attribute1: 1, subDto: { name: 'Vincent' } }\n```\n\n```text\nconst errors = await validate(myDtoObject)\n```\n\n```text\nconst errors = await validate(myDtoObject, { skipMissingProperties: true })\n```\n\n```text\nconst myBodyObject = { attribute1: 1 }\n```\n\n```text\n@IsPositive({ message: `Attribute1 must be a positive number.` })\nreadonly attribute1: number\n```\n\n```text\nexpect(stringified(errors)).toContain(`Attribute1 must be a positive number.`)\n```\n\n```text\nexport function stringified(errors: ValidationError[]): string {\n  return JSON.stringify(errors)\n}\n```\n\n```text\nit('should fail on invalid DTO', async () => {\n  const myBodyObject = { attribute1: -1, subDto: { name: 'Vincent' } }\n  const myDtoObject = plainToInstance(MyDto, myBodyObject)\n  const errors = await validate(myDtoObject)\n  expect(errors.length).not.toBe(0)\n  expect(stringified(errors)).toContain(`Attribute1 must be a positive number.`)\n}\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-transformer\n```\n\n```text\nplainToInstance()\n```\n\n```text\nmyBodyObject\n```\n\n```text\nplainToInstance()\n```\n\n```text\nvalidate()\n```\n\n```text\nmyDtoObject\n```\n\n```text\nvalidate()\n```\n\n```text\nclass-validator\n```\n\n```text\nsubDto\n```\n\n```text\nsubDto\n```\n\n```text\nerrors\n```\n\n```text\nerrors\n```\n\n```text\nstringified()\n```\n\n```text\ncontroller.spec.ts\n```\n\n```text\nmy-dto.spec.ts\n```\n\n```text\nmyDtoObject\n```\n\n```text\nreadonly\n```\n\n```text\nplainToInstance()\n```\n\n========================================\n\nComments:\n- How would one go about that registering pipes approach?\n- As mentioned, if you normally use `app.useGlobalPipes()` in your `main.ts`, you'll need to do the same in an `e2e` test, as the `RootTestModule` does not run through the `main.ts` (nor should it, as it is a completely different context)\n- Thanks!! This is what I was looking for. And it makes much more sense to test it in the e2e tests.\n- Hey, I disagree with you, because you may want to control transformed values and improve test coverage\n- Thank you for a complete reply! I learned a couple of useful things here. Now, this leaves me with 2 additional questions. A/ with this method, how do you additionnally assert that validations will actually be applied by the controller?\n- B/ some of my controllers are doing some additionnal validations (whole logic concerns the precise and specific nature of the DTO content (example: if attribute1=3, subDto name can not be 'Vincent'), which could not be tested by the dto-unit-test way you propose, but is testable using e2e approach. Any thoughts?\n- @Bob, A/ How the Controller interacts with the DTO should be tested in e2e or integration tests, because it's an integration between the DTO and Controller. Simply pass the invalid input in the Supertest and assert that it throws your specified error.\n- @Bob, B/ sounds like your business logic. To check If some input meets your business requirements, should be analysed and validated inside your Service and throw errors from there. Controllers should be kept dumb. They should not include any logic nor the validations. Their main job is routing and parsing input. Simply forward the request from the controllers to the Service where you include all the business related validations and other logic. DTO validations should only include universal validations like username min length, max length or sanitations like trimming spaces from input fields.\n- That makes sense. Thanks for the hints and your time!\n- This answer deserves more upvotes\n- Great explanation, thank you for the verbose explanation.","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":317,"estimatedTokens":2529}}95{"id":"stack-62799708","source":"stackoverflow","questionId":62799708,"title":"Nest.js Auth Guard JWT Authentication constantly returns 401 unauthorized","tags":["passport.js","nestjs","jwt","passport-jwt"],"text":"Title: Nest.js Auth Guard JWT Authentication constantly returns 401 unauthorized\nTags: passport.js, nestjs, jwt, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nUsing Postman to test my endpoints, I am able to successfully \"login\" and receive a JWT token. Now, I am trying to hit an endpoint that supposedly has an `AuthGuard` to ensure that now that I am logged in, I can now access it.\n\nHowever, it constantly returns `401 Unauthorized` even when presented the JWT token in Postman.\n\nHere is my code:\n\n**user.controller.ts**\n\n```\n@Controller('users')\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @UseGuards(AuthGuard())\n @Get()\n getUsers() {\n return this.usersService.getUsersAsync();\n }\n}\n```\n\n**jwt.strategy.ts**\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authenticationService: AuthenticationService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: 'SuperSecretJWTKey',\n });\n }\n\n async validate(payload: any, done: Function) {\n console.log('I AM HERE'); // this never gets called.\n const user = await this.authenticationService.validateUserToken(payload);\n\n if (!user) {\n return done(new UnauthorizedException(), false);\n }\n\n done(null, user);\n }\n}\n```\n\nI have tried `ExtractJWT.fromAuthHeaderWithScheme('JWT')` as well but that does not work.\n\n**authentication.module.ts**\n\n```\n@Module({\n imports: [\n ConfigModule,\n UsersModule,\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n secret: 'SuperSecretJWTKey',\n signOptions: { expiresIn: 3600 },\n }),\n ],\n controllers: [AuthenticationController],\n providers: [AuthenticationService, LocalStrategy, JwtStrategy],\n exports: [AuthenticationService, LocalStrategy, JwtStrategy],\n})\nexport class AuthenticationModule {}\n```\n\n**authentication.controller.ts**\n\n```\n@Controller('auth')\nexport class AuthenticationController {\n constructor(\n private readonly authenticationService: AuthenticationService,\n private readonly usersService: UsersService,\n ) {}\n\n @UseGuards(AuthGuard('local'))\n @Post('login')\n public async loginAsync(@Response() res, @Body() login: LoginModel) {\n const user = await this.usersService.getUserByUsernameAsync(login.username);\n\n if (!user) {\n res.status(HttpStatus.NOT_FOUND).json({\n message: 'User Not Found',\n });\n } else {\n const token = this.authenticationService.createToken(user);\n return res.status(HttpStatus.OK).json(token);\n }\n }\n}\n```\n\nIn Postman, I am able to use my login endpoint to successfully login with the proper credentials and receive a JWT token. Then, I add an `Authentication` header to a GET request, copy and paste in the JWT token, and I have tried both \"Bearer\" and \"JWT\" schemes and both return `401 Unauthorized` as you can see in the images below.\n\nhttps://i.sstatic.net/3dbeQ.png\n\nhttps://i.sstatic.net/ndnMd.png\n\nI used the JWT.IO debugger, to check if there's anything wrong with my token and it appears correct:\nhttps://i.sstatic.net/k6MIf.png\n\nI am at a lost as to what could be the issue here. Any help would be greatly appreciated.\n\n========================================\n\nTop Answer:\nI had the exact same problem.My problem was that JwtModule secret and JwtStrategy secretOrKey was different. Hope this might help someone stuck with this!\n\n========================================\n\nCode:\n```js\n@Controller('users')\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @UseGuards(AuthGuard())\n  @Get()\n  getUsers() {\n    return this.usersService.getUsersAsync();\n  }\n}\n```\n\n```js\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authenticationService: AuthenticationService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: 'SuperSecretJWTKey',\n    });\n  }\n\n  async validate(payload: any, done: Function) {\n    console.log('I AM HERE'); // this never gets called.\n    const user = await this.authenticationService.validateUserToken(payload);\n\n    if (!user) {\n      return done(new UnauthorizedException(), false);\n    }\n\n    done(null, user);\n  }\n}\n```\n\n```js\n@Module({\n  imports: [\n    ConfigModule,\n    UsersModule,\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.register({\n      secret: 'SuperSecretJWTKey',\n      signOptions: { expiresIn: 3600 },\n    }),\n  ],\n  controllers: [AuthenticationController],\n  providers: [AuthenticationService, LocalStrategy, JwtStrategy],\n  exports: [AuthenticationService, LocalStrategy, JwtStrategy],\n})\nexport class AuthenticationModule {}\n```\n\n```js\n@Controller('auth')\nexport class AuthenticationController {\n  constructor(\n    private readonly authenticationService: AuthenticationService,\n    private readonly usersService: UsersService,\n  ) {}\n\n  @UseGuards(AuthGuard('local'))\n  @Post('login')\n  public async loginAsync(@Response() res, @Body() login: LoginModel) {\n    const user = await this.usersService.getUserByUsernameAsync(login.username);\n\n    if (!user) {\n      res.status(HttpStatus.NOT_FOUND).json({\n        message: 'User Not Found',\n      });\n    } else {\n      const token = this.authenticationService.createToken(user);\n      return res.status(HttpStatus.OK).json(token);\n    }\n  }\n}\n```\n\n```text\nAuthGuard\n```\n\n```text\n401 Unauthorized\n```\n\n```text\nExtractJWT.fromAuthHeaderWithScheme('JWT')\n```\n\n```text\nAuthentication\n```\n\n```text\n401 Unauthorized\n```\n\n```js\nasync validate(payload: JwtPayload): Promise<User> {\n  const { email } = payload\n  const user = await this.authService.getActiveUser(email)\n\n  if (!user) {\n    throw new UnauthorizedException()\n  }\n\n  return user\n}\n```\n\n```js\nasync login(authCredentialsDto: AuthCredentialsDto): Promise<{ accessToken: string }> {\n    const { email, password } = authCredentialsDto\n\n    const success = await this.usersRepository.verifyCredentials(email, password)\n\n    if (!success) {\n      throw new UnauthorizedException('Invalid credentials')\n    }\n\n    // roles, email, etc can be added to the payload - but don't add sensitive info!\n    const payload: JwtPayload = { email } \n    const accessToken = this.jwtService.sign(payload)\n\n    this.logger.debug(`Generated JWT token with payload ${JSON.stringify(payload)}`)\n\n    return { accessToken }\n  }\n```\n\n```text\nvalidate()\n```\n\n```text\nreturn\n```\n\n```text\nvalidate()\n```\n\n```text\ndone()\n```\n\n```text\nvalidate()\n```\n\n```text\nauthenticationService.validateUserToken()\n```\n\n```text\njwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()\n```\n\n```text\nBearer TOKEN\n```\n\n```text\nauthentication.controller.ts\n```\n\n```text\n@Request\n```\n\n```text\n@Response\n```\n\n```text\n@Get()\n```\n\n```text\nPost()\n```\n\n```text\n@Reponse res\n```\n\n```text\nthrow new UnauthorizedException('User Not Found')\n```\n\n```text\nreturn { token }\n```\n\n```text\nAuthGuard('jwt')\n```\n\n```text\nAuthGuard('local')\n```\n\n```text\nloginAsync()\n```\n\n```text\ncreateToken()\n```\n\n```text\njwtService\n```\n\n```text\nprivate jwtService: JwtService\n```\n\n```text\nJwtPayload\n```\n\n```text\nany\n```\n\n```text\nBearer ${token}\n```\n\n```js\nasync validate(username: string, password: string): Promise<any> {\n    const user = await this.authService.validateUser(username, password);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return user;\n  }\n```\n\n```text\nemail\n```\n\n```text\npassword\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nconstructor(private configService: ConfigService) {\n  super({\n    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n    ignoreExpiration: false,\n    algorithms:[\"RS256\"],\n    secretOrKey: configService.get('jwtPublicKey'),\n  });\n}\n```\n\n```text\n\"RS256\"\n```\n\n```text\njwtStrategy\n```\n\n```text\nMake Sure that inside your strategy the path of secretKey in \nsecretOrKey is implemented correctly.\n\n    \n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: appConfig().appSecret,\n    });\n  }\n \n    async validate(payload: any) {\n    return { userId: payload.userId, username: payload.username };\n  }\n}\n```\n\n```text\nconst token = await response.json()\ntoken.accessToken\n```\n\n```text\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy, 'local') {\n   private readonly logger = new Logger(LocalStrategy.name)\n   constructor(\n      @InjectRepository(User)\n      private readonly userRepository: Repository<User>,\n   ) {\n      super({\n         usernameField: 'email',\n         passwordField: 'password',\n      })\n   }\n...\n```\n\n========================================\n\nComments:\n- The problem may be in your request from Postman. Try to create new request and be cautious what you place in headers. If you are using bearer token place it in auth section, not in headers. Or place it in headers, not in auth section. Make a few experiments, it can help.\n- Thank you. This was a great help. What was happening is that I was using a package called `jsonwebtoken` and doing something like `import * as jwt from 'jsonwebtoken'` followed by `jwt.sign(...)`. When using the actual `JwtService` from `@nestjs&#47;jwt`, that fixed it.\n- I'm glad this helped, for sure using the actual `@nestjs&#47;jwt` is the way to go with this approach! Cheers!\n- Writing a quick JS file helped me find the problem. Thank you for the suggestion!\n- I have exactly same problem! Related to .env not being loaded correctly. It's the 3rd problem I've noticed related to this and still can't figure it out.\n- I had the same problem. Copied the code from the official documentation with '60s' :) Thanks man!\n- You can pass options object to modify the property names. Have a look at this answer stackoverflow.com/a/71001043/7039250\n- @Safi I had the same problem, thanks for noting this edge case\n- lol I got stuck for one hour because of this... thank you\n- Thanks a lot, your answer was the most useful for me!","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":49,"totalLines":461,"estimatedTokens":2522}}96{"id":"stack-62646494","source":"stackoverflow","questionId":62646494,"title":"NestJS - [TypeOrmModule] Unable to connect to the database. Retrying ER_PARSE_ERROR","tags":["nestjs","typeorm"],"text":"Title: NestJS - [TypeOrmModule] Unable to connect to the database. Retrying ER_PARSE_ERROR\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nCannot able to connect database with correct connection info, followed documentation to connect database from https://docs.nestjs.com/techniques/database\n\n**Database connected on SQLYog**\n\nhttps://i.sstatic.net/2ecFX.png\n\nFollowing same database information in **app.module.ts**\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: null,\n database: 'the_local_db',\n entities: [\n Table_one,\n ],\n // entities: ['../typeorm/entities/*.ts'],\n\n synchronize: true,\n }),\n StaffModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nError Details\n\n`[Nest] 5528 - 06/30/2020, 1:39:51 AM [ExceptionHandler] ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''\"'' at line 1 +18m\nQueryFailedError: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''\"'' at line 1\n\nat new QueryFailedError (C:\\Users\\UserName\\ProjectName\\nrwl\\src\\error\\QueryFailedError.ts:9:9)\nat Query. (C:\\Users\\UserName\\ProjectName\\nrwl\\src\\driver\\mysql\\MysqlQueryRunner.ts:167:37)\nat Query. (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\Connection.js:526:10)\nat Query._callback (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\Connection.js:488:16)\nat Query.Sequence.end (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\sequences\\Sequence.js:83:24)\nat Query.ErrorPacket (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\sequences\\Query.js:92:8)\nat Protocol._parsePacket (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Protocol.js:291:23)\nat Parser._parsePacket (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Parser.js:433:10)\nat Parser.write (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Parser.js:43:10)\nat Protocol.write (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Protocol.js:38:16)`\n\n========================================\n\nTop Answer:\nCheck if you have synchronize connection option set to true in database configuration. Make it to false.\nIt worked for me.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: null,\n      database: 'the_local_db',\n      entities: [\n        Table_one,\n      ],\n      // entities: ['../typeorm/entities/*.ts'],\n\n      synchronize: true,\n    }),\n    StaffModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mysql',\n      host: 'localhost',\n      username: 'root',\n      password: null,\n      database: 'the_local_db',\n      entities: [\n        Table_one,\n      ],\n      // entities: ['../typeorm/entities/*.ts'],\n\n      synchronize: true,\n    }),\n    StaffModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n$ npm install mysql2 --save\n```\n\n```text\n$ npm uninstall mysql --save\n```\n\n```text\nmysql2\n```\n\n```text\nmysql\n```\n\n```text\nmysql\n```\n\n```text\nTypeOrmModule.forRoot({\n  type: 'mysql',\n  host: '127.0.0.1',\n  port: 3306,\n  username: 'test',\n  password: '123456',\n  database: 'nest',\n  entities: [\"dist/**/*.entity{.ts,.js}\"],\n  synchronize: true,\n  dropSchema:true })\n```\n\n```text\ndbConfig: {\n    type: 'mongodb',\n    url: process.env.MONGO_CONNECTION_STRING,\n    ssl: true,\n    useUnifiedTopology: true,\n    autoLoadEntities: true,\n    synchronize: false,\n    logging: true,\n}\n```\n\n```text\nMONGO_CONNECTION_STRING: mongodb://ussername:password@host_name:port/?authSource=admin\n```\n\n```text\nuseNewUrlParser: true\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nipv6\n```\n\n```text\nlocalhost\n```\n\n```text\n::1\n```\n\n```text\n127.0.0.1\n```\n\n```text\nERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...\napi         | Error: connect ECONNREFUSED 192.168.80.2:3306\n```\n\n```text\nversion: \"3\"\nservices:\n  api:\n    build:\n      context: ../\n      dockerfile: ./docker/files/dev.Dockerfile\n    container_name: \"api\"\n    env_file:\n      - ./env/api.env\n    depends_on:\n      - database\n    ports:\n      - \"3000:3000\"\n    volumes:\n      - /usr/src/app/node_modules\n      - ../app/:/usr/src/app/\n    working_dir: /usr/src/app\n    command: [\"npm\", \"run\", \"start:dev\"]\n\n  database:\n    image: mysql:8\n    restart: unless-stopped\n    container_name: database\n    env_file:\n      - ./env/db.env\n    volumes:\n      - db1:/var/lib/mysql   //Provious db  (change 1)\n    ports:\n      - \"3307:3306\"\n\n\nvolumes:\n  db1: //Provious db (change 2)\n```\n\n```js\nTypeOrmModule.forRoot({\n      // other options\n      synchronize: true,\n      // other options\n}),\n```\n\n```text\nsynchronize: true\n```\n\n```text\n@Column\n```\n\n```text\n@Column\n```\n\n========================================\n\nComments:\n- You should include the code of your Table_one entity. PS. In the title you mention a different error than in the question text.\n- Table_one entity already imported at top of file, but not shown here.\n- This worked for me, instead of loading the entities like this entities: [__dirname + '/../**/*.entity{.ts,.js}'], Import the entity in an array. I don't know the rationale behind it, and I would love some explanation too.\n- The important part is uninstall mysql. Great answer.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Hi, it worked for me. But if I need to run in synchronized mode I've to set it to true right? For that is there any ways or work arounds?\n- @Vaddadi if it is set to true - it might be for a reason. like in my case\n- It was the problem in my case too, thank you @Vaddadi\n- Also worked for my NestJS, TypeORM and CockroachDB setup!\n- Context on why this could be the reason: github.com/node-fetch/node-fetch/issues/&hellip;\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.409Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":273,"estimatedTokens":1752}}97{"id":"stack-54535867","source":"stackoverflow","questionId":54535867,"title":"Is there a way to use configService in App.Module.ts?","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Is there a way to use configService in App.Module.ts?\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am building RESTful service with NestJs, I have followed the example to build configurations for different environments. It works well for most code. However I am wondering if I can use it in my `app.module.ts`?\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: `${config.get('mongo_url') || 'localhost'}`,\n port: 27017,\n username: 'a',\n password: 'b',\n database: 'my_db',\n entities: [__dirname + '/MyApp/*.Entity{.ts,.js}'],\n synchronize: true}),\n MyModule,\n ConfigModule,\n ],\n controllers: [],\n providers: [MyService],\n})\nexport class AppModule { }\n```\n\nAs you can see I do want to move the MongoDb Url info outside the code and I am thinking to leverage `.env` files. But after some attempts, it does not seem to work.\n\nOf course I can use `${process.env.MONGODB_URL || 'localhost'}` instead, and set the environment variables. I'm still curious if I can make the `configService` work.\n\n========================================\n\nTop Answer:\nBetter to use MongooseModule function from the same package for config and properties as given below:\n\n```\nMongooseModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: (configService: ConfigService) => ({\n uri: `mongodb://${configService.get(\n 'MONGODB_USERNAME',\n )}:${configService.get('MONGODB_PASSWORD')}@${configService.get(\n 'MONGODB_HOST',\n )}:27017/nest?authSource=admin`,\n }),\n inject: [ConfigService],\n}),\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mongodb',\n      host: `${config.get('mongo_url') || 'localhost'}`,\n      port: 27017,\n      username: 'a',\n      password: 'b',\n      database: 'my_db',\n      entities: [__dirname + '/MyApp/*.Entity{.ts,.js}'],\n      synchronize: true}),\n    MyModule,\n    ConfigModule,\n  ],\n  controllers: [],\n  providers: [MyService],\n})\nexport class AppModule { }\n```\n\n```text\napp.module.ts\n```\n\n```text\n.env\n```\n\n```text\n${process.env.MONGODB_URL || 'localhost'}\n```\n\n```text\nconfigService\n```\n\n```text\nTypeOrmModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: (configService: ConfigService) => ({\n    type: 'mongodb',\n    host: configService.databaseHost,\n    port: configService.databasePort,\n    username: configService.databaseUsername,\n    password: configService.databasePassword,\n    database: configService.databaseName,\n    entities: [__dirname + '/**/*.entity{.ts,.js}'],\n    synchronize: true,\n  }),\n  inject: [ConfigService],\n}),\n```\n\n```text\nMongooseModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: (configService: ConfigService) => ({\n    uri: `mongodb://${configService.get(\n      'MONGODB_USERNAME',\n    )}:${configService.get('MONGODB_PASSWORD')}@${configService.get(\n      'MONGODB_HOST',\n    )}:27017/nest?authSource=admin`,\n  }),\n  inject: [ConfigService],\n}),\n```\n\n========================================\n\nComments:\n- Why must use `inject` into it ?\n- @soroush configService is a dependency that will be used to resolve to env variables and passed to typeorm, so nest is passing the configService into the usefactory so it can be used.","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":127,"estimatedTokens":811}}98{"id":"stack-67032343","source":"stackoverflow","questionId":67032343,"title":"Nestjs: import modules undefined, but methods and functions from modules can be imported","tags":["node.js","typescript","webstorm","nestjs","ts-node"],"text":"Title: Nestjs: import modules undefined, but methods and functions from modules can be imported\nTags: node.js, typescript, webstorm, nestjs, ts-node\nSource: Stack Overflow\n\nQuestion:\nI am using `Nestjs` with WebStorm & TS 4.2.3^latest.\n\nThe problem that I am facing is a bit strange. For example, some modules, like `axios` can be installed, imported, and used as usual. But some modules, *especially Nodejs Core, like `fs` or `path`*, can't be imported as modules. **BUT** their methods can be imported and used just fine!\n\n```\n// ERROR: Module undefined on run:dev, but no error in IDE\nimport path from 'path';\nimport fs from 'fs';\n\n// Working fine\nimport { join } from 'path';\nimport { readFileSync } from 'path';\n```\n\nI am sure, they have correct TS types, even installed manually. For example:\n\n```\nimport axios from 'axios';\nimport path from 'path'; // path is undefined\nimport { join } from 'path';\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n async test(input: string): Promise {\n // working fine\n await axios.get() \n // Cannot read property 'join' of undefined\n await path.join() \n\n // await join() Works fine!\n }\n}\n```\n\nI have only one `tsconfig.json` which is generated by Nest Cli. I am starting my apps via `npm start:dev -name` and IDE doesn't show any errors in code until I run code.\n\nhttps://i.sstatic.net/Z3on8.png\n\ntsconfig.json module part, just to be sure: `\"module\": \"commonjs\"`, package.json doesn't have `module` part at all.\n\n========================================\n\nTop Answer:\nonly enable the \"esModuleInterop\": true flag on the tsconfig.json\n\nit's solve the problem because. it's allow to import the common js module in es6 like\nimport Razorpay form 'razoray';\n\n========================================\n\nCode:\n```js\n// ERROR: Module undefined on run:dev, but no error in IDE\nimport path from 'path';\nimport fs from 'fs';\n\n// Working fine\nimport { join } from 'path';\nimport { readFileSync } from 'path';\n```\n\n```text\nimport axios from 'axios';\nimport path from 'path'; // path is undefined\nimport { join } from 'path';\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n  async test(input: string): Promise<void> {\n    // working fine\n    await axios.get() \n    // Cannot read property 'join' of undefined\n    await path.join() \n\n    // await join() Works fine!\n  }\n}\n```\n\n```text\nNestjs\n```\n\n```text\naxios\n```\n\n```text\nfs\n```\n\n```text\npath\n```\n\n```text\ntsconfig.json\n```\n\n```text\nnpm start:dev -name\n```\n\n```text\n\"module\": \"commonjs\"\n```\n\n```text\nmodule\n```\n\n```text\nimport * as fs from 'fs';\n```\n\n```text\n\"esModuleInterop\": true,\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Thanks. IDE was auto importing but import wasn't correct as you stated.\n- Just had this same issue, also with IntelliJ IDEs.\n- enabling: `\"esModuleInterop\": true` in your `tsconfig.json` solved that for me","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":136,"estimatedTokens":733}}99{"id":"stack-55720448","source":"stackoverflow","questionId":55720448,"title":"NestJS: How to setup ClassSerializerInterceptor as global interceptor","tags":["interceptor","nestjs"],"text":"Title: NestJS: How to setup ClassSerializerInterceptor as global interceptor\nTags: interceptor, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using in every Controller code like `@UseInterceptors(ClassSerializerInterceptor)` so I decided make it global and was trying to setup it with no luck.\n\nI was trying without and with `new` and ended up with something like this totally not working.\n\n`app.useGlobalInterceptors(new ClassSerializerInterceptor(new Reflector()));`\n\nI checked NestJS source code and I assume that it cannot be used as global but it should.\n\n========================================\n\nTop Answer:\nI do prefer injecting global interceptors inside `app.modules.ts` instead.\n\nGlobal interceptors registered from outside of any module with `useGlobalInterceptors()` cannot inject dependencies since this is done outside the context of any module.\n\n```\nimport { ClassSerializerInterceptor, Module } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n providers: [\n {\n provide: APP_INTERCEPTOR,\n useClass: ClassSerializerInterceptor,\n },\n ],\n})\nexport class AppModule {}\n```\n\nReference:\n\nHow to use Service in Global-interceptor in NEST Js\n\nhttps://docs.nestjs.com/interceptors#binding-interceptors\n\n========================================\n\nCode:\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\nnew\n```\n\n```text\napp.useGlobalInterceptors(new ClassSerializerInterceptor(new Reflector()));\n```\n\n```js\napp.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));\n```\n\n```js\nimport { ClassSerializerInterceptor, Module } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: ClassSerializerInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\napp.modules.ts\n```\n\n```text\nuseGlobalInterceptors()\n```\n\n```text\nimport { ClassSerializerInterceptor, Module } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_INTERCEPTOR,\n      inject: [Reflector],\n      useFactory: (reflector: Reflector) => {\n        return new ClassSerializerInterceptor(reflector, {\n          enableImplicitConversion: true,\n          excludeExtraneousValues: true,\n        });\n      },\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- Did you make it work? I'm also not finding a way of making it work. I tried `app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));`\n- won't work cause `ClassSerializerInterceptor` needs proper constructor argument to be provided\n- Alright it's true ! The `ClassSerializerInterceptor` needs a `Reflector` instance to be instantiated properly\n- @G.Bar I updated my answer, maybe it suits your case. Let me know.\n- I feel like this should be the preferred answer...","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":112,"estimatedTokens":725}}100{"id":"stack-59451585","source":"stackoverflow","questionId":59451585,"title":"In NestJs, how to inject a service based on its interface?","tags":["javascript","node.js","typescript","ecmascript-6","nestjs"],"text":"Title: In NestJs, how to inject a service based on its interface?\nTags: javascript, node.js, typescript, ecmascript-6, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have the next module: payment.module.ts\n\n```\n@Module({\n controllers: [PaymentController],\n})\nexport class PaymentModule {}\n```\n\nAnd in the next service I want to have access to a service based on an interface\n\npayment.service.ts\n\n```\nexport class PaymentService {\n constructor(private readonly notificationService: NotificationInterface,\n}\n```\n\nnotification.interface.ts\n\n```\nexport interface NotificationInterface {\n // some method definitions\n}\n```\n\nnotification.service.ts\n\n```\n@Injectable()\nexport class NotificationService implements NotificationInterface {\n // some implemented methods\n}\n```\n\nThe question is how do I inject `NotificationService` based on `NotificationInterface`?\n\n========================================\n\nTop Answer:\nAs was mentioned by Gabriel, you cannot use interfaces since they are not present at runtime, but you *can* use an **abstract class**. They are available at runtime, so they can be used as your dependency injection token.\n\nIn Typescript, class delcarations also create types, so you can also *implement* them, you don't have to extend them.\n\nFollowing your example, you could do the following:\n\nnotification.interface.ts\n\n```\nexport abstract class NotificationInterface {\n abstract send(): Promise;\n // ... other method definitions\n}\n```\n\nnotification.service.ts\n\n```\nexport class NotificationService implements NotificationInterface {\n async send() {...}\n}\n```\n\nThen in your module, provide it like so:\n\n```\nimport NotificationInterface from \"...\"\nimport NotificationService from \"...\"\n\n@Module({\n providers: [\n {\n provide: NotificationInterface,\n useClass: NotificationService\n }\n ]\n})\nexport class PaymentModule {}\n```\n\nAnd finally, use the injected service via the interface in payments.service.ts\n\n```\nexport class PaymentService {\n constructor(private readonly notificationService: NotificationInterface) {}\n}\n```\n\nNow you don't need to provide any custom tokens (as strings or symbols) that are somewhat \"unrelated\" to your class implementation (and only a DI construct), but you can use the structure from your OOP model.\n\n========================================\n\nCode:\n```text\n@Module({\n  controllers: [PaymentController],\n})\nexport class PaymentModule {}\n```\n\n```text\nexport class PaymentService {\n   constructor(private readonly notificationService: NotificationInterface,\n}\n```\n\n```text\nexport interface NotificationInterface {\n  // some method definitions\n}\n```\n\n```text\n@Injectable()\nexport class NotificationService implements NotificationInterface {\n  // some implemented methods\n}\n```\n\n```text\nNotificationService\n```\n\n```text\nNotificationInterface\n```\n\n```text\n@Module({\n  providers: [\n    {\n      provide: 'NotificationInterface',\n      useClass: NotificationService\n    }\n  ]\n})\nexport class PaymentModule {}\n```\n\n```text\nexport class PaymentService {\n   constructor(@Inject('NotificationInterface') private readonly notificationService: NotificationInterface,\n}\n```\n\n```text\nexport abstract class NotificationInterface {\n  abstract send(): Promise<void>;\n  // ... other method definitions\n}\n```\n\n```js\nexport class NotificationService implements NotificationInterface {\n  async send() {...}\n}\n```\n\n```js\nimport NotificationInterface from \"...\"\nimport NotificationService from \"...\"\n\n@Module({\n  providers: [\n    {\n      provide: NotificationInterface,\n      useClass: NotificationService\n    }\n  ]\n})\nexport class PaymentModule {}\n```\n\n```js\nexport class PaymentService {\n   constructor(private readonly notificationService: NotificationInterface) {}\n}\n```\n\n========================================\n\nComments:\n- Good answer, this is the approach I use and the recommended NestJS of solving this problem\n- There is a nice blog for this implementation. jasonwhite.xyz/posts/2020/10/20/&hellip;\n- @BurcuGeneci could you suggest how to resolve these kind of dependency in unit test . I am after making similar changes reading the blog you mentioned, i am getting this error:`Nest could not find MyService element (this provider does not exist in the current context)`\n- @Gabriel can you let me know how to add these kind of dependencies when writing unit tests.?\n- Thanks for the example, helped me figure out how to solve my injection jungle :)\n- Is there a way to do this when there are multiple implementations? I want to get all services that implement this interface, or have this key?\n- @Berethor if useClass doesn't work you can supply the instance you want using useFactory: () => {return new ConcreteClass()}\n- Thank you so much for your solution. I have implemented the interfaces in your way and it works.\n- How can I choose which implementation to use if I have more? I don't want to put it in my service class (`PayementService` here) but rather configure it outside of the use site.\n- The wiring of the dependencies happens in the modules @AdamArold. The PaymentService should not need to know which notification service it is using.","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":198,"estimatedTokens":1268}}101{"id":"stack-53249800","source":"stackoverflow","questionId":53249800,"title":"Optional Authentication in nestjs","tags":["javascript","node.js","typescript","passport.js","nestjs"],"text":"Title: Optional Authentication in nestjs\nTags: javascript, node.js, typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to know if there is a decorator that makes the `req.user` object available in a controller method, if the user is logged in (Authaurization header sent), if not then just let the `req.user` be null.\n\nThe `AuthGuard` decorator will return 401 if the user is not logged in, so it's not suitable for my case.\n\n========================================\n\nTop Answer:\nAnother way of doing this is by creating an anonymous passport strategy:\n\n```\n// In anonymous.strategy.ts\n@Injectable()\nexport class AnonymousStrategy extends PassportStrategy(Strategy, 'anonymous') {\n constructor() {\n super()\n }\n\n authenticate() {\n return this.success({})\n }\n}\n```\n\nThen, chaining this strategy in the controller:\n\n```\n// In create-post.controller.ts\n@Controller()\nexport class CreatePostController {\n @UseGuards(AuthGuard(['jwt', 'anonymous'])) // first success wins\n @Post('/posts')\n async createPost(@Req() req: Request, @Body() dto: CreatePostDto) {\n const user = req.user as ExpressUser\n\n if (user.email) {\n // Do something if user is authenticated\n } else {\n // Do something if user is not authenticated\n }\n ...\n }\n}\n```\n\n========================================\n\nCode:\n```text\nreq.user\n```\n\n```text\nreq.user\n```\n\n```text\nAuthGuard\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\nexport const User = createParamDecorator((data, req) => {\n  return req.user;\n});\n```\n\n```text\n@Injectable()\nexport class MyAuthGuard extends AuthGuard('jwt') {\n\n  handleRequest(err, user, info) {\n    // no error is thrown if no user is found\n    // You can use info for logging (e.g. token is expired etc.)\n    // e.g.: if (info instanceof TokenExpiredError) ...\n    return user;\n  }\n\n}\n```\n\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: 'secretKey',\n    });\n  }\n\n  async validate(payload) {\n    const user = await this.authService.validateUser(payload);\n    // in the docs an error is thrown if no user is found\n    return user;\n  }\n}\n```\n\n```text\n@Get()\n@UseGuards(MyAuthGuard)\ngetUser(@User() user) {\n  return {user};\n}\n```\n\n```text\nAuthGuard\n```\n\n```text\nJwtStrategy\n```\n\n```text\nController\n```\n\n```text\n// In anonymous.strategy.ts\n@Injectable()\nexport class AnonymousStrategy extends PassportStrategy(Strategy, 'anonymous') {\n  constructor() {\n    super()\n  }\n\n  authenticate() {\n    return this.success({})\n  }\n}\n```\n\n```text\n// In create-post.controller.ts\n@Controller()\nexport class CreatePostController {\n  @UseGuards(AuthGuard(['jwt', 'anonymous'])) // first success wins\n  @Post('/posts')\n  async createPost(@Req() req: Request, @Body() dto: CreatePostDto) {\n    const user = req.user as ExpressUser\n\n    if (user.email) {\n      // Do something if user is authenticated\n    } else {\n      // Do something if user is not authenticated\n    }\n    ...\n  }\n}\n```\n\n```text\n//decorator.ts\nexport const IS_PUBLIC_KEY = 'AllAnonymous';\nexport const AllAnonymous = () => SetMetadata(IS_PUBLIC_KEY, true);\n```\n\n```text\n//JWT authguard.ts\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  constructor(private reflector: Reflector) {\n    super();\n  }\n  canActivate(context: ExecutionContext) {\n    return super.canActivate(context);\n  }\n\n  handleRequest(err: any, user: any, info: any, context: ExecutionContext) {\n    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n\n    if (isPublic && !user) {\n      return null;\n    }\n\n    if (err || !user) {\n      throw err || new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\n```text\n//controller.ts\n  @AllAnonymous()\n  @UseGuards(JwtAuthGuard)\n  @Get('profile')\n  getUserProfile(@Req() req: any) {\n    {\n      const { user } = req;\n\n      console.log(user);\n\n      return user\n    }\n  }\n```\n\n========================================\n\nComments:\n- If you have not already, have a look at: docs.nestjs.com/techniques/authentication\n- Perfect answer. Could not find it looking all over stackoverflow and githubs.\n- I cannot find the @User decorator\n- @jeromerg It is a custom decoator that is defined in the very first code snippet of this answer.\n- Thank you, I think using this is more flexible. Because sometimes We need to reject the Unauthenticated user.\n- I implemented it with my Graphql Guard ``` import { Injectable, ExecutionContext } from '@nestjs/common' import { AuthGuard } from '@nestjs/passport' import { GqlExecutionContext } from '@nestjs/graphql' @Injectable() export class EveryoneGqlAuthGuard extends AuthGuard(['jwt', 'anonymous']) { getRequest(context: ExecutionContext) { const ctx = GqlExecutionContext.create(context) return ctx.getContext().req } } ```","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":218,"estimatedTokens":1251}}102{"id":"stack-50111330","source":"stackoverflow","questionId":50111330,"title":"NestJS - Injected service is undefined in the constructor","tags":["javascript","node.js","dependency-injection","nestjs"],"text":"Title: NestJS - Injected service is undefined in the constructor\nTags: javascript, node.js, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nAs per the documentation, I inject a service in a controller's constructor, but it turns out as `undefined`.\n\n**processScraped.controller.ts**\n\n```\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { ProcessScrapedService } from \"./processScraped.service\"\n\nconsole.log(`\\nController - ProcessScrapedService = `, ProcessScrapedService) // logs : class ProcessScrapedService { ......\n\n@Controller('processScraped')\nexport class ProcessScrapedController {\n\n constructor(private readonly pss: ProcessScrapedService) {\n console.log(`constructor - pss = `, pss) // logs : undefined (Should not !)\n console.log(`constructor - this.pss = `, this.pss) // logs : undefined (Should not !)\n }\n\n @Post()\n async processScraped(@Body() body) {\n console.log(`processScraped - this.pss = `,this.pss) // logs : undefined (Should not !)\n return this.pss.processScraped(body) // TypeError: Cannot read property 'processScraped' of undefined\n }\n}\n```\n\nSo :\n\nThe service exists\n\nIt's imported and logged correctly as a service after import\n\nWhen I inject it in my controller, it's undefined.\n\nMaybe the problem is in the service definition?\n\n**processScraped.service.ts**\n\n```\nimport { Component } from '@nestjs/common';\n\n@Component()\nexport class ProcessScrapedService {\n async processScraped(body) {\n // Some logic here\n return\n }\n}\n```\n\n... Or maybe in the module?\n\n**processScraped.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\n\nimport { ProcessScrapedController } from './processScraped.controller';\nimport { ProcessScrapedService } from './processScraped.service';\n\nconsole.log(`\\Module - nProcessScrapedService = `, ProcessScrapedService) // logs : class ProcessScrapedService { ......\n\n@Module({\n controllers: [ProcessScrapedController],\n components: [ProcessScrapedService],\n})\nexport class ProcessScrapedModule { }\n```\n\nI really can't see what I'm doing wrong here??\n\n**EDIT** - here are my dependencies :\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^4.5.9\",\n \"@nestjs/core\": \"^4.5.10\",\n \"@nestjs/microservices\": \"^4.5.8\",\n \"@nestjs/mongoose\": \"^3.0.1\",\n \"@nestjs/testing\": \"^4.5.5\",\n \"@nestjs/websockets\": \"^4.5.8\",\n \"@types/mongoose\": \"^5.0.9\",\n \"bluebird\": \"^3.5.1\",\n \"dotenv\": \"^5.0.1\",\n \"elasticsearch\": \"^14.2.2\",\n \"express\": \"^4.16.3\",\n \"mongoose\": \"^5.0.16\",\n \"mongoose-elasticsearch-xp\": \"^5.4.1\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rxjs\": \"^5.5.6\",\n \"shortid\": \"^2.2.8\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^8.0.0\"\n }\n```\n\nand my tsconfig.json :\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ES2017\",\n \"module\": \"commonjs\",\n \"lib\": [ \n \"dom\",\n \"es2017\"\n ],\n \"outDir\": \"../../dist/server\",\n \"removeComments\": true,\n \"strict\": true,\n \"noImplicitAny\": false,\n \"typeRoots\": [\n \"node_modules/@types\"\n ],\n \"types\": [\n \"node\"\n ],\n \"experimentalDecorators\": true\n }\n}\n```\n\n========================================\n\nTop Answer:\nJust stumbled across the same issue in one of my providers - the problem was that I forgot to annotate the provider with an `@Injectable()` decorator after I have added it to the respective module.\n\n========================================\n\nCode:\n```text\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { ProcessScrapedService } from \"./processScraped.service\"\n\nconsole.log(`\\nController - ProcessScrapedService = `, ProcessScrapedService) // logs : class ProcessScrapedService { ......\n\n@Controller('processScraped')\nexport class ProcessScrapedController {\n\n    constructor(private readonly pss: ProcessScrapedService) {\n        console.log(`constructor - pss = `, pss) // logs : undefined (Should not !)\n        console.log(`constructor - this.pss = `, this.pss) // logs : undefined (Should not !)\n    }\n\n    @Post()\n    async processScraped(@Body() body) {\n        console.log(`processScraped - this.pss = `,this.pss) // logs : undefined (Should not !)\n        return this.pss.processScraped(body) // TypeError: Cannot read property 'processScraped' of undefined\n    }\n}\n```\n\n```text\nimport { Component } from '@nestjs/common';\n\n@Component()\nexport class ProcessScrapedService {\n    async processScraped(body) {\n        // Some logic here\n        return\n    }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\n\nimport { ProcessScrapedController } from './processScraped.controller';\nimport { ProcessScrapedService } from './processScraped.service';\n\nconsole.log(`\\Module - nProcessScrapedService = `, ProcessScrapedService) // logs : class ProcessScrapedService { ......\n\n@Module({\n    controllers: [ProcessScrapedController],\n    components: [ProcessScrapedService],\n})\nexport class ProcessScrapedModule { }\n```\n\n```text\n\"dependencies\": {\n    \"@nestjs/common\": \"^4.5.9\",\n    \"@nestjs/core\": \"^4.5.10\",\n    \"@nestjs/microservices\": \"^4.5.8\",\n    \"@nestjs/mongoose\": \"^3.0.1\",\n    \"@nestjs/testing\": \"^4.5.5\",\n    \"@nestjs/websockets\": \"^4.5.8\",\n    \"@types/mongoose\": \"^5.0.9\",\n    \"bluebird\": \"^3.5.1\",\n    \"dotenv\": \"^5.0.1\",\n    \"elasticsearch\": \"^14.2.2\",\n    \"express\": \"^4.16.3\",\n    \"mongoose\": \"^5.0.16\",\n    \"mongoose-elasticsearch-xp\": \"^5.4.1\",\n    \"reflect-metadata\": \"^0.1.12\",\n    \"rxjs\": \"^5.5.6\",\n    \"shortid\": \"^2.2.8\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^8.0.0\"\n  }\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"target\": \"ES2017\",\n        \"module\": \"commonjs\",\n        \"lib\": [ \n            \"dom\",\n            \"es2017\"\n        ],\n        \"outDir\": \"../../dist/server\",\n        \"removeComments\": true,\n        \"strict\": true,\n        \"noImplicitAny\": false,\n        \"typeRoots\": [\n            \"node_modules/@types\"\n        ],\n        \"types\": [\n            \"node\"\n        ],\n        \"experimentalDecorators\": true\n    }\n}\n```\n\n```text\nundefined\n```\n\n```text\n\"emitDecoratorMetadata\": true\n```\n\n```text\ntsconfig.json\n```\n\n```text\n@Injectable()\n```\n\n```text\nREQUEST\n```\n\n```text\nReflect.defineMetadata(\n      'scope:options',\n      { scope: Scope.DEFAULT },\n      YourService,\n    );\n```\n\n```text\nReflect\n```\n\n========================================\n\nComments:\n- What version are you using? Could you your `tsconfig` file?\n- @KamilMyล›liwiec Alright, I have updated my question with my dependencies and tsconfig\n- Oh wow O_o I have no idea what this is, but it fixed the problem. I would never have found that by myself. Thanks Kamil, you're the man.\n- had the same (similar) issue today, had to add the following to my tsconfig.json \"experimentalDecorators\": true, \"declaration\": true, \"removeComments\": true, \"emitDecoratorMetadata\": true\n- You saved my day, weird it's not included in the default `nest new project` template\n- Because of an issue with Jest test coverage in Angular, I did a global remove of emitDecoratorMetadata since Angular no longer needs it. Which also removed from nest which does still need the flag.\n- Haha, I love when this happens. It's like a checklist with possible adjacent problems. Thanks!\n- Thank you so much for this. You just saved me from spinning my wheels for hours.\n- This should be upvoted higher\n- Also had an issue using `@Inject(REQUEST)` on a provider constructor elsewhere in my code.","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":278,"estimatedTokens":1796}}103{"id":"stack-50082365","source":"stackoverflow","questionId":50082365,"title":"NestJS - How to access post body using @Body() decorator?","tags":["typescript","express","nestjs"],"text":"Title: NestJS - How to access post body using @Body() decorator?\nTags: typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { MyService } from 'my.service';\nimport { MyDto } from './dto/my.dto';\n\n@Controller('my-route')\nexport class MyController {\n\n constructor(private readonly _myService: MyService) {}\n\n @Post()\n async myMethod(@Body() myDto: MyDto) {\n console.log(myDto); // undefined\n return await this._myService.doStuff(myDto.elementOfInterest); // Passes undefined variable into method.\n }\n}\n```\n\nI'm confused about the proper way to access the body form data from a POST in Nest. The documentation and examples all show simple use of the `@Body()` decorator preceding the name of a parameter which will contain the body (or a specific element in the body if a parameter is used). Yet in my example above, the body is never populated, and the method is called with `myDto` being undefined. Even changing its type to a string and simply passing a single key/value pair in the body of my POST leaves it undefined. \n\nWhat's the correct way to handle POST bodies in Nest?\n\n========================================\n\nTop Answer:\nIn case anyone stumbles on my problem.\nI had this issue too, but for me was it in the server setup in the `main.ts`.\n\nI set this code to include a ssl certificate to work with https, but only in production\n\n```\nlet serverOptions = null;\nif (environment.production) {\n const httpsOptions = {\n key: fs.readFileSync(environment.sslKeyPath),\n cert: fs.readFileSync(environment.sslCertPath),\n };\n\n serverOptions = { httpsOptions };\n}\nconst app = await NestFactory.create(AppModule, serverOptions)\n```\n\nbut apparently creating a server with options `null`, will break it.\n\nSo I changed it to something like this, since it works with undefined\n\n```\nconst app = await NestFactory.create(AppModule, serverOptions ?? undefinded)\n```\n\nalternatively do something like this, cause I don't know if setting the options to undefined is safe\n\n```\nconst app = serverOptions ? await NestFactory.create(AppModule, serverOptions) : await NestFactory.create(AppModule)\n```\n\nHope this helps someone with a similar problem\n\n========================================\n\nCode:\n```text\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { MyService } from 'my.service';\nimport { MyDto } from './dto/my.dto';\n\n@Controller('my-route')\nexport class MyController {\n\n    constructor(private readonly _myService: MyService) {}\n\n    @Post()\n    async  myMethod(@Body() myDto: MyDto) {\n        console.log(myDto); // undefined\n        return await this._myService.doStuff(myDto.elementOfInterest); // Passes undefined variable into method.\n    }\n}\n```\n\n```text\n@Body()\n```\n\n```text\nmyDto\n```\n\n```text\nContent-Type\n```\n\n```text\nContent-Type\n```\n\n```text\napplication/json\n```\n\n```text\nlet serverOptions = null;\nif (environment.production) {\n    const httpsOptions = {\n        key: fs.readFileSync(environment.sslKeyPath),\n        cert: fs.readFileSync(environment.sslCertPath),\n    };\n\n    serverOptions = { httpsOptions };\n}\nconst app = await NestFactory.create(AppModule, serverOptions)\n```\n\n```text\nconst app = await NestFactory.create(AppModule, serverOptions ?? undefinded)\n```\n\n```text\nconst app = serverOptions ? await NestFactory.create(AppModule, serverOptions) : await NestFactory.create(AppModule)\n```\n\n```text\nmain.ts\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- Did you add any global `Pipe` or `Interceptor`? I just made a quick check from a blank Nest project, creating a `@Post()` controller with a `@Body()` parameter, and I got it working as expected. **Edit** - I just tried your exact code, without MyDto and MyService, and it worked too. Which version of NestJS are you using?\n- No pipes or interceptors. I tested in both 4.5.10 and 4.6.6 and had the same behavior. When I send form data to the server, the code executes, but the body parameter is undefined.\n- Also, keep in mind to set `Content-Type` request header into `application&#47;json`.\n- That solved it.","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":141,"estimatedTokens":1025}}104{"id":"stack-70225539","source":"stackoverflow","questionId":70225539,"title":"How to validate query params in nestjs","tags":["javascript","node.js","design-patterns","nestjs"],"text":"Title: How to validate query params in nestjs\nTags: javascript, node.js, design-patterns, nestjs\nSource: Stack Overflow\n\nQuestion:\nYo, i have store application with nestjs, i need validate mongo id, which is pass by query, the problem is that i also pass and search query. I write pipe which validate all values, and exclude this search query\n\n```\n@Injectable()\nexport class ValidationObjectId implements PipeTransform {\n transform(value: UniqueId, metadata: ArgumentMetadata) {\n if (\n !Types.ObjectId.isValid(value) &&\n metadata.data !== \"searchString\"\n ) {\n throw new BadRequestException(\"ะะตะฒะตั€ะฝั‹ะน ะฟะฐั€ะฐะผะตั‚ั€ ะทะฐะฟั€ะพัะฐ\");\n }\n\n return value;\n }\n}\n```\n\nBut this code not reusable for other case. I want get some examples, how i can do this\n\n========================================\n\nTop Answer:\nFor single query param usage, you can play with this example:\n\n```\nimport { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common';\n\ntype TOptional = T | undefined;\n\n@Injectable()\nexport class ValidateEnum> implements PipeTransform {\n constructor(public readonly enumObj: T, public readonly isRequired = false) {}\n\n async transform(value: TOptional, { data: argName }: ArgumentMetadata): Promise> {\n const withValidation = this.isRequired ? true : value !== undefined;\n if (withValidation) {\n const enumValues = Object.values(this.enumObj);\n if (!enumValues.includes(value)) {\n throw new BadRequestException(`Invalid ${argName}=${value} - possible values: ${enumValues.join('|')}`);\n }\n }\n\n return value;\n }\n}\n```\n\nIf you want to use a pipe with a DTO object, check this out:\n\n```\nimport { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';\nimport { plainToInstance, Type } from 'class-transformer';\nimport { IsInt, IsOptional } from 'class-validator';\n\nexport class PaginationRequestDto {\n @Type(() => Number)\n @IsInt()\n @IsOptional()\n public readonly page?: number;\n\n @Type(() => Number)\n @IsInt()\n @IsOptional()\n public readonly take?: number;\n}\n\n@Injectable()\nexport class PaginationTransformPipe implements PipeTransform {\n async transform(dto: PaginationRequestDto, { metatype }: ArgumentMetadata) {\n if (!metatype) {\n return dto;\n }\n\n return plainToInstance(metatype, dto);\n }\n}\n```\n\nAnd usage example:\n\n```\n@Get('')\n// @UsePipes(new PaginationTransformPipe()) // also possible\npublic async someOperation(\n @Query(new PaginationTransformPipe()) pagination: PaginationRequestDto,\n @Query('status', new ValidateEnum(ESomeEnum)) status?: ESomeEnum\n ) {\n // ...your logic\n}\n```\n\nFor someone, it can be helpful to use default pipes\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class ValidationObjectId implements PipeTransform {\n    transform(value: UniqueId, metadata: ArgumentMetadata) {\n        if (\n            !Types.ObjectId.isValid(value) &&\n            metadata.data !== \"searchString\"\n        ) {\n            throw new BadRequestException(\"ะะตะฒะตั€ะฝั‹ะน ะฟะฐั€ะฐะผะตั‚ั€ ะทะฐะฟั€ะพัะฐ\");\n        }\n\n        return value;\n    }\n}\n```\n\n```text\nimport { IsBoolean, IsOptional } from \"class-validator\";\n\nexport class PostHelloQueryDTO {\n    @IsOptional()\n    @IsBoolean()\n    public useExclamation?: boolean;\n}\n```\n\n```text\n@Query(new ValidationPipe({\n    transform: true,\n    transformOptions: {enableImplicitConversion: true},\n    forbidNonWhitelisted: true\n})) query: PostHelloQueryDTO\n```\n\n```text\nValidationPipe\n```\n\n```text\n@Query()\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\nuseExclamation\n```\n\n```text\nenableInplicitConversion\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-validator\n```\n\n```text\n@IsMongoDB\n```\n\n```text\nimport { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common';\n\ntype TOptional<T> = T | undefined;\n\n@Injectable()\nexport class ValidateEnum<T extends Record<string, unknown>> implements PipeTransform<T> {\n    constructor(public readonly enumObj: T, public readonly isRequired = false) {}\n\n    async transform(value: TOptional<T>, { data: argName }: ArgumentMetadata): Promise<TOptional<T>> {\n        const withValidation = this.isRequired ? true : value !== undefined;\n        if (withValidation) {\n            const enumValues = Object.values(this.enumObj);\n            if (!enumValues.includes(value)) {\n                throw new BadRequestException(`Invalid ${argName}=${value} - possible values: ${enumValues.join('|')}`);\n            }\n        }\n\n        return value;\n    }\n}\n```\n\n```text\nimport { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';\nimport { plainToInstance, Type } from 'class-transformer';\nimport { IsInt, IsOptional } from 'class-validator';\n\nexport class PaginationRequestDto {\n    @Type(() => Number)\n    @IsInt()\n    @IsOptional()\n    public readonly page?: number;\n\n    @Type(() => Number)\n    @IsInt()\n    @IsOptional()\n    public readonly take?: number;\n}\n\n@Injectable()\nexport class PaginationTransformPipe implements PipeTransform {\n    async transform(dto: PaginationRequestDto, { metatype }: ArgumentMetadata) {\n        if (!metatype) {\n            return dto;\n        }\n\n        return plainToInstance(metatype, dto);\n    }\n}\n```\n\n```text\n@Get('')\n// @UsePipes(new PaginationTransformPipe()) // also possible\npublic async someOperation(\n    @Query(new PaginationTransformPipe()) pagination: PaginationRequestDto,\n    @Query('status', new ValidateEnum(ESomeEnum)) status?: ESomeEnum\n    ) {\n    // ...your logic\n}\n```\n\n========================================\n\nComments:\n- Great answer. But how we can validate nested request query and transform it like if I send query this way: `&#47;user?id[gte]=12` And get query object like this: `{ id: { gte: '12' } }`\n- @AmeerHamza use the combination of `@Type` from `class-transformer` (github.com/typestack/&hellip;) and `@ValidateNested` from `class-validator` (github.com/typestack/class-validator#validating-nested-obje&zwnj;&#8203;cts). Otherwise, everything is the same.\n- For me, the transformation logic, with the same config as the answer did not work. so I added a manual transformation `@Transform((value: string) => Number(value))` on the property","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":249,"estimatedTokens":1543}}105{"id":"stack-69057271","source":"stackoverflow","questionId":69057271,"title":"Why are cookies not sent to the server via getServerSideProps in Next.js?","tags":["node.js","reactjs","jwt","next.js","nestjs"],"text":"Title: Why are cookies not sent to the server via getServerSideProps in Next.js?\nTags: node.js, reactjs, jwt, next.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nCookies are not sent to the server via `getServerSideProps`, here is the code in the front-end:\n\n```\nexport async function getServerSideProps() {\n const res = await axios.get(\"http://localhost:5000/api/auth\", {withCredentials: true});\n const data = await res.data;\n return { props: { data } }\n}\n```\n\nOn the server I have a strategy that checks the access JWT token.\n\n```\nexport class JwtStrategy extends PassportStrategy(Strategy, \"jwt\") {\n constructor() {\n super({\n ignoreExpiration: false,\n secretOrKey: \"secret\",\n jwtFromRequest: ExtractJwt.fromExtractors([\n (request: Request) => {\n console.log(request.cookies) // [Object: null prototype] {}\n let data = request.cookies['access'];\n return data;\n }\n ]),\n });\n }\n\n async validate(payload: any){\n return payload;\n }\n}\n```\n\nThat is, when I send a request via `getServerSideProps` cookies do not come to the server, although if I send, for example via `useEffect`, then cookies come normally.\n\n========================================\n\nTop Answer:\n**Explanation:**\n\nIn Next.js, cookies are not automatically sent to the server via data fetching methods like `getServerSideProps` because these methods are executed on the server-side, and cookies are stored on the client-side. This means that if you're making a request from `getServerSideProps`, it will not have access to the client's cookies by default, and the request will be sent with an empty cookie.\n\nAlthough, we can set the client's cookies in `getServerSideProps` by extracting them from the incoming request headers. Whenever a user requests a page from the browser, the request is sent to the frontend server where the Next.js application is running. The server then builds the initial HTML and executes `getServerSideProps`. At this point, Next.js inject context parameter to `getServerSideProps` that contains information about the incoming request, including the request object, response object, query parameters, and more. We can access the browser request headers and extract the cookies from there. Once we have the cookies, we can set them explicitly in any further request made from `getServerSideProps`.\n\n```\nexport async function getServerSideProps(context) {\n const {req} = context;\n const res = await axios.get(\"http://localhost:5000/api/auth\", {\n withCredentials: true,\n headers: {\n Cookie: req.headers.cookie //like this\n }\n });\n const data = await res.data;\n return { props: { data } }\n}\n```\n\n========================================\n\nCode:\n```text\nexport async function getServerSideProps() {\n  const res = await axios.get(\"http://localhost:5000/api/auth\", {withCredentials: true});\n  const data = await res.data;\n  return { props: { data } }\n}\n```\n\n```text\nexport class JwtStrategy extends PassportStrategy(Strategy, \"jwt\") {\n    constructor() {\n        super({\n            ignoreExpiration: false,\n            secretOrKey: \"secret\",\n            jwtFromRequest: ExtractJwt.fromExtractors([\n                (request: Request) => {\n                    console.log(request.cookies) // [Object: null prototype] {}\n                    let data = request.cookies['access'];\n                    return data;\n                }\n            ]),\n        });\n    }\n\n    async validate(payload: any){\n        return payload;\n    }\n}\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetServerSideProps\n```\n\n```text\nuseEffect\n```\n\n```js\nexport async function getServerSideProps({ req }) {\n    const res = await axios.get(\"http://localhost:5000/api/auth\", {\n        withCredentials: true,\n        headers: {\n            Cookie: req.headers.cookie\n        }\n    });\n    const data = await res.data;\n    return { props: { data } }\n}\n```\n\n```js\nexport default function handler(req, res) {\n    const res = await axios.get(\"http://localhost:5000/api/auth\", {\n        withCredentials: true,\n        headers: {\n            Cookie: req.headers.cookie\n        }\n    });\n    const data = await res.data;\n    res.status(200).json(data)\n}\n```\n\n```text\ngetServerSideProps\n```\n\n```text\naxios\n```\n\n```text\nexport async function getServerSideProps(context) {\n    const {req} = context;\n    const res = await axios.get(\"http://localhost:5000/api/auth\", {\n        withCredentials: true,\n        headers: {\n            Cookie: req.headers.cookie //like this\n        }\n    });\n    const data = await res.data;\n    return { props: { data } }\n}\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetServerSideProps\n```\n\n========================================\n\nComments:\n- `getServerSideProps` get a ctx argument which has req, and res, refer here , you can use nookies library to parse the cookies\n- @SachinAnanthakumar, could you show me please how this is done with my code example?\n- refer to this\n- @SachinAnanthakumar also getting [Object: null prototype] {} on server :(\n- @ะžะฒะพะฒะžั‡ะพั‹ You need to explicitly pass the cookies from `getServerSideProps` context to the `axios` request. If you tried that and it's still not working can you show us how you're doing it?\n- @juliomalves please tell me how can i explicitly pass cookie through axios?\n- I have got a similar problem, but in the opposite direction. When I set a cookie from my seperate Node.js environment, the fetch called inside `getServerSideProps()` does not set cookies in the browser too. I understand why cookies are not being passed to the server, but I cannot get why they are not set from the server to the frontend\n- thanks mate. this helps to resolve issue on nextjs + lumen api based app.\n- Did not work... srcshare.io/?id=6246c6b123709353aaa1a350 @juliomalves\n- @OzanKurt It's not clear from the link you posted what's not working. I'd recommend you create a new question describing in detail the issue you're having.\n- @juliomalves what would you recommend to avoid settings header for every request? Is it possible to do that in axios interceptor?\n- @LouayHamada I'm not entirely sure you could use an axios interceptor as you'd need access to the `req` object to set the cookies. However, you could create a wrapper around axios itself that would add the additional cookies logic.\n- @juliomalves I didn't get the idea of creating wrapper around axios, can you please provide an example?\n- @LouayHamada Like an abstraction where you'd pass `req` and it would call and pass the cookies to the axios request.\n- I find it quite annoying though. Having to manually retrieve the cookie and pass it in each request like that is a big loss of energy. What if I have 600 server rendered pages ?\n- @shellking4 There's no way around it, the cookies need to be explicitly set when making a request from the server. You could create an abstraction to do it on every request.\n- Is it safe to pass the cookies like this?\n- In my case, i can clearly see the correct cookie is attached to the javascript bundles for the particular route (`_app.js`, `index.js`, etc), but when I attempt to access it via `req.cookies` or `req.headers.cookie` in my `[route]&#47;index.tsx`'s `getServerSideProps`, I pull a blank. `getServerSideProps` only seems to get the cookie when navigating from another page on the client-side (.e.g from `&#47;` to`&#47;app`). How is this possible?","metadata":{"transformedAt":"2026-08-18T18:33:02.410Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":202,"estimatedTokens":1851}}106{"id":"stack-56397866","source":"stackoverflow","questionId":56397866,"title":"Nest.Js Redirect from a controller to another","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: Nest.Js Redirect from a controller to another\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo I have this module:\n\n```\n@Module({\n imports: [],\n controllers: [AppController, AnotherController],\n providers: [],\n})\n```\n\nAnd in `AppController` on some route I want to do `res.redirect('/books')` where `/books` is a route found in `AnotherController`.\n\nFor some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.\n\n========================================\n\nTop Answer:\nAnother way to do that is to use the @Redirect() decorator as documented here:\nhttps://docs.nestjs.com/controllers#redirection\n\nThis should work as well:\n\n```\n@Controller()\nexport class AppController {\n @Get()\n @Redirect('books')\n redirect(){}\n}\n\n@Controller('books')\nexport class AnotherController {\n @Get()\n getBooks() {\n return 'books';\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [],\n  controllers: [AppController, AnotherController],\n  providers: [],\n})\n```\n\n```text\nAppController\n```\n\n```text\nres.redirect('/books')\n```\n\n```text\n/books\n```\n\n```text\nAnotherController\n```\n\n```text\n@Controller()\nexport class AppController {\n  @Get()\n  redirect(@Res() res) {\n    return res.redirect('/books/greet');\n  }\n}\n\n@Controller('books')\nexport class AnotherController {\n  @Get('greet')\n  greet() {\n    return 'hello';\n  }\n}\n```\n\n```text\nres.redirect(target)\n```\n\n```text\n@Controller('books')\n```\n\n```text\n@Get('greet')\n```\n\n```text\n/books/greet\n```\n\n```text\n@Controller()\nexport class AppController {\n  @Get()\n  @Redirect('books')\n  redirect(){}\n}\n\n@Controller('books')\nexport class AnotherController {\n  @Get()\n  getBooks() {\n    return 'books';\n  }\n}\n```\n\n========================================\n\nComments:\n- This is indeed the correct answer. What is weird is that I keep my controllers in 2 separate files and it doesn't work like that. It only works if i don't specify anything in the `@Controller()` and then write `@Get('&#47;books&#47;greet')`. Which is weird because this is something that I understand is by default.\n- Apparently having another route like `&#47;books&#47;:id` written as `@Get(':id')` was breaking it.\n- note, this only works with `GET` method, any url provided with otherwise will be sent with a get first causing the endpoint not to be found","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":128,"estimatedTokens":592}}107{"id":"stack-55560858","source":"stackoverflow","questionId":55560858,"title":"In nest.js, is it possible to get service instance inside a param decorator?","tags":["javascript","node.js","typescript","decorator","nestjs"],"text":"Title: In nest.js, is it possible to get service instance inside a param decorator?\nTags: javascript, node.js, typescript, decorator, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to achieve something like this using nest.js:\n(something very similar with Spring framework)\n\n```\n@Controller('/test')\nclass TestController {\n @Get()\n get(@Principal() principal: Principal) {\n\n }\n}\n```\n\nAfter hours of reading documentation, I found that nest.js supports creating custom decorator. So I decided to implement my own `@Principal` decorator. The decorator is responsible for retrieving access token from http header and get principal of user from my own auth service using the token.\n\n```\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Principal = createParamDecorator((data: string, req) => {\n const bearerToken = req.header.Authorization;\n // parse.. and call my authService..\n // how to call my authService here?\n return null;\n});\n```\n\nBut the problem is that I have no idea how to get my service instance inside a decorator handler. Is it possible? And how? Thank you in advance\n\n========================================\n\nTop Answer:\n**for NestJS v7**\n\nCreate custom pipe\n\n```\n// parse-token.pipe.ts\nimport { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';\nimport { AuthService } from './auth.service';\n\n@Injectable()\nexport class ParseTokenPipe implements PipeTransform {\n // inject any dependency\n constructor(private authService: AuthService) {}\n \n async transform(value: any, metadata: ArgumentMetadata) {\n console.log('additional options', metadata.data);\n return this.authService.parse(value);\n }\n}\n```\n\nUse this pipe with property decorator\n\n```\n// decorators.ts\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { ParseTokenPipe} from './parse-token.pipe';\n\nexport const GetToken = createParamDecorator((data: unknown, ctx: ExecutionContext) => {\n return ctx.switchToHttp().getRequest().header.Authorization;\n});\n\nexport const Principal = (additionalOptions?: any) => GetToken(additionalOptions, ParseTokenPipe);\n```\n\nUse this decorator with or without additional options\n\n```\n@Controller('/test')\nclass TestController {\n @Get()\n get(@Principal({hello: \"world\"}) principal) {}\n}\n```\n\n========================================\n\nCode:\n```text\n@Controller('/test')\nclass TestController {\n  @Get()\n  get(@Principal() principal: Principal) {\n\n  }\n}\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Principal = createParamDecorator((data: string, req) => {\n  const bearerToken = req.header.Authorization;\n  // parse.. and call my authService..\n  // how to call my authService here?\n  return null;\n});\n```\n\n```text\n@Principal\n```\n\n```text\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  constructor(private authService: AuthService) {}\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const bearerToken = request.header.Authorization;\n    const user = await this.authService.authenticate(bearerToken);\n    request.principal = user;\n    // If you want to allow the request even if auth fails, always return true\n    return !!user;\n  }\n}\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Principal = createParamDecorator((data: string, req) => {\n  return req.principal;\n});\n```\n\n```text\n@Get()\n@UseGuards(AuthGuard)\nget(@Principal() principal: Principal) {\n  // ...\n}\n```\n\n```text\nAuthGuard\n```\n\n```text\nrequest\n```\n\n```ts\ninterface AccountData {\n  accId: string;\n  iat: number;\n  exp: number;\n}\n\ninterface RequestWithAccountId extends Request {\n  accId: string;\n}\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n  constructor(private readonly authenticationService: AuthenticationService) {}\n  async use(req: RequestWithAccountId, res: Response, next: NextFunction) {\n    const token =\n      req.body.token || req.query.token || req.headers['authorization'];\n    if (!token) {\n      throw new UnauthorizedException();\n    }\n    try {\n      const {\n        accId,\n      }: AccountData = await this.authenticationService.verifyToken(token);\n      req.accId = accId;\n      next();\n    } catch (err) {\n      throw new UnauthorizedException();\n    }\n  }\n}\n```\n\n```ts\nimport {\n  createParamDecorator,\n  ExecutionContext,\n  UnauthorizedException,\n} from '@nestjs/common';\n\nexport const AccountId = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const req = ctx.switchToHttp().getRequest();\n    const token = req.accId;\n    if (!token) {\n      throw new UnauthorizedException();\n    }\n    return token;\n  },\n);\n```\n\n```ts\n@Get()\n  async someEndpoint(\n    @AccountId() accountId,\n  ) {\n    console.log('accountId',accontId)\n  }\n```\n\n```text\n// parse-token.pipe.ts\nimport { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';\nimport { AuthService } from './auth.service';\n\n@Injectable()\nexport class ParseTokenPipe implements PipeTransform {\n    // inject any dependency\n    constructor(private authService: AuthService) {}\n    \n    async transform(value: any, metadata: ArgumentMetadata) {\n        console.log('additional options', metadata.data);\n        return this.authService.parse(value);\n    }\n}\n```\n\n```text\n// decorators.ts\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { ParseTokenPipe} from './parse-token.pipe';\n\nexport const GetToken = createParamDecorator((data: unknown, ctx: ExecutionContext) => {\n  return ctx.switchToHttp().getRequest().header.Authorization;\n});\n\nexport const Principal = (additionalOptions?: any) => GetToken(additionalOptions, ParseTokenPipe);\n```\n\n```text\n@Controller('/test')\nclass TestController {\n  @Get()\n  get(@Principal({hello: \"world\"}) principal) {}\n}\n```\n\n```js\nimport { UserSession } from '@interfaces/types/auth/user-session';\nimport { CanActivate, ExecutionContext, Inject, Injectable, createParamDecorator } from '@nestjs/common';\nimport { FastifyRequest } from 'fastify';\nimport { AuthService } from '../services/auth/auth.service';\n\nconst SYMBOL = Symbol('BasicAuthGuard');\n\nexport const Session = createParamDecorator<never, ExecutionContext, UserSession>((_, ctx) => {\n  const request = ctx.switchToHttp().getRequest();\n  return request[SYMBOL];\n})\n\n@Injectable()\nexport class BasicAuthGuard implements CanActivate {\n\n  constructor(\n    @Inject(AuthService)\n    private readonly auth_service: AuthService\n  ) { }\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n\n    const request = context.switchToHttp().getRequest<FastifyRequest>();\n\n    const [type, credential] = request.headers.authorization?.split(' ') || [];\n\n    if (type !== 'Bearer')\n      return false;\n\n    const session = await this.auth_service.authenticate({ credential });\n    (request as any)[SYMBOL] = session;\n\n    return true;\n  }\n}\n```\n\n```js\nimport { UserSession } from '@interfaces/types/auth/user-session';\nimport { ResidentListSearchParams } from '@interfaces/types/resident';\nimport { Controller, Get, Inject, Query, UseGuards } from '@nestjs/common';\nimport { BasicAuthGuard, Session } from '../../guards/basic-auth.guard';\nimport { ResidentService } from '../../services/resident/resident.service';\n\n@Controller('residents')\nexport class ResidentController {\n\n  constructor(\n    @Inject(ResidentService)\n    private resident_service: ResidentService\n  ) { }\n\n  @Get()\n  @UseGuards(BasicAuthGuard)\n  async list(\n    @Query() search_params: ResidentListSearchParams,\n    @Session() user: UserSession\n  ) {\n    console.log(user); // { email: 'foo@bar.com', id: 1 }\n    return await this.resident_service.list({ search_params });\n  }\n}\n```\n\n```text\nrequest\n```\n\n========================================\n\nComments:\n- This is not an appropriate use of guards, imo. There's a solution below that makes use of Pipes which is probably a better option in a NestJS context.\n- @TaylorBuckner This is exactly what the default `AuthGuard` does in the @nestjs/passport library, see github.com/nestjs/passport/blob/&hellip;\n- using `async someEndPoint (@Request() req) { return req.accId }` is is much simpler, no need to use decorator...","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":322,"estimatedTokens":2049}}108{"id":"stack-54885935","source":"stackoverflow","questionId":54885935,"title":"How to save relation in @ManyToMany in typeORM","tags":["javascript","node.js","orm","nestjs","typeorm"],"text":"Title: How to save relation in @ManyToMany in typeORM\nTags: javascript, node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThere are 2 entities named `Article` and `Classification`. And the relation of them is `@ManyToMany`.\n\nHere's my question: How to save the relation?\n\nMy code as below:\n\n```\n@Entity()\n export class Article {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @CreateDateColumn()\n createTime: Date;\n\n @UpdateDateColumn()\n updateTime: Date;\n\n @Column({\n type: 'text',\n })\n content: string;\n\n @Column({\n default: 0,\n })\n likeAmount: number;\n\n @Column({\n default: 0,\n })\n commentAmount: number;\n }\n\n @Entity()\n export class Classification {\n @PrimaryGeneratedColumn()\n id: number;\n\n @CreateDateColumn()\n createTime: Date;\n\n @UpdateDateColumn()\n updateTime: Date;\n\n @Column()\n name: string;\n\n @ManyToMany(type => Article)\n @JoinTable()\n articles: Article[];\n }\n```\n\nI can save the `Article` and `Classification` successful. But I'm not sure how to save the relation of them.\n\nI have tried to save the relation via below code:\n\n```\nasync create(dto: ArticleClassificationDto): Promise {\n const article = this.repository.save(dto);\n article.then(value => {\n console.log(value);//console the object article\n value.classification.forEach(item => {\n const classification = new Classification();\n classification.id = item.id;\n classification.articles = [];\n classification.articles.push(value);\n this.classificationService.save(classification);\n })\n });\n console.log(article);\n return null;\n }\n```\n\nAnd the post data strcture like that\n\n```\n{\n \"name\":\"artile name\",\n \"content\":\"article content\",\n \"classification\":[{\n \"id\":4\n },{\n \"id\":3\n }]\n }\n```\n\nAt the beginning, it works.\n\nhttps://i.sstatic.net/7yrPB.png\n\nBut when I post the data again, the old record was replaced rather create another record.\n\nhttps://i.sstatic.net/HBFlc.png\n\nWhat should I do next?\n\nJust look below code please.\n\n```\nasync create(dto: ArticleClassificationDto): Promise {\n this.repository.save(dto).then(article => {\n article.classification.forEach(item => {\n this.ClassificationRepository.findOne(\n {\n // the privous method is get all the articles from databse and push into this array\n // relations: ['articles'],\n where: { id: item }// now I change the data strcture, just contains id instead of {id}\n }\n ).then(classification => {\n // console.log(article);\n console.log(classification);\n // cmd will show ' UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined' withous below line code. But if I init the array manually,the old record will be replaced again.\n // classification.articles = [];\n classification.articles.push(article);\n this.ClassificationRepository.save(classification);\n });\n })\n })\n return null;\n }\n```\n\n========================================\n\nTop Answer:\nin my case i have user and role, 1st you have to initialize your manytomany in your entities :\n\nin user entity :\n\n```\n@ManyToMany((type) => Role, {\n cascade: true,\n })\n @JoinTable({\n name: \"users_roles\",\n joinColumn: { name: \"userId\", referencedColumnName: \"id\" },\n inverseJoinColumn: { name: \"roleId\" }\n })\n roles: Role[];\n```\n\nin role entity :\n\n```\n//Many-to-many relation with user\n @ManyToMany((type) => User, (user) => user.roles)\n users: User[];\n```\n\nin my service i create a new entity from my data then i added role data to my new entity object :\n\n```\nlet entity = await this.userRepository.create(data);\nlet entity2 = {\n ...entity,\n roles: data.selectedRoles,\n };\nconst user = await this.userRepository.save(entity2);\n```\n\nthis is the exemple in typeorm website :\n\n```\nconst category1 = new Category();\ncategory1.name = \"animals\";\nawait connection.manager.save(category1);\n\nconst category2 = new Category();\ncategory2.name = \"zoo\";\nawait connection.manager.save(category2);\n\nconst question = new Question();\nquestion.title = \"dogs\";\nquestion.text = \"who let the dogs out?\";\nquestion.categories = [category1, category2];\nawait connection.manager.save(question);\n```\n\n========================================\n\nCode:\n```text\n@Entity()\n    export class Article {\n        @PrimaryGeneratedColumn()\n        id: number;\n\n        @Column()\n        name: string;\n\n        @CreateDateColumn()\n        createTime: Date;\n\n        @UpdateDateColumn()\n        updateTime: Date;\n\n        @Column({\n            type: 'text',\n        })\n        content: string;\n\n        @Column({\n            default: 0,\n        })\n        likeAmount: number;\n\n        @Column({\n            default: 0,\n        })\n        commentAmount: number;\n    }\n\n    @Entity()\n    export class Classification {\n        @PrimaryGeneratedColumn()\n        id: number;\n\n        @CreateDateColumn()\n        createTime: Date;\n\n        @UpdateDateColumn()\n        updateTime: Date;\n\n        @Column()\n        name: string;\n\n        @ManyToMany(type => Article)\n        @JoinTable()\n        articles: Article[];\n    }\n```\n\n```text\nasync create(dto: ArticleClassificationDto): Promise<any> {\n    const article = this.repository.save(dto);\n    article.then(value => {\n      console.log(value);//console the object article\n      value.classification.forEach(item => {\n        const classification = new Classification();\n        classification.id = item.id;\n        classification.articles = [];\n        classification.articles.push(value);\n        this.classificationService.save(classification);\n      })\n    });\n    console.log(article);\n    return null;\n  }\n```\n\n```text\n{\n        \"name\":\"artile name\",\n        \"content\":\"article content\",\n        \"classification\":[{\n            \"id\":4\n        },{\n            \"id\":3\n        }]\n    }\n```\n\n```text\nasync create(dto: ArticleClassificationDto): Promise<any> {\n    this.repository.save(dto).then(article => {\n      article.classification.forEach(item => {\n        this.ClassificationRepository.findOne(\n          {\n            // the privous method is get all the articles from databse and push into this array\n            // relations: ['articles'],\n            where: { id: item }// now I change the data strcture, just contains id instead of {id}\n          }\n        ).then(classification => {\n          // console.log(article);\n          console.log(classification);\n          // cmd will show ' UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined' withous below line code. But if I init the array manually,the old record will be replaced again.\n          // classification.articles = [];\n          classification.articles.push(article);\n          this.ClassificationRepository.save(classification);\n        });\n      })\n    })\n    return null;\n  }\n```\n\n```text\nArticle\n```\n\n```text\nClassification\n```\n\n```text\n@ManyToMany\n```\n\n```text\nArticle\n```\n\n```text\nClassification\n```\n\n```text\nclassification.articles = [article1, article2];\nawait this.classificationRepository.save(classification);\n```\n\n```text\n@ManyToMany(type => Article, article => article.classifications, { cascade: true })\n```\n\n```text\nasync create(dto: ArticleClassificationDto): Promise<any> {\n  let article = await this.repository.create(dto);\n  article = await this.repository.save(article);\n  const classifications = await this.classificationRepository.findByIds(article.classification, {relations: ['articles']});\n  for (const classification of classifications) {\n    classification.articles.push(article);\n  }\n  return this.classificationRepository.save(classifications);\n}\n```\n\n```text\narticles\n```\n\n```text\ncascade\n```\n\n```text\ntrue\n```\n\n```text\n@ManyToMany((type) => Role, {\n    cascade: true,\n  })\n  @JoinTable({\n    name: \"users_roles\",\n    joinColumn: { name: \"userId\", referencedColumnName: \"id\" },\n    inverseJoinColumn: { name: \"roleId\" }\n  })\n  roles: Role[];\n```\n\n```text\n//Many-to-many relation with user\n  @ManyToMany((type) => User, (user) => user.roles)\n  users: User[];\n```\n\n```text\nlet entity = await this.userRepository.create(data);\nlet entity2 = {\n        ...entity,\n        roles: data.selectedRoles,\n      };\nconst user = await this.userRepository.save(entity2);\n```\n\n```text\nconst category1 = new Category();\ncategory1.name = \"animals\";\nawait connection.manager.save(category1);\n\nconst category2 = new Category();\ncategory2.name = \"zoo\";\nawait connection.manager.save(category2);\n\nconst question = new Question();\nquestion.title = \"dogs\";\nquestion.text = \"who let the dogs out?\";\nquestion.categories = [category1, category2];\nawait connection.manager.save(question);\n```\n\n========================================\n\nComments:\n- I have tried your method. And it didn't work for me. I have updated my question, can u help next?\n- This is a different problem now: You are posting the `classifications` with their `id`'s. `id` is the `PrimaryGeneratedColumn` of the `classification` entity. If you want to create a new object, you must not include the primary column, otherwise the entity will be updated instead of created if the primary column (`id`) already exists.\n- But I just wanna save the relation of them. Not save the entity `Classification`.I do wanna create a new object, but not `classification`, just new relation of `classification` and `article`.And I need the `id` of `Classification` automatically generated with an auto-increment value when I insert a new `Classification`. I'm not clear how to realize my target?\n- Ok, so all entities already exist; you just want to create the relation between the entities!? Then just load your classification entity from the database `findOne(classificationId)`, assign the articles to the classification entity you loaded from the database and then save the classification entity.\n- I have done as what u said. But there was something wrong with it. I have posted the code in the question.\n- You are creating a new entity `const classification = new Classification();` instead of loading the existing one from the database.\n- Are you sure the code you watched is below `Just look below code please`?\n- Let us continue this discussion in chat.\n- thx, I have tried to add ManyToMany in Article,Now I have ManyToMany in Article and Classification,but still not work for me. And I tried another solution: find all articles that classification contains, just like `classification{id:4,articles:[article1,article2]}`,then `classification.articles.push(newArticle)`.Then it works. But I know this is a terrible solution.\n- I guess I figure it out. When I create a object of Classification. And set its id. In that time, the articles is empty. So I push one article in it, the typeorm will think it has only one article even if it has a lot of articles in database? So the previous solution is right?\n- Mh, I'm afraid I can't completely what you're doing. :-/ However, you should *either* create a new entity without setting an `id` or load an existing entity from the database with its `id`.\n- emm,sorry to bother u, cause my english is not good. How about chatting in the linking now you posted yesterday?","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":409,"estimatedTokens":2730}}109{"id":"stack-70897363","source":"stackoverflow","questionId":70897363,"title":"How to define the response body object, in a NestJs-generated Swagger document?","tags":["typescript","swagger","nestjs"],"text":"Title: How to define the response body object, in a NestJs-generated Swagger document?\nTags: typescript, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm Using NestJs and its Swagger plugin to auto-generate documentation of my API.\n\nProblem is, I cant figure out how to make the **response** schema appear in the documentation. In my GET routes, all i get is \"Code 200\", with no data structure.\n\nI have a typical setup, where a controller method uses a corresponding service method, which in turn uses a TypeOrm repository. For example:\n\n```\n@Get()\n findAll() { \n return this.usersService.findAll();\n}\n```\n\nI tried using the *@ApiResponse* decorator, but didn't really see any way to make it serve this purpose. Also, creating a user.dto.ts and making it the return type of the controller route didn't do any good.\n\nEventually, this is what i get in the Swagger:\n\nhttps://i.sstatic.net/7mFM4.png\n\nHow can i define the response body schema?\n\n========================================\n\nTop Answer:\nYou can annotate controller action with `ApiExtraModels`:\n\n```\nimport { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger'\nimport { Controller, Get, Param } from '@nestjs/common';\n\n@Controller('users')\nexport class UsersController {\n\n @ApiExtraModels(UserDto)\n @ApiResponse({\n status: 200,\n schema: {\n $ref: getSchemaPath(UserDto),\n },\n })\n @Get('/:userId')\n getById(@Param('userId') userId: string): UserDto {\n ... something happens ... \n return myUserDto;\n }\n\n}\n```\n\nand you have to also annotate `UserDto` properties with `ApiProperty`:\n\n```\nimport { ApiProperty } from '@nestjs/swagger'\nimport { Expose } from 'class-transformer'\nimport { IsString } from 'class-validator'\n\nexport class UserDto {\n\n @ApiProperty()\n @IsString()\n @Expose()\n id: string;\n}\n```\n\nBtw, check CLI plugin for generating ApiProperty\n\n========================================\n\nCode:\n```text\n@Get()\n findAll() {    \n   return this.usersService.findAll();\n}\n```\n\n```text\n@ApiOkResponse({\n    description: 'The user records',\n    type: User,\n    isArray: true\n})\n@Get()\n findAll() {    \n   return this.usersService.findAll();\n}\n```\n\n```text\ntype\n```\n\n```text\nisArray\n```\n\n```text\nApiResponse\n```\n\n```text\nimport { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger'\nimport { Controller, Get, Param } from '@nestjs/common';\n\n@Controller('users')\nexport class UsersController {\n\n\n @ApiExtraModels(UserDto)\n @ApiResponse({\n    status: 200,\n    schema: {\n      $ref: getSchemaPath(UserDto),\n    },\n  })\n  @Get('/:userId')\n  getById(@Param('userId') userId: string): UserDto {\n     ... something happens ... \n     return myUserDto;\n  }\n\n}\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger'\nimport { Expose } from 'class-transformer'\nimport { IsString } from 'class-validator'\n\nexport class UserDto {\n\n  @ApiProperty()\n  @IsString()\n  @Expose()\n  id: string;\n}\n```\n\n```text\nApiExtraModels\n```\n\n```text\nUserDto\n```\n\n```text\nApiProperty\n```\n\n```text\nimport { User } from './entities/user.entity';\n\n@Get()\nfindAll(): Promise<User[]> {    \n  return this.usersService.findAll();\n}\n```\n\n```text\n{\n  // ...\n        \"responses\": {\n          \"200\": {\n            \"description\": \"\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n-                    \"type\": \"object\"\n+                    \"$ref\": \"#/components/schemas/User\"\n                  }\n                }\n              }\n            }\n          }\n        },\n  // ...\n}\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- This worked once the \"type\" property referred to a simple dto, not to the User entity of Typeorm. Which one did you mean, by type:User? Anyhow, thanx!\n- It needs to be a DTO, unless you're using the Swagger CLI plugin which can infer a lot of this stuff for you automatically\n- Yes so I used the plugin, but it didn't seem to infer the data correctly from the User entity that is eventually returned by the route. Perhaps some tweaking is needed?\n- @JesseCarter Does the plugin extract the type inside a `Promise`? I have an async `findAll` and it seems the plugin cannot infer the DTO type wrapped by the promise.","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":199,"estimatedTokens":1056}}110{"id":"stack-53296157","source":"stackoverflow","questionId":53296157,"title":"How to refresh token in Nestjs","tags":["javascript","node.js","typescript","passport.js","nestjs"],"text":"Title: How to refresh token in Nestjs\nTags: javascript, node.js, typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { JwtPayload } from './model/jwt-payload.model';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: 'secretKey',\n });\n }\n\n async validate(payload: JwtPayload) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return true;\n }\n}\n```\n\nToken is extracted from the request by `PassportStrategy`. I don't know how to catch the error when the token expires or gets invalid. My purpose is if there is an error because the token expired, I need to refresh the token. Otherwise do something else.\n\n========================================\n\nTop Answer:\nRefresh token implementation could be handled in `canActivate` method in custom auth guard.\n\nIf the access token is expired, the refresh token will be used to obtain a new access token. In that process, refresh token is updated too.\n\nIf both tokens aren't valid, cookies will be cleared.\n\n```\n@Injectable()\nexport class CustomAuthGuard extends AuthGuard('jwt') {\n private logger = new Logger(CustomAuthGuard.name);\n\n constructor(\n private readonly authService: AuthService,\n private readonly userService: UserService,\n ) {\n super();\n }\n\n async canActivate(context: ExecutionContext): Promise {\n const request = context.switchToHttp().getRequest();\n const response = context.switchToHttp().getResponse();\n\n try {\n const accessToken = ExtractJwt.fromExtractors([cookieExtractor])(request);\n if (!accessToken)\n throw new UnauthorizedException('Access token is not set');\n\n const isValidAccessToken = this.authService.validateToken(accessToken);\n if (isValidAccessToken) return this.activate(context);\n\n const refreshToken = request.cookies[REFRESH_TOKEN_COOKIE_NAME];\n if (!refreshToken)\n throw new UnauthorizedException('Refresh token is not set');\n const isValidRefreshToken = this.authService.validateToken(refreshToken);\n if (!isValidRefreshToken)\n throw new UnauthorizedException('Refresh token is not valid');\n\n const user = await this.userService.getByRefreshToken(refreshToken);\n const {\n accessToken: newAccessToken,\n refreshToken: newRefreshToken,\n } = this.authService.createTokens(user.id);\n\n await this.userService.updateRefreshToken(user.id, newRefreshToken);\n\n request.cookies[ACCESS_TOKEN_COOKIE_NAME] = newAccessToken;\n request.cookies[REFRESH_TOKEN_COOKIE_NAME] = newRefreshToken;\n\n response.cookie(ACCESS_TOKEN_COOKIE_NAME, newAccessToken, COOKIE_OPTIONS);\n response.cookie(\n REFRESH_TOKEN_COOKIE_NAME,\n newRefreshToken,\n COOKIE_OPTIONS,\n );\n\n return this.activate(context);\n } catch (err) {\n this.logger.error(err.message);\n response.clearCookie(ACCESS_TOKEN_COOKIE_NAME, COOKIE_OPTIONS);\n response.clearCookie(REFRESH_TOKEN_COOKIE_NAME, COOKIE_OPTIONS);\n return false;\n }\n }\n\n async activate(context: ExecutionContext): Promise {\n return super.canActivate(context) as Promise;\n }\n\n handleRequest(err, user) {\n if (err || !user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\nAttaching user to the request is done in `validate` method in `JwtStrategy` class, it will be called if the access token is valid\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n readonly configService: ConfigService,\n private readonly userService: UserService,\n ) {\n super({\n jwtFromRequest: cookieExtractor,\n ignoreExpiration: false,\n secretOrKey: configService.get('jwt.secret'),\n });\n }\n\n async validate({ id }): Promise {\n const user = await this.userService.get(id);\n if (!user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\nExample for custom cookie extractor\n\n```\nexport const cookieExtractor = (request: Request): string | null => {\n let token = null;\n if (request && request.signedCookies) {\n token = request.signedCookies[ACCESS_TOKEN_COOKIE_NAME];\n }\n return token;\n};\n```\n\n========================================\n\nCode:\n```text\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { JwtPayload } from './model/jwt-payload.model';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: 'secretKey',\n    });\n  }\n\n  async validate(payload: JwtPayload) {\n    const user = await this.authService.validateUser(payload);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return true;\n  }\n}\n```\n\n```text\nPassportStrategy\n```\n\n```text\n@Injectable()\nexport class MyAuthGuard extends AuthGuard('jwt') {\n\n  handleRequest(err, user, info: Error) {\n    if (info instanceof TokenExpiredError) {\n      // do stuff when token is expired\n      console.log('token expired');\n    }\n    return user;\n  }\n\n}\n```\n\n```text\nAuthGuard\n```\n\n```text\ncanActivate\n```\n\n```text\nAuthGuard\n```\n\n```text\n@Injectable()\nexport class CustomAuthGuard extends AuthGuard('jwt') {\n  private logger = new Logger(CustomAuthGuard.name);\n\n  constructor(\n    private readonly authService: AuthService,\n    private readonly userService: UserService,\n  ) {\n    super();\n  }\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const response = context.switchToHttp().getResponse();\n\n    try {\n      const accessToken = ExtractJwt.fromExtractors([cookieExtractor])(request);\n      if (!accessToken)\n        throw new UnauthorizedException('Access token is not set');\n\n      const isValidAccessToken = this.authService.validateToken(accessToken);\n      if (isValidAccessToken) return this.activate(context);\n\n      const refreshToken = request.cookies[REFRESH_TOKEN_COOKIE_NAME];\n      if (!refreshToken)\n        throw new UnauthorizedException('Refresh token is not set');\n      const isValidRefreshToken = this.authService.validateToken(refreshToken);\n      if (!isValidRefreshToken)\n        throw new UnauthorizedException('Refresh token is not valid');\n\n      const user = await this.userService.getByRefreshToken(refreshToken);\n      const {\n        accessToken: newAccessToken,\n        refreshToken: newRefreshToken,\n      } = this.authService.createTokens(user.id);\n\n      await this.userService.updateRefreshToken(user.id, newRefreshToken);\n\n      request.cookies[ACCESS_TOKEN_COOKIE_NAME] = newAccessToken;\n      request.cookies[REFRESH_TOKEN_COOKIE_NAME] = newRefreshToken;\n\n      response.cookie(ACCESS_TOKEN_COOKIE_NAME, newAccessToken, COOKIE_OPTIONS);\n      response.cookie(\n        REFRESH_TOKEN_COOKIE_NAME,\n        newRefreshToken,\n        COOKIE_OPTIONS,\n      );\n\n      return this.activate(context);\n    } catch (err) {\n      this.logger.error(err.message);\n      response.clearCookie(ACCESS_TOKEN_COOKIE_NAME, COOKIE_OPTIONS);\n      response.clearCookie(REFRESH_TOKEN_COOKIE_NAME, COOKIE_OPTIONS);\n      return false;\n    }\n  }\n\n  async activate(context: ExecutionContext): Promise<boolean> {\n    return super.canActivate(context) as Promise<boolean>;\n  }\n\n  handleRequest(err, user) {\n    if (err || !user) {\n      throw new UnauthorizedException();\n    }\n\n    return user;\n  }\n}\n```\n\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(\n    readonly configService: ConfigService,\n    private readonly userService: UserService,\n  ) {\n    super({\n      jwtFromRequest: cookieExtractor,\n      ignoreExpiration: false,\n      secretOrKey: configService.get('jwt.secret'),\n    });\n  }\n\n  async validate({ id }): Promise<User> {\n    const user = await this.userService.get(id);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n\n    return user;\n  }\n}\n```\n\n```text\nexport const cookieExtractor = (request: Request): string | null => {\n  let token = null;\n  if (request && request.signedCookies) {\n    token = request.signedCookies[ACCESS_TOKEN_COOKIE_NAME];\n  }\n  return token;\n};\n```\n\n```text\ncanActivate\n```\n\n```text\nvalidate\n```\n\n```text\nJwtStrategy\n```\n\n========================================\n\nComments:\n- I don't understand. How should I pass a new access token to the client using this approach? Would you please elaborate?\n- @Albert It really depends on your specific requirements, but maybe this thread will be helpful.\n- WHere TOken ExpirationError from?\n- this doesn't attach the user to the request\n- attaching the user to the request is done in `validate` method in `JwtStrategy` class, I added an example for that\n- where the cookieExtractors comes from?\n- cookieExtractor is a custom extractor, example is updated with it\n- With this solution you send the refreshToken in each request. So what is the point of using a refreshToken? The goal is precisely to avoid sharing it too frequently.\n- @PaulSerre what if the RToken is already from db, not from cookie?","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":344,"estimatedTokens":2344}}111{"id":"stack-63257879","source":"stackoverflow","questionId":63257879,"title":"Get current user in nestjs on a route without an AuthGuard","tags":["node.js","typescript","passport.js","nestjs","nestjs-passport"],"text":"Title: Get current user in nestjs on a route without an AuthGuard\nTags: node.js, typescript, passport.js, nestjs, nestjs-passport\nSource: Stack Overflow\n\nQuestion:\nI use nestjs with passport with jwt strategy. And I want to get a current user on some of my requests.\nCurrently, I have a decorator that looks like this:\n\n```\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n (data: string, ctx: ExecutionContext) => {\n const user = ctx.switchToHttp().getRequest().user;\n\n if (!user) {\n return null;\n }\n\n return data ? user[data] : user; // extract a specific property only if specified or get a user object\n },\n);\n```\n\nIt works as intended when i use it on a route with an AuthGuard:\n\n```\n@Get('test')\n @UseGuards(AuthGuard())\n testRoute(@CurrentUser() user: User) {\n console.log('Current User: ', user);\n return { user };\n }\n```\n\nBut how do i make it work (get current user) on non-guarded routes? I need users to be able to post their comments regardless of if they are authorized or not, however, when they are logged in, i need to get their name.\n\nBasically, I need a way to propagate req.user on every(or at least on some of not AuthGuard'ed request), it is really straight forward to do in express by applying passport middleware, but I'm not sure how to do it with @nestjs/passport.\n\n[EDIT]\nThanks to vpdiongzon for pointing me in the right direction, I chose to make a guard based on his answer, that just populates req.user with either user or null:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class ApplyUser extends AuthGuard('jwt') {\n handleRequest(err: any, user: any) {\n if (user) return user;\n return null;\n }\n}\n```\n\nAnd now I could just use it on any unprotected route that needs to get the current user\n\n```\n@Get('me')\n@UseGuards(ApplyUser)\nme(@CurrentUser() user: User) {\n return { user };\n}\n```\n\n========================================\n\nTop Answer:\n```\n\"Basically, I need a way to propagate req.user on every(or at least on some of not AuthGuard'ed request), it is realy straight forward to do in express by applying passport middleware, but im not sure how to do it with @nestjs/passport.\"\n```\n\nTo achieve this we write an interceptor because we need to use the UsersService. UserService is part of the dependency injection system. We cannot just import the user service and create a new instance of it ourselves. The service makes use of the users repository and that users repository is setup only through dependency injection.\n\nThe thing is we cannot make use of dependency injection with a parameter decorator. This decorator cannot reach into the system in any way and try to get access to some instance of anything inside there. This is how we write the interceptor. I make comments on the code:\n\n```\n// this interceptor will be used by the custom param decoratro to fetch the current User\nimport {NestInterceptor,ExecutionContext,CallHandler,Injectable} from '@nestjs/common';\nimport { UsersService } from '../users.service';\n\n@Injectable()\n// \"implements\" guide us how to put together an interceptor\nexport class CurrentUserInterceptor implements NestInterceptor {\n constructor(private userService: UsersService) {}\n // handler refers to the route handler\n async intercept(context: ExecutionContext, handler: CallHandler) {\n const request = context.switchToHttp().getRequest();\n const { userId } = request.session || {};\n if (userId) {\n const user = await this.userService.findOne(userId);\n // we need to pass this down to the decorator. SO we assign the user to request because req can be retrieved inside the decorator\n // ------THIS IS WHAT YOU WANTED--------\n request.currentUser = user;\n }\n // run the actual route handler\n return handler.handle();\n }\n}\n```\n\nNow you need to register this to the module:\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [UsersService, AuthService, CurrentUserInterceptor],\n })\n```\n\nInside controller:\n\n```\n@Controller('auth')\n@UseInterceptors(CurrentUserInterceptor)\nexport class UsersController {\n constructor(\"inject services) {}\n\n @Get('/me')\n me(@CurrentUser() user: User) {\n return user;\n }\n}\n```\n\nIn any route handler you use CurrentUser param decorator, you will have access to \"user\".\n\n### You actually do not need to write a custom param decorator\n\nyou could just use the interceptor, its implementation would be different:\n\n```\n@Get('/me')\nme(@CurrentUserInterceptor() request: Request) {\n // You have access to request.currentUser\n return request.currentUser\n}\n```\n\n### Set interceptor globally\n\nThe current setup for the interceptor is tedious. We are applying the interceptor to one controller at a time. (Thats called controlled scope) Instead you could globally make this interceptor available:\n\nusers Module:\n\n```\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n // this createes repository\n imports: [TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [\n UsersService,\n AuthService,\n {\n provide: APP_INTERCEPTOR,\n useClass: CurrentUserInterceptor,\n },\n ],\n})\n```\n\nThis approach has one downside. Not every controller cares about what the current user is. In those controllers, you still have to make request to the database to fetch the current User.\n\n========================================\n\nCode:\n```js\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n  (data: string, ctx: ExecutionContext) => {\n    const user = ctx.switchToHttp().getRequest().user;\n\n    if (!user) {\n      return null;\n    }\n\n    return data ? user[data] : user; // extract a specific property only if specified or get a user object\n  },\n);\n```\n\n```js\n@Get('test')\n  @UseGuards(AuthGuard())\n  testRoute(@CurrentUser() user: User) {\n    console.log('Current User: ', user);\n    return { user };\n  }\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class ApplyUser extends AuthGuard('jwt') {\n  handleRequest(err: any, user: any) {\n    if (user) return user;\n    return null;\n  }\n}\n```\n\n```js\n@Get('me')\n@UseGuards(ApplyUser)\nme(@CurrentUser() user: User) {\n  return { user };\n}\n```\n\n```text\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  constructor(private readonly reflector: Reflector) {\n    super();\n  }\n\n  handleRequest(err, user, info, context) {\n    const request = context.switchToHttp().getRequest();       \n\n    const allowAny = this.reflector.get<string[]>('allow-any', context.getHandler());\n    if (user) return user;\n    if (allowAny) return true;\n    throw new UnauthorizedException();\n  }\n}\n```\n\n```text\nimport { APP_GUARD, Reflector } from '@nestjs/core';\nimport { AppController } from './app.controller';\nimport { JwtAuthGuard } from './app.guard';\n\n\n\n@Module({\n  imports: ],\n  controllers: [AppController],\n  providers: [\n    {\n      provide: APP_GUARD,\n      useFactory: ref => new JwtAuthGuard(ref),\n      inject: [Reflector],\n    },\n    AppService,\n  ],\n})\nexport class AppModule {\n}\n```\n\n```text\nimport { SetMetadata } from '@nestjs/common';\n\nexport const AllowAny = () => SetMetadata('allow-any', true);\n```\n\n```text\n@Post('testPost')\n  @AllowAny()\n  async testPost(@Req() request) {\n    console.log(request.user)\n  }\n```\n\n```text\n\"Basically, I need a way to propagate req.user on every(or at least on some of not AuthGuard'ed request), it is realy straight forward to do in express by applying passport middleware, but im not sure how to do it with @nestjs/passport.\"\n```\n\n```text\n//  this interceptor will be used by the custom param decoratro to fetch the current User\nimport {NestInterceptor,ExecutionContext,CallHandler,Injectable} from '@nestjs/common';\nimport { UsersService } from '../users.service';\n\n@Injectable()\n// \"implements\" guide us how to put together an interceptor\nexport class CurrentUserInterceptor implements NestInterceptor {\n  constructor(private userService: UsersService) {}\n  // handler refers to the route handler\n  async intercept(context: ExecutionContext, handler: CallHandler) {\n    const request = context.switchToHttp().getRequest();\n    const { userId } = request.session || {};\n    if (userId) {\n      const user = await this.userService.findOne(userId);\n      // we need to pass this down to the decorator. SO we assign the user to request because req can be retrieved inside the decorator\n      // ------THIS IS WHAT YOU WANTED--------\n      request.currentUser = user;\n    }\n    // run the actual route handler\n    return handler.handle();\n  }\n}\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  controllers: [UsersController],\n  providers: [UsersService, AuthService, CurrentUserInterceptor],\n })\n```\n\n```text\n@Controller('auth')\n@UseInterceptors(CurrentUserInterceptor)\nexport class UsersController {\n  constructor(\"inject services) {}\n\n  @Get('/me')\n  me(@CurrentUser() user: User) {\n    return user;\n  }\n}\n```\n\n```js\n@Get('/me')\nme(@CurrentUserInterceptor() request: Request) {\n  // You have access to request.currentUser\n  return  request.currentUser\n}\n```\n\n```text\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n  // this createes repository\n  imports: [TypeOrmModule.forFeature([User])],\n  controllers: [UsersController],\n  providers: [\n    UsersService,\n    AuthService,\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: CurrentUserInterceptor,\n    },\n  ],\n})\n```\n\n```js\nimport {Req}  from '@nestjs/common'\nimport { Request } from 'express'\n\n@Post()\ncreate(@Req() request: Request) {\n    console.log('user', request.user)\n}\n```\n\n```text\nrequest.user\n```\n\n========================================\n\nComments:\n- I think one can directly use,`me(@Request() req) { return req.user }` which will give us all the details of the current user.\n- Thanks. Useful question and I used your version of the answer.\n- Why do you need the first line of handleRequest (the request constant)?\n- without using a guard the user is undefined","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":366,"estimatedTokens":2521}}112{"id":"stack-57127512","source":"stackoverflow","questionId":57127512,"title":"How to use config module on main.ts file","tags":["nestjs"],"text":"Title: How to use config module on main.ts file\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have set a config module, according to https://docs.nestjs.com/techniques/configuration then how can I use it on main.ts??\n\nnestjs version: 6.1.1\n\n========================================\n\nCode:\n```text\nmain.ts\n```\n\n```text\nNestFactory\n```\n\n```text\nconst configService = app.get<ConfigService>(ConfigService);\n```\n\n```text\nconfigService.get('key');\n```\n\n========================================\n\nComments:\n- I need the configService already within the NestFactory to create my microservice app. There is an issue open for 4 years to support this, unfortunately they always lock conversations on all issues: github.com/nestjs/nest/issues/2343","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":32,"estimatedTokens":185}}113{"id":"stack-50354176","source":"stackoverflow","questionId":50354176,"title":"Getting 404 Not Found on OPTIONS with NestJS","tags":["node.js","typescript","cors","http-options-method","nestjs"],"text":"Title: Getting 404 Not Found on OPTIONS with NestJS\nTags: node.js, typescript, cors, http-options-method, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS and on every route my web app is trying to query, it fails on the OPTIONS request, getting:\n\n {\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot OPTIONS\n /authenticate\"}\n\nhowever trying a direct GET or POST request works fine.\n\n========================================\n\nTop Answer:\nSome extra info on CORS, if you enable it via:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule, { cors: true });\n await app.listen(3000);\n}\nbootstrap();\n```\n\nThis will allow Cross Origin Requests from any domain. Which is generally not security best practice.\n\nIf you want to allow CORS to intercept your preflight requests, but also only allow origin requests from within the server, you can use this config:\n\n```\n.....\n const app = await NestFactory.create(ApplicationModule, {cors: {\n origin: true,\n preflightContinue: false,\n }});\n.....\n```\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, { cors: true });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nmain.ts\n```\n\n```text\ncors: true\n```\n\n```text\nNestFactory.create\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, { cors: true });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n.....\n  const app = await NestFactory.create(ApplicationModule, {cors: {\n    origin: true,\n    preflightContinue: false,\n  }});\n.....\n```\n\n```text\napp.enableCors();\n```\n\n========================================\n\nComments:\n- The cors is a built-in feature, see here for more details: docs.nestjs.com/techniques/cors :)\n- @KamilMyล›liwiec This still doesn't work for me. Neither does app.enableCors(). All HTTP OPTIONS requests just fail with a 404. Not sure what's wrong\n- @KamilMyล›liwiec where did the CORS documentation go on the nestjs documentation site? it appears there is a redirect now","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":97,"estimatedTokens":580}}114{"id":"stack-60505649","source":"stackoverflow","questionId":60505649,"title":"Forbid specific enum value for DTO in Nestjs","tags":["nestjs","class-validator"],"text":"Title: Forbid specific enum value for DTO in Nestjs\nTags: nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nMy \"AppState\" enum has following possible enum values:\n\n```\nexport enum AppState {\n SUCCESS,\n ERROR,\n RUNNING\n}\n```\n\nI have a *UpdateAppStateDTO* with an `appState` which should accept every enum value except *RUNNING*.\n\n```\nexport class UpdateAppStateDTO {\n @IsEnum(AppState)\n @NotEquals(AppState.RUNNING) // Doesn't work properly\n public appState: AppState;\n}\n```\n\nFor the route I have this example\n\n```\n@Patch()\n public setState(@Body() { appState }: UpdateAppStateDTO): void {\n console.log(appState);\n }\n```\n\nIf the request has an empty body or a non valid enum value like \"foobar\" for `appState` I'm getting a 400, which is fine.\n\nThe problem is that when I send \"RUNNING\" I'm still getting a 200 instead of a 400.\n\nHow can I prevent this behaviour?\n\n========================================\n\nTop Answer:\nThe problem is that when I send \"RUNNING\" I'm still getting a 200 instead of a 400.\n\nit seems that you are using the string(!) \"RUNNING\" as value in your request payload as such:\n\n```\n{ appState: \"RUNNING\" }\n```\n\nIn this case, `IsEnum` and `NotEquals` both regard the payload as valid.\n\n**Why is that?**\n\nFirst of all numeric enums are reverse mapped by typescript so your enum is internally (as javascript object) represented as follows:\n\n```\n{\n '0': 'SUCCESS',\n '1': 'ERROR',\n '2': 'RUNNING',\n 'SUCCESS': 0,\n 'ERROR': 1,\n 'RUNNING': 2\n}\n```\n\nNow class-validator's `isEnum()` is coded as follows:\n\n```\nisEnum(value: unknown, entity: any): boolean {\n const enumValues = Object.keys(entity)\n .map(k => entity[k]);\n return enumValues.indexOf(value) >= 0;\n}\n```\n\nand since the enum is reverse-mapped `isEnum('RUNNNING', AppState)` will return true.\n\nAt the same time `NotEquals`, which is coded as such...\n\n```\nnotEquals(value: unknown, comparison: unknown): boolean {\n return value !== comparison;\n}\n```\n\nwill compare the string 'RUNNING' against `AppState.RUNNING` (which equates to `2`) and also conclude that this is valid since `'RUNNING' != 2`.\n\nSo there you have it why the payload `{ appState: \"RUNNING\" }` will result in a 200 instead of a 400 status code.\n\nHow can I prevent this behaviour?\n\nThe enum value `AppState.RUNNING` equates to `2` so when you make a request, you should use the numeric value of `2` in your payload:\n\n```\n{ appState: 2 }\n```\n\nIn the above case, the class-validator's `NotEquals` validator will then correctly deny the request with the response containing:\n\n```\n\"constraints\": {\n \"notEquals\": \"appState should not be equal to 2\"\n}\n```\n\n========================================\n\nCode:\n```ts\nexport enum AppState {\n  SUCCESS,\n  ERROR,\n  RUNNING\n}\n```\n\n```ts\nexport class UpdateAppStateDTO {\n  @IsEnum(AppState)\n  @NotEquals(AppState.RUNNING) // Doesn't work properly\n  public appState: AppState;\n}\n```\n\n```ts\n@Patch()\n  public setState(@Body() { appState }: UpdateAppStateDTO): void {\n    console.log(appState);\n  }\n```\n\n```text\nappState\n```\n\n```text\nappState\n```\n\n```js\nexport enum AppState {\n  SUCCESS = 0,\n  ERROR = 1,\n  RUNNING = 2\n}\n```\n\n```js\nexport enum AppState {\n  SUCCESS = 'SUCCESS',\n  ERROR = 'ERROR',\n  RUNNING = 'RUNNING'\n}\n```\n\n```js\nexport class UpdateAppStateDTO {\n  @IsEnum(AppState)\n  @NotEquals(AppState[AppState.RUNNING])\n  public appState: AppState;\n}\n```\n\n```text\n'RUNNING'\n```\n\n```text\n'RUNNING'\n```\n\n```text\nRUNNING !== 2\n```\n\n```text\ntrue\n```\n\n```text\n@IsEnum()\n```\n\n```text\n'RUNNING'\n```\n\n```text\nstring enum\n```\n\n```text\nAppState\n```\n\n```text\n@NotEquals()\n```\n\n```text\nappState\n```\n\n```text\n{ appState: \"RUNNING\" }\n```\n\n```text\n{\n  '0': 'SUCCESS',\n  '1': 'ERROR',\n  '2': 'RUNNING',\n  'SUCCESS': 0,\n  'ERROR': 1,\n  'RUNNING': 2\n}\n```\n\n```text\nisEnum(value: unknown, entity: any): boolean {\n    const enumValues = Object.keys(entity)\n        .map(k => entity[k]);\n    return enumValues.indexOf(value) >= 0;\n}\n```\n\n```text\nnotEquals(value: unknown, comparison: unknown): boolean {\n    return value !== comparison;\n}\n```\n\n```text\n{ appState: 2 }\n```\n\n```text\n\"constraints\": {\n    \"notEquals\": \"appState should not be equal to 2\"\n}\n```\n\n```text\nIsEnum\n```\n\n```text\nNotEquals\n```\n\n```text\nisEnum()\n```\n\n```text\nisEnum('RUNNNING', AppState)\n```\n\n```text\nNotEquals\n```\n\n```text\nAppState.RUNNING\n```\n\n```text\n2\n```\n\n```text\n'RUNNING' != 2\n```\n\n```text\n{ appState: \"RUNNING\" }\n```\n\n```text\nAppState.RUNNING\n```\n\n```text\n2\n```\n\n```text\n2\n```\n\n```text\nNotEquals\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\nimport { IsNotEmpty, IsEnum } from 'class-validator';\n\nenum TYPE {\n  SUPPORT = 'SUPPORT',\n}\n\nexport class requestBody {\n  @ApiProperty()\n  @IsNotEmpty()\n  @IsEnum(TYPE)\n  type: string;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":312,"estimatedTokens":1171}}115{"id":"stack-50913705","source":"stackoverflow","questionId":50913705,"title":"Nestjs/swagger: Complex Objects","tags":["swagger","nestjs"],"text":"Title: Nestjs/swagger: Complex Objects\nTags: swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI was wondering if there's a way to support complex objects for Nestjs/swagger. I just finished the migration and I am now working on the swagger documentation. A lot of my requests return complex objects and I'm wondering if there's an easier way.\nExample:\n\n```\nclass Foobar{\n prop1: {\n subprop1: {\n subsub1: string;\n };\n };\n}\n```\n\nBecomes:\n\n```\nclass SubSub{\n @ApiModelProperty()\n subsub1: string;\n}\nclass SubProp{\n @ApiModelProperty()\n subporp1: SubSub;\n}\nclass Foobar {\n @ApiModelProperty()\n prop1: SubProp;\n}\n```\n\nIf I do this:\n\n```\nclass Foobar{\n @ApiModelProperty()\n prop1: {\n subprop1: {\n subsub1: string;\n };\n };\n}\n```\n\nI get this in swagger:\n\n```\n{\n \"prop1\": {}\n}\n```\n\n========================================\n\nTop Answer:\n```\nclass SubSub {\n @ApiProperty()\n subsub1: string;\n}\n\nclass SubProp {\n @ApiProperty({ type: SubSub })\n subporp1: SubSub;\n}\n```\n\nor if Array\n\n```\nclass SubProp {\n @ApiProperty({ isArray: true, type: SubSub })\n subporp1: SubSub[];\n //or subporp1: [SubSub];\n}\n```\n\n========================================\n\nCode:\n```text\nclass Foobar{\n  prop1: {\n    subprop1: {\n      subsub1: string;\n    };\n  };\n}\n```\n\n```text\nclass SubSub{\n  @ApiModelProperty()\n  subsub1: string;\n}\nclass SubProp{\n  @ApiModelProperty()\n  subporp1: SubSub;\n}\nclass Foobar {\n  @ApiModelProperty()\n  prop1: SubProp;\n}\n```\n\n```text\nclass Foobar{\n  @ApiModelProperty()\n  prop1: {\n    subprop1: {\n      subsub1: string;\n    };\n  };\n}\n```\n\n```text\n{\n  \"prop1\": {}\n}\n```\n\n```js\nclass SubSub{\n      @ApiProperty()\n      subsub1: string;\n    }\n\n    class SubProp{\n      @ApiProperty({ type: SubSub })\n      subporp1: SubSub;\n    }\n\n    class Foobar {\n      @ApiProperty({ type: () => SubProp })\n      prop1: SubProp;\n    }\n```\n\n```text\nclass SubSub{\n  @ApiModelProperty()\n  subsub1: string;\n}\n\nclass SubProp{\n  @ApiModelProperty({ type: SubSub })\n  subporp1: SubSub;\n}\n\nclass Foobar {\n  @ApiModelProperty({ type: SubProp })\n  prop1: SubProp;\n}\n```\n\n```text\nApiModelProperty\n```\n\n```text\nApiProperty\n```\n\n```text\nApiProperty\n```\n\n```text\n@ApiModelProperty\n```\n\n```text\ntype\n```\n\n```text\nclass SubSub {\n  @ApiProperty()\n  subsub1: string;\n}\n\nclass SubProp {\n  @ApiProperty({ type: SubSub })\n  subporp1: SubSub;\n}\n```\n\n```text\nclass SubProp {\n  @ApiProperty({ isArray: true,  type: SubSub })\n  subporp1: SubSub[];\n  //or subporp1: [SubSub];\n}\n```\n\n========================================\n\nComments:\n- `@ApiModelProperty` has since been renamed to `@ApiProperty`\n- @ApiProperty({ type: () => [SubProp], }) This is for array of object.\n- `@ApiProperty({ type: [SubProp] })` was the only way I got it working.","metadata":{"transformedAt":"2026-08-18T18:33:02.411Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":206,"estimatedTokens":673}}116{"id":"stack-56703570","source":"stackoverflow","questionId":56703570,"title":"Unable to run tests because Nest cannot find a module","tags":["nestjs"],"text":"Title: Unable to run tests because Nest cannot find a module\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have followed the unit test example but I am unable to run a test, i don't know why it doesn't work. I have this following error : `Cannot find module 'src/Application/Auth/Command/LoginCommandHandler' from 'LoginCommandHandler.spec.ts'` but my handler is correctly imported.\nThanks for your help.\n\nHere is my unit test:\n\n```\nimport { LoginCommandHandler } from 'src/Application/Auth/Command/LoginCommandHandler';\nimport { UserRepository } from 'src/Infrastructure/User/Repository/UserRepository';\nimport { EncryptionAdapter } from 'src/Infrastructure/Adapter/EncryptionAdapter';\n\n// ...\n\nconst module: TestingModule = await Test.createTestingModule({\n providers: [LoginCommandHandler, UserRepository, EncryptionAdapter],\n }).compile();\n\n userRepository = module.get(UserRepository);\n encryptionAdapter = module.get(EncryptionAdapter);\n handler = new LoginCommandHandler(userRepository, encryptionAdapter);\n```\n\nHere is my src/Application/Auth/Command/LoginCommandHandler/LoginCommandHandler : \n\n```\nexport class LoginCommandHandler {\n constructor(\n @Inject('IUserRepository')\n private readonly userRepository: IUserRepository,\n @Inject('IEncryptionAdapter')\n private readonly encryptionAdapter: IEncryptionAdapter,\n ) {}\n// ...\n```\n\nAnd here is my AuthModule : \n\n```\n@Module({\n imports: [\n // ...\n TypeOrmModule.forFeature([User]),\n ],\n providers: [\n // ...\n { provide: 'IUserRepository', useClass: UserRepository },\n { provide: 'IEncryptionAdapter', useClass: EncryptionAdapter },\n LoginCommandHandler,\n ],\n})\nexport class AuthModule {}\n```\n\n========================================\n\nTop Answer:\nAdd this to your jest config in the `package.json` file:\n\n```\n\"moduleNameMapper\": {\n \"^src/(.*)$\": \"/$1\"\n}\n```\n\n========================================\n\nCode:\n```text\nimport { LoginCommandHandler } from 'src/Application/Auth/Command/LoginCommandHandler';\nimport { UserRepository } from 'src/Infrastructure/User/Repository/UserRepository';\nimport { EncryptionAdapter } from 'src/Infrastructure/Adapter/EncryptionAdapter';\n\n// ...\n\nconst module: TestingModule = await Test.createTestingModule({\n      providers: [LoginCommandHandler, UserRepository, EncryptionAdapter],\n    }).compile();\n\n    userRepository = module.get(UserRepository);\n    encryptionAdapter = module.get(EncryptionAdapter);\n    handler = new LoginCommandHandler(userRepository, encryptionAdapter);\n```\n\n```text\nexport class LoginCommandHandler {\n  constructor(\n    @Inject('IUserRepository')\n    private readonly userRepository: IUserRepository,\n    @Inject('IEncryptionAdapter')\n    private readonly encryptionAdapter: IEncryptionAdapter,\n  ) {}\n// ...\n```\n\n```text\n@Module({\n  imports: [\n    // ...\n    TypeOrmModule.forFeature([User]),\n  ],\n  providers: [\n    // ...\n    { provide: 'IUserRepository', useClass: UserRepository },\n    { provide: 'IEncryptionAdapter', useClass: EncryptionAdapter },\n    LoginCommandHandler,\n  ],\n})\nexport class AuthModule {}\n```\n\n```text\nCannot find module 'src/Application/Auth/Command/LoginCommandHandler' from 'LoginCommandHandler.spec.ts'\n```\n\n```text\nmoduleDirectories\n```\n\n```text\njest.config\n```\n\n```text\nmoduleNameMapper\n```\n\n```text\njest.config\n```\n\n```text\n\"moduleNameMapper\": {\n  \"^src/(.*)$\": \"<rootDir>/$1\"\n}\n```\n\n```text\npackage.json\n```\n\n```text\nimport { AuthService } from 'src/auth/auth.service'\n```\n\n```text\nimport { AuthService } from '../auth/auth.service'\n```\n\n```text\nimport\n```\n\n```text\nimport\n```\n\n```text\nImport Module Specifier\n```\n\n```text\nshortest\n```\n\n```text\nrelative\n```\n\n```text\n\"moduleNameMapper\": {\n  \"^src/(.*)$\": \"<rootDir>/src/$1\",\n}\n```\n\n========================================\n\nComments:\n- Thanks for the VS Code default settings tip. Super helpful and it sorted my module/testing issues in Nest.\n- This was a very useful answer - thank you. Are there any downsides to using relative paths instead of absolute paths?\n- @MichaelJay, None that I'm aware of. In the past, we used to have problems with relative paths when we moved files around. But now the IDEs are gettting smarter, they suggest us to automatically refactor the changed paths.","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":184,"estimatedTokens":1048}}117{"id":"stack-60461314","source":"stackoverflow","questionId":60461314,"title":"How To Specify Which Module to add Controller to in NestJS CLI?","tags":["typescript","nestjs"],"text":"Title: How To Specify Which Module to add Controller to in NestJS CLI?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIve been playing with NestJS for about a week. So far, Im really liking it. The Module system is great. And, I love how easy it is to do things like parse requests.\n\nOne question I do have is with regards to the NestJS CLI.\n\nSuppose I have multiple modules. I can create a controller with the following command.\n\n```\nnest g controller Accounts\n```\n\nHow do I specify which module this controller belongs to? \n\nThe CLI seems to default to the last module you created.\n\nHow do I change this behavior?\n\n========================================\n\nTop Answer:\nIf a module already exists, you can simply add its name after the controller/service (or else ..)\n\n```\nnest generate controller [--flat]\n```\n\n\"--flat\" option, if you don't want a new folder generated for your controller\n\n========================================\n\nCode:\n```text\nnest g controller Accounts\n```\n\n```sh\nnest g mo accounts\nnest g mo contacts\nnest g mo leads\n```\n\n```sh\nnest g co leads\nnest g co accounts\nnest g co contacts\n```\n\n```sh\nnest g co leads accounts\n```\n\n```text\nAccountsController\n```\n\n```text\nAccountsModule\n```\n\n```text\nLeadsController\n```\n\n```text\nLeadsModule\n```\n\n```text\nContactsController\n```\n\n```text\nContactsModule\n```\n\n```text\nLeadsController\n```\n\n```text\nAccountsModule\n```\n\n```text\npath\n```\n\n```text\nsrc\n```\n\n```text\nnest-cli.json\n```\n\n```text\naccounts/leads\n```\n\n```text\nleads.controller.ts\n```\n\n```text\nAccountsModule\n```\n\n```text\nAppModule\n```\n\n```text\nnest g  pr PriceLevel PriceLevel\n```\n\n```text\nnest generate controller <controller_name> <module_name> [--flat]\n```\n\n```text\nnest g service [path]\n\nexample: nest g service modules/users\n```\n\n========================================\n\nComments:\n- Thanks for your response. I've been looking for this for days, so I can create services and controllers without creating directories for them.\n- @DiegoC&#226;ndidodaSilva That's a pleasure\n- Thank you, this helps me keep my injectables in subdirectories so that I can use something like `npx nest generate service some-service my-module&#47;services --flat` to have the generated file placed in the correct directory.\n- This should be the default option imo\n- That what i have been looking for","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":137,"estimatedTokens":578}}118{"id":"stack-53378667","source":"stackoverflow","questionId":53378667,"title":"Cast entity to dto","tags":["node.js","typescript","nestjs"],"text":"Title: Cast entity to dto\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nJust wondering the best way to convert a NestJS entity object to a DTO.\n\nLets say I have the following:\n\n```\nimport { IsString, IsNumber, IsBoolean } from 'class-validator';\nimport { Exclude } from 'class-transformer';\n\nexport class PhotoSnippetDto {\n @IsNumber()\n readonly id: number;\n\n @IsString()\n readonly name: string;\n\n constructor(props) {\n Object.assign(this, props);\n }\n}\n\nexport class Photo {\n\n @IsNumber()\n id: number;\n\n @IsString()\n name: string;\n\n @IsString()\n description: string;\n\n @IsString()\n filename: string;\n\n @IsNumber()\n views: number;\n\n @IsBoolean()\n isPublished: boolean;\n\n @Exclude()\n @IsString()\n excludedPropery: string;\n\n constructor(props) {\n Object.assign(this, props);\n }\n}\n\n@Controller()\nexport class AppController {\n\n @Get()\n @UseInterceptors(ClassSerializerInterceptor)\n root(): PhotoSnippetDto {\n const photo = new Photo({\n id: 1,\n name: 'Photo 1',\n description: 'Photo 1 description',\n filename: 'photo.png',\n views: 10,\n isPublished: true,\n excludedPropery: 'Im excluded'\n });\n\n return new PhotoSnippetDto(photo);\n }\n\n}\n```\n\nI was expecting the ClassSerializerInterceptor to serialize the photo object to the DTO and return something like this:\n\n```\n{\n id: 1,\n name: 'Photo 1'\n}\n```\n\nBut I'm getting a response containing all the properties still:\n\n```\n{\n id = 1,\n name = 'Photo 1',\n description = 'Photo 1 description',\n filename = 'file.png',\n views = 10,\n isPublished = true\n}\n```\n\nI basically want to strip out all properties that are not defined in the DTO.\n\nI know the ClassSerializerInterceptor works perfectly when using @Exclude(), I was just also expecting it to remove undefined properties also.\n\nI'm curious as to the best way to go about this? I know I could do something like:\n\n```\n@Get('test')\n@UseInterceptors(ClassSerializerInterceptor)\ntest(): PhotoSnippetDto {\n const photo = new Photo({\n id: 1,\n name: 'Photo 1',\n description: 'Photo 1 description',\n filename: 'photo.png',\n views: 10,\n isPublished: true,\n excludedPropery: 'Im excluded'\n });\n const { id, name } = photo;\n return new PhotoSnippetDto({id, name});\n}\n```\n\nBut if I ever want to add another property to the response I'd have to do more than just add the new property to the class.. I'm wondering if there's a better 'Nest way' of doing it.\n\n========================================\n\nTop Answer:\nSo based on Jesse's awesome answer I ended up creating the DTO using @Exclude() and @Expose() to remove all but exposed properties:\n\n```\nimport { IsString, IsEmail } from 'class-validator';\nimport { Exclude, Expose } from 'class-transformer';\n\n@Exclude()\nexport class PhotoSnippetDto {\n @Expose()\n @IsNumber()\n readonly id: number;\n\n @Expose()\n @IsString()\n readonly name: string;\n}\n```\n\nAnd then I created a generic transform interceptor that calls plainToclass to convert the object:\n\n```\nimport { Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { plainToClass } from 'class-transformer';\n\ninterface ClassType {\n new(): T;\n}\n\n@Injectable()\nexport class TransformInterceptor implements NestInterceptor, T> {\n\n constructor(private readonly classType: ClassType) {}\n\n intercept(context: ExecutionContext, call$: Observable>, ): Observable {\n return call$.pipe(map(data => plainToClass(this.classType, data)));\n }\n}\n```\n\nAnd then use this interceptor to transform the data to any type:\n\n```\n@Get('test')\n@UseInterceptors(new TransformInterceptor(PhotoSnippetDto))\ntest(): PhotoSnippetDto {\n const photo = new Photo({\n id: 1,\n name: 'Photo 1',\n description: 'Photo 1 description',\n filename: 'photo.png',\n views: 10,\n isPublished: true,\n excludedPropery: 'Im excluded'\n });\n return photo;\n}\n```\n\nWhich gives me what I wanted:\n\n```\n{\n id: 1,\n name: 'Photo 1'\n}\n```\n\nDefinitely feels more nest-like! I can use the same interceptor where ever I need and to change the response I only ever need to change the DTOs.\n\nHappy days.\n\n========================================\n\nCode:\n```text\nimport { IsString, IsNumber, IsBoolean } from 'class-validator';\nimport { Exclude } from 'class-transformer';\n\nexport class PhotoSnippetDto {\n  @IsNumber()\n  readonly id: number;\n\n  @IsString()\n  readonly name: string;\n\n  constructor(props) {\n    Object.assign(this, props);\n  }\n}\n\nexport class Photo {\n\n  @IsNumber()\n  id: number;\n\n  @IsString()\n  name: string;\n\n  @IsString()\n  description: string;\n\n  @IsString()\n  filename: string;\n\n  @IsNumber()\n  views: number;\n\n  @IsBoolean()\n  isPublished: boolean;\n\n  @Exclude()\n  @IsString()\n  excludedPropery: string;\n\n  constructor(props) {\n    Object.assign(this, props);\n  }\n}\n\n@Controller()\nexport class AppController {\n\n  @Get()\n  @UseInterceptors(ClassSerializerInterceptor)\n  root(): PhotoSnippetDto {\n    const photo = new Photo({\n      id: 1,\n      name: 'Photo 1',\n      description: 'Photo 1 description',\n      filename: 'photo.png',\n      views: 10,\n      isPublished: true,\n      excludedPropery: 'Im excluded'\n    });\n\n    return new PhotoSnippetDto(photo);\n  }\n\n}\n```\n\n```text\n{\n  id: 1,\n  name: 'Photo 1'\n}\n```\n\n```text\n{\n  id = 1,\n  name = 'Photo 1',\n  description = 'Photo 1 description',\n  filename = 'file.png',\n  views = 10,\n  isPublished = true\n}\n```\n\n```text\n@Get('test')\n@UseInterceptors(ClassSerializerInterceptor)\ntest(): PhotoSnippetDto {\n  const photo = new Photo({\n    id: 1,\n    name: 'Photo 1',\n    description: 'Photo 1 description',\n    filename: 'photo.png',\n    views: 10,\n    isPublished: true,\n    excludedPropery: 'Im excluded'\n  });\n  const { id, name } = photo;\n  return new PhotoSnippetDto({id, name});\n}\n```\n\n```text\n@Exclude()\nexport class PhotoSnippetDto {\n   @Expose()\n   @IsNumber()\n   readonly id: number;\n\n   @Expose()\n   @IsString()\n   readonly name: string;\n}\n```\n\n```text\n@Exclude\n```\n\n```text\n@Expose\n```\n\n```text\nplainToClass\n```\n\n```text\nconst dto = plainToClass(PhotoSnippetDto, photo);\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\n@Expose\n```\n\n```text\nObject.assign\n```\n\n```text\nimport { IsString, IsEmail } from 'class-validator';\nimport { Exclude, Expose } from 'class-transformer';\n\n@Exclude()\nexport class PhotoSnippetDto {\n   @Expose()\n   @IsNumber()\n   readonly id: number;\n\n   @Expose()\n   @IsString()\n   readonly name: string;\n}\n```\n\n```text\nimport { Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { plainToClass } from 'class-transformer';\n\ninterface ClassType<T> {\n    new(): T;\n}\n\n@Injectable()\nexport class TransformInterceptor<T> implements NestInterceptor<Partial<T>, T> {\n\n    constructor(private readonly classType: ClassType<T>) {}\n\n    intercept(context: ExecutionContext, call$: Observable<Partial<T>>, ): Observable<T> {\n        return call$.pipe(map(data => plainToClass(this.classType, data)));\n    }\n}\n```\n\n```text\n@Get('test')\n@UseInterceptors(new TransformInterceptor(PhotoSnippetDto))\ntest(): PhotoSnippetDto {\n  const photo = new Photo({\n    id: 1,\n    name: 'Photo 1',\n    description: 'Photo 1 description',\n    filename: 'photo.png',\n    views: 10,\n    isPublished: true,\n    excludedPropery: 'Im excluded'\n  });\n  return photo;\n}\n```\n\n```text\n{\n  id: 1,\n  name: 'Photo 1'\n}\n```\n\n```text\nnpm install --save @fabio.formosa/metamorphosis-nest\n```\n\n```text\nimport { MetamorphosisNestModule } from '@fabio.formosa/metamorphosis-nest';\n\n@Module({\n  imports: [MetamorphosisModule.register()],\n  ...\n}\nexport class MyApp{ }\n```\n\n```text\nimport { Convert, Converter } from '@fabio.formosa/metamorphosis';\n\n@Injectable()\n@Convert(Photo, PhotoSnippetDto )\nexport default class PhotoToPhotoSnippetDtoConverter implements Converter<Photo, \nPhotoSnippetDto> {\n\npublic convert(source: Photo): PhotoSnippetDto {\n  const target = new PhotoSnippetDto();\n  target.id = source.id;\n  target.name = source.name;\n  return target;\n }\n}\n```\n\n```text\nconst photoSnippetDto = <PhotoSnippetDto> await this.convertionService.convert(photo, PhotoSnippetDto);\n```\n\n```text\n@Injectable()\n @Convert(Photo, PhotoSnippetDto )\n export default class PhotoToPhotoSnippetDtoConverter implements Converter<Photo, PhotoSnippetDto> {\n\n   public convert(source: Photo): PhotoSnippetDto {\n     return plainToClass(PhotoSnippetDto, source);\n   }\n }\n```\n\n========================================\n\nComments:\n- Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!\n- @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P\n- Why plainToClass though? We are not getting entities as raw from typeorm, wouldn't classToClass be a better in this case?\n- Hey, I tried your solution but I am getting a run-time error: `Error: Nest can't resolve dependencies of the TransformInterceptor (?). Please make sure that the argument Object at index [0] is available in the ****Module context.`\n- quick question, this should work when we want to exclude the properties but what if we need additional properties in our DTO that are not there in entity. Also, what if I want to change the name ?","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":466,"estimatedTokens":2311}}119{"id":"stack-60968223","source":"stackoverflow","questionId":60968223,"title":"Disable colored console output","tags":["logging","nestjs"],"text":"Title: Disable colored console output\nTags: logging, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs it possible to disable the colored console output of the NestJS default logger? \nI can't find an option to turn it off :-(\n\n*(Some more text, because this question is too simple for StackOverflow.)*\n\n========================================\n\nTop Answer:\nWhile @Andreas's 2nd part of the answer is correct about setting the environment variable `NO_COLOR`, the first part is wrong. NestJS (at least as of v8) does not use the `cli-color` module (maybe earlier they were using it).\n\nSeems they have implemented their own `clc` thing but they do respect the `NO_COLOR` flag.\n\nSource code- https://github.com/nestjs/nest/blob/v8.0.8/packages/common/utils/cli-colors.util.ts#L3\n\nAnd their documentation also says the same thing-\n\n**HINT**\n\nTo disable color in the default logger's messages, set the `NO_COLOR` environment variable.\n\nSo below is the output in my local when running without the variable-\n\nhttps://i.sstatic.net/j9pMm.png\n\nAnd this is when I do `export NO_COLOR=true`-\n\nhttps://i.sstatic.net/0dGPF.png\n\nThis works well in AWS CloudWatch logs as well.\n\n========================================\n\nCode:\n```text\ncli-color\n```\n\n```text\nNO_COLOR\n```\n\n```text\nNestFactory.create()\n```\n\n```text\nlogger: false\n```\n\n```text\nawait NestFactory.create(ApplicationModule, { logger: false })\n```\n\n```text\nexport class MyLogger implements LoggerService {\n  log(message: string) {\n    /* your implementation */\n  }\n  error(message: string, trace: string) {\n    /* your implementation */\n  }\n  warn(message: string) {\n    /* your implementation */\n  }\n  debug(message: string) {\n    /* your implementation */\n  }\n  verbose(message: string) {\n    /* your implementation */\n  }\n}\n\nconst app = await NestFactory.create(ApplicationModule, {\n  logger: new MyLogger(),\n});\nawait app.listen(3000);\n```\n\n```text\nimport { Logger } from '@nestjs/common';\n\nexport class MyLogger extends Logger {\n  error(message: string, trace: string) {\n    // add your tailored logic here\n    super.error(message, trace);\n  }\n}\n```\n\n```text\nNO_COLOR\n```\n\n```text\ncli-color\n```\n\n```text\nclc\n```\n\n```text\nNO_COLOR\n```\n\n```text\nNO_COLOR\n```\n\n```text\nexport NO_COLOR=true\n```\n\n========================================\n\nComments:\n- This option turns off logging, but I want to disable the colored output -> no color codes in logfile.\n- Not sure that it's possible. Nestjs colorized log messages in `logger.service`, you can try to install `cli-color` *(Nestjs uses it)* package and configure it locally in project\n- This doesn't answer the question. This just disables logs.","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":124,"estimatedTokens":658}}120{"id":"stack-77084231","source":"stackoverflow","questionId":77084231,"title":"bun compatibility with nestjs?","tags":["nestjs","bun"],"text":"Title: bun compatibility with nestjs?\nTags: nestjs, bun\nSource: Stack Overflow\n\nQuestion:\nI am currently having a project that uses nestjs and I was wondering how compatible is it with bun 1.0. I haven't found a clear answer on the internet and I don't want to transfer my project on bun just to end up on a dead end because of compatibility problems.\n\nThis is a small project that uses react and mongodb for the moment but I plan on using the built-in support of sqlite from bun.\n\nI've already tried to use bun on the project and I can install the modules that I am currently using but I am scared of how far is it going. I haven't had the time to test everything so if I can get some info that would be nice.\n\n========================================\n\nCode:\n```text\nemitDecoratorMetadata\n```\n\n========================================\n\nComments:\n- Bun's 1.0 release blog post says it works with NestJS, but I am not too sure how to set it up. Maybe the NestJS team will come up with it in the docs in a while, but until then you could try starting a new simple project and tweak it to use Bun.\n- thank you for the GH issue link, i can see that they haven't been fully transparent as they showed the nestjs logo in their presentation to show the compatible framework but apparently it is still a work in progress.\n- As of Bun version 1.0.3 `emitDecoratorMetadata` is supported. Looks like you might be in luck. bun.sh/blog/bun-v1.0.3\n- @Tamb Yup, Just checked it out. It works pretty good except the build part. And It seems the performance advantage for development at least is minimal ( I use nest with SWC so ). Maybe for runtime & live performance, it seems a superior runtime ( assuming RAM isn't an issue )","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":25,"estimatedTokens":428}}121{"id":"stack-64716494","source":"stackoverflow","questionId":64716494,"title":"Please make sure that the argument ContactRepository at index [0] is available in the RootTestModule context","tags":["typescript","jestjs","nestjs"],"text":"Title: Please make sure that the argument ContactRepository at index [0] is available in the RootTestModule context\nTags: typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to test a class via Nest. In this class (cf image below), the person who coded the class, create a repository via typeorm.\n\nhttps://i.sstatic.net/YRM0F.png\n\nWhen I try to test the \"createContact\" function I get the following error : \"Nest can't resolve dependencies of the ContactService (?). Please make sure that the argument ContactRepository at index [0] is available in the AuthModule context\".\n\nThis is my test class :\n\nhttps://i.sstatic.net/3A2mH.png\n\nDo you know how to make the test take this into account and therefore not get the error anymore?\n\n========================================\n\nTop Answer:\nCheck if your service constructor is injecting the Contact entity, or any other that is being accused as missing:\n\n```\n@InjectRepository(EntityName)\n private entityNameRepository: Repository,\n```\n\nJust replace entityName with the corresponding entity\n\n========================================\n\nCode:\n```js\nbeforeEach(async () => {\n  const module = await Test.createTestingModule({\n    providers: [\n      ContactService,\n      {\n        provide: getRepositoryToken(Contact),\n        useValue: {\n          save: jest.fn().mockResolvedValue(mockContact),\n          find: jest.fn().mockResolvedValue([mockContact]),\n        },\n      },\n    ],\n  }).compile();\n});\n```\n\n```text\n@InjectRepository(Contact)\n```\n\n```text\ngetRepositoryToken()\n```\n\n```text\nsave\n```\n\n```text\nfind\n```\n\n```text\n@InjectRepository(EntityName)\n    private entityNameRepository: Repository<EntityName>,\n```\n\n========================================\n\nComments:\n- Hi, thanks for your response. it's work but not a all. I use this github.com/jmcdo29/testing-nestjs/blob/master/apps/&hellip; has exemple, but i have the error connectionnotfounderror : COnnection \"default\" was not found. when i call the \"createContact\" fonction\n- You probably have `imports: [TypeOrmModule.forFeature()]` used in the test, or you're importing the module that contains the service you're testing, or some sort of combination of the two. The sample you linked works fine, you can see the CI jobs run every night and have no problems\n- Hi, i have open &#224; new question for that stackoverflow.com/questions/64728017/&hellip; The problem seem to be with the repository typeorm, but i do not found why\n- This is a terrible answer. So you basically suggest mocking the dependency instead of figuring out why is the compilation failing. Genius. ๐Ÿคก","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":649}}122{"id":"stack-55848238","source":"stackoverflow","questionId":55848238,"title":"Nestjs unit-test - mock method guard","tags":["unit-testing","dependency-injection","mocking","jestjs","nestjs"],"text":"Title: Nestjs unit-test - mock method guard\nTags: unit-testing, dependency-injection, mocking, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have started to work with NestJS and have a question about mocking guards\nfor unit-test.\nI'm trying to test a basic HTTP `controller` that has a method Guard attach to it.\n\nMy issue started when I injected a service to the Guard (I needed the `ConfigService` for the Guard).\n\nWhen running the test the DI is unable to resolve the Guard\n\n```\nโ— AppController โ€บ root โ€บ should return \"Hello World!\"\n\n Nest can't resolve dependencies of the ForceFailGuard (?). Please make sure that the argument at index [0] is available in the _RootTestModule context.\n```\n\nMy force fail Guard:\n\n```\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Injectable()\nexport class ForceFailGuard implements CanActivate {\n\n constructor(\n private configService: ConfigService,\n ) {}\n\n canActivate(context: ExecutionContext) {\n return !this.configService.get().shouldFail;\n }\n}\n```\n\nSpec file:\n\n```\nimport { CanActivate } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ForceFailGuard } from './force-fail.guard';\n\ndescribe('AppController', () => {\n let appController: AppController;\n\n beforeEach(async () => {\n\n const mock_ForceFailGuard = { CanActivate: jest.fn(() => true) };\n\n const app: TestingModule = await Test\n .createTestingModule({\n controllers: [AppController],\n providers: [\n AppService,\n ForceFailGuard,\n ],\n })\n .overrideProvider(ForceFailGuard).useValue(mock_ForceFailGuard)\n .overrideGuard(ForceFailGuard).useValue(mock_ForceFailGuard)\n .compile();\n\n appController = app.get(AppController);\n });\n\n describe('root', () => {\n\n it('should return \"Hello World!\"', () => {\n expect(appController.getHello()).toBe('Hello World!');\n });\n\n });\n});\n```\n\nI wasn't able to find examples or documentation on this issues. Am i missing something or is this a real issue ?\n\nAppreciate any help,\nThanks.\n\n========================================\n\nTop Answer:\nIf you ever need/want to unit test your custom guard implementation in addition to the controller unit test, you could have something similar to the test below in order to expect for errors etc\n\n```\n// InternalGuard.ts\n@Injectable()\nexport class InternalTokenGuard implements CanActivate {\n constructor(private readonly config: ConfigService) {\n }\n\n public async canActivate(context: ExecutionContext): Promise {\n const token = this.config.get(\"internalToken\");\n\n if (!token) {\n throw new Error(`No internal token was provided.`);\n }\n\n const request = context.switchToHttp().getRequest();\n const providedToken = request.headers[\"authorization\"];\n\n if (token !== providedToken) {\n throw new UnauthorizedException();\n }\n\n return true;\n }\n}\n```\n\nAnd your spec file\n\n```\n// InternalGuard.spec.ts\nbeforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [],\n providers: [\n InternalTokenGuard,\n {\n provide: ConfigService,\n useValue: {\n get: jest.fn((key: string) => {\n if (key === \"internalToken\") {\n return 123;\n }\n return null;\n })\n }\n }\n ]\n }).compile();\n\n config = module.get(ConfigService);\n guard = module.get(InternalTokenGuard);\n});\n\nit(\"should throw UnauthorizedException when token is not Bearer\", async () => {\n const context = {\n getClass: jest.fn(),\n getHandler: jest.fn(),\n switchToHttp: jest.fn(() => ({\n getRequest: jest.fn().mockReturnValue({\n headers: {\n authorization: \"providedToken\"\n }\n })\n }))\n } as any;\n\n await expect(guard.canActivate(context)).rejects.toThrow(\n UnauthorizedException\n );\n expect(context.switchToHttp).toHaveBeenCalled();\n});\n```\n\n========================================\n\nCode:\n```text\nโ— AppController โ€บ root โ€บ should return \"Hello World!\"\n\n    Nest can't resolve dependencies of the ForceFailGuard (?). Please make sure that the argument at index [0] is available in the _RootTestModule context.\n```\n\n```js\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Injectable()\nexport class ForceFailGuard implements CanActivate {\n\n  constructor(\n    private configService: ConfigService,\n  ) {}\n\n  canActivate(context: ExecutionContext) {\n    return !this.configService.get().shouldFail;\n  }\n}\n```\n\n```js\nimport { CanActivate } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ForceFailGuard } from './force-fail.guard';\n\ndescribe('AppController', () => {\n  let appController: AppController;\n\n  beforeEach(async () => {\n\n    const mock_ForceFailGuard = { CanActivate: jest.fn(() => true) };\n\n    const app: TestingModule = await Test\n      .createTestingModule({\n        controllers: [AppController],\n        providers: [\n          AppService,\n          ForceFailGuard,\n        ],\n      })\n      .overrideProvider(ForceFailGuard).useValue(mock_ForceFailGuard)\n      .overrideGuard(ForceFailGuard).useValue(mock_ForceFailGuard)\n      .compile();\n\n    appController = app.get<AppController>(AppController);\n  });\n\n  describe('root', () => {\n\n    it('should return \"Hello World!\"', () => {\n      expect(appController.getHello()).toBe('Hello World!');\n    });\n\n  });\n});\n```\n\n```text\ncontroller\n```\n\n```text\nConfigService\n```\n\n```js\nimport { CanActivate } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ForceFailGuard } from './force-fail.guard';\n\ndescribe('AppController', () => {\n  let appController: AppController;\n\n  beforeEach(async () => {\n    const mock_ForceFailGuard: CanActivate = { canActivate: jest.fn(() => true) };\n\n    const app: TestingModule = await Test\n      .createTestingModule({\n        controllers: [AppController],\n        providers: [\n          AppService,\n        ],\n      })\n      .overrideGuard(ForceFailGuard).useValue(mock_ForceFailGuard)\n      .compile();\n\n    appController = app.get<AppController>(AppController);\n  });\n\n  describe('root', () => {\n    it('should return \"Hello World!\"', () => {\n      expect(appController.getHello()).toBe('Hello World!');\n    });\n  });\n});\n```\n\n```text\n.overrideGuard()\n```\n\n```text\nForceFailGuard\n```\n\n```text\nproviders\n```\n\n```text\nConfigService\n```\n\n```text\nTestingModule\n```\n\n```text\nForceFailGuard\n```\n\n```text\nproviders\n```\n\n```text\n.overrideGuard()\n```\n\n```text\nmock_ForceFailGuard\n```\n\n```text\nCanActivate\n```\n\n```text\ncanActivate\n```\n\n```typescript\n// InternalGuard.ts\n@Injectable()\nexport class InternalTokenGuard implements CanActivate {\n  constructor(private readonly config: ConfigService) {\n  }\n\n  public async canActivate(context: ExecutionContext): Promise<boolean> {\n    const token = this.config.get(\"internalToken\");\n\n    if (!token) {\n      throw new Error(`No internal token was provided.`);\n    }\n\n    const request = context.switchToHttp().getRequest();\n    const providedToken = request.headers[\"authorization\"];\n\n    if (token !== providedToken) {\n      throw new UnauthorizedException();\n    }\n\n    return true;\n  }\n}\n```\n\n```typescript\n// InternalGuard.spec.ts\nbeforeEach(async () => {\n  const module: TestingModule = await Test.createTestingModule({\n    controllers: [],\n    providers: [\n      InternalTokenGuard,\n      {\n        provide: ConfigService,\n        useValue: {\n          get: jest.fn((key: string) => {\n            if (key === \"internalToken\") {\n              return 123;\n            }\n            return null;\n          })\n        }\n      }\n    ]\n  }).compile();\n\n  config = module.get<ConfigService>(ConfigService);\n  guard = module.get<InternalTokenGuard>(InternalTokenGuard);\n});\n\nit(\"should throw UnauthorizedException when token is not Bearer\", async () => {\n  const context = {\n    getClass: jest.fn(),\n    getHandler: jest.fn(),\n    switchToHttp: jest.fn(() => ({\n      getRequest: jest.fn().mockReturnValue({\n        headers: {\n          authorization: \"providedToken\"\n        }\n      })\n    }))\n  } as any;\n\n  await expect(guard.canActivate(context)).rejects.toThrow(\n    UnauthorizedException\n  );\n  expect(context.switchToHttp).toHaveBeenCalled();\n});\n```\n\n========================================\n\nComments:\n- Have you found a solution for this? I'm facing the same issue.\n- In the future, please paste the relevant code into your question. This makes the question future proof, for when you change or delete the repository you have linked to. This is especially needed in a case like this, when this question is the first thing that pops up when googling \"nestjs mock guard\".\n- Thank you for this answer It helped in my custom nestJs guard","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":390,"estimatedTokens":2217}}123{"id":"stack-65041545","source":"stackoverflow","questionId":65041545,"title":"How can i use longitude and latitude with typeorm and postgres","tags":["postgresql","nestjs","typeorm"],"text":"Title: How can i use longitude and latitude with typeorm and postgres\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy current entity looks like this:\n\n```\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Landmark extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n longitude: number \n\n @Column()\n latitude: number \n}\n```\n\nBut i wonder if there is a better way to do this, with a special postgres type, that works with typeorm.\n\n========================================\n\nTop Answer:\nExtending JosephHall Answer\n\nUsed postgres,postgis,typeORM,@types/geojson, Nest JS\n\n```\nimport { Column, Entity, Index, PrimaryGeneratedColumn} from 'typeorm';\nimport { Point } from 'geojson';\n\n@Entity({ name: 't_test_location' })\nexport class TestLocation {\n @PrimaryGeneratedColumn('increment')\n pk_id: number;\n \n @Column({ type: 'varchar', name: 's_city' })\n city: string;\n\n @Index({ spatial: true })\n @Column({\n type: 'geography',\n spatialFeatureType: 'Point', \n srid: 4326,\n nullable: true,\n })\n location:Point\n}\n```\n\nService class\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { getManager, QueryBuilder, Repository } from 'typeorm';\nimport { Geometry, Point } from 'geojson';\n@Injectable()\nexport class LocationService {\n constructor(\n @InjectRepository(TestLocation) private readonly repo: Repository,\n ) {}\n\n public async getAll() {\n return await this.repo.find();\n }\n\n public async create(location:TestLocation){\n const pointObject :Point= {\n type: \"Point\",\n coordinates: [location.long,location.lat]\n };\n location.location = pointObject;\n return await this.repo.save(location)\n }\n```\n\nController\n\n```\nimport { Body, Controller, Get, Post } from '@nestjs/common';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { LocationService } from './location.service';\n\n@Controller('location')\nexport class LocationController {\n constructor(private serv: LocationService) {}\n\n @Get()\n public async getAll() {\n return await this.serv.getAll();\n }\n @Post()\n createLocation(@Body() location : TestLocation): void{\n this.serv.create(location);\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Landmark extends BaseEntity {\n    @PrimaryGeneratedColumn('uuid')\n    id: string;\n\n    @Column()\n    longitude: number \n\n    @Column()\n    latitude: number \n}\n```\n\n```text\nimport { Geometry } from 'geojson';\n...\n@Column\nlocation: Geometry\n```\n\n```text\nUPDATE customers SET location = 'point(37.7, 122.4)' where id = 123;\n```\n\n```text\n-- Assuming you have a lat and lon columns on the `customers` table that you are migrating to the PostGIS geometry(point) type\nUPDATE customers SET location = ST_MakePoint(lat, lon) where id = 123;\n```\n\n```text\n@types/geojson\n```\n\n```text\nGeometry\n```\n\n```text\nlatitude\n```\n\n```text\nlongitude\n```\n\n```text\nlocation\n```\n\n```text\npoint()\n```\n\n```text\nGeometry\n```\n\n```text\nlocation\n```\n\n```text\ncustomers\n```\n\n```text\ngeometry(point)\n```\n\n```text\nlocation\n```\n\n```text\ngeometry(point)\n```\n\n```text\nST_MakePoint\n```\n\n```text\nimport { Column, Entity, Index, PrimaryGeneratedColumn} from 'typeorm';\nimport { Point } from 'geojson';\n\n@Entity({ name: 't_test_location' })\nexport class TestLocation {\n  @PrimaryGeneratedColumn('increment')\n  pk_id: number;\n  \n  @Column({ type: 'varchar', name: 's_city' })\n  city: string;\n\n  @Index({ spatial: true })\n  @Column({\n    type: 'geography',\n    spatialFeatureType: 'Point', \n    srid: 4326,\n    nullable: true,\n  })\n  location:Point\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { getManager, QueryBuilder, Repository } from 'typeorm';\nimport { Geometry, Point } from 'geojson';\n@Injectable()\nexport class LocationService {\n  constructor(\n    @InjectRepository(TestLocation) private readonly repo: Repository<TestLocation>,\n  ) {}\n\n  public async getAll() {\n    return await this.repo.find();\n  }\n\n  public async create(location:TestLocation){\n    const pointObject :Point= {\n      type: \"Point\",\n      coordinates: [location.long,location.lat]\n  };\n  location.location = pointObject;\n  return await this.repo.save(location)\n  }\n```\n\n```text\nimport { Body, Controller, Get, Post } from '@nestjs/common';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { LocationService } from './location.service';\n\n@Controller('location')\nexport class LocationController {\n  constructor(private serv: LocationService) {}\n\n  @Get()\n  public async getAll() {\n    return await this.serv.getAll();\n  }\n  @Post()\n  createLocation(@Body() location : TestLocation): void{\n    this.serv.create(location);\n  }\n}\n```\n\n========================================\n\nComments:\n- Why do you import `Geometry`? I don't see it used anywhere.\n- @SergeyYarotskiy Yes, no need to import. Updated the answer. Thank you!!\n- getting error `QueryFailedError: type \"geography\" does not exist` what is the reason ?\n- @rickster the reason for that because the postgis extension not added to the postgres so the pg does not identifying this special type that is provided by the postgis extension","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":268,"estimatedTokens":1354}}124{"id":"stack-57616136","source":"stackoverflow","questionId":57616136,"title":"Generate package.json on nx build / deployment","tags":["nestjs","nrwl-nx"],"text":"Title: Generate package.json on nx build / deployment\nTags: nestjs, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nI've a monorepo using nx with multiple node/nestjs apps. Some of the apps doesn't require all the packages used in the other apps. Because it's a monorepo, I need to install all packages for every apps during the deployment. \n\nIs there a way generate a package.json on build that would contain only the packages needed for the app that I'm building?\n\nI've tryed to use \"generate-package-json-webpack-plugin\" to generate the package.json, but it only detect half the dependencies.\n\nI've also tried to build a single js file containing all the apps, but it doesn't seem to work and always require tslib.\n\n========================================\n\nTop Answer:\nAfter I look at the nx source code I found the answer.\n\nSet `generatePackageJson` to `true` in `workspace.json` where `/targets/build/options`.\n\nThis will generate you package.json with the necessary dependencies for your app.\n\nHere example:\n\n```\n\"node-api\": {\n \"root\": \"apps/node-api\",\n \"sourceRoot\": \"apps/node-api/src\",\n \"projectType\": \"application\",\n \"prefix\": \"node-api\",\n \"targets\": {\n \"build\": {\n \"executor\": \"@nrwl/node:build\",\n \"outputs\": [\"{options.outputPath}\"],\n \"options\": {\n \"showCircularDependencies\": false,\n \"outputPath\": \"dist/apps/node-api\",\n \"main\": \"apps/node-api/src/main.ts\",\n \"tsConfig\": \"apps/node-api/tsconfig.app.json\",\n \"assets\": [\"apps/node-api/src/assets\"],\n \"generatePackageJson\": true <----------------------\n },\n....\n```\n\n========================================\n\nCode:\n```json\n{\n  \"targetDefaults\": {\n    \"build\": {\n      \"executor\": \"@nx/webpack:webpack\",\n      \"options\": {\n        \"generatePackageJson\": true\n      },\n      // ...\n    },\n    // ...\n  },\n  // ...\n}\n```\n\n```json\n{\n  \"targets\": {\n    \"build\": {\n      \"executor\": \"@nx/webpack:webpack\",\n      \"options\": {\n        \"generatePackageJson\": true\n      },\n      //...\n    },\n    // ...\n  }\n  // ...\n}\n```\n\n```json\n{\n  \"name\": \"...\",\n  \"scripts\": {\n    // ...\n  },\n  \"nx\": {\n    \"targets\": {\n      \"build\": {\n        \"executor\": \"@nx/webpack:webpack\",\n        \"options\": {\n          \"generatePackageJson\": true\n        },\n      },\n      // ...\n    },\n    // ...\n  },\n  // ...\n}\n```\n\n```text\nworkspace.json\n```\n\n```text\ngeneratePackageJson\n```\n\n```text\nnx.json\n```\n\n```text\nproject.json\n```\n\n```text\npackage.json\n```\n\n```text\n\"node-api\": {\n      \"root\": \"apps/node-api\",\n      \"sourceRoot\": \"apps/node-api/src\",\n      \"projectType\": \"application\",\n      \"prefix\": \"node-api\",\n      \"targets\": {\n        \"build\": {\n          \"executor\": \"@nrwl/node:build\",\n          \"outputs\": [\"{options.outputPath}\"],\n          \"options\": {\n            \"showCircularDependencies\": false,\n            \"outputPath\": \"dist/apps/node-api\",\n            \"main\": \"apps/node-api/src/main.ts\",\n            \"tsConfig\": \"apps/node-api/tsconfig.app.json\",\n            \"assets\": [\"apps/node-api/src/assets\"],\n            \"generatePackageJson\": true <----------------------\n          },\n....\n```\n\n```text\ngeneratePackageJson\n```\n\n```text\ntrue\n```\n\n```text\nworkspace.json\n```\n\n```text\n<project-name>/targets/build/options\n```\n\n```text\nconst { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin');\nconst { join } = require('path');\n\nmodule.exports = {\n  output: {\n    path: join(__dirname, '../../dist/apps/your-app'), // change path as needed\n  },\n  plugins: [\n    new NxAppWebpackPlugin({\n      target: 'node',\n      compiler: 'tsc',\n      main: './src/main.ts',\n      tsConfig: './tsconfig.app.json',\n      assets: ['./src/assets'],\n      generatePackageJson: true // <- Right here\n    })\n  ],\n};\n```\n\n```text\ngeneratePackageJson\n```\n\n```text\nplugins\n```\n\n```text\nwebpack.config.js\n```\n\n```text\npackage.json\n```\n\n```text\npackage-lock.json\n```\n\n```text\ntsc\n```\n\n```text\nswc\n```\n\n========================================\n\nComments:\n- thanks for your answer. The problem is not with CI, but more for deployment. If I have an app with 500MB+ of dependencies and I need to write a microservice that work with the main app. It feel just wrong to install all packages for the microservice when it almost require no package. After some research, there's an open issue here: github.com/nrwl/nx/issues/1518\n- hmm, this should not affect deployment at all. When you build you would only bundle those dependencies that you use. In this example you would end up with two bundles; One fore your client app and a separate one for your microservice. The microservice would only have the code needed for it (and not include the client side code)\n- Although you need to install the dependencies in order to start building, your artifact wouldn't contain your entire node_modules - only the code that you're actually using (via tree shaking)\n- When you run a server like next.js you need to install production depdendencies to run the app, and the nx repo only has one list of them in the root dir, so you get everything. Now when you do this in a docker container you now have a 1~2GB image that could be just 200mb for a small service.This hurts especially if you want to run this image on a serverless platform that deals with cold starts. I agree NX should provide a better way to have a `install production dependencies only for this app` command\n- Exactly like @MakuraYami said. Electrichead you are confusing the web app with the server app. You can't bundle all the server code into one js file same as for web apps.\n- How does it work on the latest versions? Seems like `'generatePackageJson' is not found in schema` this is what I'm getting.\n- @hackp0int nx.dev/node/webpack#generatepackagejson\n- nx.dev/packages/node/executors/webpack#generatepackagejson","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":219,"estimatedTokens":1421}}125{"id":"stack-53426069","source":"stackoverflow","questionId":53426069,"title":"Getting User Data by using Guards (Roles, JWT)","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Getting User Data by using Guards (Roles, JWT)\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nThe documentation is kinda thin here so I ran into a problem. I try to use Guards to secure Controller or it's Actions, so I gonna ask for the role of authenticated requests (by JWT). In my auth.guard.ts I ask for \"request.user\" but it's empty, so I can't check the users role. I don't know how to define \"request.user\". Here is my auth module and it's imports.\n\n**auth.controller.ts**\n\n```\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\nimport { RolesGuard } from './auth.guard';\n\n@Controller('auth')\nexport class AuthController {\n constructor(private readonly authService: AuthService) {}\n\n @Get('token')\n async createToken(): Promise {\n return await this.authService.signIn();\n }\n\n @Get('data')\n @UseGuards(RolesGuard)\n findAll() {\n return { message: 'authed!' };\n }\n}\n```\n\n**roles.guard.ts**\n\nHere user.request is empty, because I never define it. The documentation doesn't show how or where.\n\n```\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private readonly reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const roles = this.reflector.get('roles', context.getHandler());\n if (!roles) {\n return true;\n }\n const request = context.switchToHttp().getRequest();\n const user = request.user; // it's undefined\n const hasRole = () =>\n user.roles.some(role => !!roles.find(item => item === role));\n return user && user.roles && hasRole();\n }\n}\n```\n\n**auth.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { HttpStrategy } from './http.strategy';\nimport { UserModule } from './../user/user.module';\nimport { AuthController } from './auth.controller';\nimport { JwtStrategy } from './jwt.strategy';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\n\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n secretOrPrivateKey: 'secretKey',\n signOptions: {\n expiresIn: 3600,\n },\n }),\n UserModule,\n ],\n providers: [AuthService, HttpStrategy],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n**auth.service.ts**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { UserService } from '../user/user.service';\nimport { JwtService } from '@nestjs/jwt';\n\n@Injectable()\nexport class AuthService {\n constructor(\n private readonly userService: UserService,\n private readonly jwtService: JwtService,\n ) {}\n\n async signIn(): Promise {\n // In the real-world app you shouldn't expose this method publicly\n // instead, return a token once you verify user credentials\n const user: any = { email: 'user@email.com' };\n const token: string = this.jwtService.sign(user);\n return { token };\n }\n\n async validateUser(payload: any): Promise {\n // Validate if token passed along with HTTP request\n // is associated with any registered account in the database\n return await this.userService.findOneByEmail(payload.email);\n }\n}\n```\n\n**jwt.strategy.ts**\n\n```\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: 'secretKey',\n });\n }\n\n async validate(payload: any) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\nDocumentation: https://docs.nestjs.com/guards\n\nThanks for any help.\n\n========================================\n\nTop Answer:\nYou can attach multiple guards together (@UseGuards(AuthGuard('jwt'), RolesGuard)) to pass the context between them. Then you will have access 'req.user' object inside 'RolesGuard'.\n\n========================================\n\nCode:\n```text\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\nimport { RolesGuard } from './auth.guard';\n\n@Controller('auth')\nexport class AuthController {\n  constructor(private readonly authService: AuthService) {}\n\n  @Get('token')\n  async createToken(): Promise<any> {\n    return await this.authService.signIn();\n  }\n\n  @Get('data')\n  @UseGuards(RolesGuard)\n  findAll() {\n    return { message: 'authed!' };\n  }\n}\n```\n\n```text\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const roles = this.reflector.get<string[]>('roles', context.getHandler());\n    if (!roles) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const user = request.user; // it's undefined\n    const hasRole = () =>\n      user.roles.some(role => !!roles.find(item => item === role));\n    return user && user.roles && hasRole();\n  }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { HttpStrategy } from './http.strategy';\nimport { UserModule } from './../user/user.module';\nimport { AuthController } from './auth.controller';\nimport { JwtStrategy } from './jwt.strategy';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\n\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.register({\n      secretOrPrivateKey: 'secretKey',\n      signOptions: {\n        expiresIn: 3600,\n      },\n    }),\n    UserModule,\n  ],\n  providers: [AuthService, HttpStrategy],\n  controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { UserService } from '../user/user.service';\nimport { JwtService } from '@nestjs/jwt';\n\n@Injectable()\nexport class AuthService {\n  constructor(\n    private readonly userService: UserService,\n    private readonly jwtService: JwtService,\n  ) {}\n\n  async signIn(): Promise<object> {\n    // In the real-world app you shouldn't expose this method publicly\n    // instead, return a token once you verify user credentials\n    const user: any = { email: 'user@email.com' };\n    const token: string = this.jwtService.sign(user);\n    return { token };\n  }\n\n  async validateUser(payload: any): Promise<any> {\n    // Validate if token passed along with HTTP request\n    // is associated with any registered account in the database\n    return await this.userService.findOneByEmail(payload.email);\n  }\n}\n```\n\n```text\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: 'secretKey',\n    });\n  }\n\n  async validate(payload: any) {\n    const user = await this.authService.validateUser(payload);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\n```text\n@UseGuards(AuthGuard('jwt'))\n```\n\n```text\n@Injectable()\nexport class MyAuthGuard extends AuthGuard('jwt') {\n\n  handleRequest(err, user, info: Error) {\n    // don't throw 401 error when unauthenticated\n    return user;\n  }\n\n}\n```\n\n```text\nconst user = await passportFn(\n  type || this.options.defaultStrategy,\n  options,\n  // This is the callback passed to passport. handleRequest returns the user.\n  (err, info, user) => this.handleRequest(err, info, user)\n);\n// Then the user object is attached to the request\n// under the default property 'user' which you can change by configuration.\nrequest[options.property || defaultOptions.property] = user;\n```\n\n```text\nRolesGuard\n```\n\n```text\nAuthGuard\n```\n\n```text\nAuthGuard\n```\n\n```text\nAuthGuard\n```\n\n```text\nhandleRequest\n```\n\n```text\nAuthGuard\n```\n\n```text\nAuthGuard\n```\n\n```text\nreq.authInfo\n```\n\n```text\nreq.authInfo\n```\n\n```text\nvalidate\n```\n\n```js\n@Injectable()\n    export class LocalStrategy extends PassportStrategy(Strategy, 'local') {\n    \n        constructor(private authService: AuthService) {\n            super({\n                passReqToCallback: true\n            })\n        }\n\n        // rest of the strategy (validate)\n    }\n```\n\n========================================\n\nComments:\n- It works since I use @UseGuards(AuthGuard('jwt'), RolesGuard) as decorator. I extending AuthGuard for my RolesGuard and overwriting the functions, but it's seems they don't get called.\n- I'm glad it's working now. :-) I think from a single responsibility perspective it makes sense to have them separate. If you still wanted to extend in your case, you would probably want to override `canActivate(...)` and then call `super.canActivate(...)` from within.\n- As a general question, a guard is not supposed to have a single responsability and are not intended to modify the request object?, dont we have interceptors/middlewares for that?. Is a good/normal practice to inject values inside the guard? @KimKern","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":369,"estimatedTokens":2427}}126{"id":"stack-63896604","source":"stackoverflow","questionId":63896604,"title":"NestJS - Combine multiple Guards and activate if one returns true","tags":["nestjs"],"text":"Title: NestJS - Combine multiple Guards and activate if one returns true\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nIs it possible to use multiple auth guards on a route (in my case basic and ldap auth).\nThe route should be authenticated when one guard was successful.\n\n========================================\n\nTop Answer:\n### According to AuthGuard it just works out of the box\n\n### AuthGuard definition\n\nIf you look at AuthGuard then you see the following definition:\n\n(File is node_modules/@nestjs/passport/dist/auth.guard.d.ts)\n\n```\nexport declare const AuthGuard: (type?: string | string[]) => Type;\n```\n\nThat means that AuthGuard can receive an array of strings.\n\n### Code\n\nIn my code I did the following:\n\n```\n@UseGuards(AuthGuard([\"jwt\", \"api-key\"]))\n @Get()\n getOrders() {\n return this.orderService.getAllOrders();\n }\n```\n\n### Postman test\n\nIn Postman, the endpoint can have the api-key and the JWT.\n\n- Tested with JWT in Postman Authorization: It works\n\n- Tested with API-Key in Postman Authorization: It works\n\nThat implies there is an OR function between the 2 Guards.\n\n========================================\n\nCode:\n```js\nexport BasicGuard implements CanActivate {\n  constructor(\n      protected readonly reflector: Reflector\n  ) {}\n\n  async canActivate(context: ExecutionContext) {\n     const request = context.switchToHttp().getRequest();\n     if () {\n        // Do some logic and return true if access is granted\n        return true;\n     }\n\n    return false;\n  }\n}\n```\n\n```js\nexport LdapGuard extends BasicGuard implements CanActivate {\n  constructor(\n      protected readonly reflector: Reflector\n  ) {\n   super(reflector);\n}\n\n  async canActivate(context: ExecutionContext) {\n     const request = context.switchToHttp().getRequest();\n     if () {\n        // Do some logic and return true if access is granted\n        return true;\n     }\n    \n    // Basically if this guard is false then try the super.canActivate.  If its true then it would have returned already\n    return await super.canActivate(context);\n  }\n}\n```\n\n```text\ntrue\n```\n\n```text\nsuper.canActivate()\n```\n\n```js\n@Injectable()\nexport class MultipleAuthorizeGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector, private readonly moduleRef: ModuleRef) {}\n\n  public canActivate(context: ExecutionContext): Observable<boolean> {\n    const allowedGuards = this.reflector.get<Type<CanActivate>[]>('multipleGuardsReferences', context.getHandler()) || [];\n\n    const guards = allowedGuards.map((guardReference) => this.moduleRef.get<CanActivate>(guardReference));\n\n    if (guards.length === 0) {\n      return of(true);\n    }\n\n    if (guards.length === 1) {\n      return guards[0].canActivate(context) as Observable<boolean>;\n    }\n\n    const checks$: Observable<boolean>[] = guards.map((guard) =>\n      (guard.canActivate(context) as Observable<boolean>).pipe(\n        catchError((err) => {\n          if (err instanceof UnauthorizedException) {\n            return of(false);\n          }\n          throw err;\n        }),\n      ),\n    );\n\n    return forkJoin(checks$).pipe(map((results: boolean[]) => any(identity, results)));\n  }\n}\n```\n\n```js\nexport const MultipleGuardsReferences = (...guards: Type<CanActivate>[]) =>\n  SetMetadata('multipleGuardsReferences', guards);\n```\n\n```js\n@Get()\n@MultipleGuardsReferences(BasicGuard, LdapGuard)\n@UseGuards(MultipleAuthorizeGuard)\npublic getUser(): Observable<User> {\n  return this.userService.getUser();\n}\n```\n\n```text\nBasicGuard\n```\n\n```text\nLdapGuard\n```\n\n```text\nUserController\n```\n\n```text\n@Get()\n```\n\n```text\nMultipleAuthorizeGuard\n```\n\n```text\nObservable\n```\n\n```text\nforkJoin\n```\n\n```text\nMultipleAuthorizeGuard\n```\n\n```text\nMultipleGuardsReferences\n```\n\n```text\nguards([useGuard('basic') ,useGuard('ldap')])\n```\n\n```js\nexport declare const AuthGuard: (type?: string | string[]) => Type<IAuthGuard>;\n```\n\n```js\n@UseGuards(AuthGuard([\"jwt\", \"api-key\"]))\n  @Get()\n  getOrders() {\n    return this.orderService.getAllOrders();\n  }\n```\n\n```text\nimport {\n  CanActivate,\n  ExecutionContext,\n  Injectable,\n  SetMetadata,\n  Type,\n} from '@nestjs/common';\nimport { ModuleRef, Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class MultipleAuthorizeGuard implements CanActivate {\n  constructor(\n    private readonly reflector: Reflector,\n    private readonly moduleRef: ModuleRef,\n  ) {}\n\n  public async canActivate(context: ExecutionContext): Promise<boolean> {\n    const allowedGuards =\n      this.reflector.get<Type<CanActivate>[]>(\n        'multipleGuardsReferences',\n        context.getHandler(),\n      ) || [];\n\n    const guards = allowedGuards.map((guardReference) =>\n      this.moduleRef.get<CanActivate>(guardReference),\n    );\n\n    if (guards.length === 0) {\n      return Promise.resolve(true);\n    }\n\n    if (guards.length === 1) {\n      return guards[0].canActivate(context) as Promise<boolean>;\n    }\n\n    return Promise.any(\n      guards.map((guard) => {\n        return guard.canActivate(context) as Promise<boolean>;\n      }),\n    );\n  }\n}\n```\n\n```text\nexport const MultipleGuardsReferences = (...guards: Type<CanActivate>[]) =>\n  SetMetadata('multipleGuardsReferences', guards);\n```\n\n```text\n@Get()\n@MultipleGuardsReferences(BasicGuard, LdapGuard)\n@UseGuards(MultipleAuthorizeGuard)\npublic getUser(): Promise<User> {\n  return this.userService.getUser();\n}\n```\n\n```text\nconst guards = allowedGuards.map((guardReference) => this.moduleRef.get<CanActivate>(guardReference, { strict: false }), );\n```\n\n```js\n@Injectable()\n    export class ApiKeyGuard extends AuthGuard('jwt') {\n      private logger = new Logger('APIKeyGuard', {timestamp: true});\n    \n      constructor(\n          @Inject(forwardRef(()=> ApikeyGard)) private authGuard: AuthGuard) {\n        super();\n      }\n```\n\n```js\nasync canActivate(context: ExecutionContext) {\n        const isAPIKeyValid = this.apikeyService.isValid(user?.key);\n        if(!isAPIKey) hasPermission = await \n    this.authGuard.canActivate(context);  //Here you are using the second guard to check if there is a token and if its valid\n        \n    \n        return isAPIKeyValid === true || hasPermission === true;  //If any of both is valid the guard will allow the access\n      }\n```\n\n```text\napikey\n```\n\n```text\nvalidation\n```\n\n```text\ncanActivate()\n```\n\n========================================\n\nComments:\n- Your metadata keys do not match. You need to change 'allowedGuards' to 'multipleGuardsReferences' in the first line of canActivate method.\n- Thank you for the suggestion. I'll fix the example\n- You can also let the `MultipleGuardsReferences` decorator set `UseGuards(MultipleAuthorizeGuard)`, so you only need `@MultipleGuardsReferences(BasicGuard, LdapGuard)` on your controller.\n- Great and simple solution! This works for me too.\n- for some reason iI found that the order of `[\"jwt\", \"api-key\"]` matters. `[\"api-key\", \"jwt\"]` did NOT work","metadata":{"transformedAt":"2026-08-18T18:33:02.412Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":302,"estimatedTokens":1714}}127{"id":"stack-52531707","source":"stackoverflow","questionId":52531707,"title":"nest.js @Post setting the content-type of the response","tags":["typescript","post","content-type","nestjs"],"text":"Title: nest.js @Post setting the content-type of the response\nTags: typescript, post, content-type, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement a POST endpoint to my API, which returns an HTML string when called at.\n\nMy code looks like this at the moment:\n\n```\nimport { Controller, Post } from '@nestjs/common';\n@Controller()\nexport class MyController {\n @Post('/endpoint')\n public create(): string {\n return `\n \n โ€ฆ\n `;\n }\n}\n```\n\nHow can I tell the POST endpoint to send the correct content-type together with it's response? I've searched all documentations but was not able to find anything helpful for me.\n\nThank you in advance for your help\n\n========================================\n\nTop Answer:\nAnother option (assuming Express is used), is to specify content type when sending the response. This will allow you to conditionally return JSON (or other response types) while processing the request:\n\n```\nimport { Response } from 'express';\n\n@Post('/endpoint')\npublic create(@Res() res: Response): string {\n // ...\n if (error) {\n return res.status(404).json({message: 'image not found'});\n }\n // ...\n return res.status(200).contentType('text/html').send(document);\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Controller, Post } from '@nestjs/common';\n@Controller()\nexport class MyController {\n    @Post('/endpoint')\n    public create(): string {\n        return `\n            <!DOCTYPE html>\n            โ€ฆ\n            </html>`;\n    }\n}\n```\n\n```ts\nimport { Header } from '@nestjs/common'\n\n@Post('/endpoint')\n@Header('content-type', 'text/html')\npublic create(): string {\n  //\n}\n```\n\n```text\n@Header\n```\n\n```text\n@Post\n```\n\n```text\nimport { Response } from 'express';\n\n@Post('/endpoint')\npublic create(@Res() res: Response): string {\n    // ...\n    if (error) {\n        return res.status(404).json({message: 'image not found'});\n    }\n    // ...\n    return res.status(200).contentType('text/html').send(document);\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":94,"estimatedTokens":492}}128{"id":"stack-62512778","source":"stackoverflow","questionId":62512778,"title":"How to get an array as an input for a GraphQL resolver","tags":["typescript","rest","graphql","nestjs","graphql-js"],"text":"Title: How to get an array as an input for a GraphQL resolver\nTags: typescript, rest, graphql, nestjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI want to get an array of strings as `ids` parameter from the query variables and use it inside my resolver. Below here is my code.\n\n### People.resolver.ts\n\n```\nimport {\n Resolver, Query, Mutation, Args,\n} from '@nestjs/graphql';\nimport { People } from './People.entity';\nimport { PeopleService } from './People.service';\n\n@Resolver(() => People)\nexport class PeopleResolver {\n constructor(private readonly peopleService: PeopleService) { }\n\n @Mutation(() => String)\n async deletePeople(@Args('ids') ids: string[]) : Promise {\n const result = await this.peopleService.deletePeople(ids);\n return JSON.stringify(result);\n }\n}\n```\n\nHowever, I am getting the following error,\n\n```\n[Nest] 8247 - 06/22/2020, 6:32:53 PM [RouterExplorer] Mapped {/run-migrations, POST} route +1ms\n(node:8247) UnhandledPromiseRejectionWarning: Error: You need to provide explicit type for PeopleResolver#deletePeople parameter #0 !\n at Object.findType (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/findType.js:17:15)\n at Object.getParamInfo (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/params.js:9:49)\n at /Users/eranga/Documents/Project/node_modules/type-graphql/dist/decorators/Arg.js:9:159\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/decorators/args.decorator.js:34:113\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:36\n at Array.forEach ()\n at LazyMetadataStorageHost.load (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:22)\n at GraphQLSchemaBuilder. (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:31:57)\n at Generator.next ()\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:17:71\n(node:8247) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)\n(node:8247) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nI also tried the following variations,\n\n```\n@Args('ids', () => string[]) ids: string[]\n\n@Args('ids', () => String[]) ids: String[]\n\n@Args('ids', () => [String]) ids: String[]\n\n@Args('ids', { type: () => String[] }) ids: String[]\n```\n\nBut if I am to change my mutation like below to take a single string it works.\n\n```\n@Mutation(() => String)\nasync deletePeople(@Args('id') id: string) : Promise {\n const result = await this.peopleService.deletePeople([id]);\n return JSON.stringify(result);\n}\n```\n\nAny idea why this happens?\n\n========================================\n\nCode:\n```js\nimport {\n  Resolver, Query, Mutation, Args,\n} from '@nestjs/graphql';\nimport { People } from './People.entity';\nimport { PeopleService } from './People.service';\n\n@Resolver(() => People)\nexport class PeopleResolver {\n  constructor(private readonly peopleService: PeopleService) { }\n\n  @Mutation(() => String)\n  async deletePeople(@Args('ids') ids: string[]) : Promise<String> {\n    const result = await this.peopleService.deletePeople(ids);\n    return JSON.stringify(result);\n  }\n}\n```\n\n```bash\n[Nest] 8247   - 06/22/2020, 6:32:53 PM   [RouterExplorer] Mapped {/run-migrations, POST} route +1ms\n(node:8247) UnhandledPromiseRejectionWarning: Error: You need to provide explicit type for PeopleResolver#deletePeople parameter #0 !\n    at Object.findType (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/findType.js:17:15)\n    at Object.getParamInfo (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/params.js:9:49)\n    at /Users/eranga/Documents/Project/node_modules/type-graphql/dist/decorators/Arg.js:9:159\n    at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/decorators/args.decorator.js:34:113\n    at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:36\n    at Array.forEach (<anonymous>)\n    at LazyMetadataStorageHost.load (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:22)\n    at GraphQLSchemaBuilder.<anonymous> (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:31:57)\n    at Generator.next (<anonymous>)\n    at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:17:71\n(node:8247) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)\n(node:8247) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```js\n@Args('ids', () => string[]) ids: string[]\n\n@Args('ids', () => String[]) ids: String[]\n\n@Args('ids', () => [String]) ids: String[]\n\n@Args('ids', { type: () => String[] }) ids: String[]\n```\n\n```js\n@Mutation(() => String)\nasync deletePeople(@Args('id') id: string) : Promise<String> {\n  const result = await this.peopleService.deletePeople([id]);\n  return JSON.stringify(result);\n}\n```\n\n```text\nids\n```\n\n```js\n@Args({ name: 'ids', type: () => [String] }) ids: String[]\n```\n\n```js\n@UseGuards(GraphqlAuthGuard)\n@Mutation(() => String)\nasync deletePeople(@Args({ name: 'ids', type: () => [String] }) ids: String[]) : Promise<String> {\n  const result = await this.peopleService.deletePeople(ids);\n  return JSON.stringify(result);\n}\n```\n\n========================================\n\nComments:\n- I am trieng to achieve simular with an array of objects. Do you have any idea how to achieve this?\n- You should change your resolver to get the argument like `@Args({ name: , type: () => [<YOUR_OBJECT_INPUT_TYPE_AS_A_GRAPHQL_TYPE] }`\n- how can we pass multiple arguments? let's say we have updated mutations. i need to pass id and payload separatley. Is there any way to do that?\n- You can create 2 arg parameters. `deletePeople(@Args({ name: 'ids', type: () => [String] }) ids: String[], @Args({ name: 'payload', type: () => PayloadInputType }) payload: PayloadInputType)`\n- Is this outdated? it seems it answers no overload in this call\n- The answer is not outdated. I didn't understand what you meant by \"it answers no overload in this call\".\n- Yes, it is outdated, the new overload is like this - `@Args('', () => [ [String]) ids: String[])`\n- I think the answer is still valid as of today. I can see that the latest version (v10.0.16) still contains the overload matching the answer. However, I don't see an overload matching your answer though.","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":156,"estimatedTokens":1767}}129{"id":"stack-73591752","source":"stackoverflow","questionId":73591752,"title":"Eslint error `is defined but never used` warning in NestJs for all decorators","tags":["typescript","nestjs","eslint","decorator","typescript-decorator"],"text":"Title: Eslint error `is defined but never used` warning in NestJs for all decorators\nTags: typescript, nestjs, eslint, decorator, typescript-decorator\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJs framework for a project. Today discovered that EsLint finds 587 wrong problems.\n\n### All decorators generate this error:\n\n```\nwarning 'IsBoolean' is defined but never used @typescript-eslint/no-unused-vars\nwarning 'IsEmail' is defined but never used @typescript-eslint/no-unused-vars\nwarning 'IsEnum' is defined but never used @typescript-eslint/no-unused-vars\nwarning 'IsInt' is defined but never used @typescript-eslint/no-unused-vars\nwarning 'IsOptional' is defined but never used @typescript-eslint/no-unused-vars\n...\n```\n\n### And all index files generate this errors\n\n```\nerror No named exports found in module './users.controller' import/export\nerror No named exports found in module './users.service' import/export\nerror No named exports found in module './users.module'\n```\n\nBut all decorators are used and no index files has a named export.\nThis is a sample of my DTO class\n\n```\nimport {\n IsBoolean,\n IsEmail,\n IsEnum,\n IsInt,\n IsOptional,\n IsString,\n Matches,\n Max,\n MaxLength,\n Min,\n MinLength,\n} from 'class-validator';\n\nexport class UpdateUserDto {\n @IsOptional()\n @IsString()\n @Matches(/^[a-zA-Z0-9-_.@]+$/)\n @MinLength(3)\n @MaxLength(32)\n @ToCase({strategy: 'lower'})\n @Trim()\n username?: string;\n...\n```\n\nAnd this is one of my index files:\n\n```\nexport * from './users.controller';\nexport * from './users.service';\nexport * from './users.module';\nexport * from './auth.controller';\nexport * from './auth.service';\n```\n\nAnd my eslintrc.js:\n\n```\nmodule.exports = {\n parser: '@typescript-eslint/parser',\n parserOptions: {\n project: 'tsconfig.json',\n sourceType: 'module',\n },\n plugins: ['@typescript-eslint/eslint-plugin', 'import'],\n extends: [\n './node_modules/gts/',\n 'plugin:@typescript-eslint/recommended',\n 'prettier/@typescript-eslint',\n 'plugin:prettier/recommended',\n 'plugin:import/errors',\n 'plugin:import/warnings',\n 'plugin:import/typescript',\n ],\n root: true,\n env: {\n node: true,\n jest: true,\n },\n rules: {\n '@typescript-eslint/interface-name-prefix': 'off',\n '@typescript-eslint/explicit-function-return-type': 'off',\n '@typescript-eslint/explicit-module-boundary-types': 'off',\n '@typescript-eslint/no-explicit-any': 'warn',\n 'import/no-unresolved': 'error',\n 'import/no-cycle': 'warn',\n 'node/no-extraneous-import': [\n 'error',\n {\n allowModules: ['express'],\n },\n ],\n },\n settings: {\n ['import/parsers']: {'@typescript-eslint/parser': ['.ts', '.tsx']},\n ['import/resolver']: {\n node: {\n extensions: ['.ts'],\n moduleDirectory: ['node_modules', 'src/'],\n },\n typescript: {\n alwaysTryTypes: true, // always try to resolve types under `@types` directory even it doesn't contain any source code, like `@types/unist`\n \n },\n },\n },\n};\n```\n\n========================================\n\nCode:\n```js\nwarning  'IsBoolean' is defined but never used      @typescript-eslint/no-unused-vars\nwarning  'IsEmail' is defined but never used        @typescript-eslint/no-unused-vars\nwarning  'IsEnum' is defined but never used         @typescript-eslint/no-unused-vars\nwarning  'IsInt' is defined but never used          @typescript-eslint/no-unused-vars\nwarning  'IsOptional' is defined but never used     @typescript-eslint/no-unused-vars\n...\n```\n\n```js\nerror  No named exports found in module './users.controller'  import/export\nerror  No named exports found in module './users.service'     import/export\nerror  No named exports found in module './users.module'\n```\n\n```js\nimport {\n  IsBoolean,\n  IsEmail,\n  IsEnum,\n  IsInt,\n  IsOptional,\n  IsString,\n  Matches,\n  Max,\n  MaxLength,\n  Min,\n  MinLength,\n} from 'class-validator';\n\nexport class UpdateUserDto {\n  @IsOptional()\n  @IsString()\n  @Matches(/^[a-zA-Z0-9-_.@]+$/)\n  @MinLength(3)\n  @MaxLength(32)\n  @ToCase({strategy: 'lower'})\n  @Trim()\n  username?: string;\n...\n```\n\n```js\nexport * from './users.controller';\nexport * from './users.service';\nexport * from './users.module';\nexport * from './auth.controller';\nexport * from './auth.service';\n```\n\n```js\nmodule.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceType: 'module',\n  },\n  plugins: ['@typescript-eslint/eslint-plugin', 'import'],\n  extends: [\n    './node_modules/gts/',\n    'plugin:@typescript-eslint/recommended',\n    'prettier/@typescript-eslint',\n    'plugin:prettier/recommended',\n    'plugin:import/errors',\n    'plugin:import/warnings',\n    'plugin:import/typescript',\n  ],\n  root: true,\n  env: {\n    node: true,\n    jest: true,\n  },\n  rules: {\n    '@typescript-eslint/interface-name-prefix': 'off',\n    '@typescript-eslint/explicit-function-return-type': 'off',\n    '@typescript-eslint/explicit-module-boundary-types': 'off',\n    '@typescript-eslint/no-explicit-any': 'warn',\n    'import/no-unresolved': 'error',\n    'import/no-cycle': 'warn',\n    'node/no-extraneous-import': [\n      'error',\n      {\n        allowModules: ['express'],\n      },\n    ],\n  },\n  settings: {\n    ['import/parsers']: {'@typescript-eslint/parser': ['.ts', '.tsx']},\n    ['import/resolver']: {\n      node: {\n        extensions: ['.ts'],\n        moduleDirectory: ['node_modules', 'src/'],\n      },\n      typescript: {\n        alwaysTryTypes: true, // always try to resolve types under `<root>@types` directory even it doesn't contain any source code, like `@types/unist`\n        \n      },\n    },\n  },\n};\n```\n\n```text\n@typescript-eslint/*\n```\n\n```text\n@5.35.1\n```\n\n========================================\n\nComments:\n- And if you are using eslint extension in VSCode, please try to reload disable and enable or reload the editor. For me I had to disable and enable the extension.\n- If you are using automatic ESLint configuration in WebStorm, you will need to disable ESLint and then re-enable it in order to get the warnings to go away.\n- I had to update to version 6 before the errors were gone.","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":239,"estimatedTokens":1492}}130{"id":"stack-66371656","source":"stackoverflow","questionId":66371656,"title":"Difference forRoot and forFeature [Nest JS]","tags":["javascript","typescript","nestjs","typeorm"],"text":"Title: Difference forRoot and forFeature [Nest JS]\nTags: javascript, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to understand the difference between forRoot and forFeature in nest js dynamic modules.\n\nI also would like to understand this difference in the case of the TypeOrm dynamic module used with nestjs.\n\n========================================\n\nTop Answer:\nFrom Nest.js Discord,\n\n- `forRoot` / `forRootAsync`: configure a module **one time**. This is either for a global service, or a re-used configuration internally\n\n- `forFeature` / `forFeatureAsync`: make use of the configuration from forRoot/forRootAsync **for a specific provider**. This usually creates an injection token.\n\n- `register` / `registerAsync`: a module that can be registered **multiple times** with different configurations each time.\n\n========================================\n\nCode:\n```text\nforRoot\n```\n\n```text\nregister\n```\n\n```text\nforFeature\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nforRoot()\n```\n\n```text\nconnection\n```\n\n```text\nforFeature\n```\n\n```text\n<EntityName>Repository\n```\n\n```text\nforRoot\n```\n\n```text\nforFeature\n```\n\n```text\nforRoot\n```\n\n```text\nforRootAsync\n```\n\n```text\nforFeature\n```\n\n```text\nforFeatureAsync\n```\n\n```text\nregister\n```\n\n```text\nregisterAsync\n```\n\n========================================\n\nComments:\n- Why doesn't the forRoot method here: github.com/nestjs/typeorm/blob/7.0.0/lib/typeorm.module.ts return an object with an export member?\n- @Platus, it does. What about the explanation here that kind of conflicts or expands upon what you said? gist.github.com/darwinsubramaniam/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":92,"estimatedTokens":407}}131{"id":"stack-61684382","source":"stackoverflow","questionId":61684382,"title":"NestJS cli error: Collection \"@nestjs/schematics\" cannot be resolved","tags":["node.js","nestjs"],"text":"Title: NestJS cli error: Collection \"@nestjs/schematics\" cannot be resolved\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to learn NestJS and just following simple tutorial to create nestjs app. \n\nGetting following error while executing cli command **nest new test-project**\n\nNestJS cli Version: 7.1.5\nNodeJS Version: v10.18.1\n\nError:\n\n```\nError: Collection \"@nestjs/schematics\" cannot be resolved.\nat NodeModulesEngineHost.resolve (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/node-module-engine-host.js:74:19)\nat NodeModulesEngineHost._resolveCollectionPath (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/node-module-engine-host.js:79:37)\nat NodeModulesEngineHost.createCollectionDescription (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/file-system-engine-host-base.js:109:27)\nat SchematicEngine._createCollectionDescription (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/engine/engine.js:147:40)\nat SchematicEngine.createCollection (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/engine/engine.js:140:43)\nat NodeWorkflow.execute (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/workflow/base.js:100:41)\nat main (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:224:24)\nat Object. (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:315:5)\nat Module._compile (internal/modules/cjs/loader.js:778:30)\nat Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n```\n\nFailed to execute command: \"/Users/tsuthar/.config/yarn/global/node_modules/@nestjs/cli/node_modules/.bin/schematics\" @nestjs/schematics:application --name=nestjs-task-management --directory=undefined --no-dry-run --no-skip-git --package-manager=undefined --language=\"ts\" --collection=\"@nestjs/schematics\"\n\n========================================\n\nTop Answer:\nI had the same problem. same `error` message.\nI installed nest with yarn so I use command bellow to add(install) **shematics**:\n\n```\nyarn global add @nestjs/schematics\n```\n\nIf you use npm use this\n\n```\nnpm i -g @nestjs/schematics\n```\n\n========================================\n\nCode:\n```text\nError: Collection \"@nestjs/schematics\" cannot be resolved.\nat NodeModulesEngineHost.resolve (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/node-module-engine-host.js:74:19)\nat NodeModulesEngineHost._resolveCollectionPath (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/node-module-engine-host.js:79:37)\nat NodeModulesEngineHost.createCollectionDescription (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/tools/file-system-engine-host-base.js:109:27)\nat SchematicEngine._createCollectionDescription (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/engine/engine.js:147:40)\nat SchematicEngine.createCollection (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/engine/engine.js:140:43)\nat NodeWorkflow.execute (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics/src/workflow/base.js:100:41)\nat main (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:224:24)\nat Object.<anonymous> (/Users/tsuthar/.config/yarn/global/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:315:5)\nat Module._compile (internal/modules/cjs/loader.js:778:30)\nat Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\n```\n\n```text\nyarn global add @nestjs/schematics\n```\n\n```text\nnpm i -g @nestjs/schematics\n```\n\n```text\nyarn global add @nestjs/schematics\n```\n\n```text\nyarn global add @nestjs/schematics\n```\n\n```text\nnpm i -g @nestjs/schematics\n```\n\n```text\nerror\n```\n\n```text\nyarn add @nestjs/schematics\n```\n\n```text\nnest new your-project-name\n```\n\n```text\nnestJS\n```\n\n```text\nyarn\n```\n\n```text\nyarn cache clean\n```\n\n```text\nyarn global remove @nestjs/cli\n```\n\n```text\nyarn global add @nestjs/cli\n```\n\n```text\nnest new project-name\n```\n\n```text\nyarn\n```\n\n```text\napollo-server-core: 3.7.0\n```\n\n```bash\n> yarn global add @nestjs/schematics\nyarn global v1.22.21\n[1/4] ๐Ÿ”  Resolving packages...\n[2/4] ๐Ÿšš  Fetching packages...\nerror @angular-devkit/core@17.1.2: The engine \"node\" is incompatible with this module. Expected version \"^18.13.0 || >=20.9.0\". Got \"16.20.2\"\nerror Found incompatible module.\ninfo Visit https://yarnpkg.com/en/docs/cli/global for documentation about this command.\n```\n\n```text\n@nestjs/cli\n```\n\n```text\n@nestjs/schematics\n```\n\n```text\nyarn global add @nestjs/cli@9.2.0\n```\n\n```text\nyarn global add @nestjs/schematics@9.2.0\n```\n\n```text\nnpx @nestjs/cli new my-app-name-here\n```\n\n========================================\n\nComments:\n- Your answer could be improved by providing an example of the solution and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":161,"estimatedTokens":1256}}132{"id":"stack-60073385","source":"stackoverflow","questionId":60073385,"title":"Nest.Js not accepting any changes","tags":["node.js","typescript","caching","nestjs"],"text":"Title: Nest.Js not accepting any changes\nTags: node.js, typescript, caching, nestjs\nSource: Stack Overflow\n\nQuestion:\nI tried creating a new method inside **AppController** but it's not reflecting changes. I even tried to change the default **getHello()** method but it's outputting **\"Hello World!\"**. How is this possible?\n\n**Insomnia**\n\nhttps://i.sstatic.net/vyBwU.png\n\n**AppController**\n\nhttps://i.sstatic.net/d2fbH.png\n\n**AppService**\n\nhttps://i.sstatic.net/3Go3W.png\n\n========================================\n\nTop Answer:\nUse `npm run start:dev --watch` for full automation and fast coding.\n\n========================================\n\nCode:\n```text\nnpm run build && npm run start\n```\n\n```text\nnpm run start:dev --watch\n```\n\n```js\n{\n ...\n \"baseUrl\": \"../\",\n \"paths\": {\n     \"@gli/sockets\": [\"packages/sockets\"]\n  }\n}\n```\n\n```text\nError: Cannot find module '/Users/dht/projects/gli/server/dist/main'\n```\n\n```text\nbaseUrl\n```\n\n```text\ntsconfig.json\n```\n\n```text\nNestJS\n```\n\n```text\ndist\n```\n\n```bash\nCD C:\\Windows\\System32\\WBEM && dir /b *.mof *.mfl | findstr /v /i\nuninstall > moflist.txt & for /F %s in (moflist.txt) do mofcomp %s\n```\n\n========================================\n\nComments:\n- How are you running your nest application? Are you using the dev target? -- Please post your code as text instead of images; this makes it easier to work with your code.\n- @KimKern I tried running every command: nest run start, nest run start:dev, nest run start:debug but still no success\n- Have you tried using `npm run build && npm run start`?\n- Really weired error. Your solution works!\n- can anyone explain why does this happen? Deleting dist folder worked for me, but this is a really weird bug, I have spent an hour trying to figure out why my code is not working, before realizing the changes are not being compiled\n- I had the same problem. Just making `rm -rf build&#47;` made it. I suspect the `--watch` is having trouble detecting changes whenever you manually triggered a previous build but I'm not sure\n- I'm experiencing the same error. In my case I've updated the db connection string and the app - even after deleting the dist folder and using `npm run build && npm run start` - is still connecting using the old one. I don'r understand what's going on here.\n- The start:dev already have watch? `\"start:dev\": \"nest start --watch\",`","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":81,"estimatedTokens":586}}133{"id":"stack-59767377","source":"stackoverflow","questionId":59767377,"title":"How can I unit test that a guard is applied on a controller in NestJS?","tags":["node.js","typescript","jestjs","nestjs"],"text":"Title: How can I unit test that a guard is applied on a controller in NestJS?\nTags: node.js, typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've got a controller configured in NestJS and I want to check that the appropriate guards are set - does anyone have an example of how it could be done?\n\nThis (abridged) example works correctly as an application so I'm only after guidance on testing.\n\nYou'll notice in the user test there are tests where I'm calling `Reflect.getMetadata`. I'm after something like this - when I check it on the `__guards__` metadata, this is a function and I'm struggling to mock it out so I can check that it's applied with `AuthGuard('jwt')` as it's setting.\n\nUser.controller.ts\n\n```\n@Controller('/api/user')\nexport class UserController {\n @UseGuards(AuthGuard('jwt'))\n @Get()\n user(@Request() req) {\n return req.user;\n }\n}\n```\n\nUser.controller.spec.ts\n\n```\ndescribe('User Controller', () => {\n // beforeEach setup as per the cli generator\n\n describe('#user', () => {\n beforeEach(() => {\n // This is how I'm checking the @Get() decorator is applied correctly - I'm after something for __guards__\n expect(Reflect.getMetadata('path', controller.user)).toBe('/');\n expect(Reflect.getMetadata('method', controller.user)).toBe(RequestMethod.GET);\n });\n\n it('should return the user', () => {\n const req = {\n user: 'userObj',\n };\n\n expect(controller.user(req)).toBe(req.user);\n });\n });\n});\n```\n\n========================================\n\nTop Answer:\nFor what it's worth, you shouldn't need to test that the decorators provided by the framework set what you expect them too. That's why the framework has tests on them to begin with. Nevertheless, if you want to check that the decorator actually sets the expected metadata you can see that done here.\n\nIf you are just looking to test the guard, you can instantiate the GuardClass directly and test its `canActivate` method by providing an `ExecutionContext` object. I've got an example here. The example uses a library that creates mock objects for you (since then renamed), but the idea of it is that you'd create an object like\n\n```\nconst mockExecutionContext: Partial,\n jest.MockedFunction\n >\n> = {\n switchToHttp: jest.fn().mockReturnValue({\n getRequest: jest.fn(),\n getResponse: jest.fn(),\n }),\n};\n```\n\nWhere `getRequest` and `getResponse` return HTTP Request and Response objects (or at least partials of them). To just use this object, you'll need to also use `as any` to keep Typescript from complaining too much.\n\n========================================\n\nCode:\n```js\n@Controller('/api/user')\nexport class UserController {\n  @UseGuards(AuthGuard('jwt'))\n  @Get()\n  user(@Request() req) {\n    return req.user;\n  }\n}\n```\n\n```js\ndescribe('User Controller', () => {\n  // beforeEach setup as per the cli generator\n\n  describe('#user', () => {\n    beforeEach(() => {\n      // This is how I'm checking the @Get() decorator is applied correctly - I'm after something for __guards__\n      expect(Reflect.getMetadata('path', controller.user)).toBe('/');\n      expect(Reflect.getMetadata('method', controller.user)).toBe(RequestMethod.GET);\n    });\n\n    it('should return the user', () => {\n      const req = {\n        user: 'userObj',\n      };\n\n      expect(controller.user(req)).toBe(req.user);\n    });\n  });\n});\n```\n\n```text\nReflect.getMetadata\n```\n\n```text\n__guards__\n```\n\n```text\nAuthGuard('jwt')\n```\n\n```text\nimport { Controller } from '@nestjs/common';\nimport { UseGuards } from '@nestjs/common';\nimport { JwtAuthGuard } from './jwtAuthGuard';\n\n@Controller()\nexport class MyController {\n\n  @UseGuards(JwtAuthGuard)\n  user() {\n    ...\n  }\n}\n```\n\n```text\nit('should ensure the JwtAuthGuard is applied to the user method', async () => {\n  const guards = Reflect.getMetadata('__guards__', MyController.prototype.user)\n  const guard = new (guards[0])\n\n  expect(guard).toBeInstanceOf(JwtAuthGuard)\n});\n```\n\n```text\nit('should ensure the JwtAuthGuard is applied to the controller', async () => {\n  const guards = Reflect.getMetadata('__guards__', MyController)\n  const guard = new (guards[0])\n\n  expect(guard).toBeInstanceOf(JwtAuthGuard)\n});\n```\n\n```text\nconst mockExecutionContext: Partial<\n  Record<\n    jest.FunctionPropertyNames<ExecutionContext>,\n    jest.MockedFunction<any>\n  >\n> = {\n  switchToHttp: jest.fn().mockReturnValue({\n    getRequest: jest.fn(),\n    getResponse: jest.fn(),\n  }),\n};\n```\n\n```text\ncanActivate\n```\n\n```text\nExecutionContext\n```\n\n```text\ngetRequest\n```\n\n```text\ngetResponse\n```\n\n```text\nas any\n```\n\n```text\nit(`should be protected with JwtAuthGuard.`, async () => {\n  expect(isGuarded(UsersController.prototype.findMe, JwtAuthGuard)).toBe(true)\n})\n```\n\n```text\nexpect(isGuarded(UsersController, JwtAuthGuard)).toBe(true)\n```\n\n```text\n/**\n * Checks whether a route or a Controller is protected with the specified Guard.\n * @param route is the route or Controller to be checked for the Guard.\n * @param guardType is the type of the Guard, e.g. JwtAuthGuard.\n * @returns true if the specified Guard is applied.\n */\nexport function isGuarded(\n  route: ((...args: any[]) => any) | (new (...args: any[]) => unknown),\n  guardType: new (...args: any[]) => CanActivate\n) {\n  const guards: any[] = Reflect.getMetadata('__guards__', route)\n\n  if (!guards) {\n    throw Error(\n      `Expected: ${route.name} to be protected with ${guardType.name}\\nReceived: No guard`\n    )\n  }\n\n  let foundGuard = false\n  const guardList: string[] = []\n  guards.forEach((guard) => {\n    guardList.push(guard.name)\n    if (guard.name === guardType.name) foundGuard = true\n  })\n\n  if (!foundGuard) {\n    throw Error(\n      `Expected: ${route.name} to be protected with ${guardType.name}\\nReceived: only ${guardList}`\n    )\n  }\n  return true\n}\n```\n\n```text\nExpected: findMe to be protected with JwtAuthGuard\n```\n\n```text\nReceived: only AdminGuard,EditorGuard\n```\n\n```text\nisGuarded()\n```\n\n```text\ntest/utils.ts\n```\n\n========================================\n\nComments:\n- I used to make this test using e2e but definitely they are completelly valid regression testing in my opinion.\n- @RuslanGonzalez yeah, e2e tests are important. I'd argue that the e2e tests check that they're applying the correct functionality and the unit tests check that they're being applied - both are important and crucial that they're working in concert. Unit tests tend to be faster though\n- That's not really what I'm after doing. I'm looking to ensure that the guard decorator is set for the method. I don't care what the decorator does underneath (for the reasons you mention) and I've got tests around the guard itself. If this were a \"classic\" Express app, I could be able to test that the middleware is applied for routing which is what I'm trying to achieve here, but with the decorators\n- I'm not quite sure I understand what it is you are trying to achieve then. The first link shows tests that show the metadata being set correctly on both classes and class methods which is how the guards are \"set\". If you're wanting to test that when you call the route the guard is executed, then you need to set up supertest to make the call to the route. Maybe I'm not understanding what you're looking to do\n- Yeah, an e2e test is one option of achieving that. It may well be that's a more appropriate way of doing it. The example I gave does check that the correct metadata is set, but that's because I couldn't work out a better way of testing that the @Get decorator is applied (I'm open to suggestions). What I'm trying to achieve is a test to ensure that the appropriate guards are set - I'd prefer to do it through unit tests rather than e2e, because it'll appear in coverage reports but that's not a deal-breaker\n- It seems that reflection of metadata is still going to be your best bet here. In your above example you could have a test like `expect(Reflect.getMetadata('__guards__', UserController.user)).toEqual(MixinAuthGuard)`. MixinAuthGuard is the class that the mixin `AuthGuard('jwt')` produces (or should be). This would assert that the guard applied to the UserController.user method (i.e. the GET /api/user route) would be the correct guard\n- Also see a related question (stackoverflow.com/questions/62595603/&hellip;), there's an up-to-date example for mocking an `ExecutionContext` there. Also worth mentioning -- the package `@golevelup&#47;nestjs-testing` has been renamed to `@golevelup&#47;ts-jest`, see github.com/golevelup/nestjs/issues/265\n- thanks @JayMcDoniel for providing the lib, awesome man !\n- Great, thanks. As I said in the OP, I'm not after testing what the decorators do, just that they're applied with the appropriate configuration. As we're relying upon it in the code, I'm of the opinion that this should be part of the unit tests","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":257,"estimatedTokens":2182}}134{"id":"stack-64725626","source":"stackoverflow","questionId":64725626,"title":"How to fix 400 error bad request in socket io?","tags":["javascript","vue.js","websocket","socket.io","nestjs"],"text":"Title: How to fix 400 error bad request in socket io?\nTags: javascript, vue.js, websocket, socket.io, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a frontend application(VUE JS)\n\nI have a backend (Nest JS)\n\nVue JS app get data from backend via websockets using vue-socket.io-extended library\nWhen Vue JS app starts I see errors in browser:\n\npolling-xhr.js?d33e:229 POST\nhttp://localhost:11050/socket.io/?EIO=4&transport=polling&t=NMXgCF1\n400 (Bad Request)\n\nhttps://i.sstatic.net/ruEKy.jpg\n\n**How can I fix this error?**\n\nI think it is not connected with library, I tried just socket io library and the result was the same.\n\nServer is working, because it sends logs and show who is connected:\n\nhttps://i.sstatic.net/d1VrH.jpg\n\n**Server(Nest JS)**\nmain.ts file:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.enableCors();\n await app.listen(11050);\n}\nbootstrap();\n```\n\nApp.gateway:\n\n```\n@WebSocketGateway()\nexport class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {\n\n private logger: Logger = new Logger('AppGatway');\n\n @SubscribeMessage('msgToServer')\n handleMessage(client: Socket, text: string): WsResponse {\n return { event: 'msgToClient', data: text };\n }\n\n afterInit(server: Server) {\n this.logger.log('Initialised!');\n }\n\n handleConnection(client: Socket, ...args: any[]): any {\n this.logger.log(`Client connected: ${client.id}`);\n }\n\n handleDisconnect(client: Socket): any {\n this.logger.log(`Client disconnected: ${client.id}`);\n }\n}\n```\n\n**Frontend(Vue JS):**\n\n```\nimport VueSocketIOExt from \"vue-socket.io-extended\";\nimport Vue from \"vue\";\nimport io from \"socket.io-client\";\nconst socket = io(\"http://localhost:11050/\");\n\nVue.use(VueSocketIOExt, socket);\n\ndata: () => ({\nsocket: null,\n connection: null,\n sockets: {\n connect() {\n console.log(\"socket connected\");\n },\n },\n}\n```\n\n========================================\n\nTop Answer:\nTry below configuration on **server side**\n\n```\nconst io = require('socket.io')(server, {\n cors: {\n origin: \"http://localhost:8100\",\n methods: [\"GET\", \"POST\"],\n transports: ['websocket', 'polling'],\n credentials: true\n },\n allowEIO3: true\n});\n```\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.enableCors();\n  await app.listen(11050);\n}\nbootstrap();\n```\n\n```text\n@WebSocketGateway()\nexport class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {\n\n\n  private logger: Logger = new Logger('AppGatway');\n\n  @SubscribeMessage('msgToServer')\n  handleMessage(client: Socket, text: string): WsResponse<string> {\n    return { event: 'msgToClient', data: text };\n  }\n\n  afterInit(server: Server) {\n    this.logger.log('Initialised!');\n  }\n\n  handleConnection(client: Socket, ...args: any[]): any {\n    this.logger.log(`Client connected: ${client.id}`);\n  }\n\n  handleDisconnect(client: Socket): any {\n    this.logger.log(`Client disconnected: ${client.id}`);\n  }\n}\n```\n\n```text\nimport VueSocketIOExt from \"vue-socket.io-extended\";\nimport Vue from \"vue\";\nimport io from \"socket.io-client\";\nconst socket = io(\"http://localhost:11050/\");\n\nVue.use(VueSocketIOExt, socket);\n\ndata: () => ({\nsocket: null,\n    connection: null,\n    sockets: {\n      connect() {\n        console.log(\"socket connected\");\n      },\n    },\n}\n```\n\n```text\nsocket.io-client\n```\n\n```text\n^3.0.0\n```\n\n```text\n^2.3.0\n```\n\n```json\n\"dependencies\": {\n    \"@testing-library/jest-dom\": \"^5.11.8\",\n    \"@testing-library/react\": \"^11.2.3\",\n    \"@testing-library/user-event\": \"^12.6.0\",\n    \"@types/jest\": \"^26.0.20\",\n    \"@types/node\": \"^12.19.12\",\n    \"@types/react\": \"^16.14.2\",\n    \"@types/react-dom\": \"^16.9.10\",\n    \"moment\": \"^2.29.1\",\n    \"react\": \"^17.0.1\",\n    \"react-dom\": \"^17.0.1\",\n    \"react-moment\": \"^1.1.1\",\n    \"react-scripts\": \"4.0.1\",\n    \"socket.io-client\": \"^2.3.1\",\n    \"typescript\": \"^4.1.3\",\n    \"web-vitals\": \"^0.2.4\"\n  }\n```\n\n```json\n\"dependencies\": {\n    \"@nestjs/common\": \"^7.5.1\",\n    \"@nestjs/config\": \"^0.6.1\",\n    \"@nestjs/core\": \"^7.5.1\",\n    \"@nestjs/mongoose\": \"^7.2.1\",\n    \"@nestjs/platform-express\": \"^7.5.1\",\n    \"@nestjs/platform-socket.io\": \"^7.6.5\",\n    \"@nestjs/swagger\": \"^4.7.10\",\n    \"@nestjs/websockets\": \"^7.6.5\",\n    \"class-validator\": \"^0.13.1\",\n    \"mongoose\": \"^5.11.11\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^6.6.3\",\n    \"swagger-ui-express\": \"^4.1.6\"\n  }\n```\n\n```text\nconst io = require('socket.io')(server, {\n    cors: {\n        origin: \"http://localhost:8100\",\n        methods: [\"GET\", \"POST\"],\n        transports: ['websocket', 'polling'],\n        credentials: true\n    },\n    allowEIO3: true\n});\n```\n\n```text\nconst io = SocketIO(server,{\n        cors: {\n                origin: \"http://localhost\",\n                methods: [\"GET\", \"POST\"],\n                credentials: true,\n                transports: ['websocket', 'polling'],\n        },\n        allowEIO3: true\n        })\n```\n\n```text\nsocket.io.js\n```\n\n```text\nsocket.io\n```\n\n```text\nallowEIO3: true\n```\n\n```text\nconst io = require('socket.io')(server, {pingTimeout: 60000});\n```\n\n```text\nvar socket = io(\"http://localhost:3003/\")\n```\n\n```text\nsocket = io(\"http://localhost:3002\", {\n  transports: ['websocket']\n})\n```\n\n========================================\n\nComments:\n- Do you can your report?... I'm having same problem :(\n- This fixed me, in March 2021... :|\n- thanks , but how can use higher version of socket ?\n- @MojtabaDarzi go to socket.io/docs/v4/server-installation, socket.io/docs/v4/client-installation and choose the server-client version accordingly\n- This was my problem, I needed my socket.io-client and socket.io versions to match. my backend was socket.io 4.40 and my client was socket.io-client 2.4.0. I did npm uninstall socket.io-client, on my frontend, then did npm install socket.io-client@4.4.0 and my issue was fixed.\n- You saved me! Downgrading the socket version worked for me too!\n- Thank you for an answer!\n- Thanks, allow EIO3 helped me. I couldn't find what was connected to my production server that wasn't on EIO4.\n- Thanks, in my case I needed to add `polling` to the array of `transports`, didn't read that the URL was like `http:&#47;&#47;localhost:3000&#47;socket.io&#47;?EIO=4&transport=polling&t=P&zwnj;&#8203;8kdKf3`\n- Please elaborate what have you updated in socker.io file?\n- In the accepted answer: `the issue is related to mismatched socket.io server and client versions`\n- Also mentioned in foxer lee's answer.\n- This works, as it disables the \"polling\" option, which is included in the default transports of `[\"polling\", \"websocket\"]`. My case of the Bad Request is always when the app starts, the client attempts to reconnect with the old SID I guess, which is dead. so this solves the issue, but perhaps better would be to clear the old SID when the app closes, or when started. I need to read more on the client api.","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":277,"estimatedTokens":1727}}135{"id":"stack-52283713","source":"stackoverflow","questionId":52283713,"title":"How do I pass plain text as my request body using NestJS?","tags":["javascript","typescript","http","postman","nestjs"],"text":"Title: How do I pass plain text as my request body using NestJS?\nTags: javascript, typescript, http, postman, nestjs\nSource: Stack Overflow\n\nQuestion:\nOne of the controller methods in my NestJS application is supposed to take plain text as its body but whenever I try to make a request, the parameter is received as an empty object. Is this even possible or am I going to have to create some sort of DTO to pass that single string?\n\nExample:\n\n```\n@Post()\n myFunction(@Body() id: string) {\n // do something here\n }\n```\n\n========================================\n\nTop Answer:\nAdding on @yumaa's post above\n\nHere's the working decorator with NestJS v7.0.8:\n\n```\nimport { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common';\nimport * as rawBody from \"raw-body\";\n\nexport const PlainBody = createParamDecorator(async (_, context: ExecutionContext) => {\n const req = context.switchToHttp().getRequest();\n if (!req.readable) { throw new BadRequestException(\"Invalid body\"); }\n\n const body = (await rawBody(req)).toString(\"utf8\").trim();\n return body;\n})\n```\n\n========================================\n\nCode:\n```text\n@Post()\n  myFunction(@Body() id: string) {\n    // do something here\n  }\n```\n\n```js\nimport * as rawbody from 'raw-body';\nimport { Controller, Post, Body, Req } from '@nestjs/common';\n\n@Controller('/')\nexport class IndexController {\n\n  @Post()\n  async index(@Body() data, @Req() req) {\n\n    // we have to check req.readable because of raw-body issue #57\n    // https://github.com/stream-utils/raw-body/issues/57\n    if (req.readable) {\n      // body is ignored by NestJS -> get raw body from request\n      const raw = await rawbody(req);\n      const text = raw.toString().trim();\n      console.log('body:', text);\n\n    } else {\n      // body is parsed by NestJS\n      console.log('data:', data);\n    }\n\n    // ...\n  }\n\n}\n```\n\n```js\nimport * as rawbody from 'raw-body';\nimport { createParamDecorator, HttpException, HttpStatus } from '@nestjs/common';\n\nexport const PlainBody = createParamDecorator(async (data, req) => {\n  if (req.readable) {\n    return (await rawbody(req)).toString().trim();\n  }\n  throw new HttpException('Body aint text/plain', HttpStatus.INTERNAL_SERVER_ERROR);\n});\n```\n\n```js\n@Post()\nasync index(@PlainBody() text: string) {\n  // ...\n```\n\n```text\nbody-parser\n```\n\n```text\nraw-body\n```\n\n```text\nimport * as bodyParser from 'body-parser';\n\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.use(bodyparser({ ...options })) // for plain/text bodies\n  await app.listen(3000)\n}\nbootstrap();\n```\n\n```js\nimport { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common';\nimport * as rawBody from \"raw-body\";\n\nexport const PlainBody = createParamDecorator(async (_, context: ExecutionContext) => {\n    const req = context.switchToHttp().getRequest<import(\"express\").Request>();\n    if (!req.readable) { throw new BadRequestException(\"Invalid body\"); }\n\n    const body = (await rawBody(req)).toString(\"utf8\").trim();\n    return body;\n})\n```\n\n```text\nimport { json } from 'body-parser';\nimport * as cloneBuffer from 'clone-buffer';\n\nexport const cachedRawBodyRequestKey = 'rawBodyBuffer';\n\n/**\n * Clones the request buffer and stores it on the request object for reading later \n */\nexport const cacheRawBodyOnRequest = json({\n  verify: (req: any, res, buf, encoding) => {\n\n    // only clone the buffer if we're receiving a Xero webhook request\n    if (req.headers['x-xero-signature'] && Buffer.isBuffer(buf)) {\n      req[cachedRawBodyRequestKey] = cloneBuffer(buf);\n    }\n    return true;\n  },\n});\n```\n\n```text\napp.use(cacheRawBodyOnRequest);\n```\n\n```text\nconst textBody = req[cachedRawBodyRequestKey].toString('utf-8');\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { NestExpressApplication } from \"@nestjs/platform-express\";\n\nimport { json, urlencoded } from \"express\";\nimport type { Request } from \"express\";\nimport type http from \"http\";\n\nexport const HTTP_REQUEST_RAW_BODY = \"rawBody\";\n\n/**\n * make sure you configure the nest app with <code>preserveRawBodyInRequest</code>\n * @example\n * webhook(@RawBody() rawBody: string): Record<string, unknown> {\n *   return { received: true };\n * }\n * @see preserveRawBodyInRequest\n */\nexport const RawBody = createParamDecorator(\n  async (data: unknown, context: ExecutionContext) => {\n    const request = context\n      .switchToHttp()\n      .getRequest<Request>()\n    ;\n\n    if (!(HTTP_REQUEST_RAW_BODY in request)) {\n      throw new Error(\n        `RawBody not preserved for request in handler: ${context.getClass().name}::${context.getHandler().name}`,\n      );\n    }\n\n    const rawBody = request[HTTP_REQUEST_RAW_BODY];\n\n    return rawBody;\n  },\n);\n\n/**\n * @example\n * const app = await NestFactory.create<NestExpressApplication>(\n *   AppModule,\n *   {\n *     bodyParser: false, // it is prerequisite to disable nest's default body parser\n *   },\n * );\n * preserveRawBodyInRequest(\n *   app,\n *   \"signature-header\",\n * );\n * @param app\n * @param ifRequestContainsHeader\n */\nexport function preserveRawBodyInRequest(\n  app: NestExpressApplication,\n  ...ifRequestContainsHeader: string[]\n): void {\n  const rawBodyBuffer = (\n    req: http.IncomingMessage,\n    res: http.ServerResponse,\n    buf: Buffer,\n  ): void => {\n    if (\n      buf?.length\n      && (ifRequestContainsHeader.length === 0\n        || ifRequestContainsHeader.some(filterHeader => req.headers[filterHeader])\n      )\n    ) {\n      req[HTTP_REQUEST_RAW_BODY] = buf.toString(\"utf8\");\n    }\n  };\n\n  app.use(\n    urlencoded(\n      {\n        verify: rawBodyBuffer,\n        extended: true,\n      },\n    ),\n  );\n  app.use(\n    json(\n      {\n        verify: rawBodyBuffer,\n      },\n    ),\n  );\n}\n```\n\n```text\npreserveRawBodyInRequest\n```\n\n```text\nRawBody\n```\n\n```js\nfunction readPost(req: IncomingMessage) {\n  return new Promise<string>((resolve, reject) => {\n    let body = '';\n    req.on('data', (data: string) => (body += data));\n    req.on('error', (error: unknown) => reject(error));\n    req.on('end', () => resolve(body));\n  });\n}\n```\n\n```js\nimport { Post, Req } from '@nestjs/common';\nimport { IncomingMessage } from 'http';\n...\n@Post()\nmyFunction(@Req() req: IncomingMessage) {\n  const bodyStr = await readPost(req);\n  console.log('request body:', bodyStr);\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport type { NestExpressApplication } from '@nestjs/platform-express';\n\nconst app = await NestFactory.create<NestExpressApplication>(module, {\n  rawBody: true\n});\n\napp.useBodyParser('text')\n```\n\n```text\nimport { Controller, Post, RawBodyRequest, Req } from '@nestjs/common';\nimport { Request } from 'express';\n\n@Post()\nasync post(@Req() req: RawBodyRequest<Request>) {\n  console.log(req.rawBody?.toString('utf-8') ?? '')\n}\n```\n\n```text\nrawBody: true\n```\n\n```text\n// main.ts\nimport { NestExpressApplication } from '@nestjs/platform-express';\n\n// ...\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\n\napp.useBodyParser('text');\n// ...other code\n```\n\n```text\n// some.controller.ts\n@Post('text')\npublic async register(@Body() payload: string) {\n    console.log(payload);\n}\n```\n\n========================================\n\nComments:\n- Are you passing a valid content-type ?\n- I've tried both \"text\" and \"text/plain\" in Postman and neither of them are picked up by nest as strings.\n- I've tried both \"text\" and \"text/plain\" in Postman and neither of them are picked up by nest as strings.\n- While this works (I tested it) the only issue is you can not be strict with the types, as rawbody requires whatever gets parsed into it to be streamable and the Request type that @Req actually is not that. So you have to turn off strict typing to get it to work, for instance if you want to check the content-length as well (which you should) But works, so thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":325,"estimatedTokens":1966}}136{"id":"stack-58993405","source":"stackoverflow","questionId":58993405,"title":"How can I handle TypeORM error in NestJS?","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: How can I handle TypeORM error in NestJS?\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'd like to create a custom exception filter that handles different kinds of TypeORM errors. I've looked up the TypeORM error classes, and it seems like there's no such thing in TypeORM like MongoError.\n\nI wanted to make something similar to 1FpGLLjZSZMx6k's answer, and here's what I've done so far.\n\n```\nimport { QueryFailedError } from 'typeorm';\n\n@Catch(QueryFailedError)\nexport class QueryFailedExceptionFilter implements ExceptionFilter {\n catch(exception: QueryFailedError, host: ArgumentsHost) {\n const context = host.switchToHttp();\n const response = context.getResponse();\n const request = context.getRequest();\n const { url } = request;\n const { name } = exception;\n const errorResponse = {\n path: url,\n timestamp: new Date().toISOString(),\n message: name,\n };\n\n response.status(HttpStatus.BAD_REQUEST).json(errorResponse);\n }\n}\n```\n\nIf I need to catch another error for instance, `EntityNotFoundError`, I have to write the same code which is a very cumbersome task to do it.\n\nIt would be nice if I could handle errors by a single filter like below. Any ideas?\n\n```\n@Catch(TypeORMError)\nexport class EntityNotFoundExceptionFilter implements ExceptionFilter {\n catch(exception: MongoError, host: ArgumentsHost) {\n switch (exception.code) {\n case some error code:\n // handle error\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nTo handle different kinds of TypeOrm errors, you can switch / case the exception constructor if it matches any TypeOrm error (from node_modules\\typeorm\\error). Additionally, the (exception as any).code will provide the actual database error that occured. Notice the @catch() decorator is empty in order to catch all error types.\n\n```\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { QueryFailedError, EntityNotFoundError, CannotCreateEntityIdMapError } from 'typeorm';\nimport { GlobalResponseError } from './global.response.error';\n\n@Catch()\nexport class GlobalExceptionFilter implements ExceptionFilter {\n catch(exception: unknown, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n let message = (exception as any).message.message;\n let code = 'HttpException';\n\n Logger.error(message, (exception as any).stack, `${request.method} ${request.url}`);\n\n let status = HttpStatus.INTERNAL_SERVER_ERROR;\n \n switch (exception.constructor) {\n case HttpException:\n status = (exception as HttpException).getStatus();\n break;\n case QueryFailedError: // this is a TypeOrm error\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as QueryFailedError).message;\n code = (exception as any).code;\n break;\n case EntityNotFoundError: // this is another TypeOrm error\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as EntityNotFoundError).message;\n code = (exception as any).code;\n break;\n case CannotCreateEntityIdMapError: // and another\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as CannotCreateEntityIdMapError).message;\n code = (exception as any).code;\n break;\n default:\n status = HttpStatus.INTERNAL_SERVER_ERROR\n }\n\n response.status(status).json(GlobalResponseError(status, message, code, request));\n }\n}\n\nimport { Request } from 'express';\nimport { IResponseError } from './response.error.interface';\n\nexport const GlobalResponseError: (statusCode: number, message: string, code: string, request: Request) => IResponseError = (\n statusCode: number,\n message: string,\n code: string,\n request: Request\n): IResponseError => {\n return {\n statusCode: statusCode,\n message,\n code,\n timestamp: new Date().toISOString(),\n path: request.url,\n method: request.method\n };\n};\n\nexport interface IResponseError {\n statusCode: number;\n message: string;\n code: string;\n timestamp: string;\n path: string;\n method: string;\n}\n```\n\n*Note: As of new version of `typeorm` import for `EntityNotFoundError` and `CannotCreateEntityIdMapError` will be as bellow*\n\n```\nimport { QueryFailedError } from 'typeorm';\nimport { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';\nimport { CannotCreateEntityIdMapError } from 'typeorm/error/CannotCreateEntityIdMapError';\n```\n\n========================================\n\nCode:\n```js\nimport { QueryFailedError } from 'typeorm';\n\n@Catch(QueryFailedError)\nexport class QueryFailedExceptionFilter implements ExceptionFilter {\n  catch(exception: QueryFailedError, host: ArgumentsHost) {\n    const context = host.switchToHttp();\n    const response = context.getResponse<Response>();\n    const request = context.getRequest<Request>();\n    const { url } = request;\n    const { name } = exception;\n    const errorResponse = {\n      path: url,\n      timestamp: new Date().toISOString(),\n      message: name,\n    };\n\n    response.status(HttpStatus.BAD_REQUEST).json(errorResponse);\n  }\n}\n```\n\n```js\n@Catch(TypeORMError)\nexport class EntityNotFoundExceptionFilter implements ExceptionFilter {\n  catch(exception: MongoError, host: ArgumentsHost) {\n    switch (exception.code) {\n      case some error code:\n        // handle error\n    }\n  }\n}\n```\n\n```text\nEntityNotFoundError\n```\n\n```text\n@Catch(QueryFailedError, EntityNotFoundError)\n```\n\n```text\n@Catch()\n```\n\n```text\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { QueryFailedError, EntityNotFoundError, CannotCreateEntityIdMapError } from 'typeorm';\nimport { GlobalResponseError } from './global.response.error';\n\n@Catch()\nexport class GlobalExceptionFilter implements ExceptionFilter {\n    catch(exception: unknown, host: ArgumentsHost) {\n        const ctx = host.switchToHttp();\n        const response = ctx.getResponse<Response>();\n        const request = ctx.getRequest<Request>();\n        let message = (exception as any).message.message;\n        let code = 'HttpException';\n\n        Logger.error(message, (exception as any).stack, `${request.method} ${request.url}`);\n\n        let status = HttpStatus.INTERNAL_SERVER_ERROR;\n        \n        switch (exception.constructor) {\n            case HttpException:\n                status = (exception as HttpException).getStatus();\n                break;\n            case QueryFailedError:  // this is a TypeOrm error\n                status = HttpStatus.UNPROCESSABLE_ENTITY\n                message = (exception as QueryFailedError).message;\n                code = (exception as any).code;\n                break;\n            case EntityNotFoundError:  // this is another TypeOrm error\n                status = HttpStatus.UNPROCESSABLE_ENTITY\n                message = (exception as EntityNotFoundError).message;\n                code = (exception as any).code;\n                break;\n            case CannotCreateEntityIdMapError: // and another\n                status = HttpStatus.UNPROCESSABLE_ENTITY\n                message = (exception as CannotCreateEntityIdMapError).message;\n                code = (exception as any).code;\n                break;\n            default:\n                status = HttpStatus.INTERNAL_SERVER_ERROR\n        }\n\n        response.status(status).json(GlobalResponseError(status, message, code, request));\n    }\n}\n\n\nimport { Request } from 'express';\nimport { IResponseError } from './response.error.interface';\n\nexport const GlobalResponseError: (statusCode: number, message: string, code: string, request: Request) => IResponseError = (\n    statusCode: number,\n    message: string,\n    code: string,\n    request: Request\n): IResponseError => {\n    return {\n        statusCode: statusCode,\n        message,\n        code,\n        timestamp: new Date().toISOString(),\n        path: request.url,\n        method: request.method\n    };\n};\n\n\nexport interface IResponseError {\n    statusCode: number;\n    message: string;\n    code: string;\n    timestamp: string;\n    path: string;\n    method: string;\n}\n```\n\n```text\nimport { QueryFailedError } from 'typeorm';\nimport { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';\nimport { CannotCreateEntityIdMapError } from 'typeorm/error/CannotCreateEntityIdMapError';\n```\n\n```text\ntypeorm\n```\n\n```text\nEntityNotFoundError\n```\n\n```text\nCannotCreateEntityIdMapError\n```\n\n```js\nimport { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';\nimport { TypeORMError } from 'typeorm';\nimport { ErrorMessage } from '../error.interface';\n\n@Catch(TypeORMError)\nexport class TypeOrmFilter implements ExceptionFilter {\n    catch(exception: TypeORMError, host: ArgumentsHost) {\n        const response = host.switchToHttp().getResponse();\n        let message: string = (exception as TypeORMError).message;\n        let code: number = (exception as any).code;\n        const customResponse: ErrorMessage = {\n            status: 500,\n            message: 'Something Went Wrong',\n            type: 'Internal Server Error',\n            errors: [{ code: code, message: message }],\n            errorCode: 300,\n            timestamp: new Date().toISOString(),\n        };\n\n        response.status(customResponse.status).json(customResponse);\n    }\n}\n```\n\n```text\n@Catch(TypeORMError)\nexport class EntityNotFoundExceptionFilter implements ExceptionFilter {\n  catch(exception: TypeORMError, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n    let status = exception.getStatus();\n    let message = '';\n    switch (instanceof exception) {\n      case InitializedRelationError:\n        // handle error like\n        staus = 1;\n        message = '2';\n        break;\n      case AlreadyHasActiveConnectionError:\n        // handle other error\n        break;\n      ...\n        // ATTENTION other exception classes from node_modules/typeorm/errors \n      ...\n      default:\n        // handle it like internal server error\n        status = 500;\n        message = 'Database exception';\n    }\n    \n    response\n      .status(status)\n      .json({\n        statusCode: status,\n        timestamp: new Date().toISOString(),\n        path: request.url,\n      });\n  }\n}\n```\n\n========================================\n\nComments:\n- Thanks for the response. So how am I supposed to handle different exceptions? What would be the first parameter in catch() method?\n- @JeffMinsungKim As they all extend `Error` the type can either be `Error` or an explicit list of the types `QueryFailedError | EntityNotFoundError`. If you have code specific to certain errors, you can guard this logic with `instanceof`.\n- Very useful answer! However, I'm wondering if it is secure to return the database exception to the user. Isn't it bad if potential attackers can obtain table names, foreign keys, etc. by purposely throwing exceptions?\n- How can I use it in my code?\n- Great! Useful answer.\n- Please provide more details on your solution, not only code.\n- Please , how and where to use this implementation. an answer like this doesn't do any good","metadata":{"transformedAt":"2026-08-18T18:33:02.413Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":352,"estimatedTokens":2783}}137{"id":"stack-58714466","source":"stackoverflow","questionId":58714466,"title":"In NestJS is there any way to pass data from Guards to the controller?","tags":["javascript","express","nestjs","fastify"],"text":"Title: In NestJS is there any way to pass data from Guards to the controller?\nTags: javascript, express, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nSo I am currently using NestJS extensively in my organization. And for authentication purposes we are using our own guards. So my question is that can anyone please guide me if there any way to pass data from guard to the controller, other than `response.locals` of expressjs? This is creating an hard dependency on the framework and I don't want that at this moment.\n\nTIA.\n\n========================================\n\nTop Answer:\nThe only ways possible to pass data from a Guard to a Controller is to either attach the data to a field on the request or to use some sort of metadata reflection, which may become more challenging than it is worth. \n\nIn your guard you could have a `canActivate` function like\n\n```\ncanActivate(context: ExecutionContext): boolean | Promise | Observable {\n const req = context.switchToHttp().getRequest();\n if (/* some logic with req */) {\n req.myData = 'some custom value';\n }\n return true;\n}\n```\n\nAnd in your controller you could then pull `req.myData` and get the `some custom value` string back.\n\n========================================\n\nCode:\n```text\nresponse.locals\n```\n\n```text\nexport const Authorization = createParamDecorator((_, request: any) => {\n  const { authorization: accessToken } = request.headers;\n  try {\n    const decoded = jwt.verify(accessToken, process.env.JWT_HASH);\n    return pick(decoded, 'userId');\n  } catch (ex) {\n    throw new InvalidToken();\n  }\n});\n\nexport interface AuthUser {\n  userId: string;\n}\n```\n\n```text\n@Post()\n  createFeedback(\n    @Body() body: FeedbackBody,\n    @Authorization() user: AuthUser,\n  ): Promise<Feedback> {\n    body.userId = user.userId;\n    return this.feedbackService.feedback(body, user);\n  }\n```\n\n```text\ncanActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {\n  const req = context.switchToHttp().getRequest();\n  if (/* some logic with req */) {\n    req.myData = 'some custom value';\n  }\n  return true;\n}\n```\n\n```text\ncanActivate\n```\n\n```text\nreq.myData\n```\n\n```text\nsome custom value\n```\n\n```js\n// profile.controller.ts\nimport { Controller, Get } from '@nestjs/common';\nimport { AuthenticationToken } from 'src/authentication/authentication.decorator';\nimport { UserEntity } from 'src/users/users.entity';\nimport { UserFromTokenPipe } from 'src/users/users.pipe';\n\n@Controller('profile')\nexport class ProfileController {\n  @Get()\n  public getProfile(@AuthenticationToken(UserFromTokenPipe) user: UserEntity) {\n    const { email, firstname, lastname } = user;\n\n    return {\n      email,\n      firstname,\n      lastname\n    }\n  }\n}\n```\n\n```js\n// authentication.decorator.ts\nimport { createParamDecorator, ExecutionContext, UnauthorizedException } from '@nestjs/common';\nimport { Request } from 'express';\n\nexport const AuthenticationToken = createParamDecorator((_data: unknown, context: ExecutionContext) => {\n  const request = context.switchToHttp().getRequest<Request>();\n\n  const authorizationToken = request.headers.authorization;\n\n  if (!authorizationToken) {\n    throw new UnauthorizedException(\"Missing authorization token\");\n  }\n\n  const [bearer, token] = authorizationToken.split(' ');\n\n  if (bearer !== 'Bearer') {\n    throw new UnauthorizedException(\"Invalid authorization token type\");\n  }\n\n  return token;\n});\n```\n\n```js\n// users.pipe.ts\nimport { ArgumentMetadata, Injectable, PipeTransform, UnauthorizedException } from '@nestjs/common';\nimport { JwtService } from '@nestjs/jwt';\nimport { UserRole } from './users.enum';\nimport { UsersService } from './users.service';\n\n@Injectable()\nexport class UserFromTokenPipe implements PipeTransform {\n  public constructor(\n    private readonly jsonWebTokenService: JwtService,\n    private readonly usersService: UsersService\n  ) { }\n\n  public async transform(token: string, _metadata: ArgumentMetadata) {\n    try {\n      const payload = this.jsonWebTokenService.verify(token);\n\n      const user = await this.usersService.findOneById(payload.id);\n\n      if (!user) {\n        throw new UnauthorizedException(\"Invalid user\");\n      }\n\n      return user;\n    } catch (error) {\n      if (error instanceof UnauthorizedException) {\n        throw error;\n      }\n\n      throw new UnauthorizedException(\"Token\");\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- Hi Jay, Thanks for your answer. This works but is a workaround and `response.locals` is kinda same and this thing is not elegant and definitely not readable.\n- What data are you trying to pass from the guard to the controller?\n- The way Passport does it (from a middleware, not a guard, but same idea) is to attach it to `req.user`. Other than that, or possibly trying to get some clever/tricky reflect-metadata setup going on, there isn't another way. The guard is there to return true or false (or an async variant of it) so that the system knows whether or not to continue the request or return an error code.\n- > And in your controller you could then pull `req.myData`... And how exactly would that look in the controller?\n- Either make a custom decorator, or in the handler have `@Req() req` and then `req.myData`\n- For me, passing an argument to the guard is quite useful to validate a joi schema without using the class way. I'm used to that with type-graphql, but seems like it's not a thing in nestjs.\n- @OmarDulaimi I'm not sure what you mean. You can use a mixin to pass an object to the guard class without needing to use reflection or something like `class-validator`. This way you could also still use DI for the guard and it's dependencies\n- Additionally, you can create a custom decorator to ease the process of accessing the req.myData object.\n- So basically it just to transport the `userId` via the `body` itself. So that means there most be @Body on event function that would need this form of Authoriztion.\n- @Vixson the `userId` is not transported via the `body`. Instead, it is injected using a decorator.","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":179,"estimatedTokens":1510}}138{"id":"stack-62299932","source":"stackoverflow","questionId":62299932,"title":"how to get user data with req.user on decorator in nest js","tags":["nestjs","nestjs-passport"],"text":"Title: how to get user data with req.user on decorator in nest js\nTags: nestjs, nestjs-passport\nSource: Stack Overflow\n\nQuestion:\nI created the authentication ( jwt ) and the process is done properly.\n\nI can access the user's information using the following code, but I can't get the user's information using the decorator!\n\ncontroller : \n\n```\n@Post('/me/info')\n @UseGuards(AuthGuard())\n myInfo(\n @GetUser() user,\n @Req() req,\n ) {\n console.log(user); // undefined \n console.log(req.user); // get user data object\n }\n```\n\nmy decorator is:\n\n```\nimport { createParamDecorator } from '@nestjs/common';\nimport { User } from './user.entity';\n\nexport const GetUser = createParamDecorator((data, req): User => {\n return req.user;\n});\n```\n\nwhat is my code problem ?\n\n========================================\n\nTop Answer:\nHi I was working with Typescript and graphql so the above solution didn't work for me. Perhaps you should see this solution.\n\nNestJS custom decorator returns undefined\n\n========================================\n\nCode:\n```text\n@Post('/me/info')\n  @UseGuards(AuthGuard())\n  myInfo(\n    @GetUser() user,\n    @Req() req,\n  ) {\n    console.log(user); // undefined \n    console.log(req.user); // get user data object\n  }\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\nimport { User } from './user.entity';\n\nexport const GetUser = createParamDecorator((data, req): User => {\n  return req.user;\n});\n```\n\n```ts\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return request.user;\n  },\n);\n```\n\n```text\ncreateParamDecorator\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":81,"estimatedTokens":430}}139{"id":"stack-66117005","source":"stackoverflow","questionId":66117005,"title":"TypeORM - left joining without \"deletedAt IS NULL\"","tags":["nestjs","typeorm"],"text":"Title: TypeORM - left joining without \"deletedAt IS NULL\"\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nBeen searching this one for a while now, not sure if this is something unorthodox in the SQL world but I am trying to do a left join that counts with not null \"deletedAt\" column, but I cannot seem to find a way to do a left join which includes deletes.\n\nThis is just a dummy example that illustrates what I am trying to do, in this case I want to retrieve the person's information as well as the job's, but the job has been soft-deleted.\n\n```\nthis.createQueryBuilder('person')\n .leftJoinAndSelect('person.job', 'job')\n```\n\nThe SQL query produced by this implicitly adds \"IS NOT NULL\" on the **left join** but I have this scenario in which I need the information from a record that is indeed deleted.\n\nI haven't been able to find a way to include this as you would do it at the root level by including.\n\n```\n.withDeleted();\n```\n\nAnyone has any tips?\n\n========================================\n\nCode:\n```text\nthis.createQueryBuilder('person')\n  .leftJoinAndSelect('person.job', 'job')\n```\n\n```text\n.withDeleted();\n```\n\n```text\n// Normal case: Exclude both soft-deleted 'Person' and 'Job':\n        this.createQueryBuilder(\"Person\")\n        .leftJoinAndSelect('Person.job', 'Job');\n\n// 'withDeleted() after the join: Include soft-deleted 'Person' BUT EXCLUDE soft-deleted 'Job':\n        this.createQueryBuilder(\"Person\")\n        .leftJoinAndSelect('Person.job', 'Job')\n        .withDeleted();\n\n// 'withDeleted() before the join: Include both soft-deleted 'Person' and 'Job':\n        this.createQueryBuilder(\"Person\")\n        .withDeleted()\n        .leftJoinAndSelect('Person.job', 'Job');\n```\n\n```text\n// 'withDeleted() before the join with extra condition: Exclude soft-deleted 'Person' BUT INCLUDE soft-deleted 'Job':\n        this.createQueryBuilder(\"Person\")\n        .withDeleted()\n        .andWhere(\"Person.deletedAt Is Null\")\n        .leftJoinAndSelect('Person.job', 'Job');\n```\n\n```text\n.withDeleted()\n```\n\n```text\n.leftJoinAndSelect()\n```\n\n```text\n\"Person.deletedAt IS NULL\"\n```\n\n========================================\n\nComments:\n- Try using the .getRaw methods or this.repository.manager.createQueryBuilder() with the second method you have to specify the from clause and the selected fields.\n- Hello there @Edward, thanks for the reply. I am using TypeORM 0.2.31 which appears to be the version of that thread you've linked! As per the logging, which I was luckily already using, the query always prints ' AND \"job\".\"deletedAt\" IS NULL'. I am querying using getMany: this.createQueryBuilder('person').leftJoinAndSelect('person.&zwnj;&#8203;job', 'job').getMany(); I am using postgres. I've noticed the change github.com/typeorm/typeorm/commit/&hellip; could it be metadata?\n- Hello again @FPJ: I was completely wrong: It DOES add' AND \"job\".\"deletedAt\" IS NULL' , as you said. It seems bad behaviour to me, not what I expected, and I missed it when I tested - I guess I saw what I wanted to see! Same behaviour for both TypeORM 0.2.30 and 0.2.31. I'm going to edit my answer to suggest a workaround.\n- Hey again @Edward. Completely fine, the behaviour appears to be something new if I am not mistaken. This workaround unfortunately does not work. The withDeleted is applied to \"Person\" and I actually wanted it to be added to \"Job\". The only work around I've found so far is to make a RAW query (since my actual query is pretty big), which defeats completely the purpose of TypeORM :( I just don't understand why I can't find an option to simply shut down the implicit condition applied by the left join...\n- Hi again @FPJ : I changed my answer again - The generated query seems to depend on where you place .withDeleted(). I hope you use my final idea to make it work for you.\n- I believe I missed my tests with the withDeleted positioning. I've resorted to reverting back to 0.2.30 since I am close to a release and wanted everything stable, but I do whole heartedly appreciate your explanation as I'll be taking this to my next update. Not sure of why such a big change on their end but I'm sure it'll make sense. Big thank you for the effort, you've been quite helpful!","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":1049}}140{"id":"stack-56826709","source":"stackoverflow","questionId":56826709,"title":"How can I make sure at least one field is not empty? (Itโ€™s OK if only one is not empty.)","tags":["node.js","nestjs","class-validator"],"text":"Title: How can I make sure at least one field is not empty? (Itโ€™s OK if only one is not empty.)\nTags: node.js, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm writing a registration endpoint for an API I'm working on and I'm using NestJS and class-validator to validate the input data.\n\nThe user can register using either their phone number or email address or both. So to validate the input, I should make sure that at least one of them is provided. But I'm having a hard time figuring out how to do it without making a mess.\n\nThis is my DTO:\n\n```\nexport class register {\n @ApiModelProperty()\n @IsNotEmpty()\n @IsAlpha()\n firstName: string\n\n @ApiModelProperty()\n @IsNotEmpty()\n @IsAlpha()\n lastName: string\n\n @ApiModelProperty()\n @ValidateIf(o => o.email == undefined)\n @IsNotEmpty()\n @isIRMobile()\n phone: string\n\n @ApiModelProperty()\n @ValidateIf(o => o.phone == undefined)\n @IsNotEmpty()\n @IsEmail()\n email: string\n\n @ApiModelProperty()\n @IsNotEmpty()\n password: string\n}\n```\n\nAs you can see, I've used conditional validation which works for the cases that only one of phone number or email address is provided. But the problem is that when both are provided, one of them won't be validated, and an invalid value will be allowed.\n\nAny suggestions?\n\n========================================\n\nTop Answer:\nI think you just need to add\n\n```\n@ValidateIf(o => o.email == undefined || o.phone)\nphone: string\n```\n\nand\n\n```\n@ValidateIf(o => o.phone == undefined || o.email)\nemail: string\n```\n\nI'd suggest validating like this:\n\n```\n@ValidateIf(o => !o.email || o.phone)\nphone: string\n\n@ValidateIf(o => !o.phone || o.email)\nemail: string\n```\n\nto properly handle *null*, *0* and *\"\"* (empty string).\n\nOtherwise, this will be correct as well (it shouldn't be):\n\n```\nconst data = new register();\ndata.phone = '';\ndata.email = '';\n```\n\n========================================\n\nCode:\n```js\nexport class register {\n  @ApiModelProperty()\n  @IsNotEmpty()\n  @IsAlpha()\n  firstName: string\n\n  @ApiModelProperty()\n  @IsNotEmpty()\n  @IsAlpha()\n  lastName: string\n\n  @ApiModelProperty()\n  @ValidateIf(o => o.email == undefined)\n  @IsNotEmpty()\n  @isIRMobile()\n  phone: string\n\n  @ApiModelProperty()\n  @ValidateIf(o => o.phone == undefined)\n  @IsNotEmpty()\n  @IsEmail()\n  email: string\n\n  @ApiModelProperty()\n  @IsNotEmpty()\n  password: string\n}\n```\n\n```js\nexport function AnyOf(properties: string[]) {\n  return function (target: any) {\n    for (const property of properties) {\n      const otherProps = properties.filter(prop => prop !== property);\n      const decorators = [\n        // Validates if all other properties are undefined.\n        ValidateIf((obj: any) =>\n          obj[property] !== undefined || otherProps.reduce(\n            (acc, prop) => acc && obj[prop] === undefined,\n            true,\n          ),\n        ),\n      ];\n\n      for (const decorator of decorators) {\n        applyDecorators(decorator)(target.prototype, property);\n      }\n    }\n  };\n}\n\n@AnyOf(['email', 'phone'])\nclass CreateUserDto {\n  @IsString()\n  email: string\n\n  @IsString()\n  phone: string\n}\n```\n\n```text\n@ValidateIf(o => o.email == undefined || o.phone)\nphone: string\n```\n\n```text\n@ValidateIf(o => o.phone == undefined || o.email)\nemail: string\n```\n\n```text\n@ValidateIf(o => !o.email || o.phone)\nphone: string\n\n@ValidateIf(o => !o.phone || o.email)\nemail: string\n```\n\n```text\nconst data = new register();\ndata.phone = '';\ndata.email = '';\n```\n\n```text\nimport { IsNotEmpty, IsNumber, ValidateIf, Length } from 'class-validator';\n\nexport class ProposalBody {\n  @ValidateIf((req) => !req.proposalNo || req.mobileNumber)\n  @IsNotEmpty()\n  @IsNumber()\n  @Length(10, 10, { message: \"Invalid Mobile Number. It should be a 10-digit number.\" })\n  mobileNumber: number;\n\n  @ValidateIf((req) => !req.mobileNumber || req.proposalNo)\n  @IsNotEmpty()\n  @IsNumber()\n  proposalNo: number;\n}\n```\n\n```text\nimport {\n  registerDecorator,\n  ValidationOptions,\n  ValidationArguments,\n  ValidatorConstraint,\n  ValidatorConstraintInterface,\n} from 'class-validator'\n\n/**\n * Validator constraint that checks if at least one of the specified fields is provided\n */\n@ValidatorConstraint({ name: 'atLeastOneOf', async: false })\nexport class AtLeastOneOfConstraint implements ValidatorConstraintInterface {\n  validate(value: any, args: ValidationArguments): boolean {\n    const [fields] = args.constraints\n    const object = args.object as any\n\n    // Check if at least one field is provided and non-empty\n    return fields.some((field: string) => {\n      const fieldValue = object[field]\n      return fieldValue !== undefined && fieldValue !== null && fieldValue !== ''\n    })\n  }\n\n  defaultMessage(args: ValidationArguments): string {\n    const [fields] = args.constraints\n    return `At least one of the following fields must be provided: ${fields.join(', ')}`\n  }\n}\n\n/**\n * Decorator that validates at least one of the specified fields is provided\n *\n * @param fields Array of field names to check\n * @param validationOptions Optional validation options\n *\n * @example\n * ```typescript\n * class ShareDto {\n *   @AtLeastOneOf(['email', 'userId'])\n *   email?: string;\n *\n *   @AtLeastOneOf(['email', 'userId'])\n *   userId?: string;\n * }\n * ```\n */\nexport function AtLeastOneOf(fields: string[], validationOptions?: ValidationOptions) {\n  return function (object: Object, propertyName: string) {\n    registerDecorator({\n      target: object.constructor,\n      propertyName: propertyName,\n      options: validationOptions,\n      constraints: [fields],\n      validator: AtLeastOneOfConstraint,\n    })\n  }\n}\n```\n\n========================================\n\nComments:\n- You can see this feat request too: github.com/typestack/class-validator/issues/1581\n- Thanks. From this approach i have implemented a working solution for me\n- JFI: Do not annotate the optional fields with `@IsOptional()`. Actually if you add it to the `email` and `phone`.","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":255,"estimatedTokens":1474}}141{"id":"stack-55717089","source":"stackoverflow","questionId":55717089,"title":"Test NestJS Service against Actual Database","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Test NestJS Service against Actual Database\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to be able to test my Nest service against an actual database. I understand that most unit tests should use a mock object, but it also, at times, makes sense to test against the database itself.\n\nI have searched through SO and the GH issues for Nest, and am starting to reach the transitive closure of all answers. :-)\n\nI am trying to work from https://github.com/nestjs/nest/issues/363#issuecomment-360105413. Following is my Unit test, which uses a custom provider to pass the repository to my service class.\n\n```\ndescribe(\"DepartmentService\", () => {\n const token = getRepositoryToken(Department);\n let service: DepartmentService;\n let repo: Repository;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n DepartmentService,\n {\n provide: token,\n useClass: Repository\n }\n ]\n }).compile();\n\n service = module.get(DepartmentService);\n repo = module.get(token);\n });\n```\n\nEverything compiles properly, TypeScript seems happy. However, when I try to execute `create` or `save` on **my** `Repository` instance, the underlying `Repository` appears to be undefined. Here's the stack backtrace:\n\n```\nTypeError: Cannot read property 'create' of undefined\n\n at Repository.Object..Repository.create (repository/Repository.ts:99:29)\n at DepartmentService. (relational/department/department.service.ts:46:53)\n at relational/department/department.service.ts:19:71\n at Object..__awaiter (relational/department/department.service.ts:15:12)\n at DepartmentService.addDepartment (relational/department/department.service.ts:56:16)\n at Object. (relational/department/test/department.service.spec.ts:46:35)\n at relational/department/test/department.service.spec.ts:7:71\n```\n\nIt appears that the `EntityManager` instance with the TypeORM `Repository` class is not being initialized; it is the `undefined` reference that this backtrace is complaining about. \n\nHow do I get the `Repository` and `EntityManager` to initialize properly?\n\nthanks,\ntom.\n\n========================================\n\nTop Answer:\nI prefer not using `@nestjs/testing` for the sake of simplicity.\n\nFirst of all, create a reusable helper:\n\n```\n/* src/utils/testing-helpers/createMemDB.js */\nimport { createConnection, EntitySchema } from 'typeorm'\ntype Entity = Function | string | EntitySchema\n\nexport async function createMemDB(entities: Entity[]) {\n return createConnection({\n // name, // let TypeORM manage the connections\n type: 'sqlite',\n database: ':memory:',\n entities,\n dropSchema: true,\n synchronize: true,\n logging: false\n })\n}\n```\n\nThen, write test:\n\n```\n/* src/user/user.service.spec.ts */\nimport { Connection, Repository } from 'typeorm'\nimport { createMemDB } from '../utils/testing-helpers/createMemDB'\nimport UserService from './user.service'\nimport User from './user.entity'\n\ndescribe('User Service', () => {\n let db: Connection\n let userService: UserService\n let userRepository: Repository\n\n beforeAll(async () => {\n db = await createMemDB([User])\n userRepository = await db.getRepository(User)\n userService = new UserService(userRepository) // db.close())\n\n it('should create a new user', async () => {\n const username = 'HelloWorld'\n const password = 'password'\n\n const newUser = await userService.createUser({ username, password })\n expect(newUser.id).toBeDefined()\n\n const newUserInDB = await userRepository.findOne(newUser.id)\n expect(newUserInDB.username).toBe(username)\n })\n})\n```\n\nRefer to https://github.com/typeorm/typeorm/issues/1267#issuecomment-483775861\n\n========================================\n\nCode:\n```js\ndescribe(\"DepartmentService\", () => {\n  const token = getRepositoryToken(Department);\n  let service: DepartmentService;\n  let repo: Repository<Department>;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        DepartmentService,\n        {\n          provide: token,\n          useClass: Repository\n        }\n      ]\n    }).compile();\n\n    service = module.get<DepartmentService>(DepartmentService);\n    repo = module.get(token);\n  });\n```\n\n```text\nTypeError: Cannot read property 'create' of undefined\n\n  at Repository.Object.<anonymous>.Repository.create (repository/Repository.ts:99:29)\n  at DepartmentService.<anonymous> (relational/department/department.service.ts:46:53)\n  at relational/department/department.service.ts:19:71\n  at Object.<anonymous>.__awaiter (relational/department/department.service.ts:15:12)\n  at DepartmentService.addDepartment (relational/department/department.service.ts:56:16)\n  at Object.<anonymous> (relational/department/test/department.service.spec.ts:46:35)\n  at relational/department/test/department.service.spec.ts:7:71\n```\n\n```text\ncreate\n```\n\n```text\nsave\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```text\nRepository\n```\n\n```text\nundefined\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```text\nTest.createTestingModule({\n  imports: [\n   TypeOrmModule.forRoot({\n        type: 'mysql',\n        // ...\n   }),\n   TypeOrmModule.forFeature([Department])\n  ]\n```\n\n```text\nTypeOrmModule\n```\n\n```js\ndescribe(\"DepartmentService\", () => {\n  let service: DepartmentService;\n  let repo: Repository<Department>;\n  let module: TestingModule;\n\n  beforeAll(async () => {\n    module = await Test.createTestingModule({\n      imports: [\n        TypeOrmModule.forRoot(),\n        TypeOrmModule.forFeature([Department])\n      ],\n      providers: [DepartmentService]\n    }).compile();\n\n    service = module.get<DepartmentService>(DepartmentService);\n    repo = module.get<Repository<Department>>(getRepositoryToken(Department));\n  });\n\n  afterAll(async () => {\n    module.close();\n  });\n\n  it(\"should be defined\", () => {\n    expect(service).toBeDefined();\n  });\n\n  // ...\n}\n```\n\n```js\n/* src/utils/testing-helpers/createMemDB.js */\nimport { createConnection, EntitySchema } from 'typeorm'\ntype Entity = Function | string | EntitySchema<any>\n\nexport async function createMemDB(entities: Entity[]) {\n  return createConnection({\n    // name, // let TypeORM manage the connections\n    type: 'sqlite',\n    database: ':memory:',\n    entities,\n    dropSchema: true,\n    synchronize: true,\n    logging: false\n  })\n}\n```\n\n```text\n/* src/user/user.service.spec.ts */\nimport { Connection, Repository } from 'typeorm'\nimport { createMemDB } from '../utils/testing-helpers/createMemDB'\nimport UserService from './user.service'\nimport User from './user.entity'\n\ndescribe('User Service', () => {\n  let db: Connection\n  let userService: UserService\n  let userRepository: Repository<User>\n\n  beforeAll(async () => {\n    db = await createMemDB([User])\n    userRepository = await db.getRepository(User)\n    userService = new UserService(userRepository) // <--- manually inject\n  })\n  afterAll(() => db.close())\n\n  it('should create a new user', async () => {\n    const username = 'HelloWorld'\n    const password = 'password'\n\n    const newUser = await userService.createUser({ username, password })\n    expect(newUser.id).toBeDefined()\n\n    const newUserInDB = await userRepository.findOne(newUser.id)\n    expect(newUserInDB.username).toBe(username)\n  })\n})\n```\n\n```text\n@nestjs/testing\n```\n\n```js\n// ../test/db.ts\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport { EntitySchema } from 'typeorm';\n\ntype Entity = Function | string | EntitySchema<any>;\n\nexport const createTestConfiguration = (\n  entities: Entity[],\n): TypeOrmModuleOptions => ({\n  type: 'sqlite',\n  database: ':memory:',\n  entities,\n  dropSchema: true,\n  synchronize: true,\n  logging: false,\n});\n```\n\n```js\n// books.service.test.ts\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { HttpModule, HttpService } from '@nestjs/common';\nimport { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { BooksService } from './books.service';\nimport { Book } from './book.entity';\nimport { createTestConfiguration } from '../../test/db';\n\ndescribe('BooksService', () => {\n  let module: TestingModule;\n  let service: BooksService;\n  let httpService: HttpService;\n  let repository: Repository<Book>;\n\n  beforeAll(async () => {\n    module = await Test.createTestingModule({\n      imports: [\n        HttpModule,\n        TypeOrmModule.forRoot(createTestConfiguration([Book])),\n        TypeOrmModule.forFeature([Book]),\n      ],\n      providers: [BooksService],\n    }).compile();\n\n    httpService = module.get<HttpService>(HttpService);\n    service = module.get<BooksService>(BooksService);\n    repository = module.get<Repository<Book>>(getRepositoryToken(Book));\n  });\n\n  afterAll(() => {\n    module.close();\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n```\n\n```text\nlet service: SampleService;\n  let connection: Connection;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports: [AppModule, TypeOrmModule.forFeature([SampleEntity])],\n      providers: [SampleService],\n    }).compile();\n\n    service = module.get<SampleService>(SampleService);\n    connection = await module.get(getConnectionToken());\n  });\n\n  afterEach(async () => {\n    await connection.close();\n  });\n```\n\n```text\nAppModule\n```\n\n```text\nimport { INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from '../../../app.module';\nimport { AuthService } from '../auth.service';\nimport { UserRepo } from '../../user/user.repo';\n\ndescribe('AuthService', () => {\n    let app: INestApplication;\n    let service: AuthService;\n    let repo: UserRepo;\n\n    beforeAll(async () => {\n        app = await NestFactory.create(AppModule);\n        service = app.get(AuthService);\n\n        repo = app.get(UserRepo); // or with private access service['userRepo'];\n    });\n\n    afterAll(async () => {\n        await app.close();\n    });\n\n    it('AuthService should be defined', () => {\n        expect(service).toBeDefined();\n    });\n\n    describe('login', () => {\n        it('should login user', async () => {\n            const user = await service.login({ email: 'user@gmail.com', password: '12345678' });\n\n            expect(user.id).toBeDefined();\n        });\n    });\n\n    describe('userRepo', () => {\n        it('should find user without errors', async () => {\n            const user = await repo.findBy({ email: 'user@gmail.com' });\n\n            expect(user).toBeDefined();\n        });\n\n        it('should throw not found exception', async () => {    \n            await expect(repo.findBy({ email: 'not_found_user@gmail.com' })).rejects.toThrow();\n        });\n    });\n});\n```\n\n```text\nimport { config as testConfig } from 'dotenv';\n\nif (process.env.NODE_ENV === 'test') {\n    testConfig({ path: resolve('./.test.env') });\n}\n```\n\n========================================\n\nComments:\n- That is a huge step in the right direction! It appears that this causes a new database connection to be created each time the code runs. Is that correct? If so, is the right way to close the connection to run `module.close()`? Do you recommend setting up the module in a `beforeAll` or a `beforeEach`?\n- Yep, it's important that you close the connection. Otherwise your test will not exit and you have to force close jest. beforeAll/afterAll sound reasonable, you can also pass `KEEP_CONNECTION_ALIVE: true` to typeorm to reuse the connection.\n- It seems not working with a custom repository. Any ideas @KimKern?\n- @JeffMinsungKim I'd assume you have to set up your test the same way you set up your database in the real application (i.e. imports). If you need more support, better open a new question so that you can post your setup (app + test that doesn't work)\n- @JeffMinsungKim in my case the `forFeature` included the custom repositories. As Kime said, use the same tht you uses in your module. In my case: `imports: [TypeOrmModule.forRoot(TypeOrmConfig), TypeOrmModule.forFeature([UserRepository, MessageRepository])],`\n- Can you add how `user.service` is defined?\n- Is this working for e2e testing, I mean when I use superset, and call the endpoint. Does this work as expected?","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":437,"estimatedTokens":3052}}142{"id":"stack-50864001","source":"stackoverflow","questionId":50864001,"title":"How to handle mongoose error with nestjs","tags":["typescript","nestjs"],"text":"Title: How to handle mongoose error with nestjs\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI followed the example from https://docs.nestjs.com/techniques/mongodb\n\nThe issue is when there is a mongoose validation error (e.g i have a schema with a required field and it isn't provided):\n\nFrom games.service.ts:\n\n```\nasync create(createGameDto: CreateGameDto): Promise {\n const createdGame = new this.gameModel(createGameDto);\n return await createdGame.save();\n }\n```\n\nThe save() function returns a Promise.\n\nNow i have this in the game.controller.ts\n\n```\n@Post()\n async create(@Body() createGameDto: CreateGameDto) {\n this.gamesService.create(createGameDto);\n }\n```\n\nWhat is the best way to handle an error and then return a response with a different http status and maybe a json text?\nYou would usually throw a `HttpException` but from where? I can't do that if i handle the errors using .catch() in the promise.\n\n(Just started using the nestjs framework)\n\n========================================\n\nTop Answer:\nYou can use ***Error** in mongoose* and add it in *AllExceptionFilter*\n\nPlease refer to NestJS documentation for exception-filters\n\n```\nimport {\n ExceptionFilter,\n Catch,\n ArgumentsHost,\n HttpException,\n HttpStatus,\n InternalServerErrorException\n} from \"@nestjs/common\";\n\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n catch(exception: InternalServerErrorException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n\n const status =\n exception instanceof HttpException\n ? exception.getStatus()\n : HttpStatus.INTERNAL_SERVER_ERROR;\n\n /**\n * @description Exception json response\n * @param message\n */\n const responseMessage = (type, message) => {\n response.status(status).json({\n statusCode: status,\n path: request.url,\n errorType: type,\n errorMessage: message\n });\n };\n\n // Throw an exceptions for either\n // MongoError, ValidationError, TypeError, CastError and Error\n if (exception.message.error) {\n responseMessage(\"Error\", exception.message.error);\n } else {\n responseMessage(exception.name, exception.message);\n }\n }\n}\n```\n\nYou can add it in the main.ts like so but it really depends on your use case. You can check it in the Nest.js documentation.\n\n```\nasync function bootstrap() {\n\n const app = await NestFactory.create(AppModule);\n\n app.useGlobalFilters(new AllExceptionsFilter());\n\n await app.listen(3000);\n}\nbootstrap();\n```\n\nHope it helps.\n\n========================================\n\nCode:\n```text\nasync create(createGameDto: CreateGameDto): Promise<IGame> {\n    const createdGame = new this.gameModel(createGameDto);\n    return await createdGame.save();\n  }\n```\n\n```text\n@Post()\n  async create(@Body() createGameDto: CreateGameDto) {\n    this.gamesService.create(createGameDto);\n  }\n```\n\n```text\nHttpException\n```\n\n```text\nimport { ArgumentsHost, Catch, ConflictException, ExceptionFilter } from '@nestjs/common';\nimport { MongoError } from 'mongodb';\n\n@Catch(MongoError)\nexport class MongoExceptionFilter implements ExceptionFilter {\n  catch(exception: MongoError, host: ArgumentsHost) {\n    switch (exception.code) {\n      case 11000:\n        // duplicate exception\n        // do whatever you want here, for instance send error to client\n    }\n  }\n}\n```\n\n```text\nimport { MongoExceptionFilter } from '<path>/mongo-exception.filter';\n\n@Get()\n@UseFilters(MongoExceptionFilter)\nasync findAll(): Promise<User[]> {\n  return this.userService.findAll();\n}\n```\n\n```text\nreturn\n```\n\n```text\n@Catch\n```\n\n```text\nasync create(createGameDto: CreateGameDto): Promise<IGame> {\n    try {\n      const createdGame = new this.gameModel(createGameDto);\n      return await createdGame.save();\n    } catch (e) {\n       // the e here would be MongoError\n       throw new InternalServerException(e.message);\n    }\n  }\n```\n\n```text\nException Filters\n```\n\n```text\ntry/catch\n```\n\n```text\nasync getUser(id: string, validateUser ?: boolean): Promise<Users> {\n    try {\n      const user = await this.userModel.findById(id).exec();\n      if(!user && validateUser) {\n        throw new UnauthorizedException();\n      }else if(!user) {\n        throw new HttpException(`Not found this id: ${id}`, HttpStatus.NOT_FOUND)\n      }\n      return user;\n    } catch (err) {\n      throw new HttpException(`Callback getUser ${err.message}`, HttpStatus.BAD_REQUEST);\n    }\n```\n\n```text\nimport {\n  ExceptionFilter,\n  Catch,\n  ArgumentsHost,\n  HttpException,\n  HttpStatus,\n  InternalServerErrorException\n} from \"@nestjs/common\";\n\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n  catch(exception: InternalServerErrorException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse();\n    const request = ctx.getRequest();\n\n    const status =\n      exception instanceof HttpException\n        ? exception.getStatus()\n        : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    /**\n     * @description Exception json response\n     * @param message\n     */\n    const responseMessage = (type, message) => {\n      response.status(status).json({\n        statusCode: status,\n        path: request.url,\n        errorType: type,\n        errorMessage: message\n      });\n    };\n\n    // Throw an exceptions for either\n    // MongoError, ValidationError, TypeError, CastError and Error\n    if (exception.message.error) {\n      responseMessage(\"Error\", exception.message.error);\n    } else {\n      responseMessage(exception.name, exception.message);\n    }\n  }\n}\n```\n\n```text\nasync function bootstrap() {\n\n  const app = await NestFactory.create(AppModule);\n\n  app.useGlobalFilters(new AllExceptionsFilter());\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nimport { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from \"@nestjs/common\";\nimport { MongoError } from 'mongodb';\nimport { Response } from 'express';\n\n@Catch(MongoError)\nexport class MongoExceptionFilter implements ExceptionFilter {\n\n    catch(exception: MongoError, host: ArgumentsHost) {\n        switch (exception.code) {\n            case 11000:\n                const ctx = host.switchToHttp();\n                const response = ctx.getResponse<Response>();\n                response.statusCode = HttpStatus.FORBIDDEN;\n                response\n                    .json({\n                        statusCode: HttpStatus.FORBIDDEN,\n                        timestamp: new Date().toISOString(),\n                        message: 'You are already registered'\n                    });\n        }\n    }\n}\n```\n\n```text\n@UseFilters(MongoExceptionFilter)\n  @Post('signup')\n  @HttpCode(HttpStatus.OK)\n  async createUser(@Body() createUserDto: CreateUserDto) {\n    await this.userService.create(createUserDto);\n  }\n```\n\n```text\nimport { ArgumentsHost, Catch, RpcExceptionFilter } from '@nestjs/common';\nimport { Error } from 'mongoose';\nimport ValidationError = Error.ValidationError;\n\n@Catch(ValidationError)\nexport class ValidationErrorFilter implements RpcExceptionFilter {\n\n  catch(exception: ValidationError, host: ArgumentsHost): any {\n\n    const ctx = host.switchToHttp(),\n      response = ctx.getResponse();\n\n    return response.status(400).json({\n      statusCode: 400,\n      createdBy: 'ValidationErrorFilter',\n      errors: exception.errors,\n    });\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ValidationErrorFilter } from './validation-error.filter';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalFilters(new ValidationErrorFilter());\n  await app.listen(process.env.PORT || 3000);\n}\nbootstrap();\n```\n\n```text\n{\n  \"statusCode\": 400,\n  \"createdBy\": \"ValidationErrorFilter\",\n  \"errors\": {\n    \"dob\": {\n      \"properties\": {\n        \"message\": \"Path `dob` is required.\",\n        \"type\": \"required\",\n        \"path\": \"dob\"\n      },\n      \"kind\": \"required\",\n      \"path\": \"dob\"\n    },\n    \"password\": {\n      \"properties\": {\n        \"message\": \"Path `password` is required.\",\n        \"type\": \"required\",\n        \"path\": \"password\"\n      },\n      \"kind\": \"required\",\n      \"path\": \"password\"\n    }\n  }\n}\n```\n\n```text\nimport { ArgumentsHost, Catch, ExceptionFilter, RpcExceptionFilter } from '@nestjs/common';\nimport { Error } from 'mongoose';\nimport { IDTOError } from '../errors/bad-request-exception.error';\nimport ValidationError = Error.ValidationError;\nimport { MongoError } from 'mongodb';\n\n\n@Catch(MongoError)\nexport class MongoExceptionFilter implements ExceptionFilter {\n  catch(exception: MongoError, host: ArgumentsHost) {\n    // switch (exception.code) {\n    //   case 11000:\n    //   default: console.log(exception,'ALERT ERROR CATCHED');\n    //     // duplicate exception\n    //     // do whatever you want here, for instance send error to client\n\n\n    //     /** MAIGOD */\n    // }\n    const ctx = host.switchToHttp(),\n      response = ctx.getResponse();\n\n    return response.status(400).json(<IDTOError>{\n      statusCode: 400,\n      createdBy: 'ValidationErrorFilter, Schema or Model definition',\n      errors: exception,\n    });\n\n  }\n}\n\n@Catch(ValidationError)\nexport class ValidationErrorFilter implements RpcExceptionFilter {\n\n  catch(exception: ValidationError, host: ArgumentsHost): any {\n\n    const ctx = host.switchToHttp(),\n      response = ctx.getResponse();\n\n    return response.status(400).json(<IDTOError>{\n      statusCode: 400,\n      createdBy: 'ValidationErrorFilter, Schema or Model definition',\n      errors: exception.errors,\n    });\n  }\n}\n```\n\n```text\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';\n\nimport * as MongooseError from 'mongoose/lib/error'; // I couldn't see the error class is being exported from Mongoose\n\n@Catch(MongooseError)\nexport class MongoExceptionFilter implements ExceptionFilter {\n  catch(exception: MongooseError, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse();\n    // const request = ctx.getRequest();\n\n    let error;\n\n    switch (exception.name) {\n      case 'DocumentNotFoundError': {\n        error = {\n          statusCode: HttpStatus.NOT_FOUND,\n          message: \"Not Found\"\n        }\n        break;\n      }\n      // case 'MongooseError': { break; } // general Mongoose error\n      // case 'CastError': { break; }\n      // case 'DisconnectedError': { break; }\n      // case 'DivergentArrayError': { break; }\n      // case 'MissingSchemaError': { break; }\n      // case 'ValidatorError': { break; }\n      // case 'ValidationError': { break; }\n      // case 'ObjectExpectedError': { break; }\n      // case 'ObjectParameterError': { break; }\n      // case 'OverwriteModelError': { break; }\n      // case 'ParallelSaveError': { break; }\n      // case 'StrictModeError': { break; }\n      // case 'VersionError': { break; }\n      default: {\n        error = {\n          statusCode: HttpStatus.INTERNAL_SERVER_ERROR,\n          message: \"Internal Error\"\n        }\n        break;\n      }\n    }\n\n    response.status(error.statusCode).json(error);\n  }\n}\n```\n\n```text\nimport { MongoExceptionFilter } from './filters/mongo-exception.filter';\n\nasync function bootstrap() {\n  // .......\n\n  app.useGlobalFilters(new MongoExceptionFilter); // Use Mongo exception filter\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nimport {\n  ArgumentsHost,\n  Catch,\n  ExceptionFilter,\n  HttpException,\n  HttpStatus,\n  Inject,\n  LoggerService,\n} from '@nestjs/common';\nimport { Response } from 'express';\nimport { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';\n\n@Catch()\nexport class HttpExceptionFilter implements ExceptionFilter {\n  constructor(\n    @Inject(WINSTON_MODULE_NEST_PROVIDER)\n    private readonly logger: LoggerService,\n  ) {}\n  catch(exp: any, host: ArgumentsHost) {\n    console.log(exp);\n    this.logger.error(exp);\n    const context = host.switchToHttp();\n    const response = context.getResponse<Response>();\n    const request = context.getRequest<Request>();\n\n    const hasKey = Object.keys(exp).length > 0 && exp.hasOwnProperty('response') ? true : false;\n    const isHttpInstance = exp instanceof HttpException ? true : false;\n\n    const validErrors = hasKey && Array.isArray(exp.response.message) ? exp.response.message : [];\n    const statusCode = isHttpInstance ? exp.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;\n    const type = hasKey && exp.response.type ? exp.response.type : 'some_thing_went_error';\n    const message = isHttpInstance ? exp.message : 'Oops Something went wrong!';\n    const error = hasKey ? exp.response.error : exp;\n\n    response.status(statusCode).json({\n      message,\n      type,\n      validationErrors: validErrors,\n      statusCode,\n      error,\n      timestamp: new Date().toISOString(),\n      path: request.url,\n    });\n  }\n}\n```\n\n```text\n{\n    \"message\": \"Oops Something went wrong!\",\n    \"type\": \"some_thing_went_error\",\n    \"validationErrors\": [],\n    \"statusCode\": 500,\n    \"error\": {\n        \"errors\": {\n            \"subRegion\": {\n                \"name\": \"ValidatorError\",\n                \"message\": \"Path `subRegion` is required.\",\n                \"properties\": {\n                    \"message\": \"Path `subRegion` is required.\",\n                    \"type\": \"required\",\n                    \"path\": \"subRegion\"\n                },\n                \"kind\": \"required\",\n                \"path\": \"subRegion\"\n            }\n        },\n        \"_message\": \"ServiceRequest validation failed\",\n        \"name\": \"ValidationError\",\n        \"message\": \"ServiceRequest validation failed: subRegion: Path `subRegion` is required.\"\n    },\n    \"timestamp\": \"2022-02-08T07:43:35.962Z\",\n    \"path\": \"/v1/service-request\"\n}\n```\n\n```text\n{\n    \"message\": \"Bad Request Exception\",\n    \"type\": \"some_thing_went_error\",\n    \"validationErrors\": [\n        \"isEmergency must be one of the following values: true, false\",\n        \"isEmergency must be a string\",\n        \"isEmergency should not be empty\"\n    ],\n    \"statusCode\": 400,\n    \"error\": \"Bad Request\",\n    \"timestamp\": \"2022-02-08T07:47:25.183Z\",\n    \"path\": \"/v1/service-request\"\n}\n```\n\n```text\nthrow new HttpException(\n      {\n        status: HttpStatus.FORBIDDEN,\n        type: 'otp_verification_error',\n        message: 'Please verify your mobile number to complete the signUp process!',\n      },\n      HttpStatus.FORBIDDEN,\n    );\n```\n\n```text\nMongodb: 4.7.0\n```\n\n```text\nMongodb\n```\n\n```text\nMongoose\n```\n\n```text\n@Catch(MongoError)\n```\n\n```text\nmongodb\n```\n\n```text\nmongoose\n```\n\n========================================\n\nComments:\n- I still get UnhandledPromiseRejectionWarning: using the try catch block, it doesn't work.\n- Are you sure it goes in your โ€œcreateโ€ function?\n- github.com/nartc/nest-demo/blob/master/NestDemo.Server/src/u&zwnj;&#8203;ser/&hellip; look at my repo\n- For me this solution doesn't work. I have exactly the same setup except that the controller async method is a call to the service which does a .save() on the mongodb. The custom MongoExceptionFilter won't trigger. I guess `MongoError` doesn't get 'catched', because when I leave the Catch blank it does trigger... \"@nestjs/core\": \"^5.4.0\", \"@nestjs/mongoose\": \"^5.2.2\", \"mongoose\": \"^5.4.7\",\n- Note that the error must be from mongoose's mongodb dependency, which mnay differ from project's mongodb dependency. i.e. `import { MongoError, MongoServerError } from 'mongoose&#47;node_modules&#47;mongodb';` imports the right kind of error to catch for sure.\n- This is not the best way, to do it, as you are obliged to write try/catch blocks all over your application, which is not recommended when using Nestjs as it has its own exceptions system.\n- This works for me, I put this as a GlobalFilter main.ts: `app.useGlobalFilters(new MongoExceptionFilter());`\n- This worked, thank you! The `import { Error } from 'mongoose';` is what I was missing.\n- what about code 11000 duplicate error ?","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":598,"estimatedTokens":3954}}143{"id":"stack-63848877","source":"stackoverflow","questionId":63848877,"title":"Generating migration file for a project using NestJS and TypeORM","tags":["typescript","nestjs","typeorm"],"text":"Title: Generating migration file for a project using NestJS and TypeORM\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to generate migration files for my entities, but whenever I run the command to create the entity, it creates an \"empty\" file, just the up and down methods are created.\n\nI have added this script in my package.json file: `\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\"`.\n\nIn my app.module.ts, the connection is configured like this:\n\n```\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption],\n migrations: ['src/migration/*{.ts,.js}'],\n cli: {\n migrationsDir: 'src/migration'\n },\n synchronize: true,\n })\n```\n\nWhere `database()` it's a nestjs config file and get the values from an .env file.\n\nThe script I'm using to create the migration is: `npm run typeorm migration:create -- -n QuestionTables -d src/migrations` where need to specify the **-d**, otherwise the migration file is not created (even if it's specified in the cli of the forRoot method.\n\nDo I need to write manually the SQL to create the tables?\n\nWhat if I need to add a new column to an existing table, should I create a new migration file and write manually the SQL code to add that?\n\nAnother command that I tried to run was this one: `npm run typeorm migration:generate -- -n QuestionTables -d src/migrations` and here it gives me an error: \" Error: No connection options were found in any orm configuration files.\"\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRoot({\n      type: 'mysql',\n      host: database().host,\n      port: parseInt(database().port),\n      username: database().username,\n      password: database().password,\n      database: database().schema,\n      entities: [Question, QuestionOption],\n      migrations: ['src/migration/*{.ts,.js}'],\n      cli: {\n        migrationsDir: 'src/migration'\n      },\n      synchronize: true,\n    })\n```\n\n```text\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\"\n```\n\n```text\ndatabase()\n```\n\n```text\nnpm run typeorm migration:create -- -n QuestionTables -d src/migrations\n```\n\n```text\nnpm run typeorm migration:generate -- -n QuestionTables -d src/migrations\n```\n\n```text\n// ormconfig.ts\nexport const config: TypeOrmModuleOptions = {\n      type: 'mysql',\n      host: database().host,\n      port: parseInt(database().port),\n      username: database().username,\n      password: database().password,\n      database: database().schema,\n      entities: [Question, QuestionOption], // maybe you should also consider chage it to something like:  [__dirname + '/**/*.entity.ts', __dirname + '/src/**/*.entity.js']\n      migrations: ['src/migration/*{.ts,.js}'],\n      cli: {\n        migrationsDir: 'src/migration'\n      },\n      synchronize: true,\n    }\n```\n\n```text\n// ormconfig-migrations.ts\n\nimport {config} from './ormconfig';\n\nexport = config;\n```\n\n```text\nimport {config} from './ormconfig';\n\nTypeOrmModule.forRoot(config);\n```\n\n```text\n// package.json\n\n\"scripts\": {\n     ...\n     \"typeorm:cli\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -f ./ormconfig-migrations.ts\",\n     \"migration-generate\": \"npm run typeorm:cli -- migration:generate -n\"\n}\n```\n\n```text\nnpm run typeorm migration:create\n```\n\n```text\nnpm run typeorm migration:generate\n```\n\n```text\nforRoot\n```\n\n========================================\n\nComments:\n- Could you have your migrations generate tables in a schema other than public?\n- Alright, so now if I run the command npm run migration-generate Test, it says that No changes in database schema were found - cannot generate a migration. Do I need to create a migration and code manually the SQL inside of it to create the table?\n- Have you already created any tables? If so than clear the schema, drop the tables or drop the schema and recreate it, and then run migration-generate. This error says your database already have tables matching to the entities in your project.\n- Not yet, my database is empty.\n- You have any migrations in the migrations table?\n- I deleted everything from the database, there's only a database without any tables there. If I run the npm run migration-generate, I got a message saying that no changes in database schema were found. If I run migration-create, it creates a file in the migration folder, but with up and down method empty. Should it create a migration file with some SQL code or do I need to write that SQL code?\n- Also, I modified the ormconfig.ts with this: entities: [__dirname + '/src/event/entities/*.entity.ts', __dirname + '/src/event/entities/*.entity.js'] src/event/entities is where my Typescript classes are right now\n- Nevermind my friend, I found the error, my Entity class has a constructor that was causing some sort of cannot destructure property error. I fixed that and could run the generate command!\n- Won't `synchronize: true` defeat the whole purpose? Whenever you initiation this connection it will always sync entities with the DB schema, therefore there are no migrations to be generated.\n- It is not necessary to add the `npm run`\n- Correct. To generate a migration you have to know current state and expected state, find difference between those and create SQL queries to adjust current state to match expected state. `synchronize: true` will adjust current state automatically. Not sure exactly when, I imagine typeorm does its magic on connection. Meaning DB may already be in expected state and therefore do not require a migration.","metadata":{"transformedAt":"2026-08-18T18:33:02.414Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":142,"estimatedTokens":1417}}144{"id":"stack-66909895","source":"stackoverflow","questionId":66909895,"title":"TypeORM: QueryFailedError: relation does not exist","tags":["node.js","database","postgresql","nestjs","typeorm"],"text":"Title: TypeORM: QueryFailedError: relation does not exist\nTags: node.js, database, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI need a little help with migration. I'm trying to seed DB using migration. But I get an error \"QueryFailedError: relation \"account\" does not exist\". I think it's just typical newbie mistake. So please check my code:\n\n**account.entity.ts**\n\n```\nimport { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { SourceEntity } from '../source/source.entity';\nimport { UtilsService } from '../../shared/services/utils.service';\n\n@Entity({ name: 'account' })\nexport class AccountEntity extends AbstractEntity {\n @Column({ unique: true })\n username: string;\n\n @Column({ nullable: true })\n password: string;\n\n @OneToMany(() => SourceEntity, (source) => source.account, {\n cascade: true,\n })\n sources: SourceEntity[];\n\n @BeforeInsert()\n async setPassword() {\n this.password = UtilsService.generateHash(this.password);\n }\n}\n```\n\n**seed-data.migration.ts**\n\n```\nimport { getCustomRepository, MigrationInterface, QueryRunner } from 'typeorm';\nimport { AccountRepository } from '../modules/account/account.repository';\nimport { SourceRepository } from '../modules/source/source.repository';\n\ntype DataType = {\n username: string;\n password: string;\n sources: { username: string }[];\n};\n\nexport class SeedData1617243952346 implements MigrationInterface {\n private data: DataType[] = [\n {\n username: 'test',\n password: 'password',\n sources: [\n { username: 'some_test' },\n { username: 'okey_test' },\n { username: 'super_test' },\n ],\n },\n {\n username: 'account',\n password: 'password',\n sources: [\n { username: 'some_account' },\n { username: 'okey_account' },\n { username: 'super_account' },\n ],\n },\n ];\n\n public async up(): Promise {\n await Promise.all(\n this.data.map(async (item) => {\n const accountRepository = getCustomRepository(AccountRepository);\n const accountEntity = accountRepository.create();\n accountEntity.username = item.username;\n accountEntity.password = item.password;\n\n const sourceRepository = getCustomRepository(SourceRepository);\n const sources = [];\n\n await Promise.all(\n item.sources.map(async (sourceItem) => {\n const sourceEntity = sourceRepository.create();\n sourceEntity.username = sourceItem.username;\n\n sources.push(sourceEntity);\n }),\n );\n\n accountEntity.sources = sources;\n const account = await accountRepository.save(accountEntity);\n console.log('Account created:', account.id);\n }),\n );\n }\n\n public async down(): Promise {\n await Promise.all(\n this.data.map(async (item) => {\n const sourceRepository = getCustomRepository(SourceRepository);\n const accountRepository = getCustomRepository(AccountRepository);\n\n const account = await accountRepository.findOne({\n where: { username: item.username },\n });\n if (account) {\n await Promise.all(\n item.sources.map(async (src) => {\n const source = await sourceRepository.findOne({\n where: { username: src.username },\n });\n if (source) {\n await sourceRepository.delete(source);\n }\n }),\n );\n\n await accountRepository.delete(account);\n }\n }),\n );\n }\n}\n```\n\n**source.entity.ts**\n\n```\nimport { Column, Entity, ManyToOne } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { AccountEntity } from '../account/account.entity';\n\n@Entity({ name: 'source' })\nexport class SourceEntity extends AbstractEntity {\n @Column({ unique: true })\n username: string;\n\n @Column({ default: true })\n overrideCaption: boolean;\n\n @ManyToOne(() => AccountEntity, (account) => account.sources)\n account: AccountEntity;\n}\n```\n\n**Error:**\n\n```\nError during migration run:\nQueryFailedError: relation \"account\" does not exist\n at new QueryFailedError (/home/wiha/dev/own/instahub/src/error/QueryFailedError.ts:9:9)\n at PostgresQueryRunner. (/home/wiha/dev/own/instahub/src/driver/postgres/PostgresQueryRunner.ts:228:19)\n at step (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:143:27)\n at Object.throw (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:124:57)\n at rejected (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:115:69)\n at processTicksAndRejections (internal/process/task_queues.js:97:5) {\n length: 106,\n severity: 'ERROR',\n code: '42P01',\n detail: undefined,\n hint: undefined,\n position: '13',\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'parse_relation.c',\n line: '1191',\n routine: 'parserOpenTable',\n query: 'INSERT INTO \"account\"(\"id\", \"created_at\", \"updated_at\", \"username\", \"password\") VALUES (DEFAULT, DEFAULT, DEFAULT, $1, $2) RETURNING \"id\", \"created_at\", \"updated_at\"',\n parameters: [\n 'test',\n '$2b$10$iB6yb3D8e6iGmKoVAJ7eYeYfoItclw5lcVXqauPf9VH94DlDrbuSa'\n ]\n}\n```\n\nTables are created in another migration\n\nDB: PostgreSQL 12.6\n\nNode: 14.0.0\n\nTypeORM: 0.2.32\n\n@nestjs/typeorm: 7.1.5\n\n========================================\n\nTop Answer:\nJust in case I help someone, my issue was not specifying the schema in the Entity\n\n```\n@Entity({ name: 'account', schema: 'companydbo' })\n```\n\n========================================\n\nCode:\n```ts\nimport { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { SourceEntity } from '../source/source.entity';\nimport { UtilsService } from '../../shared/services/utils.service';\n\n@Entity({ name: 'account' })\nexport class AccountEntity extends AbstractEntity {\n  @Column({ unique: true })\n  username: string;\n\n  @Column({ nullable: true })\n  password: string;\n\n  @OneToMany(() => SourceEntity, (source) => source.account, {\n    cascade: true,\n  })\n  sources: SourceEntity[];\n\n  @BeforeInsert()\n  async setPassword() {\n    this.password = UtilsService.generateHash(this.password);\n  }\n}\n```\n\n```ts\nimport { getCustomRepository, MigrationInterface, QueryRunner } from 'typeorm';\nimport { AccountRepository } from '../modules/account/account.repository';\nimport { SourceRepository } from '../modules/source/source.repository';\n\ntype DataType = {\n  username: string;\n  password: string;\n  sources: { username: string }[];\n};\n\nexport class SeedData1617243952346 implements MigrationInterface {\n  private data: DataType[] = [\n    {\n      username: 'test',\n      password: 'password',\n      sources: [\n        { username: 'some_test' },\n        { username: 'okey_test' },\n        { username: 'super_test' },\n      ],\n    },\n    {\n      username: 'account',\n      password: 'password',\n      sources: [\n        { username: 'some_account' },\n        { username: 'okey_account' },\n        { username: 'super_account' },\n      ],\n    },\n  ];\n\n  public async up(): Promise<void> {\n    await Promise.all(\n      this.data.map(async (item) => {\n        const accountRepository = getCustomRepository(AccountRepository);\n        const accountEntity = accountRepository.create();\n        accountEntity.username = item.username;\n        accountEntity.password = item.password;\n\n        const sourceRepository = getCustomRepository(SourceRepository);\n        const sources = [];\n\n        await Promise.all(\n          item.sources.map(async (sourceItem) => {\n            const sourceEntity = sourceRepository.create();\n            sourceEntity.username = sourceItem.username;\n\n            sources.push(sourceEntity);\n          }),\n        );\n\n        accountEntity.sources = sources;\n        const account = await accountRepository.save(accountEntity);\n        console.log('Account created:', account.id);\n      }),\n    );\n  }\n\n  public async down(): Promise<void> {\n    await Promise.all(\n      this.data.map(async (item) => {\n        const sourceRepository = getCustomRepository(SourceRepository);\n        const accountRepository = getCustomRepository(AccountRepository);\n\n        const account = await accountRepository.findOne({\n          where: { username: item.username },\n        });\n        if (account) {\n          await Promise.all(\n            item.sources.map(async (src) => {\n              const source = await sourceRepository.findOne({\n                where: { username: src.username },\n              });\n              if (source) {\n                await sourceRepository.delete(source);\n              }\n            }),\n          );\n\n          await accountRepository.delete(account);\n        }\n      }),\n    );\n  }\n}\n```\n\n```ts\nimport { Column, Entity, ManyToOne } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { AccountEntity } from '../account/account.entity';\n\n@Entity({ name: 'source' })\nexport class SourceEntity extends AbstractEntity {\n  @Column({ unique: true })\n  username: string;\n\n  @Column({ default: true })\n  overrideCaption: boolean;\n\n  @ManyToOne(() => AccountEntity, (account) => account.sources)\n  account: AccountEntity;\n}\n```\n\n```sh\nError during migration run:\nQueryFailedError: relation \"account\" does not exist\n    at new QueryFailedError (/home/wiha/dev/own/instahub/src/error/QueryFailedError.ts:9:9)\n    at PostgresQueryRunner.<anonymous> (/home/wiha/dev/own/instahub/src/driver/postgres/PostgresQueryRunner.ts:228:19)\n    at step (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:143:27)\n    at Object.throw (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:124:57)\n    at rejected (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:115:69)\n    at processTicksAndRejections (internal/process/task_queues.js:97:5) {\n  length: 106,\n  severity: 'ERROR',\n  code: '42P01',\n  detail: undefined,\n  hint: undefined,\n  position: '13',\n  internalPosition: undefined,\n  internalQuery: undefined,\n  where: undefined,\n  schema: undefined,\n  table: undefined,\n  column: undefined,\n  dataType: undefined,\n  constraint: undefined,\n  file: 'parse_relation.c',\n  line: '1191',\n  routine: 'parserOpenTable',\n  query: 'INSERT INTO \"account\"(\"id\", \"created_at\", \"updated_at\", \"username\", \"password\") VALUES (DEFAULT, DEFAULT, DEFAULT, $1, $2) RETURNING \"id\", \"created_at\", \"updated_at\"',\n  parameters: [\n    'test',\n    '$2b$10$iB6yb3D8e6iGmKoVAJ7eYeYfoItclw5lcVXqauPf9VH94DlDrbuSa'\n  ]\n}\n```\n\n```text\ncreateConnection({\n    type: \"mysql\",\n    host: \"localhost\",\n    port: 3306,\n    username: \"root\",\n    password: \"admin\",\n    database: \"test\",\n    entities: [\n        Photo\n    ],\n\n// ---\n    synchronize: true,\n// ---\n    logging: false\n```\n\n```text\nsynchronize: true,\n```\n\n```text\nschema:sync\n```\n\n```text\n// In a prev migration the countries table was created\n// Then in a new migration\n\nexport class SeedCountriesTable1616610473154 implements MigrationInterface {\n    public async up(queryRunner: QueryRunner): Promise<void> {\n        // Trying to commit last transcaction\n        await queryRunner.commitTransaction().then(async () => {\n            // Seeding database\n            // Then try to start another one\n            await queryRunner.startTransaction().then(async () => {\n                await getRepository('countries').save(countries);\n            });\n        });\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-empty-function\n    public async down(): Promise<void> {}\n}\n```\n\n```text\nprivate static async getProducts(): Promise<Product[]> {\n  return await getRepository(Product)\n    .createQueryBuilder('product')\n    .where('product.source = \"noobie\"') // <---- DOUBLE QUOTES = BAD!!!\n    .getMany();\n}\n```\n\n```text\nprivate static async getProducts(): Promise<Product[]> {\n  return await getRepository(Product)\n    .createQueryBuilder('product')\n    .where(\"product.source = 'noobie'\") // <---- SINGLE QUOTES!!!\n    .getMany();\n}\n```\n\n```text\n@Entity({ name: 'account', schema: 'companydbo' })\n```\n\n```text\nmigrationsTransactionMode: 'each'\n```\n\n```none\n\"test:e2e\": \"cross-env NODE_ENV=test jest --config ./test/jest-e2e.json --runInBand\"\n```\n\n```text\n--runInBand\n```\n\n```text\njest\n```\n\n```text\ntest:e2e\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- how do you initialize your db?\n- @shusson via TypeOrmModule.forRootAsync\n- can you show more code? TypeORM can create the schema for you, but it depends how you initialize the TypeORM connection.\n- @shusson check this gist\n- you need to double check your entities list includes the account entity. gist.github.com/qWici/&hellip;\n- @shusson I have next struct - screenshot on Imgur. So I think it's works fine.\n- Mark this answer as correct. But what I actually done: 1. Remove migration for creating tables for entities 2. Set **synchronize** to true 3. Recreate DB 4. Run typeorm schema:sync 5. Run migration\n- This is actually the most correct answer it tells you exactly when the issue happens and unless your project is a demo project I will not recommend turning on the synchronise:true option.\n- The documentation says: **Typically, it is unsafe to use synchronize: true for schema synchronization on production once you get data in your database. Here is where migrations come to help.** Reference: typeorm.io/docs/advanced-topics/migrations\n- Great job, this is exactly what we needed !\n- +1 to this because its really not clear why it works the first time (it assumes the 'public' schema in postgres when creating the table, which is what i would expect), but not the second time (on a rerun of sync when the table already exists). fixed my problem, don't know why dont care why, thank you.","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":478,"estimatedTokens":3342}}145{"id":"stack-65355892","source":"stackoverflow","questionId":65355892,"title":"Can you import a NestJS module on condition","tags":["module","rabbitmq","nestjs"],"text":"Title: Can you import a NestJS module on condition\nTags: module, rabbitmq, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'am creating a microservice in NestJS. Now I want to use RabbitMQ to send messages to another service.\n\nMy question is: is it possible to import the RabbitmqModule based on a `.env` variable? Such as:\n`USE_BROKER=false`. If this variable is false, than don't import the module?\n\nRabbitMQ is imported in the GraphQLModule below.\n\n```\n@Module({\n imports: [\n GraphQLFederationModule.forRoot({\n autoSchemaFile: true,\n context: ({ req }) => ({ req }),\n }),\n DatabaseModule,\n AuthModule,\n RabbitmqModule,\n ],\n providers: [UserResolver, FamilyResolver, AuthResolver],\n})\nexport class GraphQLModule {}\n```\n\nRabbitmqModule:\n\n```\nimport { Global, Module } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';\nimport { UserProducer } from './producers/user.producer';\n\n@Global()\n@Module({\n imports: [\n RabbitMQModule.forRootAsync(RabbitMQModule, {\n useFactory: async (config: ConfigService) => ({\n exchanges: [\n {\n name: config.get('rabbitMQ.exchange'),\n type: config.get('rabbitMQ.exchangeType'),\n },\n ],\n uri: config.get('rabbitMQ.url'),\n connectionInitOptions: { wait: false },\n }),\n inject: [ConfigService],\n }),\n ],\n providers: [UserProducer],\n exports: [UserProducer],\n})\nexport class RabbitmqModule {}\n```\n\n========================================\n\nTop Answer:\nWell I tried a simple workaround, in a small nest project, and it worked just fine. Check it out:\n\n```\nconst mymodules = [TypeOrmModule.forRoot(typeOrmConfig), UsersModule];\nif (config.get('importModule')) {\n mymodules.push(PoopModule);\n}\n@Module({\n imports: mymodules,\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nI created an \"importModule\" in my env/config, and tested it with true and false. If true my Poop module gets deployed, else it doesn't deploy, only the other modules.\n\nCan you try the same in your project?\n\n========================================\n\nCode:\n```javascript\n@Module({\n  imports: [\n    GraphQLFederationModule.forRoot({\n      autoSchemaFile: true,\n      context: ({ req }) => ({ req }),\n    }),\n    DatabaseModule,\n    AuthModule,\n    RabbitmqModule,\n  ],\n  providers: [UserResolver, FamilyResolver, AuthResolver],\n})\nexport class GraphQLModule {}\n```\n\n```javascript\nimport { Global, Module } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';\nimport { UserProducer } from './producers/user.producer';\n\n@Global()\n@Module({\n  imports: [\n    RabbitMQModule.forRootAsync(RabbitMQModule, {\n      useFactory: async (config: ConfigService) => ({\n        exchanges: [\n          {\n            name: config.get('rabbitMQ.exchange'),\n            type: config.get('rabbitMQ.exchangeType'),\n          },\n        ],\n        uri: config.get('rabbitMQ.url'),\n        connectionInitOptions: { wait: false },\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n  providers: [UserProducer],\n  exports: [UserProducer],\n})\nexport class RabbitmqModule {}\n```\n\n```text\n.env\n```\n\n```text\nUSE_BROKER=false\n```\n\n```js\n@Module({})\nexport class GraphQLModule {\n  static register(): DynamicModule {\n    const imports = [\n      GraphQLFederationModule.forRoot({\n        autoSchemaFile: true,\n        context: ({ req }) => ({ req }),\n      }),\n      DatabaseModule,\n      AuthModule]\n    if (process.env.USE_BROKER) {\n      imports.push(RabbitmqModule)\n    }\n    return {\n      imports,\n      providers: [UserResolver, FamilyResolver, AuthResolver],\n    };\n  }\n}\n```\n\n```javascript\nconst mymodules = [TypeOrmModule.forRoot(typeOrmConfig), UsersModule];\nif (config.get('importModule')) {\n    mymodules.push(PoopModule);\n}\n@Module({\n    imports: mymodules,\n    controllers: [AppController],\n    providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nConditionalModule.registerWhen\n```\n\n```text\n@nestjs/config\n```\n\n========================================\n\nComments:\n- Yes, calculating the imports array based on a condition is the easiest way to accomplish this functionality\n- Where did you define config in this example?\n- @jm18457 I don't have the sample project with me anymore, but I guess you can just use `dotenv` or similar library. The one described in my code is npmjs.com/package/config. You can just install it, create a `&#47;config&#47;default.json` in your project, and store values in there (I'm using `&#47;config&#47;default.yml` in a different project and it also seems to work fine). I import this lib using the syntax `import * as config from 'config';`\n- Ok, thx. I thought you were using the config service from Nest.js. I want to read .env variables from the configService.\n- I did try to use sometimes, but usually I give up on this module and install dotenv instead, sry =]\n- But what if we want to make use of ConfigService to determine whether the RabbitmqModule should be loaded or not? Instead of having process.env hardcoded\n- Any answer to above question? How do we implement this solution using ConfigService instead of process.env?\n- To use ConfigService in register method, see stackoverflow.com/a/54310397/901597\n- this is seem to be the best option\n- but can the ConditionalModule using config value instead of env?\n- The idea is neat, and the demand is there, but the implementation seems very clumsy (as of June 2024). It seems as though conditional module import can't be implemented with the intuitive syntax, but the authors wanted to give it a try anyway, and ended up with a hacky compromise. I expect this feature to be significantly improved in a year or two (or faster, if this comment is seen by NestJS collaborators ๐Ÿ™‹).\n- @Parzh well, it hasn't improved :)\n- still no improvement here, mid 2026 ๐Ÿ˜… -> it is great! But the use of only `env` is a little limiting... It passes the need we currently have, but, it does need a better implementation from nestjs. But, it will do for now ๐Ÿฅฒ\n- @Peter No it can't. It only provides the `env`, which is not ideal, but it can get the job done. It's the cleanest solution currently in 2026, but, I think they need to improve their interface a little","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":197,"estimatedTokens":1556}}146{"id":"stack-57146395","source":"stackoverflow","questionId":57146395,"title":"How to trigger application shutdown from a service in Nest.js?","tags":["javascript","node.js","typescript","lifecycle","nestjs"],"text":"Title: How to trigger application shutdown from a service in Nest.js?\nTags: javascript, node.js, typescript, lifecycle, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a way to trigger application shutdown from a service in Nest.js that will still call hooks.\n\nI have a case when I'm handling a message in a service and in some scenario this should shutdown the application. I used to throw unhandled exceptions but when I do this Nest.js doesn't call hooks like `onModuleDestroy` or even shutdown hooks like `onApplicationShutdown` which are required in my case.\n\ncalling `.close()` from `INestApplication` works as expected but how do I inject it into my service? Or maybe there is some other pattern I could use to achieve what I'm trying to do?\n\nThank you very much for all the help.\n\n========================================\n\nCode:\n```text\nonModuleDestroy\n```\n\n```text\nonApplicationShutdown\n```\n\n```text\n.close()\n```\n\n```text\nINestApplication\n```\n\n```text\nexport class ShutdownService implements OnModuleDestroy {\n  // Create an rxjs Subject that your application can subscribe to\n  private shutdownListener$: Subject<void> = new Subject();\n\n  // Your hook will be executed\n  onModuleDestroy() {\n    console.log('Executing OnDestroy Hook');\n  }\n\n  // Subscribe to the shutdown in your main.ts\n  subscribeToShutdown(shutdownFn: () => void): void {\n    this.shutdownListener$.subscribe(() => shutdownFn());\n  }\n\n  // Emit the shutdown event\n  shutdown() {\n    this.shutdownListener$.next();\n  }\n}\n```\n\n```text\n// Subscribe to your service's shutdown event, run app.close() when emitted\napp.get(ShutdownService).subscribeToShutdown(() => app.close());\n```\n\n```text\nmain.ts\n```\n\n========================================\n\nComments:\n- Still having open questions? :-)\n- It seems to get the job done, however it doesn't work nicely with @nestjs/typeorm which i'm using. I will try my luck with @nestjs/terminus package.","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":68,"estimatedTokens":482}}147{"id":"stack-60405308","source":"stackoverflow","questionId":60405308,"title":"NestJs Passport jwt unknown strategy","tags":["typescript","jwt","nestjs","nestjs-passport","nestjs-jwt"],"text":"Title: NestJs Passport jwt unknown strategy\nTags: typescript, jwt, nestjs, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement a JWT strategy for authentication in my nest application.\n\nI am getting the following error tho\n\n Unknown authentication strategy \"jwt\"\n\nThis is my code:\n\n`jwt.strategy.ts`\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy } from \"passport-local\";\nimport { ExtractJwt } from \"passport-jwt\";\nimport { jwtConstants } from \"./constants\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: jwtConstants.secret,\n })\n }\n\n async validate(payload: any) {\n console.log(payload);\n return { userId: payload.sub, username: payload.username };\n }\n}\n```\n\nMy Authentication Module:\n\n`authentication.module.ts` \n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthenticationService } from './authentication.service';\nimport { UsersModule } from 'src/users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n providers: [\n AuthenticationService,\n LocalStrategy,\n JwtStrategy\n ],\n imports: [\n UsersModule,\n PassportModule,\n JwtModule.register({\n secret: jwtConstants.secret,\n signOptions: { expiresIn: \"1d\" },\n })\n ],\n exports: [AuthenticationService]\n})\nexport class AuthenticationModule {}\n```\n\nAnd I am trying to use it in the following controller:\n\n`users.controller.ts`\n\n```\nimport { Controller, Post, Body, Put, Param, Get, UseGuards } from '@nestjs/common';\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\nimport { JwtAuthGuard } from 'src/authentication/jwt-auth.guard';\n\n@Controller('users')\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @UseGuards(JwtAuthGuard)\n @Get()\n async getAll(){\n return this.usersService.findAll();\n }\n}\n```\n\nThe Users Module looks like this:\n\n`users.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\n\n@Module({\n imports: [TypeOrmModule.forFeature([User])],\n providers: [UsersService],\n controllers: [UsersController],\n exports: [UsersService]\n})\nexport class UsersModule {}\n```\n\n`JwtAuthGuard`is just a class that extends from `AuthGuard('jwt')`\nI have the nestjs authentication guide from the official docs, but cant get it running in my UsersModule\n\n========================================\n\nTop Answer:\nFor me, I was missing importing JwtStrategy into `auth.module.ts` `providers`\n\n```\n@Module({\n controllers: [AuthController],\n imports: [\n PassportModule,\n JwtModule.register({\n secret: 'nomnom',\n signOptions: { expiresIn: '1d' },\n }),\n ],\n exports: [AuthService],\n providers: [AuthService, AccountService, LocalStrategy, JwtStrategy], // Here, make sure you have imported LocalStrategy and JwtStrategy.\n})\nexport class AuthModule {}\n```\n\n========================================\n\nCode:\n```js\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy } from \"passport-local\";\nimport { ExtractJwt } from \"passport-jwt\";\nimport { jwtConstants } from \"./constants\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: jwtConstants.secret,\n    })\n  }\n\n  async validate(payload: any) {\n    console.log(payload);\n    return { userId: payload.sub, username: payload.username };\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { AuthenticationService } from './authentication.service';\nimport { UsersModule } from 'src/users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n  providers: [\n    AuthenticationService,\n    LocalStrategy,\n    JwtStrategy\n  ],\n  imports: [\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: \"1d\" },\n    })\n  ],\n  exports: [AuthenticationService]\n})\nexport class AuthenticationModule {}\n```\n\n```js\nimport { Controller, Post, Body, Put, Param, Get, UseGuards } from '@nestjs/common';\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\nimport { JwtAuthGuard } from 'src/authentication/jwt-auth.guard';\n\n@Controller('users')\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @UseGuards(JwtAuthGuard)\n  @Get()\n  async getAll(){\n    return this.usersService.findAll();\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  providers: [UsersService],\n  controllers: [UsersController],\n  exports: [UsersService]\n})\nexport class UsersModule {}\n```\n\n```text\njwt.strategy.ts\n```\n\n```text\nauthentication.module.ts\n```\n\n```text\nusers.controller.ts\n```\n\n```text\nusers.module.ts\n```\n\n```text\nJwtAuthGuard\n```\n\n```text\nAuthGuard('jwt')\n```\n\n```js\nimport {Strategy} from \"@nest/passport-local\";\n```\n\n```js\nimport { Strategy } from \"passport-jwt\";\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\n// import authentication module here\n\n@Module({\n  imports: [\n    AuthenticationModule, // add this here\n    TypeOrmModule.forFeature([User])\n  ],\n  providers: [UsersService],\n  controllers: [UsersController],\n  exports: [UsersService]\n})\nexport class UsersModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AuthenticationService } from './authentication.service';\nimport { UsersModule } from 'src/users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n  providers: [\n    AuthenticationService,\n    LocalStrategy,\n    JwtStrategy\n  ],\n  imports: [\n    // UsersModule, # exclude this, your authentication module is not using it\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: \"1d\" },\n    })\n  ],\n  exports: [\n    JwtModule,\n    PassportModule,\n    AuthenticationService,\n\n  ]\n})\nexport class AuthenticationModule {}\n```\n\n```text\nuser.module.ts\n```\n\n```text\nauthentication.module.ts\n```\n\n```text\n@Module({\n  controllers: [AuthController],\n  imports: [\n    PassportModule,\n    JwtModule.register({\n      secret: 'nomnom',\n      signOptions: { expiresIn: '1d' },\n    }),\n  ],\n  exports: [AuthService],\n  providers: [AuthService, AccountService, LocalStrategy, JwtStrategy], // Here, make sure you have imported LocalStrategy and JwtStrategy.\n})\nexport class AuthModule {}\n```\n\n```text\nauth.module.ts\n```\n\n```text\nproviders\n```\n\n```text\nimport { Strategy } from \"passport-local\";\n```\n\n```text\nimport { Strategy } from \"passport-jwt\";\n```\n\n========================================\n\nComments:\n- Have you imported `AuthenticationModule` inside your UserModule? Be sure to export `PassportModule` and `JwtModule` as well inside your AuthenticationModule's export\n- I am Using the UserService that is beeing provided by the UserModule, so I need it in my AuthModule. I didnt need to import the AuthModule in my UserModule tho. So there is no circular dependency. It was an autoimport issue.\n- Your answer really helped me and yes, the last step of removing UserModule from AuthModule's dependencies is not needed as Nest will not be able to use userService i authservice if that is done\n- Make sure you have Strategies imported into your providers' ex: `providers: [ AuthenticationService, LocalStrategy, JwtStrategy ],`\n- Thank you...so simple to miss, saved me a afternoon's hunting down!!\n- But in this guide: docs.nestjs.com/recipes/&hellip; the example is different, and seem the \"@nest/passport-local\" is not exists\n- Thanks brother! I was learning nestJs and was confused at this point. Seems like a silly mistake :)\n- Thanks! this is useful\n- it happened also to me xd ( :( )","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":366,"estimatedTokens":2258}}148{"id":"stack-60599253","source":"stackoverflow","questionId":60599253,"title":"how to set the response to be an array in the swagger response using DTOs","tags":["nestjs","nestjs-swagger"],"text":"Title: how to set the response to be an array in the swagger response using DTOs\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\n**some-dto.ts**\n\n```\nexport class CreateCatDto {\n @ApiProperty()\n name: string;\n\n @ApiProperty()\n age: number;\n\n @ApiProperty()\n breed: string;\n }\n```\n\nI don't want response something like this:\n\n```\n@ApiOkResponse(\n description: 'Cat object',\n type: CreateCatDto\n )\n```\n\nbut my response must be array of like dto objects. \nI want smth like soo \n\n```\nApiOkResponse(\n description: 'The record has been successfully removed.',\n schema: {\n type: 'array',\n properties: {\n obj: {\n type: CreateCatDto\n }\n }\n }\n )\n```\n\n========================================\n\nTop Answer:\nI found another solution we can wrap in array like this\n\n```\n@ApiOkResponse(\n description: 'Cat object',\n type: [CreateCatDto]\n)\n```\n\n========================================\n\nCode:\n```js\nexport class CreateCatDto {\n      @ApiProperty()\n      name: string;\n\n      @ApiProperty()\n      age: number;\n\n      @ApiProperty()\n      breed: string;\n    }\n```\n\n```js\n@ApiOkResponse(\n      description: 'Cat object',\n      type: CreateCatDto\n    )\n```\n\n```js\nApiOkResponse(\n          description: 'The record has been successfully removed.',\n          schema: {\n            type: 'array',\n            properties: {\n              obj: {\n                type: CreateCatDto\n              }\n            }\n          }\n        )\n```\n\n```js\n@ApiOkResponse(\n    description: 'Cat object',\n    type: CreateCatDto,\n    isArray: true // <= diff is here\n)\n```\n\n```text\n@ApiOkResponse(\n  description: 'Cat object',\n  type: [CreateCatDto]\n)\n```\n\n```js\n@ApiOkResponse({\n  description: 'More or less dangerous animals',\n  schema: {\n    type: 'array',\n    items: {\n      oneOf: [\n        { $ref: getSchemaPath(CreateCatDto) },\n        { $ref: getSchemaPath(CreateAlligatorDto) }\n      ],\n    },\n  },\n})\n```\n\n```js\n@Controller(\"noahsark\")\n@ApiExtraModels(CreateCatDto, CreateAlligatorDto)\nexport class NoahsArkController {\n...\n}\n```\n\n========================================\n\nComments:\n- Do you have an idea if you want to respond with a list of lists? Like CreateCatDto[][]?\n- I personally haven't had to deal with such structure in past experiences. You would have to check on the web to see if this is supported and how to implement. If supported my guess is that you would need to tweak things in order to make it work ๐Ÿค” Let us know if you find a solution though !\n- Nice to know array type can be inferred from using the DTO type within an array !","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":139,"estimatedTokens":634}}149{"id":"stack-64607530","source":"stackoverflow","questionId":64607530,"title":"Use the same class as Input and Object type in GraphQL in NestJS","tags":["typescript","graphql","nestjs"],"text":"Title: Use the same class as Input and Object type in GraphQL in NestJS\nTags: typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup my graphql resover to handle an array of objects but cant get the @Args decorator configured.\n\nI created my own ArgsType\n\n```\nimportย {ย ArgsType,ย Field,ย Int,ย ObjectTypeย }ย from '@nestjs/graphql';\n\n@ArgsType()ย ย //ย toย beย usedย asย typeย inย theย resolver\n@ObjectType()ย ย //ย forย schemaย generationย \nexport class Clubย {\nย @Field(type => String)\n president: string;\n\nย @Field(type => Int)\n members?: number;\n}\n```\n\nResolver with adding a single Club works just fine!\n\n```\n@Query(()ย => Int)\n async addClub(@Args()ย club: Club)ย {\n // handle stuff\nย ย }\n```\n\nbut if I want to give an array of Club like this\n\n```\n@Query(()ย => Int)\n async addClubs(@Args({name:ย 'clubs',ย type:ย ()ย =>ย [Club]})ย clubs: Array)ย {\n // handle stuff\nย ย }\n```\n\nthis thows an error when nest is starting up\n\n```\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL input type for the \"clubs\". Make sure your class is decorated with an appropriate decorator.\n```\n\nalthough I am able to use an array of Strings like this\n\n```\n@Query(()ย =>ย [String])\n async addStrings(@Args({ย name:ย 'clubs',ย type:ย ()ย =>ย [String],ย })ย clubs: Array)ย {\n // handle stuff\nย ย }\n```\n\nI am pretty sure there should be an easy solution, but cant figure out where to go from here.\n\n========================================\n\nCode:\n```text\nimportย {ย ArgsType,ย Field,ย Int,ย ObjectTypeย }ย from '@nestjs/graphql';\n\n@ArgsType()ย ย //ย toย beย usedย asย typeย inย theย resolver\n@ObjectType()ย ย //ย forย schemaย generationย \nexport class Clubย {\nย @Field(type => String)\n president: string;\n\nย @Field(type => Int)\n members?: number;\n}\n```\n\n```text\n@Query(()ย => Int)\n async addClub(@Args()ย club: Club)ย {\n  // handle stuff\nย ย }\n```\n\n```text\n@Query(()ย => Int)\n   async addClubs(@Args({name:ย 'clubs',ย type:ย ()ย =>ย [Club]})ย clubs: Array<Club>)ย {\n   // handle stuff\nย ย }\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL input type for the \"clubs\". Make sure your class is decorated with an appropriate decorator.\n```\n\n```text\n@Query(()ย =>ย [String])\n async addStrings(@Args({ย name:ย 'clubs',ย type:ย ()ย =>ย [String],ย })ย clubs: Array<string>)ย {\n  // handle stuff\nย ย }\n```\n\n```sh\nCannot determine a GraphQL input type for the \"clubs\". Make sure your class is decorated with an appropriate decorator\n```\n\n```js\nimport { InputType, Field } from '@nestjs/graphql';\n\n@InputType()\nexport class ClubInput {\n @Field()\n president: string;\n\n @Field()\n members?: number;\n}\n```\n\n```js\n@Query(() => Int)\nasync addClubs(@Args({name: 'clubs', type: () => [ClubInput]}) clubs: Array<ClubInput>) {\n // handle stuff\n}\n```\n\n```js\nimport { Field, Int, ObjectType, InputType } from '@nestjs/graphql';\n\n@InputType(\"ClubInput\")\n@ObjectType(\"ClubType\")\nexport class Club {\n @Field(type => String)\n president: string;\n\n @Field(type => Int)\n members?: number;\n}\n```\n\n```js\n@Query(() => Int)\nasync addClubs(@Args({name: 'clubs', type: () => [ClubInput]}) clubs: Array<ClubInput>) {\n // handle stuff\n}\n```\n\n```text\nClub\n```\n\n```text\n@ObjectType\n```\n\n```text\nClub\n```\n\n```text\nClub\n```\n\n```text\nClub\n```\n\n```text\nClub\n```\n\n```text\nInputType\n```\n\n```text\nObjectType\n```\n\n========================================\n\nComments:\n- Wow thanks for that thorough explanation. So it was basically me trying to use a screwdriver as a hammer xD had no time to try it out but after checking the nestjs docs about graphql mutation, I am sure that's the solution. I will stick with solution 1 since that's the common practice and my case is not special at all\n- Please do you know how someone can go about this case. I have an `InputType` and `ObjectType`, most of their properties are same but they have few differences, is there a way i can have 2 classes where one inherits the similar properties from the other so i won't have to define duplicate properties in both classes\n- Sure, You can create an abstract class and put the similar properties of `InputType` and `ObjectType` in it. Then you can extend that class in your `InputType` and `ObjectType` concrete classes.\n- docs.nestjs.com/graphql/mapped-types this gives you a nice abstraction to achieve what you wish","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":184,"estimatedTokens":1052}}150{"id":"stack-61666498","source":"stackoverflow","questionId":61666498,"title":"File naming in Nest.js","tags":["node.js","coding-style","nestjs"],"text":"Title: File naming in Nest.js\nTags: node.js, coding-style, nestjs\nSource: Stack Overflow\n\nQuestion:\nThis question is about code styling in Nestjs.\nThis framework suggests file naming lowercase letters and across the dot.\n\nExample:\n\nfile user.service.ts\n\n```\nexport class UserService {\n}\n```\n\nanother file\n\n```\nimport { UserService } from './user.service'\n```\n\nIn most cases every file contains one class. I find it convenient to export this class as default and then import the file with the same name\n\nfile UserService.ts\n\n```\nexport default class UserService {\n}\n```\n\nanother file\n\n```\nimport UserService from './UserService'\n```\n\nBecause it is faster and easier.\n\nCould you argue to me why I should not do this? Also I donโ€™t understand why the only entity in a file is not exported as default.\nAre you comfortable working with file names in Nest JS?\n\nUPD. One more question:\nIf I have a class name consisting of several words. For example\n\"UserRoleService\". What should I name this file?\n\nuserrole.service.ts\n\nuser-role.service.ts\n\nuser_role.service.ts\n\nuser.role.service.ts\n\nIt looks weird and not readable. I think CamelCase would be preferable but here we come back where we started\n\n========================================\n\nTop Answer:\nI came a cross this old question, and I think it worths providing this answer for next visitors.\n\nLike `@Jay McDoiel` mentioned, this is a very opinionated choice. Either way is correct.\n\n**However, I found out that NestJS library used hyphen-separated `user-role.service.ts` file naming as its convention.**\n\nCheck out my the attached photo below\n\nhttps://i.sstatic.net/ePaJn.png\n\n========================================\n\nCode:\n```text\nexport class UserService {\n}\n```\n\n```text\nimport { UserService } from './user.service'\n```\n\n```text\nexport default class UserService {\n}\n```\n\n```text\nimport UserService from './UserService'\n```\n\n```text\n.ts\n```\n\n```text\n.service.ts\n```\n\n```text\nexport class <ClassName>\n```\n\n```text\nas\n```\n\n```text\ndefault exports\n```\n\n```text\nexport default MyClass\n```\n\n```text\nimport SomethingNotRelatedToTheName from path/to/MyClass\n```\n\n```text\n@Jay McDoiel\n```\n\n```text\nuser-role.service.ts\n```\n\n========================================\n\nComments:\n- `export default` is bad: basarat.gitbook.io/typescript/main-1/defaultisbad\n- This is a very convincing answer. I completely agree with you, except 2 item which does not seem to me as an argument. I've added third question about CamelCase. I would be grateful if you look it up\n- Personally, I like the `first-name-part.type.ext` approach, so you can have things like `user-role.service.ts` or `ogma-core.module.ts`. This is the same approach Nest uses with its file names. Same goes for directories, using a hyphen to keep the file as one name with multiple parts\n- Adding to the Exports part, transpiling `export default` to cjs is somewhat weird in that one has to import `.default` from that transpiled package.","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":134,"estimatedTokens":734}}151{"id":"stack-59696814","source":"stackoverflow","questionId":59696814,"title":"TypeORM - never return the password from the database when fetching a user","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: TypeORM - never return the password from the database when fetching a user\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI created a REST API using NestJs with TypeORM. Basically this is my user entity\n\n```\n@Entity('User')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public username: string;\n\n public passwordHash: string;\n}\n```\n\nWhen fetching users from the database the sensitive password information get returned too. But I only need the password field for the sign in process. So when calling the service for signing in I compare the password hash from the database user with the provided password from the client. I would never want to return the password information back to the client.\n\nAs you can image fetching users from the database happens quite often, you would have to delete the password information from the user object quite often.\n\nLet's assume you have a group entity and have a relation between them. When fetching users related to a group you would also have to take care for the sensitive data in the groups domain. \n\nAnd maybe some users are deeply nested within an object returned by a big SQL query statement. Is there a way I can \"hide\" some fields? When calling `this.usersRepository.find()` I would get a list of users and each user would have an `id` and a `username` field **but not** a `passwordHash` field. This would make things easier because I only need to fetch the hash field within my `signIn` flow.\n\n========================================\n\nTop Answer:\nYou can use @Exclude, like:\n\n```\n@Entity('User')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public username: string;\n\n @Exclude()\n @Column()\n password: string;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity('User')\nexport class User extends BaseEntity {\n  @PrimaryGeneratedColumn()\n  public id: number;\n\n  @Column({ unique: true })\n  public username: string;\n\n  public passwordHash: string;\n}\n```\n\n```text\nthis.usersRepository.find()\n```\n\n```text\nid\n```\n\n```text\nusername\n```\n\n```text\npasswordHash\n```\n\n```text\nsignIn\n```\n\n```text\n@Entity()\nexport class User {\n\n    @Column({select: false})\n    password: string;\n}\n```\n\n```text\nselect: false\n```\n\n```text\naddSelect\n```\n\n```text\n@Entity('User')\nexport class User extends BaseEntity {\n  @PrimaryGeneratedColumn()\n  public id: number;\n\n  @Column({ unique: true })\n  public username: string;\n\n  @Exclude()\n  @Column()\n  password: string;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":115,"estimatedTokens":650}}152{"id":"stack-67849597","source":"stackoverflow","questionId":67849597,"title":"How to write nested DTOs in NestJS","tags":["javascript","typescript","nestjs","dto"],"text":"Title: How to write nested DTOs in NestJS\nTags: javascript, typescript, nestjs, dto\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in NestJS and I want to write a DTO for below structure -\n\n```\n{\n something: {\n info: {\n title: string,\n score: number,\n description: string,\n time: string,\n DateOfCreation: string\n },\n Store: {\n item: {\n question: string,\n options: {\n item: {\n answer: string,\n description: string,\n id: string,\n key: string,\n option: string\n }\n }\n }\n }\n }\n}\n```\n\nI want to write a DTO for that nested Data object. I can't find a solid example for writing nested DTO in NestJS. I am a beginner in NestJS and I have never worked with DTO before. So please don't assume that I know something. I am using it with Mongoose.\n\n========================================\n\nTop Answer:\n//example :\n\n```\nexport class UserBaseDto {\n @ApiProperty({\n type: String,\n required: true,\n description: 'email user, minlength(4), maxlength(40)',\n default: \"test@email.com\",\n })\n @IsString()\n @MinLength(4)\n @MaxLength(40)\n @IsNotEmpty() \n email: string;\n//....enter code here\n}\n```\n\n========================================\n\nCode:\n```text\n{\n    something: {\n        info: {\n            title: string,\n            score: number,\n            description: string,\n            time: string,\n            DateOfCreation: string\n        },\n        Store: {\n            item: {\n                question: string,\n                options: {\n                    item: {\n                        answer: string,\n                        description: string,\n                        id: string,\n                        key: string,\n                        option: string\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n```text\nimport { Type } from \"class-transformer\";\n\nclass Info {\n    readonly title:string\n    readonly score:number\n    readonly description:string\n    readonly dateOfCreation:Date\n}\n\nexport class SampleDto {\n    @Type(() => Info)\n    @ValidateNested()\n    readonly info: Info\n\n    ...Follow same for the rest of the schema\n\n}\n```\n\n```text\nexport class UserBaseDto {\n  @ApiProperty({\n    type: String,\n    required: true,\n    description: 'email user, minlength(4), maxlength(40)',\n    default: \"test@email.com\",\n  })\n  @IsString()\n  @MinLength(4)\n  @MaxLength(40)\n  @IsNotEmpty() \n  email: string;\n//....enter code here\n}\n```\n\n========================================\n\nComments:\n- Ooh my god this thing was staring right at my face but I couldn't see it. Thank you very much. Marking this as accepted answer. And here's another answer for same question for future readers - stackoverflow.com/questions/53786383/&hellip;\n- Note that it's @ValidateNested(), not @ValidatedNested()\n- From where to import @Type. I can not find it in class-validator\n- import { Type } from \"class-transformer\";\n- I cannot confirm this. If used like that i can still send a flat structure where the properties are not nested to my endpoint and it works. But using the nested structure fails.\n- @user32312010 Just for clarification. The validation stops working for me. I can now send both a flat structure and the nested structure.","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":136,"estimatedTokens":785}}153{"id":"stack-64349628","source":"stackoverflow","questionId":64349628,"title":"What is Injectable in NestJS?","tags":["node.js","typescript","nestjs"],"text":"Title: What is Injectable in NestJS?\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am studying NestJS, here is my simple service:\n\n```\nimport { Injectable } from '@nestjs/common';\n\nconst userMock = [{ account: 'dung', password: '12345678' }];\n\n@Injectable()\nexport class UserService {\n getUser() {\n return userMock\n }\n}\n```\n\nI not really understand `@Injectable` in NestJS. Some tutorial tell `@Injectable` tell the `@Controller` know it's an install and can use it as a Dependency Injection. But when I remove it, it's still working.\n\nPlease give an example about difference between `@Injectable` and without `@Injectable`\n\n========================================\n\nTop Answer:\n`@Injectable()` is how you tell Nest this is a class that *can* have dependencies that should be instantiated by Nest and its DI system. The code you posted works because there are no injected dependencies. If, instead, you had\n\n```\nconst userMock = [{ account: 'dung', password: '12345678' }];\n\nexport class UserService {\n constructor(private readonly otherService: OtherService) {}\n getUser() {\n return userMock\n }\n}\n```\n\n`OtherService` would come back `undefined` due to `UserService` not being `@Injectable()`\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\n\nconst userMock = [{ account: 'dung', password: '12345678' }];\n\n@Injectable()\nexport class UserService {\n  getUser() {\n    return userMock\n  }\n}\n```\n\n```text\n@Injectable\n```\n\n```text\n@Injectable\n```\n\n```text\n@Controller\n```\n\n```text\n@Injectable\n```\n\n```text\n@Injectable\n```\n\n```text\n@Injectable()\nexport class PersonService {\n  getName() {\n    return 'ninezero90hy';\n  }\n}\n```\n\n```text\n@Injectable()\nexport class AppService {\n  constructor(private readonly personService: PersonService) {\n    Logger.log(this.personService.getName())\n  }\n}\n```\n\n```text\nexport declare enum Scope {\n    /**\n     * The provider can be shared across multiple classes. The provider lifetime\n     * is strictly tied to the application lifecycle. Once the application has\n     * bootstrapped, all providers have been instantiated.\n     */\n    DEFAULT = 0,\n    /**\n     * A new private instance of the provider is instantiated for every use\n     */\n    TRANSIENT = 1,\n    /**\n     * A new instance is instantiated for each request processing pipeline\n     */\n    REQUEST = 2\n}\n```\n\n```text\n@Injectable()\n```\n\n```text\n@Injectible()\n```\n\n```text\n@Injectible()\n```\n\n```js\nconst userMock = [{ account: 'dung', password: '12345678' }];\n\nexport class UserService {\n  constructor(private readonly otherService: OtherService) {}\n  getUser() {\n    return userMock\n  }\n}\n```\n\n```text\n@Injectable()\n```\n\n```text\nOtherService\n```\n\n```text\nundefined\n```\n\n```text\nUserService\n```\n\n```text\n@Injectable()\n```\n\n```text\nexport class UserService() {\n private users: Array<User> = [{\n    id: 1,\n    email: 'user@email.com',\n    password: 'kjkjkj'\n ]};\n findOne(id:number): Promise<User> { \n    // should be `return this.repo.findOne(id)` but I dont wanna get into repository\n return  \"write logic to return user\"\n }\n}\n```\n\n```text\nexport class AuthenticationService {\n   public userService: UserService;\n   constructor() {\n       this.userService = new UserService();\n   }\n async validateAUser(payload: { email: string; password: string }):\n     // Write logic\n}\n```\n\n========================================\n\nComments:\n- As I understand, if we have @Injectable, it tell NestJS know that class can use other service of other module. Right?\n- I tried import a module has been initial in module, but when remove `@Injectable` in service, still error. It's mean if we want to user other class I have to init `@Injectable`. It's correct ???\n- How then do you explain this, \"Decorator that marks a class as a provider. Providers can be injected into other classes via constructor parameter injection using Nest's built-in Dependency Injection (DI) system.\"?\n- @PromiseIhunna honestly, that's the easy answer for those who don't know how Typescript and metadata reflection works. I'll be working on adding an advanced page to the docs that kind of get more into the meat of what the decorators really do.\n- @JayMcDoniel I think I understand now, please let me know when that is ready, thanks.\n- @Jay McDoniel I think this \"Decorator that marks a class as a provider. Providers can be injected into other classes via constructor parameter injection using Nest's built-in Dependency Injection (DI) system.\" misguides the readers since it gives a totally different meaning.\n- If A is used by B ( A -> B). `@Injectable` according to this text, should be applied to A. Then it makes A \"injectable\" into B. But in reality, `@Injectble` to be applied to B to allow the DI container to detect it should resolve an instance of A to provide to B.\n- This answer is not correct. PersonService does not need the @Injectable annotation in the example.\n- This answer is wrong, @Injectable is only use if your class depends on other providers. It is used so that nestjs can build the dependencies tree in run-time","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":195,"estimatedTokens":1267}}154{"id":"stack-55538055","source":"stackoverflow","questionId":55538055,"title":"where to find all the exception classes in AWS-SDK for dynamodb in NodeJS typescript?","tags":["javascript","node.js","error-handling","amazon-dynamodb","nestjs"],"text":"Title: where to find all the exception classes in AWS-SDK for dynamodb in NodeJS typescript?\nTags: javascript, node.js, error-handling, amazon-dynamodb, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to insert some data into dynamodb, and as expected I am getting a `ConditionalCheckFailedException`. So I am trying to catch that exception for only that scenario, apart from that I want to throw server error for all other errors.\nBut to add the type, I am not able to find the `ConditionalCheckFailedException` in aws-sdk.\n\nThis is what I was trying to do.\n\n```\n// where to import this from \ntry {\n await AWS.putItem(params).promise()\n} catch (e) {\n if (e instanceof ConditionalCheckFailedException) { // unable to find this exception type in AWS SDK\n throw new Error('create error')\n } else {\n throw new Error('server error')\n }\n}\n```\n\n========================================\n\nTop Answer:\nWhen you are using aws-sdk v3 the error does not have a property `code`. Instead, you want to check `error.name`.\n\nFor example:\n\n```\nimport { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';\n\nconst key = 'myKey.json';\nconst s3Client = new S3Client({});\nconst command = new GetObjectCommand({\n Bucket: 'bucketName',\n Key: key\n});\n\ntry {\n const response = await s3Client.send(command);\n} catch (error) {\n if (error.name === 'NoSuchKey') {\n console.warning(`My key=\"${key}\" was not found.`);\n } else {\n throw error;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// where to import this from   \ntry {\n   await AWS.putItem(params).promise()\n} catch (e) {\n  if (e instanceof ConditionalCheckFailedException) { // unable to find this exception type in AWS SDK\n    throw new Error('create error')\n  } else {\n    throw new Error('server error')\n  }\n}\n```\n\n```text\nConditionalCheckFailedException\n```\n\n```text\nConditionalCheckFailedException\n```\n\n```text\nif (e.name === 'ConditionalCheckFailedException') {\n```\n\n```text\nif (e.code === 'ConditionalCheckFailedException') {\n```\n\n```text\nname\n```\n\n```text\ninstanceof\n```\n\n```text\nerr.code\n```\n\n```js\nimport { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';\n\nconst key = 'myKey.json';\nconst s3Client = new S3Client({});\nconst command = new GetObjectCommand({\n    Bucket: 'bucketName',\n    Key: key\n});\n\ntry {\n    const response = await s3Client.send(command);\n} catch (error) {\n    if (error.name === 'NoSuchKey') {\n        console.warning(`My key=\"${key}\" was not found.`);\n    } else {\n        throw error;\n    }\n}\n```\n\n```text\ncode\n```\n\n```text\nerror.name\n```\n\n```text\nimport {\n  InvalidSignatureException,\n  ResourceNotFoundException,\n  FooServiceException,\n} from \"@aws-sdk/client-foo\";\n\ntry {\n  await client.send(someCommand);\n} catch (e) {\n  if (e instanceof InvalidSignatureException) {\n    // Handle InvalidSignatureException\n  } else if (e instanceof ResourceNotFoundException) {\n    // Handle ResourceNotFoundException\n  } else if (e instanceof FooServiceException) {\n    // Handle all other server-side exceptions from Foo service\n  } else {\n    // Other errors\n  }\n}\n```\n\n========================================\n\nComments:\n- From the aws docs this looks like java exceptions not javascript, and it would be nice to have the link to the docs to see all exception names if possible","metadata":{"transformedAt":"2026-08-18T18:33:02.415Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":150,"estimatedTokens":816}}155{"id":"stack-53504621","source":"stackoverflow","questionId":53504621,"title":"How to return PDF file from controller","tags":["javascript","node.js","nestjs"],"text":"Title: How to return PDF file from controller\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to return a PDF file from a Controller Endpoint using NestJs. When not setting the `Content-type` header, the data returned by `getDocumentFile` gets returned to the user just fine. When I add the header however, the return I get seems to be some strange form of a GUID, the response always looks like this: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where `x` is a lowercase hexadecimal character. It also seems to be totally unrelated to the actual return value of the handler function, as I even get this strange GUID-thing when not returning anything at all.\n\nWhen not setting `Content-type: application/pdf`, the function returns the data of the buffer just fine, however I need to set the header in order to get the browser to recognize the response as a PDF file which is important for my use case.\n\nThe controller looks like this:\n\n```\n@Controller('documents')\nexport class DocumentsController {\n constructor(private documentsService: DocumentsService) {}\n\n @Get(':id/file')\n @Header('Content-type', 'application/pdf')\n async getDocumentFile(@Param('id') id: string): Promise {\n const document = await this.documentsService.byId(id)\n const pdf = await this.documentsService.getFile(document)\n\n // using ReadableStreamBuffer as suggested by contributor\n const stream = new ReadableStreamBuffer({\n frequency: 10,\n chunkSize: 2048,\n })\n stream.put(pdf)\n return stream\n }\n}\n```\n\nand my DocumentsService like this:\n\n```\n@Injectable()\nexport class DocumentsService {\n async getAll(): Promise> {\n return DocumentModel.find({})\n }\n\n async byId(id: string): Promise {\n return DocumentModel.findOne({ _id: id })\n }\n\n async getFile(document: DocumentDocument): Promise {\n const filename = document.filename\n const filepath = path.join(__dirname, '..', '..', '..', '..', '..', 'pdf-generator', 'dist', filename)\n\n const pdf = await new Promise((resolve, reject) => {\n fs.readFile(filepath, {}, (err, data) => {\n if (err) reject(err)\n else resolve(data)\n })\n })\n return pdf\n }\n}\n```\n\nI originally just returned the buffer (`return pdf`), but that brought the same result as the attempt above. On the repository of NestJs a user suggested to use the above method, which obviously does not work for me either. See the GitHub thread here.\n\n========================================\n\nTop Answer:\nYou can just use ready decorator @Res this is my working solution:\n\nController(NestJs):\n\n```\nasync getNewsPdfById(@Param() getNewsParams: GetNewsPdfParams, @Req() request: Request, @Res() response: Response): Promise {\n const stream = await this.newsService.getNewsPdfById(getNewsParams.newsId, request.user.ownerId);\n\n response.set({\n 'Content-Type': 'image/pdf',\n });\n\n stream.pipe(response);\n}\n```\n\nIn my case stream variable is just ready stream created by html-pdf library because i create pdf by html https://www.npmjs.com/package/html-pdf but it doesnt matter how you create your stream. The thing is that you should use @Res decorator and pipe it because its native NestJs solution.\n\nAlso here is code how to claim file on client side:\nhttps://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743\n\nAnyway lets try this one in your case:\n\n```\n@Controller('documents')\nexport class DocumentsController {\n constructor(private documentsService: DocumentsService) {}\n\n @Get(':id/file')\n async getDocumentFile(@Param('id') id: string, @Res res: Response): Promise {\n const document = await this.documentsService.byId(id)\n const pdf = await this.documentsService.getFile(document)\n\n const stream = new ReadableStreamBuffer({\n frequency: 10,\n chunkSize: 2048,\n })\n\n res.set({\n 'Content-Type': 'image/pdf',\n });\n\n stream.pipe(res);\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Controller('documents')\nexport class DocumentsController {\n  constructor(private documentsService: DocumentsService) {}\n\n  @Get(':id/file')\n  @Header('Content-type', 'application/pdf')\n  async getDocumentFile(@Param('id') id: string): Promise<Buffer> {\n    const document = await this.documentsService.byId(id)\n    const pdf = await this.documentsService.getFile(document)\n\n    // using ReadableStreamBuffer as suggested by contributor\n    const stream = new ReadableStreamBuffer({\n      frequency: 10,\n      chunkSize: 2048,\n    })\n    stream.put(pdf)\n    return stream\n  }\n}\n```\n\n```text\n@Injectable()\nexport class DocumentsService {\n  async getAll(): Promise<Array<DocumentDocument>> {\n    return DocumentModel.find({})\n  }\n\n  async byId(id: string): Promise<DocumentDocument> {\n    return DocumentModel.findOne({ _id: id })\n  }\n\n  async getFile(document: DocumentDocument): Promise<Buffer> {\n    const filename = document.filename\n    const filepath = path.join(__dirname, '..', '..', '..', '..', '..', 'pdf-generator', 'dist', filename)\n\n    const pdf = await new Promise<Buffer>((resolve, reject) => {\n      fs.readFile(filepath, {}, (err, data) => {\n        if (err) reject(err)\n        else resolve(data)\n      })\n    })\n    return pdf\n  }\n}\n```\n\n```text\nContent-type\n```\n\n```text\ngetDocumentFile\n```\n\n```text\nxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n```\n\n```text\nx\n```\n\n```text\nContent-type: application/pdf\n```\n\n```text\nreturn pdf\n```\n\n```text\nimport { Controller, Get, StreamableFile } from '@nestjs/common';\nimport { createReadStream } from 'fs';\nimport { join } from 'path';\n\n@Controller('file')\nexport class FileController {\n  @Get()\n  getFile(): StreamableFile {\n    const file = createReadStream(join(process.cwd(), 'package.json'));\n    return new StreamableFile(file);\n  }\n}\n```\n\n```text\nStreamableFile\n```\n\n```text\n@Get('pdf')\n@HttpCode(HttpStatus.OK)\n@Header('Content-Type', 'application/pdf')\n@Header('Content-Disposition', 'attachment; filename=test.pdf')\npdf() {\n    return createReadStream('./nodejs.pdf');\n}\n```\n\n```text\nStream\n```\n\n```text\nreadFile\n```\n\n```js\n@Get('pdf')\n  @HttpCode(201)\n  @Header('Content-Type', 'image/pdf')\n  @Header('Content-Disposition', 'attachment; filename=test.pdf')\n  public pdf() {\n    return fs.createReadStream('./test.pdf');\n  }\n```\n\n```text\nasync getNewsPdfById(@Param() getNewsParams: GetNewsPdfParams, @Req() request: Request, @Res() response: Response): Promise<void> {\n  const stream = await this.newsService.getNewsPdfById(getNewsParams.newsId, request.user.ownerId);\n\n  response.set({\n    'Content-Type': 'image/pdf',\n  });\n\n  stream.pipe(response);\n}\n```\n\n```text\n@Controller('documents')\nexport class DocumentsController {\n  constructor(private documentsService: DocumentsService) {}\n\n  @Get(':id/file')\n  async getDocumentFile(@Param('id') id: string, @Res res: Response): Promise<Buffer> {\n    const document = await this.documentsService.byId(id)\n    const pdf = await this.documentsService.getFile(document)\n\n\n    const stream = new ReadableStreamBuffer({\n      frequency: 10,\n      chunkSize: 2048,\n    })\n\n    res.set({\n      'Content-Type': 'image/pdf',\n    });\n\n    stream.pipe(res);\n  }\n}\n```\n\n```text\n@Get()\n  download(@Res() res) {\n    const filename = '123.pdf';\n    // make it to be inline other than downloading\n    // res.setHeader('Content-disposition', 'inline; filename=' + filename);\n    res.setHeader('Content-disposition', 'attachment; filename=' + filename);\n    const filestream = createReadStream('files/' + filename);\n    filestream.pipe(res);\n  }\n```\n\n```text\n@Get('openPdf/:filename')\n  async openPdf(\n    @Param('filename') filename: string,\n    @Response({ passthrough: true }) res: Res,\n  ):Promise<StreamableFile> {\n    try {\n     \n      //if your pdf or file is other directory add this process.cwd()+'/parentfolder/childfolder' or else leave at it is like below\n      const readableStream = fs.createReadStream(join(process.cwd(),`${filename}.pdf` ));\n     //set application type as you need json,pdf etc\n      res.set({\n        'Content-Type': 'application/pdf',\n        'Content-Disposition': `attachment; filename=${filename}.pdf`\n      })\n        // return readableStream.pipe(res)\n      const streamdata= new StreamableFile(readableStream)\n      return streamdata\n    } catch (error) {\n      return error.message\n    }\n  }\n```\n\n========================================\n\nComments:\n- There is no error, but, as I described above, I don't get the PDF data as a return but a seemingly random GUID (which is different on every request, btw). No error message whatsoever, just not the result I want, obviously\n- did you find a solution?\n- Unfortunately not. Are you having the same problem?\n- not similar but i couldn't manage to download file from a React App using axios. All i'm getting is empty blob data or this output ``\n- I copied your exact code (and replaced the filename, obviously) but the result is still the same... which version of Nest are you using?\n- i had to add `.pipe(response)` on the created read stream for it to work (and remove the `Content-Disposition` header)\n- Doesn't works for me, I create a pdf using html-pdf like a buffer (even as a stream), with header *content-type application/pdf* the response is empty, but when I only set *content-disposition* works fine...\n- The problem was Postman, with Insomia or other clients rest finally I can view response and download pdf succes\n- Won't this lead to a download of the file? What I originally wanted was to display the pdf in the browser\n- Try to replace the `attachment` into `inline`. developer.mozilla.org/en-US/docs/Web/HTTP/Headers/&hellip;\n- Nicely done. This covers the easy use of @Res and setting headers in the response, however I needed to use res.headers.set. Otherwise Beautiful! Combine this with the next post with the file attachment and it's perfect.\n- Here's the missing part. Response needs to be imported from \"express.js\" and not \"@nestjs/common\". Also, then use res.type() and res.attachment().\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":324,"estimatedTokens":2521}}156{"id":"stack-59741255","source":"stackoverflow","questionId":59741255,"title":"How can I see console.log output when running a NestJS app?","tags":["visual-studio-code","nestjs"],"text":"Title: How can I see console.log output when running a NestJS app?\nTags: visual-studio-code, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm building my first NestJS app and I see a lot of examples in their docs that use console.log(), but when I add it, there's no output in the terminal. I'm using vscode's terminal.\n\nI've also tried using the built-in Logger and start the app using npm run start:debug, and I see no output from the Logger either. I know that it's reaching my controller because I'm getting a response. Does anyone know what the issue could be?\n\n========================================\n\nTop Answer:\nyou better use Logger instead of console.\n\n```\nimport { Logger } from '@nestjs/common';\n\nLogger.log('info')\nLogger.warn('warning')\nLogger.error('something went wrong! ', error)\n```\n\n========================================\n\nCode:\n```text\nnpm run start:dev\n```\n\n```text\nimport { Logger } from '@nestjs/common';\n\nLogger.log('info')\nLogger.warn('warning')\nLogger.error('something went wrong! ', error)\n```\n\n```text\n\"terminal.integrated.profiles.linux\": \n    {\n      \"bash\": {\n          \"path\": \"bash\",\n          \"icon\": \"terminal-bash\",\n          \"color\": \"terminal.ansiGreen\",\n          \"overrideName\": true\n      },\n    .\n    .\n    .\n    }\n```\n\n```text\n\"terminal.integrated.profiles.linux\": \n    {\n      \"bash\": {\n          \"path\": [\"/bin/bash\", \"bash\"],\n          \"icon\": \"terminal-bash\",\n          \"color\": \"terminal.ansiGreen\",\n          \"overrideName\": true\n      },\n    .\n    .\n    .\n    }\n```\n\n```text\nsettings.json\n```\n\n```text\n\"/bin/bash\"\n```\n\n```text\n\"path\"\n```\n\n```text\n/dist\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nconsole.log\n```\n\n```text\nthis.logger.log\n```\n\n========================================\n\nComments:\n- What are you using to start the application? Are you piping your output into some file?\n- No piping. Was assuming that the output would go to the terminal, no?\n- How are you starting the application? What is the full command?\n- I've tried npm run start, npm run start:debug\n- Do you see the normal Nest startup logs? Are you on the `Terminal` tab of the VSCode terminal? You run the scripts through a command line and not a UI, right? There's so many possibilities I'm not sure what else to ask\n- Yes, I do all of this with vscode. Open the nest app folder, open terminal, type 'npm run start', open postman and make a request to my controller, request returns the expected value, but console.log('test') not printing on the terminal tab. I clicked on Output tab, Debug tab, and terminal. No console log\n- The only thing I can think of is that the server process that's running is not processing stdout\n- Let us continue this discussion in chat.\n- OP clearly says \"I've also tried using the built-in Logger and start the app using npm run start:debug, and I see no output from the Logger either\"\n- I'm upvoting cause it solved my problem\n- I thought I was getting crazy because none of my consoles worked, but that fixed it, thx","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":109,"estimatedTokens":744}}157{"id":"stack-62629344","source":"stackoverflow","questionId":62629344,"title":"What's the best way to do stuff when Nestjs application loads?","tags":["nestjs"],"text":"Title: What's the best way to do stuff when Nestjs application loads?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen my Nest.js application loads, i need to run some database operations. (mainly around data initialization). All these tasks are already built and working as actions in controllers. If i go manually to /api/controller/action - they work. I need a way to call each one of them when the server loads up. Any advice?\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class WarmupService implements OnApplicationBootstrap {\n    constructor(\n        private readonly db: Db\n    )\n\n    onApplicationBootstrap() {\n        this.db.doDataInitialization();\n    }\n}\n```\n\n```text\nAppModule\n```\n\n```text\nmain.ts\n```\n\n```text\napp.listen(..)\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":34,"estimatedTokens":195}}158{"id":"stack-65721426","source":"stackoverflow","questionId":65721426,"title":"TypeScript export was not found","tags":["typescript","nestjs"],"text":"Title: TypeScript export was not found\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nsince i updated the angular cli and nestjs versions I am getting hundreds of warnings that my custom type definitions and interfaces can not be found. But my nestjs api still works fine.\n\ni am exporting my interface like this\n\n```\nexport interface Role {...}\n```\n\nand getting this warning\n\n```\nWARNING in ./apps/api/src/app/users/dto/update-user.dto.ts 31:75-80\n\"export 'Role' was not found in '@project/api-datatypes'\n```\n\nmy import looks like this\n\n```\nimport { Role } from '@project/api-datatypes';\n```\n\nwhat was changed in the latest version and what do I have to do to fix those warnings?\n\ncurrently i am running the following versions:\n\n```\nโ”œโ”€โ”€ @angular/cli@11.0.6\nโ”œโ”€โ”€ @nestjs/cli@7.5.1\nโ”œโ”€โ”€ npm@6.14.4\nโ”œโ”€โ”€ nx@10.3.0\nโ””โ”€โ”€ typescript@4.0.3\n```\n\n========================================\n\nCode:\n```text\nexport interface Role {...}\n```\n\n```text\nWARNING in ./apps/api/src/app/users/dto/update-user.dto.ts 31:75-80\n\"export 'Role' was not found in '@project/api-datatypes'\n```\n\n```text\nimport { Role } from '@project/api-datatypes';\n```\n\n```text\nโ”œโ”€โ”€ @angular/cli@11.0.6\nโ”œโ”€โ”€ @nestjs/cli@7.5.1\nโ”œโ”€โ”€ npm@6.14.4\nโ”œโ”€โ”€ nx@10.3.0\nโ””โ”€โ”€ typescript@4.0.3\n```\n\n```text\nimport type { Role } from '@project/api-datatypes';\n```\n\n```text\n\"type\"\n```\n\n========================================\n\nComments:\n- FWIW, the export and import are both written correctly, so this will be a tool config or path issue.\n- thanks @T.J.Crowder but the only thing i have changed was the nestjscli and angularcli version\n- my index.ts from my library looks like this export * from './role.interface';\n- it s possible you have wrong path on project, try to add full path without project","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":436}}159{"id":"stack-60024855","source":"stackoverflow","questionId":60024855,"title":"TypeScript - \"not assignable to type never\" error on Entity in Jest's mockResolvedValueOnce method","tags":["typescript","jestjs","nestjs"],"text":"Title: TypeScript - \"not assignable to type never\" error on Entity in Jest's mockResolvedValueOnce method\nTags: typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've seen this error being solved in primitive types but I am not sure how I would solve it in this example\n\n```\nconst newUser: UserEntity = {\n user_id: 'f3bea6de-fb24-4441-b75b-d7642ca573d7',\n name: 'Test User',\n };\n\njest.spyOn(repo, 'create').mockResolvedValueOnce([newUser]); // error here on [newUser] - 'UserEntity' is not assignable to type 'never'\n```\n\nuser.entity.ts\n\n```\n@Entity('users')\nexport class UserEntity {\n @PrimaryGeneratedColumn('uuid') user_id: string;\n @Column('text') name: string;\n}\n```\n\n========================================\n\nTop Answer:\nIf you're positive that the `repo.create` is asynchronous then you can use `mockImplementation(()=> Promise.resolve([newUser]))` to navigate that problem. Sometime that's happening because the mocked fn has both callback and promise version and the callback version shadows the promise one\n\n========================================\n\nCode:\n```text\nconst newUser: UserEntity = {\n      user_id: 'f3bea6de-fb24-4441-b75b-d7642ca573d7',\n      name: 'Test User',\n    };\n\njest.spyOn(repo, 'create').mockResolvedValueOnce([newUser]); // error here on [newUser] - 'UserEntity' is not assignable to type 'never'\n```\n\n```text\n@Entity('users')\nexport class UserEntity {\n  @PrimaryGeneratedColumn('uuid') user_id: string;\n  @Column('text') name: string;\n}\n```\n\n```text\nrepo.create\n```\n\n```text\nmockResolvedValue\n```\n\n```text\npromise\n```\n\n```text\nmockReturnValueOnce\n```\n\n```text\nmockReturnValueOnce\n```\n\n```text\nmockReturnValue\n```\n\n```text\njest.spyOn(repo, 'create').mockReturnValueOnce([newUser]);\n```\n\n```text\nrepo.create\n```\n\n```text\nmockImplementation(()=> Promise.resolve([newUser]))\n```\n\n========================================\n\nComments:\n- Well, in the tutorial i'm watching it uses `mockResolvedValue` but it gives me problem with the mocked `MongoRepository`.\n- `repo.create` is not specified in the original question so how did you know that it's synchronous. Changing it to `mockReturnValue` might real remove the error but I don't think that's the proper answer. I have scenario where that's happening on asynch fn\n- @kasongoyo I was only able to make the assumption it was synchronous due to A) the error that `mockResolvedValue` made Typescript error about a `never` return type and B) my knowledge of TypeORM and knowing that `create` only instantiates the entity class, it's `save` that is the async method.\n- Got it! I have added an extension to your answer that cover another scenario that's asynchronous. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":94,"estimatedTokens":665}}160{"id":"stack-57629191","source":"stackoverflow","questionId":57629191,"title":"NestJS mock JWT authentication in e2e tests","tags":["typescript","unit-testing","authentication","mocking","nestjs"],"text":"Title: NestJS mock JWT authentication in e2e tests\nTags: typescript, unit-testing, authentication, mocking, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to mock JWT Authentication in my NestJS e2e (integration) tests. I use injected token data in my business logic, and I don't want to insert credentials on my test code.\n\nI implemented JWT authentication as per the Nest authentication docs. I use a decorator (similar) to the `@User` decorator in the examples, and use information on the User object in my business logic.\n\n```\n@Post()\nasync myPostEndpoint(@Body() body: PostBody, @User() user: MyUser){\n // do stuff using user properties\n}\n```\n\nWhen testing my application using supertest as indicated in the Nest testing docs, I don't want to make a real authentication request, as I would need to persist credentials in my version control system.\n\nI expected to be able to override providers to return a test user. But couldn't figure it out. \n\nI tried overriding the `AuthService`'s `validateClient` and `login` to return a default user using `overrideProvider + useClass/useFactory/useValue` as indicated in the Nest testing docs. I also tried overriding methods in `JwtStrategy` and `LocalStrategy`, but the requests still return 401 - Unauthorized.\n\n========================================\n\nTop Answer:\nFor people using GraphQL, this is what I did:\n\n```\nconst module: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n })\n .overrideGuard(JwtAuthGuard)\n .useValue({\n canActivate: (context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context)\n ctx.getContext().req.user = { user_id: \"abc123\" } // Your user object\n return true\n },\n })\n .compile()\n```\n\n========================================\n\nCode:\n```js\n@Post()\nasync myPostEndpoint(@Body() body: PostBody, @User() user: MyUser){\n    // do stuff using user properties\n}\n```\n\n```text\n@User\n```\n\n```text\nAuthService\n```\n\n```text\nvalidateClient\n```\n\n```text\nlogin\n```\n\n```text\noverrideProvider + useClass/useFactory/useValue\n```\n\n```text\nJwtStrategy\n```\n\n```text\nLocalStrategy\n```\n\n```text\ncanActivate (context: ExecutionContext) => {\n  const req = context.switchToHttp().getRequest();\n  req.user = myCustomUserObject;\n  return true;\n}\n```\n\n```text\noverrideGuard(AuthGuard('jwt')).useValue()\n```\n\n```text\ncanActivate()\n```\n\n```text\nmyCustomUserObject\n```\n\n```text\nreq.user\n```\n\n```js\nconst module: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    })\n      .overrideGuard(JwtAuthGuard)\n      .useValue({\n        canActivate: (context: ExecutionContext) => {\n          const ctx = GqlExecutionContext.create(context)\n          ctx.getContext().req.user = { user_id: \"abc123\" } // Your user object\n          return true\n        },\n      })\n      .compile()\n```\n\n```text\njest.mock('jsonwebtoken', () => ({\n  verify: jest.fn((token, secretOrKey, options, callback) => {\n    callback(null, {\n      payload: {\n        email: 'any@email.com',\n        sub: 1,\n      },\n      header: 'header',\n      signature: 'signature',\n    });\n  }),\n}));\n```\n\n========================================\n\nComments:\n- Might this help? stackoverflow.com/questions/53267536/testing-passport-in-nes&zwnj;&#8203;tjs\n- Unfortunately, the implementation in the accepted answer does not mock the user. Instead it does a real authentication request `.post('&#47;auth&#47;login')`, as I would like to avoid, since I would need to put credentials in my test code.\n- I think I added a `process.env.NODE_ENV` check in my auth code to handle the situation.\n- Hey Jey, I'm tried your answer, but I got \"Cannot set property 'user' of undefined\". The \"req\" value is undefined ... :(\n- I did the same, didn't get any error like @MirceaBaicu stated, but the next guard which registered on that API doesn't detect property *user* on req, hence forbidden. Any clue why?\n- Why not use a test user and crate a JWT, I thought e2e tests should be close to the real application\n- Technically, that would be the better option @MADforFUNandHappy, but as the question was specifically about mocking the guard, I figured I'd answer with that.\n- Thank you so much, I was trying to mock the `AuthGuard` itself and it never worked.","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":145,"estimatedTokens":1052}}161{"id":"stack-67327201","source":"stackoverflow","questionId":67327201,"title":"what is jwks? what actully does jwks with refresh and access tokens?","tags":["node.js","authentication","oauth","jwt","nestjs"],"text":"Title: what is jwks? what actully does jwks with refresh and access tokens?\nTags: node.js, authentication, oauth, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\ni am working on an authentication system that has access and refresh tokens and **JWT** and **JWKS**. my problem is that i don't know what is the functionality of **JWKS**. what is the functionality of **JWKS** in a authentication system that is working with **JWT** and refresh token and access token? what are public and private keys in this system? does JWKS need to connect to database?\n\n========================================\n\nCode:\n```text\nJWKS\n```\n\n```text\nJWKS endpoint\n```\n\n```text\nJWKS\n```\n\n```text\nJWKS endpoint\n```\n\n```text\nJWKS endpoint\n```\n\n```text\nJWKS endpoint\n```\n\n```text\nJWKS\n```\n\n========================================\n\nComments:\n- Linked course is a login-gated resource.","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":42,"estimatedTokens":214}}162{"id":"stack-63427319","source":"stackoverflow","questionId":63427319,"title":"How can I validate an array of enum values with Nestjs","tags":["nestjs","dto"],"text":"Title: How can I validate an array of enum values with Nestjs\nTags: nestjs, dto\nSource: Stack Overflow\n\nQuestion:\nI feel like a combination of this thread and this thread is what I need to implement, I'm having trouble drawing them together.\n\nI have a DTO that contains an `enum`.\n\nUsing Postman, I am sending a `PurchasableType` of `FOO` and expecting to get an error of some sort. Reading through the above links, it seems like the process is quite involved; which makes me thing I'm completely missing the point.\n\nHow can I use the validation pipe(s) to make sure only the values in the `purchasable-type.enum.ts` are allowed?\n\nThank you for any suggestions!\n\n```\n// create-order.dto.ts\n\nimport { IsEmail, IsNotEmpty, IsEnum } from 'class-validator';\nimport { PurchasableType } from '../enum/purchaseable-type.enum';\n\nexport class CreateOrderDto {\n @IsNotEmpty()\n readonly userId: string;\n\n @IsNotEmpty()\n readonly locationId: string;\n\n @IsNotEmpty()\n @IsEnum(PurchasableType)\n readonly purchasableType: PurchasableType;\n\n @IsNotEmpty()\n @IsEmail()\n readonly email: string;\n}\n```\n\n```\n// purchasable-type.enum.ts\n\nexport enum PurchasableType {\n CLINIC = 'CLINIC',\n EVENT = 'EVENT',\n LESSON = 'LESSON',\n RESERVATION = 'RESERVATION',\n TEAM = 'TEAM',\n}\n```\n\n**EDIT**\n\nIt seems I was also not defining the entity correctly, and that may have been the main issue. I am still curious if my implementation good/bad.\n\n```\n// order.entity.ts\n\n...\nimport { PurchasableType } from '../enum/purchaseable-type.enum';\n\n@Entity()\nexport class Order extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n@Column({\n type: 'enum',\n enum: PurchasableType,\n })\n```\n\nNow when I send a `purchasableType` of `foo` I am getting a 500 error. If I send any valid value that is within the `enum` I am getting a 200/201.\n\n**EDIT 2**\n\nSure - here is a bit wider view of what I've got. Everything *seems* to be working properly, I'd just like to have a better grasp of what was really happening.\n\n```\n// event.controller.ts\n\n@Post('/:id/orders')\n async purchaseEventTickets(@Body() createOrderDto: CreateOrderDto): \n Promise {\n return await this.eventService.purchaseEventTickets(createOrderDto);\n }\n```\n\n```\n// create-order.dto.ts\n\nexport class CreateOrderDto {\n @IsNotEmpty()\n @IsEnum(PurchasableType)\n readonly purchasableType: PurchasableType;\n}\n```\n\n```\n// event.service.ts\n\nasync purchaseEventTickets(createOrderDto: CreateOrderDto): Promise {\n ...\n return await this.orderRepository.createOrder(createOrderDto);\n}\n```\n\n```\n// order.repository.ts\n\nasync createOrder(createOrderDto: CreateOrderDto): Promise {\n const { purchasableType } = createOrderDto;\n\n const order = this.create();\n\n order.purchasableType = purchasableType;\n\n try {\n await order.save();\n } catch (error) {\n this.logger.error(`Failed to create the order: ${error.stack}`);\n\n throw new InternalServerErrorException();\n }\n\n return order;\n}\n```\n\nUsing Postman, if I send an invalid value of \"Foo\" as a `PurchasableType` I get the expected error.\n\n========================================\n\nTop Answer:\nIt took me a while to find a good solution.\n\n```\n@ApiProperty({\n description: 'List of enums',\n isArray: true,\n enum: MyEnum\n})\n@IsEnum(MyEnum, { each: true })\nprop: MyEnum[];\n```\n\n========================================\n\nCode:\n```js\n// create-order.dto.ts\n\nimport { IsEmail, IsNotEmpty, IsEnum } from 'class-validator';\nimport { PurchasableType } from '../enum/purchaseable-type.enum';\n\nexport class CreateOrderDto {\n  @IsNotEmpty()\n  readonly userId: string;\n\n  @IsNotEmpty()\n  readonly locationId: string;\n\n  @IsNotEmpty()\n  @IsEnum(PurchasableType)\n  readonly purchasableType: PurchasableType;\n\n  @IsNotEmpty()\n  @IsEmail()\n  readonly email: string;\n}\n```\n\n```js\n// purchasable-type.enum.ts\n\nexport enum PurchasableType {\n  CLINIC = 'CLINIC',\n  EVENT = 'EVENT',\n  LESSON = 'LESSON',\n  RESERVATION = 'RESERVATION',\n  TEAM = 'TEAM',\n}\n```\n\n```js\n// order.entity.ts\n\n...\nimport { PurchasableType } from '../enum/purchaseable-type.enum';\n\n@Entity()\nexport class Order extends BaseEntity {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n@Column({\n    type: 'enum',\n    enum: PurchasableType,\n  })\n```\n\n```text\n// event.controller.ts\n\n@Post('/:id/orders')\n  async purchaseEventTickets(@Body() createOrderDto: CreateOrderDto): \n    Promise<Order> {\n    return await this.eventService.purchaseEventTickets(createOrderDto);\n  }\n```\n\n```text\n// create-order.dto.ts\n\nexport class CreateOrderDto {\n    @IsNotEmpty()\n    @IsEnum(PurchasableType)\n    readonly purchasableType: PurchasableType;\n}\n```\n\n```text\n// event.service.ts\n\nasync purchaseEventTickets(createOrderDto: CreateOrderDto): Promise<Order> {\n    ...\n    return await this.orderRepository.createOrder(createOrderDto);\n}\n```\n\n```text\n// order.repository.ts\n\nasync createOrder(createOrderDto: CreateOrderDto): Promise<Order> {\n    const { purchasableType } = createOrderDto;\n\n    const order = this.create();\n\n    order.purchasableType = purchasableType;\n\n    try {\n        await order.save();\n    } catch (error) {\n        this.logger.error(`Failed to create the order: ${error.stack}`);\n\n        throw new InternalServerErrorException();\n    }\n\n    return order;\n}\n```\n\n```text\nenum\n```\n\n```text\nPurchasableType\n```\n\n```text\nFOO\n```\n\n```text\npurchasable-type.enum.ts\n```\n\n```text\npurchasableType\n```\n\n```text\nfoo\n```\n\n```text\nenum\n```\n\n```text\nPurchasableType\n```\n\n```text\n// create-order.dto.ts\n\nimport { IsEmail, IsNotEmpty, IsEnum } from 'class-validator';\nimport { PurchasableType } from '../enum/purchaseable-type.enum';\n\nexport class CreateOrderDto {\n\n    ...\n\n    @IsNotEmpty()\n    @IsEnum(PurchasableType)\n    readonly purchasableType: PurchasableType;\n}\n```\n\n```text\n// purchasable-type.enum.ts\n\nexport enum PurchasableType {\n  CLINIC = 'CLINIC',\n  EVENT = 'EVENT',\n  LESSON = 'LESSON',\n  RESERVATION = 'RESERVATION',\n  TEAM = 'TEAM',\n}\n```\n\n```text\nimport { PurchasableType } from '../interface/purchasable-type.interface';\n...\n\n@ApiProperty()\n@IsArray()\n@ArrayMinSize(7)\n@ArrayMaxSize(7)\n@ValidateNested({ each: true })\n@Type(() => PurchasableType)\n@IsNotEmpty()\nreadonly PurchasableType: PurchasableType[];\n\n...\n```\n\n```text\ncreate-dto\n```\n\n```text\nenum\n```\n\n```text\n@ApiProperty({\n  description: 'List of enums',\n  isArray: true,\n  enum: MyEnum\n})\n@IsEnum(MyEnum, { each: true })\nprop: MyEnum[];\n```\n\n```text\n@IsArray()\n  @IsEnum(enum, { each: true })\n  prop: enum[]\n```\n\n```text\n@IsEnum(myEnum, { each: true })\n  @Transform((value) => myEnum[value])\n  tags: myEnum[];\n```\n\n```text\n@Column({ type: 'enum', enum: MyEnum, array: true })\nmyProperty: MyEnum[];\n```\n\n```text\nenum PARAM_TYPE {\n  VENUE_NAME = 'VENUE_NAME',\n  USER_NAME = 'USER_NAME',\n}\n```\n\n```text\n@ApiPropertyOptional({\nisArray: true,\n enum: ENUM_TYPE\n})\n@IsEnum(PARAM_TYPE, { each: true })\nparams: PARAM_TYPE[];\n```\n\n========================================\n\nComments:\n- could you provide us a bit more info about the way you use the validation pipe ? To me the 500 error seems to be thrown by the ORM, not the validation pipe, which is not what you expect I guess\n- Sure! I've updated my question. I hope i've provided a bit more information. Thank you for your time to help!\n- Where is @ApiProperty impoerted from?\n- @KaranKumar good questions, that is a swagger(openapi) decorator I use for creating swagger documentation. For this questions is not relevant but it could be useful for those using openapi.\n- Thank you for your interest in contributing to the Stack Overflow community. This question already has a few answersโ€”including one that has been extensively validated by the community. Are you certain your approach hasnโ€™t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers arenโ€™t sufficient.** Can you kindly edit your answer to offer an explanation?","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":386,"estimatedTokens":1972}}163{"id":"stack-59547243","source":"stackoverflow","questionId":59547243,"title":"create DTOs, BOs and DAOs for NestJs REST API","tags":["typescript","nestjs","clean-architecture","onion-architecture"],"text":"Title: create DTOs, BOs and DAOs for NestJs REST API\nTags: typescript, nestjs, clean-architecture, onion-architecture\nSource: Stack Overflow\n\nQuestion:\nI would like to get into creating REST APIs with NestJs and I'm not sure how to setup scalable layer communication objects.\n\nSo from the docs on how to get started I come up with a `UsersController` dealing with the HTTP requests and responses, a `UsersService` dealing with the logic between the controller and the database accessor and the `UsersRepository` which is responsible for the database management.\n\nI use the TypeORM package provided by NestJs so my database model would be\n\n```\n@Entity('User')\nexport class UserEntity extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ unique: true })\n username: string;\n\n @Column()\n passwordHash: string;\n\n @Column()\n passwordSalt: string;\n}\n```\n\nbut as you might know this model has to be mapped to other models and vice versa because you don't want to send the password information back to the client. I will try to describe my API flow with a simple example:\n\n**Controllers**\n\nFirst I have a controller endpoint for `GET /users/:id` and `POST /users`.\n\n```\n@Get(':id')\n findById(@Param() findByIdParamsDTO: FindByIdParamsDTO): Promise {\n // find user by id and return it\n }\n\n @Post()\n create(@Body() createUserBodyDTO: CreateUserBodyDTO): Promise {\n // create a new user and return it\n }\n```\n\nI setup the DTOs and want to validate the request first. I use the class-validator package provided by NestJs and created a folder called **RequestDTOs**. Finding something by id or deleting something by id via url parameters is reusable so I can put this into a shared folder for other resources like groups, documents, etc.\n\n```\nexport class IdParamsDTO {\n @IsUUID()\n id: string;\n}\n```\n\nThe POST request is user specific\n\n```\nexport class CreateUserBodyDTO {\n @IsString()\n @IsNotEmpty()\n username: string;\n\n @IsString()\n @IsNotEmpty()\n password: string;\n}\n```\n\nNow the controller input gets validated before executing business logic. For the responses I created a folder called **ResponseDTOs** but currently it only contains the database user without its password information\n\n```\nexport interface UserDTO {\n id: string;\n username: string;\n}\n```\n\n**Services**\n\nThe service needs the bundled information from the params and the body.\n\n```\npublic async findById(findByIdBO: FindByIdBO): Promise {\n // ...\n }\n\n public async create(createBO: CreateBO): Promise {\n // ...\n }\n```\n\nThe GET request only needs the ID, but maybe it's still better to create a BO because you might want to switch from string IDs to integers later. The \"find by id\" BO is reusable, I moved it to the shared directory\n\n```\nexport interface IdBO {\n id: string;\n}\n```\n\nFor the user creation I created the folder **RequestBOs**\n\n```\nexport interface CreateBO {\n username: string;\n password: string;\n}\n```\n\nNow for the **ResponseBOs** the result would be\n\n```\nexport interface UserBO {\n id: string;\n username: string;\n}\n```\n\nand as you will notice this is the same like the **UserDTO**. So one of them seems to be redundant?\n\n**Repositories**\n\nLastly I setup the DAOs for the repositories. I could use the auto-generated user repository and would deal with my database model I mentioned above. But then I would have to deal with it within my service business logic. When creating a user I would have to do it within the service and only call the `usermodel.save` function from the repository.\n\nOtherwise I could create **RequestDAOs**\n\nThe shared one..\n\n```\nexport interface IdDAO {\n id: string;\n}\n```\n\nAnd the POST DAO\n\n```\nexport interface CreateDAO {\n username: string;\n password: string;\n}\n```\n\nWith that I could create a database user within my repository and map database responses with **ResponseDAOs** but this would always be the whole database user without the password information. Seems to generate a big overhead again.\n\nI would like to know if my approach using 3 request and 3 response interfaces is way too much and can be simplified. But I would like to keep a flexible layer because I think those layers should be highly independent... On the other hand there would be a huge amount of models out there.\n\nThanks in advance!\n\n========================================\n\nCode:\n```text\n@Entity('User')\nexport class UserEntity extends BaseEntity {\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column({ unique: true })\n  username: string;\n\n  @Column()\n  passwordHash: string;\n\n  @Column()\n  passwordSalt: string;\n}\n```\n\n```text\n@Get(':id')\n  findById(@Param() findByIdParamsDTO: FindByIdParamsDTO): Promise<UserDTO> {\n    // find user by id and return it\n  }\n\n  @Post()\n  create(@Body() createUserBodyDTO: CreateUserBodyDTO): Promise<UserDTO> {\n    // create a new user and return it\n  }\n```\n\n```text\nexport class IdParamsDTO {\n  @IsUUID()\n  id: string;\n}\n```\n\n```text\nexport class CreateUserBodyDTO {\n  @IsString()\n  @IsNotEmpty()\n  username: string;\n\n  @IsString()\n  @IsNotEmpty()\n  password: string;\n}\n```\n\n```text\nexport interface UserDTO {\n  id: string;\n  username: string;\n}\n```\n\n```text\npublic async findById(findByIdBO: FindByIdBO): Promise<UserBO> {\n    // ...\n  }\n\n  public async create(createBO: CreateBO): Promise<UserBO> {\n    // ...\n  }\n```\n\n```text\nexport interface IdBO {\n  id: string;\n}\n```\n\n```text\nexport interface CreateBO {\n  username: string;\n  password: string;\n}\n```\n\n```text\nexport interface UserBO {\n  id: string;\n  username: string;\n}\n```\n\n```text\nexport interface IdDAO {\n  id: string;\n}\n```\n\n```text\nexport interface CreateDAO {\n  username: string;\n  password: string;\n}\n```\n\n```text\nUsersController\n```\n\n```text\nUsersService\n```\n\n```text\nUsersRepository\n```\n\n```text\nGET /users/:id\n```\n\n```text\nPOST /users\n```\n\n```text\nusermodel.save\n```\n\n```js\nexport class BaseDBObject {\n  // this will expose the _id field as a string\n  // and will change the attribute name to `id`\n  @Expose({ name: 'id' })\n  @Transform(value => value && value.toString())\n  @IsOptional()\n  // tslint:disable-next-line: variable-name\n  _id: any;\n\n  @Exclude()\n  @IsOptional()\n  // tslint:disable-next-line: variable-name\n  _v: any;\n\n  toJSON() {\n    return classToPlain(this);\n  }\n\n  toString() {\n    return JSON.stringify(this.toJSON());\n  }\n}\n```\n\n```js\n@Exclude()\nexport class User extends BaseDBObject {\n  @Expose()\n  username: string;\n\n  password: string;\n\n  constructor(partial: Partial<User> = {}) {\n    super();\n    Object.assign(this, partial);\n  }\n}\n```\n\n```js\n@Get(':id')\n@UseInterceptors(ClassSerializerInterceptor)\nasync findById(@Param('id') id: string): Promise<User> {\n  return await this.usersService.find(id);\n}\n\n@Post()\n@UseInterceptors(ClassSerializerInterceptor)\nasync create(@Body() createUserBody: CreateUserBodyDTO): Promise<User> {\n  // create a new user from the createUserDto\n  const userToCreate = new User(createUserBody);\n\n  return await this.usersService.create(userToCreate);\n}\n```\n\n```js\n@Injectable()\nexport class UsersService {\n  constructor(@InjectModel('User') private readonly userModel: Model<IUser>) { }\n\n  async create(createCatDto: User): Promise<User> {\n    const userToCreate = new User(createCatDto);\n    const createdUser = await this.userModel.create(userToCreate);\n\n    if (createdUser) {\n      return new User(createdUser.toJSON());\n    }\n  }\n\n  async findAll(): Promise<User[]> {\n    const allUsers = await this.userModel.find().exec();\n    return allUsers.map((user) => new User(user.toJSON()));\n  }\n\n  async find(_id: string): Promise<User> {\n    const foundUser = await this.userModel.findOne({ _id }).exec();\n    if (foundUser) {\n      return new User(foundUser.toJSON());\n    }\n  }\n}\n```\n\n```js\nexport interface IUser extends mongoose.Document {\n  username: string;\n\n  password: string;\n}\n```\n\n```text\n{\n    \"id\": \"5e1452f93794e82db588898e\",\n    \"username\": \"username\"\n}\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Expose\n```\n\n```text\n@Exclude\n```\n\n```text\n@Transform\n```\n\n```text\nclassToPlain\n```\n\n```text\nclass-transformer\n```\n\n```text\nNestJs\n```\n\n```text\nclassToPlain\n```\n\n```text\n_id\n```\n\n```text\nid\n```\n\n```text\n@nestjs/mongoose\n```\n\n```text\nmongoose\n```\n\n```text\nTypeORM\n```\n\n```text\n@nestjs/mongoose\n```\n\n```text\nIUser\n```\n\n```text\nModel\n```\n\n```text\nDocument\n```\n\n```text\ntypegoose\n```\n\n========================================\n\nComments:\n- Honestly I believe the 3 request/response dto's is the way to go and here's why: In theory if you had a \"UsersModule\", that module would return \"User\" models to the rest of the application BUT how that module talks to the database should be no concern to the rest of the application. It would define it's own dto's for communication to the database. That way if you decide to swap out what database users get stored in, the rest of the application remains unaffected. This creates the correct separation of concerns and is a good pattern despite the \"duplication\" of models/dto's.\n- hm yes, I was just thinking about it because I only can image a user where I need to hide the sensitive data (password). Groups for example could be returned as database models ...\n- If this is close to what you're trying to achieve, let me know and I'll try and add an example on how to do this with `TypeORM` as well\n- Great answer. However for the `interface` part, I would recommend using something like `typegoose` to not involve `mongoose.Document` interface here.\n- very nice answer @ thatkookooguy :) It would be awesome if you could expand your answer and add a TypeORM example\n- as far as I understood the sensitive data gets cut off while converting the User model to the IUser interface? while running your interceptor?\n- @ChauTran wow. that's like the missing link to make this all work perfectly! thank you for opening my eyes to this :-)\n- @Question3r sure. I'll try and provide an answer with typeORM soon :-). Basically, the class you define is the internal class, while everything sensitive is cut off when either you use the function `classToPlain` from `class-transformer` or by using the nestjs `ClassSerializerInterceptor` which calls `classToPlain` behind the scenes\n- @Thatkookooguy total off topic here but here's a blog post I wrote some times ago to demonstrate the use of Typegoose in NestJS: nartc.netlify.com/blogs/nestjs-typegoose\n- nice architecture, quick question : Do we really need to call user.toJSON to transform the response, I've tried without it and it is working fine(transformation).\n- I believe your controller code will throw an error where you are trying to create an instance of User by supplying createUserBody. User constructor expect Partial as a parameter.\n- @RollerCosta You're probably right. I added the toJSON function mostly for having the ability to do things manually whenever needed (keeping some attributes from leaving a certain function). In normal controller transformations, it's probably not needed. About the error, I'll test it and check. I already changed the code in my codebase quite a bit and worked with it for a couple of months, so maybe something was fixed or got missed. I'll check the code snippet soonish and fix the problem or update the code. Thanks for the comments!\n- @Thatkookooguy appreciate your response. I'm new to this nodejs (nestjs + typorm ). Having some difficulties finding the best approach to design the entire framework. More related to dependency injection (should be inject multiple repositories inside one service or inject multiple services inside one service and resolve those dependencies at module level) . I can explain this in details but we need a platform to discuss them, could you help ?","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":42,"totalLines":466,"estimatedTokens":2907}}164{"id":"stack-61483803","source":"stackoverflow","questionId":61483803,"title":"What is the difference between `isomorphic-fetch` and `isomorphic-unfetch` npm packages","tags":["node.js","reactjs","next.js","nestjs","server-side-rendering"],"text":"Title: What is the difference between `isomorphic-fetch` and `isomorphic-unfetch` npm packages\nTags: node.js, reactjs, next.js, nestjs, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI see both are used for SSR. So what's the difference? Apart from isomorphic-fetch being older and slightly larger gzipped package. \n\nLinks:\n\nIsomorphic Unfetch\n\nIsomorphic Fetch\n\n========================================\n\nComments:\n- It's useful to either include links or at least the *names* in the body of the question. I cannot copy the names easily from the title, in order to check out what those even are, since the title is a clickable link.\n- The main difference is that they appear to be written by two different people\n- @VLAZ added links.\n- Neither of these comments were useful.","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":20,"estimatedTokens":196}}165{"id":"stack-59397687","source":"stackoverflow","questionId":59397687,"title":"What is the purpose of a Data Transfer Object in NestJS?","tags":["typescript","nestjs","dto","data-transfer-objects"],"text":"Title: What is the purpose of a Data Transfer Object in NestJS?\nTags: typescript, nestjs, dto, data-transfer-objects\nSource: Stack Overflow\n\nQuestion:\nIm struggling with a problem. Im following the documentation of NestJS. The back-end framework for NodeJS. The documentation mentions a DTO (Data Transfer Object). I created a DTO for creating a user:\n\n```\nexport class CreateUserDto {\n readonly email: string;\n readonly password: string;\n}\n```\n\nIn combination with this:\n\n```\n@Post('create')\ncreateUser(@Body() userData: CreateUserDto): User {\n return this.usersService.createUser(userData);\n}\n```\n\nFor some reason, I am able to make a post request to this route with any type of body. I can place any type of information in the body without getting an error. The whole point of such a DTO is to allow only certain information in the body, right? Instead of using export class CreateUserDTO i also tried export interface CreateUserDTO, but this isn't working either. I am new to typescript and NestJS as well. Is there anyone who might be able to explain why it's not working the way I expected or what the purpose is of such a Data Transfer Object?\n\n========================================\n\nTop Answer:\nAt runtime all types are lost, so the controller accepts whatever JSON comes from request body. If you want a type check, you should enable a ValidationPipe that leverages class-trasformer and class-validator libraries:\n\n```\napp.useGlobalPipes(\n new ValidationPipe({\n transform: true,\n transformOptions: {\n enableImplicitConversion: true,\n },\n validationError: { target: false, value: false },\n })\n );\n```\n\n========================================\n\nCode:\n```text\nexport class CreateUserDto {\n    readonly email: string;\n    readonly password: string;\n}\n```\n\n```text\n@Post('create')\ncreateUser(@Body() userData: CreateUserDto): User {\n    return this.usersService.createUser(userData);\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nruntypes\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      transform: true,\n      transformOptions: {\n        enableImplicitConversion: true,\n      },\n      validationError: { target: false, value: false },\n    })\n  );\n```\n\n========================================\n\nComments:\n- thanks @Jay McDoniel. I am using your nest repository on my private lessons, quite nice! thanks twice!","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":83,"estimatedTokens":583}}166{"id":"stack-62450501","source":"stackoverflow","questionId":62450501,"title":"NestJS controller not mapped","tags":["javascript","docker","nestjs","typeorm"],"text":"Title: NestJS controller not mapped\nTags: javascript, docker, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nSo I have an API that will be deployed in a docker container. This API has the `authentications` controller, simple and not something special.\n\nWhen I start up the API in development mode on my local machine, the auth controller will be found and everything is working fine. Same for building and running it on my local machine. But when I'll dockerize the project and run it on a virtual machine, then I'll can't access the auth controller. Every other controller is working finde, but the auth controller doesn't exist.\n\nLooking into the docker logs, no auth controller will be mapped. Both local and builded docker images should contain the same project files.\n\nauth controller:\n\n```\nimport {\n Controller,\n Post,\n Delete,\n UseGuards,\n Request,\n Body,\n} from '@nestjs/common';\n\nimport { AuthenticationsService } from './authentications.service';\nimport { JwtAuthGuard } from '../shared/guards/jwtAuth.guard';\nimport { SignInDTO } from './dtos/addGraphNodeToGraphByGraphId.dto';\n\n@Controller('authentications')\nexport class AuthenticationsController {\n constructor(\n private readonly authenticationsService: AuthenticationsService,\n ) {}\n\n @Post()\n public signIn(@Body() { username, password }: SignInDTO): Promise {\n return this.authenticationsService.signIn(username, password);\n }\n\n @Delete()\n @UseGuards(JwtAuthGuard)\n public signOut(@Request() request): Promise {\n return this.authenticationsService.signOut(\n request.encodedToken,\n request.user.tokenExpirationSinceEpochInMilliseconds,\n );\n }\n}\n```\n\nError:\n\n```\n{\n \"statusCode\": 404,\n \"message\": \"Not Found\",\n \"error\": \"Cannot POST /authentications\"\n}\n```\n\nWhat could cause that the authentications controller will not be mapped?\n\n========================================\n\nTop Answer:\nIf you have already tried everything else and nothing worked, try deleting the `dist` folder. That's what worked for me.\n\n========================================\n\nCode:\n```text\nimport {\n  Controller,\n  Post,\n  Delete,\n  UseGuards,\n  Request,\n  Body,\n} from '@nestjs/common';\n\nimport { AuthenticationsService } from './authentications.service';\nimport { JwtAuthGuard } from '../shared/guards/jwtAuth.guard';\nimport { SignInDTO } from './dtos/addGraphNodeToGraphByGraphId.dto';\n\n@Controller('authentications')\nexport class AuthenticationsController {\n  constructor(\n    private readonly authenticationsService: AuthenticationsService,\n  ) {}\n\n  @Post()\n  public signIn(@Body() { username, password }: SignInDTO): Promise<string> {\n    return this.authenticationsService.signIn(username, password);\n  }\n\n  @Delete()\n  @UseGuards(JwtAuthGuard)\n  public signOut(@Request() request): Promise<void> {\n    return this.authenticationsService.signOut(\n      request.encodedToken,\n      request.user.tokenExpirationSinceEpochInMilliseconds,\n    );\n  }\n}\n```\n\n```text\n{\n    \"statusCode\": 404,\n    \"message\": \"Not Found\",\n    \"error\": \"Cannot POST /authentications\"\n}\n```\n\n```text\nauthentications\n```\n\n```text\nnest update -f\n```\n\n```js\n@Module({\n  controllers: [AuthenticationController],\n})\nexport class AppModule {}\n```\n\n```text\ndist\n```\n\n```text\nmaster\n```\n\n```text\ndev\n```\n\n```text\npino\n```\n\n```text\ndebug\n```\n\n========================================\n\nComments:\n- If you modify an existing controller, does it repercutes the modification in the docker container ?\n- Put code of module which requires this controller into the question. Maybe there is something here. Also which operation systems do you have locally and in docker?\n- Yes, I guess if I wouldn't have done that it would also not work on my local machine\n- I already found a solution: stackoverflow.com/a/62591471/8408576\n- The selected answer didn't work for me so, I shared mine just in case anybody else is facing the same thing.\n- turnout my build was not compiling so intellij was just using the last working version :facepalm: thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":157,"estimatedTokens":988}}167{"id":"stack-52972616","source":"stackoverflow","questionId":52972616,"title":"Add headers HttpRequest in NestJS","tags":["javascript","angular","httprequest","nestjs"],"text":"Title: Add headers HttpRequest in NestJS\nTags: javascript, angular, httprequest, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a Http request in NestJS\n\nAs it's inspired from angular I jave append my Headers\n\n```\nimport { Injectable, HttpService} from '@nestjs/common';\n...\nconst headersRequest = new Headers();\nheadersRequest.append('Content-Type', 'application/json');\nheadersRequest.append('Authorization', `Basic ${encodeToken}`);\n```\n\nThen call the api\n\n```\nconst result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });\n```\n\nI get an error\n\n```\nReferenceError: Headers is not defined\n```\n\nAnd when I ass `Headers` to import\nI get this message waring in VScode\n\n```\nOnly a void function can be called with the 'new' keyword.\n```\n\n========================================\n\nTop Answer:\nAnother option (since nest v5 introduced HttpModule.registerAsync) if your `encodeToken` is pretty static or hardcoded from your config is setting it up in the module level:\n\n```\nimport { Module, HttpModule } from '@nestjs/common';\nimport { ConfigModule } from '..';\nimport { ConfigService } from '../config/config.service';\n\n@Module({\n imports: [\n ConfigModule,\n HttpModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n baseURL: configService.get('vendors.apiEndpoint'),\n headers: { \n 'Authorization': 'Basic ' + configService.get('vendors.encodeToken')\n },\n timeout: 7000,\n maxRedirects: 5\n }),\n inject: [ConfigService]\n })\n ],\n // ... other module stuff\n})\n\nexport class MyModule {}\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, HttpService} from '@nestjs/common';\n...\nconst headersRequest = new Headers();\nheadersRequest.append('Content-Type', 'application/json');\nheadersRequest.append('Authorization', `Basic ${encodeToken}`);\n```\n\n```text\nconst result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });\n```\n\n```text\nReferenceError: Headers is not defined\n```\n\n```text\nOnly a void function can be called with the 'new' keyword.\n```\n\n```text\nHeaders\n```\n\n```text\nconst headersRequest = {\n    'Content-Type': 'application/json', // afaik this one is not needed\n    'Authorization': `Basic ${encodeToken}`,\n};\n\nconst result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });\n```\n\n```text\n@Get()\n    findHeaderexample(@Res() res,@Req req) {\n        return req.headers;\n}\n```\n\n```text\nimport { Module, HttpModule } from '@nestjs/common';\nimport { ConfigModule } from '..';\nimport { ConfigService } from '../config/config.service';\n\n\n@Module({\n  imports: [\n    ConfigModule,\n    HttpModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        baseURL: configService.get('vendors.apiEndpoint'),\n        headers: {          \n          'Authorization': 'Basic ' + configService.get('vendors.encodeToken')\n        },\n        timeout: 7000,\n        maxRedirects: 5\n      }),\n      inject: [ConfigService]\n    })\n  ],\n  // ... other module stuff\n})\n\nexport class MyModule {}\n```\n\n```text\nencodeToken\n```\n\n```text\n@ApiHeader({\n  name: 'api-key',\n  description: 'api-key',\n})\n```\n\n```text\n@ApiHeader()\n```\n\n```text\nexport const HttpMessagingProvider = HttpModule.registerAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    baseURL: configService.get('vendors.apiEndpoint'),\n    timeout: 5000,\n    maxRedirects: 5,\n    withCredentials: true,\n  }),\n  inject: [ConfigService]\n});\n```\n\n```text\nthis.httpService.axiosRef.interceptors.request.use(function (config) {\n      config.headers.Authorization = `Basic ${encodeToken}`;\n      return config;\n    });\n```\n\n========================================\n\nComments:\n- Thanks Riadh but It's not exactly what I would make, I would set header to make a httpRequest inside a controller ( inside a service exactely ) and not get req headers\n- Possible explain your idea\n- How to call the API in service because the Header authorization is added here if call it shows the token is missing.","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":180,"estimatedTokens":1026}}168{"id":"stack-71869915","source":"stackoverflow","questionId":71869915,"title":"Nest can't resolve dependencies of the (?). Please make sure that the argument at index [0] is available in the RootTestModule context","tags":["nestjs"],"text":"Title: Nest can't resolve dependencies of the (?). Please make sure that the argument at index [0] is available in the RootTestModule context\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI try to run NestJs test but got the following error\n\n`Nest can't resolve dependencies of the (?). Please make sure that the argument at index [0] is available in the RootTestModule context.`\n\nThis project is using Mongoose for connecting to MongoDB\n\nYou can reproduce the error by running code in this repo\nhttps://github.com/kruyvanna/nestjs-test-error\n\nThank you in advance\n\n========================================\n\nCode:\n```text\nNest can't resolve dependencies of the (?). Please make sure that the argument at index [0] is available in the RootTestModule context.\n```\n\n```js\nconst module: TestingModule = await Test.createTestingModule({\n  providers: [CatService],\n}).compile();\n```\n\n```js\n@Injectable()\nexport class CatService {\n  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}\n}\n```\n\n```js\nconst module: TestingModule = await Test.createTestingModule({\n  providers: [CatService, { provide: getModelToken(Cat.name), useValue: jest.fn() }],\n}).compile();\n```\n\n```text\ncatModel\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.416Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":45,"estimatedTokens":301}}169{"id":"stack-65250657","source":"stackoverflow","questionId":65250657,"title":"Using services inside NestJS script run from command line","tags":["typescript","command-line","nestjs"],"text":"Title: Using services inside NestJS script run from command line\nTags: typescript, command-line, nestjs\nSource: Stack Overflow\n\nQuestion:\nI know how to run a script from command line, using `npm` or `npx ts-node [script.ts]` just as stated here.\n\nMy question is different, now that I can run scripts, can I use services that are inside modules in my project? Let's say that I have this structure that it is normally called inside the project by other modules:\n\nfoo/foo.module.ts\n\n```\nimport { HttpModule, Module } from '@nestjs/common';\n\n@Module({\n providers: [FooService],\n imports: [HttpModule],\n exports: [FooService]\n})\nexport class FooModule { }\n```\n\nfoo/foo.service.ts\n\n```\nimport { HttpService, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class FooService {\n constructor(\n private readonly httpService: HttpService,\n ) {}\n\n bar() {\n console.log('do stuff');\n }\n}\n```\n\nhow can I call `bar()` inside the file `/src/script.ts` and then call `npx ts-node script.ts` keeping all the imports? Thank you.\n\n========================================\n\nTop Answer:\nTo add to the @Emanuele answer. If you have issue with src/[...] relative path, then instead of running the script with ts-node, try run with the following\n\"node -r ts-node/register -r tsconfig-paths/register path_to_script\"\n\n========================================\n\nCode:\n```text\nimport { HttpModule, Module } from '@nestjs/common';\n\n@Module({\n  providers: [FooService],\n  imports: [HttpModule],\n  exports: [FooService]\n})\nexport class FooModule { }\n```\n\n```text\nimport { HttpService, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class FooService {\n    constructor(\n        private readonly httpService: HttpService,\n    ) {}\n\n    bar() {\n        console.log('do stuff');\n    }\n}\n```\n\n```text\nnpm\n```\n\n```text\nnpx ts-node [script.ts]\n```\n\n```text\nbar()\n```\n\n```text\n/src/script.ts\n```\n\n```text\nnpx ts-node script.ts\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { UsersModule } from './users/users.module';\n\n@Module({\n  imports: [\n    UsersModule,\n  ],\n})\nexport class ApplicationModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\n\n@Module({\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { ApplicationModule } from './application.module';\nimport { UsersService } from './users/users.service';\n\nasync function bootstrap() {\n  const application = await NestFactory.createApplicationContext(\n    ApplicationModule,\n  );\n\n  const command = process.argv[2];\n\n  switch (command) {\n    case 'create-administrator-user':\n      const usersService = application.get(UsersService);\n      await usersService.create({\n        username: 'administrator',\n        password: 'password',\n      });\n      break;\n    default:\n      console.log('Command not found');\n      process.exit(1);\n  }\n\n  await application.close();\n  process.exit(0);\n}\n\nbootstrap();\n```\n\n```text\n\"execute\": \"ts-node ./src/console.ts\"\n```\n\n```text\n// Using Yarn\nyarn execute create-administrator-user\n\n// Using NPM\nnpm run execute create-administrator-user\n```\n\n```text\nconsole.ts\n```\n\n```text\npackage.json\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.createApplicationContext(FooModule);\n  const service = app.get<FooService>(FooService); // this sets the type of service and gets the instance\n  service.bar();\n  await app.close();\n}\n```\n\n```text\nNestFactory.create\n```\n\n```text\nnode\n```\n\n```text\n{\n  \"ts-node\": {\n    // Do not forget to `npm i -D tsconfig-paths`\n    \"require\": [\"tsconfig-paths/register\"]\n  }\n}\n```\n\n========================================\n\nComments:\n- have you check this package ? nestjs-command\n- @antoineso no, I'll give a try. Thanks\n- So, the only thing is that I was forced to convert all the imports of my project from `src&#47;[...]` to relative paths because it wasn't able to resolve them. For the rest it works like a charm. Thank you\n- Just a thing that came up in my mind, if I have some nest cron jobs in the project and it happens that in the moment that I run the script it is also in the time of a cron job, is it executed or not?\n- I am using prisma and cache in the services's `constructor` , it return `Cannot find module 'src&#47;prisma.service'` error.\n- This helped a lot thanks. In my cases, a lot of my services implemented `OnModuleInit` so I created a specific module called `CLIModule` with which you can create the application context, ie. ` const application = await NestFactory.createApplicationContext(CLIModule); ` - that way you don't have to load your whole app, and can just register the services in `CLIModule` that you need.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":206,"estimatedTokens":1232}}170{"id":"stack-60852170","source":"stackoverflow","questionId":60852170,"title":"NestJs - How to unit test a DTO?","tags":["javascript","node.js","nestjs"],"text":"Title: NestJs - How to unit test a DTO?\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am asking you for help. I have created a DTO that looks like it (this is a smaller version) :\n\n```\nexport class OfImportDto {\n\n @IsString({\n message: \"should be a valid product code\"\n })\n productCode: string;\n\n @IsString({\n message: \"Enter the proper product description\"\n })\n productDescription: string;\n\n @IsDateString({\n message: \"should be a valid date format, for example : 2017-06-07T14:34:08+04:00\"\n })\n manufacturingDate : Date\n\n @IsInt({\n message: \"should be a valid planned quantity number\"\n })\n @IsPositive()\n plannedQuantity: number;\n```\n\nthe thing is that i am asking to test that, with a unit test and not a E2E test. And I Don't know how to do that. For instance, I would like to unit test \n1/ if my product code is well a string, a string should be created, if not, throw my exception\n2/ if my product description is well a string, a string should be created, if not, throw my exception\n...\nand so on.\n\nSo, can I made a spec.ts file to test that? If yes, how?\nIf not, is it better to test it within the service.spec.ts? If so, how?\n\nThank you very much, any help would be very helpful :)\n\n========================================\n\nTop Answer:\nIt would be possible to create a `OfImportDTO.spec.ts` file (or whatever your original file is called), but the thing is, there isn't any logic here to test. The closest thing you could do is create an instance of a `Validator` from `class-validator` and then instantiate an instance of the `OfImportDto` and then check that the class passes validation. If you add logic to it (e.g. getters and setters with specific functions) then it could make sense for unit testing, but otherwise, this is basically an interface being called a class so it exists at runtime for `class-validator`\n\n========================================\n\nCode:\n```text\nexport class OfImportDto {\n\n    @IsString({\n        message: \"should be a valid product code\"\n    })\n    productCode: string;\n\n    @IsString({\n        message: \"Enter the proper product description\"\n    })\n    productDescription: string;\n\n    @IsDateString({\n        message: \"should be a valid date format, for example : 2017-06-07T14:34:08+04:00\"\n    })\n    manufacturingDate : Date\n\n    @IsInt({\n        message: \"should be a valid planned quantity number\"\n    })\n    @IsPositive()\n    plannedQuantity: number;\n```\n\n```text\nit('should throw when the planned quantity is a negative number.', async () => {\n  const importInfo = { productCode: 4567, plannedQuanity: -10 }\n  const ofImportDto = plainToInstance(OfImportDto, importInfo)\n  const errors = await validate(ofImportDto)\n  expect(errors.length).not.toBe(0)\n  expect(stringified(errors)).toContain(`Planned Quantity must be a positive number.`)\n}\n```\n\n```text\nconst importInfo = { productCode: 4567, plannedQuanity: -10 }\n```\n\n```text\nconst ofImportDto = plainToInstance(OfImportDto, importInfo)\n```\n\n```text\nconst errors = await validate(ofImportDto)\n```\n\n```text\nconst errors = await validate(ofImportDto, { skipMissingProperties: true })\n```\n\n```text\nexpect(errors.length).not.toBe(0)\nexpect(stringified(errors)).toContain(`Planned Quantity must be a positive number.`)\n```\n\n```text\nexport function stringified(errors: ValidationError[]): string {\n  return JSON.stringify(errors)\n}\n```\n\n```text\nof-import.dto.spec.ts\n```\n\n```text\nplainToinstace()\n```\n\n```text\nclass-transformer\n```\n\n```text\nOfImportDto\n```\n\n```text\nvalidate()\n```\n\n```text\nvalidate()\n```\n\n```text\nclass-validator\n```\n\n```text\nerrors\n```\n\n```text\nstringified()\n```\n\n```text\nerrors\n```\n\n```text\nOfImportDTO.spec.ts\n```\n\n```text\nValidator\n```\n\n```text\nclass-validator\n```\n\n```text\nOfImportDto\n```\n\n```text\nclass-validator\n```\n\n========================================\n\nComments:\n- Yeah, that's what I thought too. Would it be possible to test it via my service.spec.ts? Because there is logic inside, perhaps calling a mock of the DTO and do some testing would work?\n- What kind of logic, because in your code snippet above it's just definition of fields along with decorators. What are you trying to test with this?\n- I still don't see anything to test with regards to the DTO file. Testing services and controllers is another thing, but testing the DTO file doesn't make much sense in this case\n- What i want is to be sure that the data from dto are ok. I wonder if i can check every field within the service test. For example : if the product code is not a string, reject it. Based on the dto and not the entity. Would it be possible?\n- Like I said in my answer, you could always use an instance of the `Validator` from `class-validator` an ensure your decorators provide the enforcement you expect them to. That's why Nest has the `pipe` enhancer: for data validation and transformation. But otherwise, running automated tests against a DTO file is not really useful.\n- Ok i'll do it this way. Thank you :)","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":182,"estimatedTokens":1237}}171{"id":"stack-61402054","source":"stackoverflow","questionId":61402054,"title":"NestJS - How to upload image to aws s3?","tags":["typescript","amazon-s3","nestjs","multer","multer-s3"],"text":"Title: NestJS - How to upload image to aws s3?\nTags: typescript, amazon-s3, nestjs, multer, multer-s3\nSource: Stack Overflow\n\nQuestion:\nI'm trying to perform an image upload to aws s3 using multer-s3 on NestJS API. I have also tried aws-sdk. I use FileInterceptor and UploadedFile decorator to capture the file request. So far what I have is:\n\n```\n// Controller\n @Post()\n @UseInterceptors(FileInterceptor('file', multerOptions))\n uploadImage(@UploadedFile() file) {\n console.log(file);\n }\n\n// multerOptions. multer.ts file\nconst configService = new ConfigService();\n\nexport const accessParams = {\n accessKeyId: configService.get('AWS_ACCESS_KEY_ID'),\n secretAccessKey: configService.get('AWS_SECRET_ACCESS_KEY'),\n region: configService.get('AWS_REGION'),\n};\n\nconst imageMimeTypes = [\n 'image/jpg',\n 'image/jpeg',\n 'image/png',\n 'image/bmp',\n];\n\nAWS.config.update(accessParams);\nexport const s3 = new AWS.S3();\n\nexport const multerOptions = {\n fileFilter: (req: any, file: any, cb: any) => {\n const mimeType = imageMimeTypes.find(im => im === file.mimetype);\n\n if (mimeType) {\n cb(null, true);\n } else {\n cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);\n }\n },\n storage: multerS3({\n s3: s3,\n bucket: configService.get('S3_BUCKET_NAME'),\n acl: 'read-public',\n metadata: function (req, file, cb) {\n cb(null, { fieldName: file.fieldname })\n },\n key: (req: any, file: any, cb: any) => {\n cb(null, `${Date.now().toString()}/${file.originalname}`);\n },\n contentType: multerS3.AUTO_CONTENT_TYPE\n }),\n};\n```\n\nwhich gives me the following error:\n\n```\n{\n \"message\": null,\n \"code\": \"InvalidArgument\",\n \"region\": null,\n \"time\": \"2020-04-24T05:34:19.009Z\",\n \"requestId\": \"DH224C558HTDF8E3\",\n \"extendedRequestId\": \"JKHKJH6877-LKJALDNC765llLKAL=\",\n \"statusCode\": 400,\n \"retryable\": false,\n \"retryDelay\": 6.790294010827713,\n \"storageErrors\": []\n}\n```\n\nAny idea? Thank you.\n\n========================================\n\nTop Answer:\nWith typings and stream:\n\n```\nimport { ReadStream } from 'fs';\nimport * as AWS from 'aws-sdk';\nimport { PromiseResult } from 'aws-sdk/lib/request';\nimport { Injectable, InternalServerErrorException } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\n\nimport { TConfig, TStorageConfig } from '../../config';\n\n@Injectable()\nexport class StorageService {\n private S3: AWS.S3;\n private BUCKET: string;\n\n constructor(private configService: ConfigService) {\n this.S3 = new AWS.S3({\n // Your config options\n accessKeyId: this.configService.get('storage').accessKeyId,\n secretAccessKey: this.configService.get('storage').secretAccessKey,\n endpoint: this.configService.get('storage').endpoint,\n s3ForcePathStyle: true,\n signatureVersion: 'v4',\n });\n this.BUCKET = this.configService.get('storage').bucket;\n }\n\n async getBlob(key: string): Promise> {\n const params = { Bucket: this.BUCKET, Key: key };\n const blob = await this.S3.getObject(params).promise();\n \n return blob;\n }\n\n async putBlob(blobName: string, blob: Buffer): Promise> {\n const params = { Bucket: this.BUCKET, Key: blobName, Body: blob };\n const uploadedBlob = await this.S3.putObject(params).promise();\n\n return uploadedBlob;\n }\n\n // to get stream you can use file.createReadStream()\n async putStream(key: string, stream: ReadStream): Promise {\n const file = await new Promise((resolve, reject) => {\n const handleError = (error) => {\n reject(error);\n };\n const chunks: Buffer[] = [];\n\n stream.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n stream.once('end', async () => {\n const fileBuffer = Buffer.concat(chunks);\n\n try {\n const uploaded = await this.putBlob(key, fileBuffer);\n\n resolve(uploaded);\n } catch (error) {\n handleError(new InternalServerErrorException(error));\n }\n });\n\n stream.on('error', (error) => handleError(new InternalServerErrorException(error)));\n });\n\n return file;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// Controller\n @Post()\n @UseInterceptors(FileInterceptor('file', multerOptions))\n    uploadImage(@UploadedFile() file) {\n        console.log(file);\n    }\n\n// multerOptions. multer.ts file\nconst configService = new ConfigService();\n\nexport const accessParams = {\n    accessKeyId: configService.get('AWS_ACCESS_KEY_ID'),\n    secretAccessKey: configService.get('AWS_SECRET_ACCESS_KEY'),\n    region: configService.get('AWS_REGION'),\n};\n\nconst imageMimeTypes = [\n    'image/jpg',\n    'image/jpeg',\n    'image/png',\n    'image/bmp',\n];\n\nAWS.config.update(accessParams);\nexport const s3 = new AWS.S3();\n\nexport const multerOptions = {\n    fileFilter: (req: any, file: any, cb: any) => {\n        const mimeType = imageMimeTypes.find(im => im === file.mimetype);\n\n        if (mimeType) {\n            cb(null, true);\n        } else {\n            cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);\n        }\n    },\n    storage: multerS3({\n        s3: s3,\n        bucket: configService.get('S3_BUCKET_NAME'),\n        acl: 'read-public',\n        metadata: function (req, file, cb) {\n            cb(null, { fieldName: file.fieldname })\n        },\n        key: (req: any, file: any, cb: any) => {\n            cb(null, `${Date.now().toString()}/${file.originalname}`);\n        },\n        contentType: multerS3.AUTO_CONTENT_TYPE\n    }),\n};\n```\n\n```text\n{\n  \"message\": null,\n  \"code\": \"InvalidArgument\",\n  \"region\": null,\n  \"time\": \"2020-04-24T05:34:19.009Z\",\n  \"requestId\": \"DH224C558HTDF8E3\",\n  \"extendedRequestId\": \"JKHKJH6877-LKJALDNC765llLKAL=\",\n  \"statusCode\": 400,\n  \"retryable\": false,\n  \"retryDelay\": 6.790294010827713,\n  \"storageErrors\": []\n}\n```\n\n```text\nimport { Post, UseInterceptors, UploadedFile } from '@nestjs/common';\n\n@Post('upload')\n@UseInterceptors(FileInterceptor('file'))\nasync upload(@UploadedFile() file) {\n  return await this.service.upload(file);\n}\n```\n\n```text\nimport { S3 } from 'aws-sdk';\nimport { Logger, Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class FileUploadService {\n    async upload(file) {\n        const { originalname } = file;\n        const bucketS3 = 'my-aws-bucket';\n        await this.uploadS3(file.buffer, bucketS3, originalname);\n    }\n\n    async uploadS3(file, bucket, name) {\n        const s3 = this.getS3();\n        const params = {\n            Bucket: bucket,\n            Key: String(name),\n            Body: file,\n        };\n        return new Promise((resolve, reject) => {\n            s3.upload(params, (err, data) => {\n            if (err) {\n                Logger.error(err);\n                reject(err.message);\n            }\n            resolve(data);\n            });\n        });\n    }\n\n    getS3() {\n        return new S3({\n            accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n        });\n    }\n}\n```\n\n```text\nimport { ReadStream } from 'fs';\nimport * as AWS from 'aws-sdk';\nimport { PromiseResult } from 'aws-sdk/lib/request';\nimport { Injectable, InternalServerErrorException } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\n\nimport { TConfig, TStorageConfig } from '../../config';\n\n@Injectable()\nexport class StorageService {\n    private S3: AWS.S3;\n    private BUCKET: string;\n\n    constructor(private configService: ConfigService<TConfig>) {\n        this.S3 = new AWS.S3({\n            // Your config options\n            accessKeyId: this.configService.get<TStorageConfig>('storage').accessKeyId,\n            secretAccessKey: this.configService.get<TStorageConfig>('storage').secretAccessKey,\n            endpoint: this.configService.get<TStorageConfig>('storage').endpoint,\n            s3ForcePathStyle: true,\n            signatureVersion: 'v4',\n        });\n        this.BUCKET = this.configService.get<TStorageConfig>('storage').bucket;\n    }\n\n    async getBlob(key: string): Promise<PromiseResult<AWS.S3.GetObjectOutput, AWS.AWSError>> {\n        const params = { Bucket: this.BUCKET, Key: key };\n        const blob = await this.S3.getObject(params).promise();\n        \n        return blob;\n    }\n\n    async putBlob(blobName: string, blob: Buffer): Promise<PromiseResult<AWS.S3.PutObjectOutput, AWS.AWSError>> {\n        const params = { Bucket: this.BUCKET, Key: blobName, Body: blob };\n        const uploadedBlob = await this.S3.putObject(params).promise();\n\n        return uploadedBlob;\n    }\n\n    // to get stream you can use file.createReadStream()\n    async putStream(key: string, stream: ReadStream): Promise<AWS.S3.PutObjectOutput> {\n        const file = await new Promise<AWS.S3.PutObjectOutput>((resolve, reject) => {\n            const handleError = (error) => {\n                reject(error);\n            };\n            const chunks: Buffer[] = [];\n\n            stream.on('data', (chunk: Buffer) => {\n                chunks.push(chunk);\n            });\n\n            stream.once('end', async () => {\n                const fileBuffer = Buffer.concat(chunks);\n\n                try {\n                    const uploaded = await this.putBlob(key, fileBuffer);\n\n                    resolve(uploaded);\n                } catch (error) {\n                    handleError(new InternalServerErrorException(error));\n                }\n            });\n\n            stream.on('error', (error) => handleError(new InternalServerErrorException(error)));\n        });\n\n        return file;\n    }\n}\n```\n\n```text\nimport * as multerS3 from 'multer-s3-transform'\nimport * as sharp from 'sharp'\nimport * as AWS from 'aws-sdk' \nexport default class AWSS3Utils {\n\n\n static uploadFile(bucket:string,transform:boolean,acl:string)\n  {\n    return multerS3({\n      s3: new AWS.S3({\n        accessKeyId: 'accessKeyId'  ,\n        secretAccessKey: 'secretAccessKey',\n      }),\n      bucket: bucket,\n      shouldTransform: true,\n      acl: acl,\n      transforms: [\n        {\n          id: 'original',\n          key: function (req, file, cb) {\n            cb(null, `${file.originalname}` )\n          },\n          transform: function (req, file, cb) {\n            cb(null, sharp().png())\n          }\n        },\n        {\n          id: 'large',\n          key: (req, file, cb) => cb(null, new Date().getTime() + `_large_${file.originalname}`),\n          transform: (req, file, cb) => cb(null, sharp().resize(1200, 900).png())\n        },\n        {\n          id: 'small',\n          key: (req, file, cb) => cb(null, new Date().getTime() + `_small_${file.originalname}`),\n          transform: (req, file, cb) => cb(null, sharp().resize(400, 300).png())\n        }\n      ]\n    })\n  }\n}\n```\n\n```text\n@Post('upload')\n  @UseInterceptors(FileInterceptor('file', {  storage: AWSS3Utils.uploadFile('nest-upload-tutorial',true,'public-read') }))\n  uploadFile(\n    @UploadedFile(\n      new ParseFilePipe({\n        validators: [new FileTypeValidator({ fileType: 'png' })],\n      }),\n    )\n    file: Express.Multer.File,\n  ) {\n    return file\n  }\n```\n\n========================================\n\nComments:\n- Thanks for the help, I am going to vote for your answer because it is correct but finally I was able to solve it using multer-s3 a little more to my liking\n- In the latest version when @UseInterceptors(FilesInterceptor(\"files\")) is given it is showing Error: connect ECONNREFUSED 127.0.0.1:4001 if interceptor line is commented code get inside controller without files and error. Any idea on this for a solution ?\n- is there a way to define access to public for uploaded files?\n- Thanks a lot! i spend 4 days in this task! you r js god!","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":411,"estimatedTokens":2856}}172{"id":"stack-75947475","source":"stackoverflow","questionId":75947475,"title":"Prisma: TypeError: Do not know how to serialize a BigInt","tags":["mysql","node.js","nestjs","prisma"],"text":"Title: Prisma: TypeError: Do not know how to serialize a BigInt\nTags: mysql, node.js, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fetch data from database and this is my prisma model:\n\n```\nmodel instant_reports {\n id BigInt @id @default(autoincrement()) @db.UnsignedBigInt\n created_at DateTime?\n updated_at DateTime?\n deleted_at DateTime?\n timestamp BigInt?\n client_id BigInt?\n uniq_users BigInt?\n}\n```\n\nSo when i fetch data like this\n\n```\nprismaService.instant_reports.findMany({\n skip: 0,\n take: 30,\n });\n```\n\nIt throws error\n\nTypeError: Do not know how to serialize a BigInt at JSON.stringify()\n\nAnd i don't even know how to deal with it, is there way to change data handler in `findMany` method?\n\nIf there is no rows in `instant_reports` so it gives me empty array without error, so the problem is in data with BigInt type\n\n========================================\n\nTop Answer:\n### This is the most simple and secure way!!!\n\n### Modifying the prototype is likely to cause problems somewhere.\n\nJust copy and paste the simple function below.\n\n```\nconst json = (param: any): any => {\n return JSON.stringify(\n param,\n (key, value) => (typeof value === \"bigint\" ? value.toString() : value) // return everything else unchanged\n );\n};\nexport default json;\n```\n\nAnd then you can use like this\n\n```\nimport json from \"../helper/json\";\n\nrouter.get(\"/\", async (req: Request, res: Response) => {\n const users = await prisma.user.findMany({\n take: 15,\n });\n res.status(200).send(json(users));\n});\n```\n\nThis is how it works:\n\nMaybe most of us just want to send those Prisma datas in JSON format using ExpressJS.\n\nWhether you are using the library or not, you will inevitably go through `JSON.stringify()` at some point in your code.\n\nUnfortunately, `JSON.stringify()` can't handle BigInt correctly.\n\nSo, we all must have to convert BigInt to String if you want to use it.\n\n### โ€ป To ExpressJS users\n\nDon't use `res.json()` method!\n\nIf you use, you will unintentionally wrap twice like below\n\n`JSON.stringify(JSON.stringify(something))`\n\n========================================\n\nCode:\n```text\nmodel instant_reports {\n  id         BigInt    @id @default(autoincrement()) @db.UnsignedBigInt\n  created_at DateTime?\n  updated_at DateTime?\n  deleted_at DateTime?\n  timestamp  BigInt?\n  client_id  BigInt?\n  uniq_users BigInt?\n}\n```\n\n```text\nprismaService.instant_reports.findMany({\n      skip: 0,\n      take: 30,\n    });\n```\n\n```text\nfindMany\n```\n\n```text\ninstant_reports\n```\n\n```js\nBigInt.prototype.toJSON = function () {\n  const int = Number.parseInt(this.toString());\n  return int ?? this.toString();\n};\n```\n\n```text\nfunction bigIntToString(value) {\n  const MAX_SAFE_INTEGER = 2 ** 53 - 1;\n  return value <= MAX_SAFE_INTEGER ? Number(value) : value.toString();\n}\n\nfunction serializeInstantReports(instantReports) {\n  return instantReports.map(report => {\n    const newReport = { ...report };\n    if (typeof report.id === 'bigint') newReport.id = bigIntToString(report.id);\n    // ...\n    // such convirtions for other BigInt fields\n    // ...\n    return newReport;\n  });\n}\n```\n\n```text\nserializeInstantReports\n```\n\n```text\nconst user = prisma.user.create({ data: { id: 1, name: \"user\"})\n```\n\n```text\nJSON.stringify({...user, id: user.id.toString()})\n```\n\n```text\nconst json = (param: any): any => {\n  return JSON.stringify(\n    param,\n    (key, value) => (typeof value === \"bigint\" ? value.toString() : value) // return everything else unchanged\n  );\n};\nexport default json;\n```\n\n```text\nimport json from \"../helper/json\";\n\nrouter.get(\"/\", async (req: Request, res: Response) => {\n  const users = await prisma.user.findMany({\n    take: 15,\n  });\n  res.status(200).send(json(users));\n});\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nres.json()\n```\n\n```text\nJSON.stringify(JSON.stringify(something))\n```\n\n```text\nconst overrideJsonBigIntSerialization = (): void => {\n  const originalJSONStringify = JSON.stringify\n    \n  JSON.stringify = function (value: any, replacer, space: number): string {\n    const bigIntReplacer = (_key: string, value: any): any => {\n      if (typeof value === 'bigint') {\n        return parseInt(value.toString())\n      }\n      return value\n    }\n\n    const customReplacer = (key: string, value: any): any => {\n      if (Array.isArray(replacer) && !replacer.includes(key) && key !== '') {\n        return undefined\n      }\n\n      const modifiedValue = bigIntReplacer(key, value)\n\n      if (typeof replacer === 'function') {\n        return replacer(key, modifiedValue)\n      }\n    \n      return modifiedValue\n    }\n  \n    return originalJSONStringify(value, replacer != null ? customReplacer : bigIntReplacer, space)\n  }\n}\n```\n\n```text\noverrideJsonBigIntSerialization()\n```\n\n========================================\n\nComments:\n- Does this answer your question? TypeScript: serialize BigInt in JSON\n- Brilliant. Thank you!\n- For NestJS, this needs to be added in bootstrap function in main.ts before app.listen line\n- Also, this must be approved as accepted answer since it solves the problem. I have upvoted it. @bluepuper\n- For nuxtjs, this could be added as a plugin // plugins/bigint-json.js export default defineNuxtPlugin(() => { BigInt.prototype.toJSON = function () { const int = Number.parseInt(this.toString()); return int ?? this.toString(); }; });\n- Even better, use superjson to handle all sorts of unsupported datatypes in addition to BigInt","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":234,"estimatedTokens":1353}}173{"id":"stack-55949600","source":"stackoverflow","questionId":55949600,"title":"How to create rooms with nestjs and socket.io","tags":["node.js","typescript","websocket","socket.io","nestjs"],"text":"Title: How to create rooms with nestjs and socket.io\nTags: node.js, typescript, websocket, socket.io, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a room on my nestjs backend but can't find any information on this subject. You can find the docs here. The docs don't seem to have anything on this subject.\n\n```\nimport {\n SubscribeMessage,\n WebSocketGateway,\n WebSocketServer,\n WsResponse,\n} from '@nestjs/websockets';\nimport { Client, Server } from 'socket.io';\n\n@WebSocketGateway({namespace: 'story'})\nexport class StoryEventsGateway {\n @WebSocketServer()\n server: Server;\n\n @SubscribeMessage('createRoom')\n createRoom(client: Client, data: string): WsResponse {\n return { event: 'roomCreated', data };\n }\n}\n```\n\n========================================\n\nTop Answer:\nWith the latest Nest JS update you can use this code where the room name can be sent from the front-end and it will passed on to the 'data' variable:\n\n```\n@SubscribeMessage('createRoom')\n createRoom(@MessageBody() data: string, @ConnectedSocket() client: Socket) {\n client.join(data, err => {\n if (err) {\n this.logger.error(err);\n }\n });\n }\n```\n\n========================================\n\nCode:\n```text\nimport {\n  SubscribeMessage,\n  WebSocketGateway,\n  WebSocketServer,\n  WsResponse,\n} from '@nestjs/websockets';\nimport { Client, Server } from 'socket.io';\n\n@WebSocketGateway({namespace: 'story'})\nexport class StoryEventsGateway {\n  @WebSocketServer()\n  server: Server;\n\n  @SubscribeMessage('createRoom')\n  createRoom(client: Client, data: string): WsResponse<unknown> {\n    return { event: 'roomCreated', data };\n  }\n}\n```\n\n```ts\nimport { Socket } from 'socket.io';\nimport { WsResponse } from '@nestjs/websockets';\n\ncreateRoom(socket: Socket, data: string): WsResponse<unknown> {\n  socket.join('aRoom');\n  socket.to('aRoom').emit('roomCreated', {room: 'aRoom'});\n  return { event: 'roomCreated', room: 'aRoom' };\n}\n```\n\n```text\nclient: Client\n```\n\n```text\nsocket: Socket\n```\n\n```text\n@SubscribeMessage('createRoom')\n  createRoom(@MessageBody() data: string, @ConnectedSocket() client: Socket) {\n    client.join(data, err => {\n      if (err) {\n        this.logger.error(err);\n      }\n    });\n  }\n```\n\n```text\nimport { Socket } from 'socket.io-client' //wrong\n\nimport { Socket } from 'socket.io' //good\n\n\n@SubscribeMessage('room')\njoinRoom(socket: Socket, roomId: string) {\n  socket.join(roomId);\n}\n```\n\n========================================\n\nComments:\n- This really should be in the documentation, highlighted. Thanks a lot for the info.\n- I agree it can be easy to overlook but for future reference if you do a search for `handleEvent(client: Socket, data: string):` on the page docs.nestjs.com/websockets/gateways they quickly mention accessing the socket instance.","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":115,"estimatedTokens":689}}174{"id":"stack-49612658","source":"stackoverflow","questionId":49612658,"title":"Socket.io acknowledgement in Nest.js","tags":["javascript","socket.io","nestjs"],"text":"Title: Socket.io acknowledgement in Nest.js\nTags: javascript, socket.io, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to enable usage of socket.io acknowledgment callbacks in Nest.js WebSocketGateways.\n\nI'd like to be able to emit this:\n\n```\nsocket.emit('event', 'some data', function (response) {\n //do something\n})\n```\n\nAnd use the message handler like this:\n\n```\n@SubscribeMessage('event')\nonStart(client, data, ack) {\n //Do stuff\n ack('stuff completed');\n}\n```\n\nAccording to this nestjs/nest GitHub issue issue there is no support for it in the library so you'd have to build your own websocket adapter. I tried it but am not sure how to do it exactly. I guess I need to do something special in the `bindMessageHandlers` function but my attempts have been in vain.\nThis is the `bindMessageHandlers` implementation in the default socket.io adapter bundled in the framework:\n\n```\npublic bindMessageHandlers(\n client,\n handlers: MessageMappingProperties[],\n process: (data: any) => Observable,\n) {\n handlers.forEach(({ message, callback }) =>\n Observable.fromEvent(client, message)\n .switchMap(data => process(callback(data)))\n .filter(result => !!result && result.event)\n .subscribe(({ event, data }) => client.emit(event, data)),\n );\n}\n```\n\nDoes anyone have any pointers on how I would go about implementing this?\n\n========================================\n\nTop Answer:\nSimply use the return statement from SubscribeMessage\n\n```\n// server\n@SubscribeMessage('message')\n async onMessage(\n client: Socket, query: string\n ) {\n try {\n console.log(query) \n return 'hello'\n } catch (e) {\n // ...\n } \n }\n```\n\non the client side use as third param a function\n\n```\n// client\nthis.socket.emit('message', query, (res) => {\n console.log(res); // should log 'hello'\n});\n```\n\n========================================\n\nCode:\n```js\nsocket.emit('event', 'some data', function (response) {\n  //do something\n})\n```\n\n```ts\n@SubscribeMessage('event')\nonStart(client, data, ack) {\n  //Do stuff\n  ack('stuff completed');\n}\n```\n\n```ts\npublic bindMessageHandlers(\n  client,\n  handlers: MessageMappingProperties[],\n  process: (data: any) => Observable<any>,\n) {\n  handlers.forEach(({ message, callback }) =>\n    Observable.fromEvent(client, message)\n      .switchMap(data => process(callback(data)))\n      .filter(result => !!result && result.event)\n      .subscribe(({ event, data }) => client.emit(event, data)),\n  );\n}\n```\n\n```text\nbindMessageHandlers\n```\n\n```text\nbindMessageHandlers\n```\n\n```text\n@SubscribeMessage('event')\nasync onEvent(client, request) {\n  let data = request[0]\n  let ack = request[1] //the acknowledgement function\n}\n```\n\n```text\nexport function extractRequest (req: any): { data: any, ack?: Function } {\n  if (Array.isArray(req)) {\n    const [data, ack] = req\n    return { data, ack }\n  } else {\n    return { data: req, ack: () => {} }\n  }\n}\n```\n\n```text\nSubscribeMessage\n```\n\n```text\nrequest\n```\n\n```text\nrequest\n```\n\n```text\ndata\n```\n\n```text\nsrc\nโ”œโ”€โ”€ app.controller.spec.ts\nโ”œโ”€โ”€ app.controller.ts\nโ”œโ”€โ”€ app.module.ts\nโ”œโ”€โ”€ common\nโ”‚ย ย  โ””โ”€โ”€ adapters\nโ”‚ย ย      โ””โ”€โ”€ ws-adapter.ts\nโ”œโ”€โ”€ events\nโ”‚ย ย  โ”œโ”€โ”€ events.gateway.ts\nโ”‚ย ย  โ””โ”€โ”€ events.module.ts\nโ””โ”€โ”€ main.ts\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { WsAdapter } from './common/adapters/ws-adapter.ts';\nimport * as cors from 'cors';\n\nlet corsOptions = {\n    origin: 'http://nestjs.test',\n    credentials: true\n}\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    app.useWebSocketAdapter(new WsAdapter(3000));\n    app.use(cors(corsOptions));\n    await app.listen(4000);\n}\nbootstrap();\n```\n\n```text\nimport * as WebSocket from 'ws';\nimport { WebSocketAdapter } from '@nestjs/common';\nimport { IoAdapter } from '@nestjs/websockets';\nimport { MessageMappingProperties } from '@nestjs/websockets';\nimport { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/observable/fromEvent';\nimport 'rxjs/add/observable/empty';\nimport 'rxjs/add/operator/switchMap';\nimport 'rxjs/add/operator/filter';\n\nexport class WsAdapter extends IoAdapter {\n  public bindMessageHandlers(\n    client,\n    handlers: MessageMappingProperties[],\n    process: (data: any) => Observable<any>,\n  ) {\n    handlers.forEach(({ message, callback }) => {\n        client.on('event', function (data, ack) {\n            console.log('DATA', data)\n            ack('woot')\n        })\n        Observable.fromEvent(client, message)\n            .switchMap(data => process(callback(data)))\n            .filter(result => !!result && result.event)\n            .subscribe(({ event, data }) => client.emit(event, data))\n        });\n  }\n}\n```\n\n```text\nsocket.emit('event', {data: 'some data'}, function (response) {\n    console.log('RESPONSE', response)\n});\nsocket.on('event', function(data) {\n    console.log('ON EVENT', data);\n});\n```\n\n```text\nmain.ts\n```\n\n```text\ncommon\\adapters\\ws-adapter.ts\n```\n\n```text\n// server\n@SubscribeMessage('message')\n  async onMessage(\n    client: Socket, query: string\n  ) {\n    try {\n      console.log(query) \n      return 'hello'\n    } catch (e) {\n      // ...\n    } \n  }\n```\n\n```text\n// client\nthis.socket.emit('message', query, (res) => {\n  console.log(res); // should log 'hello'\n});\n```\n\n```text\nsocket.emit('my-message', payload, (response) => {\n   console.log(response)  \n })\n```\n\n```text\n@SubscribeMessage('my-message')\n  async myMessage (client, payload) {\n     console.log(payload)\n\n     return {\n       ... your response data here\n     }\n  }\n```\n\n========================================\n\nComments:\n- Your solution doesn't really work since I want to run the acknowledgement function from the decorated functions in the gateway. In your example I would have to hard code every socket event in the adapter, and even that won't work since I don't have access to the services etc that I have in the gateway.","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":274,"estimatedTokens":1460}}175{"id":"stack-52705859","source":"stackoverflow","questionId":52705859,"title":"How does nestjs get the cookie in the request?","tags":["nestjs"],"text":"Title: How does nestjs get the cookie in the request?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nHow does nestjs get the cookie in the request?\n\n```\nimport { Get, Controller, Response, Request } from '@nestjs/common';\nimport { AppService } from './app.service';\n\nconst l = console.log\n@Controller()\nexport class AppController {\n @Get('json')\n json(@Request() req){\n console.log(req.cookies) // undefined\n }\n}\n```\n\n========================================\n\nTop Answer:\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as cookieParser from 'cookie-parser'\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.use(cookieParser());\n await app.listen(5000);\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nimport { Get, Controller, Response, Request } from '@nestjs/common';\nimport { AppService } from './app.service';\n\nconst l = console.log\n@Controller()\nexport class AppController {\n  @Get('json')\n  json(@Request() req){\n    console.log(req.cookies) // undefined\n  }\n}\n```\n\n```text\n$ npm install --save cookie-parser\n```\n\n```text\nconst app = await NestFactory.create(ApplicationModule);\napp.use(cookieParser());\n```\n\n```text\ncookie-parser\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as cookieParser from 'cookie-parser'\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.use(cookieParser());\n  await app.listen(5000);\n}\nbootstrap();\n```\n\n```text\n$ npm i cookie-parser\n$ npm i -D @types/cookie-parser\n```\n\n```text\n$ npm i cookie-parser\n$ npm i -D @types/cookie-parser\n```\n\n```text\nimport cookieParser from 'cookie-parser'; \n...\napp.use(cookieParser());\n```\n\n```text\nimport * as cookieParser from 'cookie-parser';\n```\n\n```text\nimport { Get, Controller, Response, Req } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { Request } from 'express';\n\nconst l = console.log\n@Controller()\nexport class AppController {\n  @Get('json')\n  json(@Req() req: Request){\n    console.log(req.cookies) // undefined\n  }\n}\n```\n\n========================================\n\nComments:\n- How to do so in e2e tests","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":119,"estimatedTokens":556}}176{"id":"stack-67812894","source":"stackoverflow","questionId":67812894,"title":"Disable X-Powered-By in nestjs does not work","tags":["nestjs"],"text":"Title: Disable X-Powered-By in nestjs does not work\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to disable `X-Powered-By` in nestjs like the following, but it does not work.\n\nmain.ts:\n\n```\nasync function bootstrap() {\n const logger = new Logger('bootstrap') \n const app = await NestFactory.create(AppModule);\n \n app.disable('X-Powered-By') // this line\n ...\n \n const PORT = process.env.PORT\n await app.listen(PORT);\n logger.log(`Application is start on port : ${PORT}`)\n }\n \n bootstrap();\n```\n\nAfter disabling the `X-Powered-By` header, in the next requests, that `X-Powered-By` header still exists.\n\nWhere am I doing something wrong?\n\n========================================\n\nTop Answer:\nIf `app.disable('x-powered-by')` does not work, you can try/fix it with:\n\n```\napp.getHttpAdapter().getInstance().disable('x-powered-by');\n```\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n    const logger = new Logger('bootstrap') \n    const app = await NestFactory.create<NestExpressApplication>(AppModule);\n  \n    app.disable('X-Powered-By') // this line\n    ...\n    \n    const PORT = process.env.PORT\n    await app.listen(PORT);\n    logger.log(`Application is start on port : ${PORT}`)\n  }\n  \n  bootstrap();\n```\n\n```text\nX-Powered-By\n```\n\n```text\nX-Powered-By\n```\n\n```text\nX-Powered-By\n```\n\n```text\napp.disable('x-powered-by')\n```\n\n```text\napp.getHttpAdapter().getInstance().disable('x-powered-by');\n```\n\n```text\napp.disable('x-powered-by')\n```\n\n```text\nconst app = await NestFactory.create<NestExpressApplication>(AppModule)\n\napp.disable('x-powered-by')\n```\n\n```text\nProperty 'disable' does not exist on type 'INestApplication'\n```\n\n```text\nNestFactory.create\n```\n\n```text\napp.disable\n```\n\n```text\nx-powered-by\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport type { NestExpressApplication } from '@nestjs/platform-express';\nimport { AppModule } from './app.module';\n\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\napp.disable('x-powered-by', 'X-Powered-By');\n```\n\n========================================\n\nComments:\n- This works for me with Nest, Express and Typescript.\n- This is the one that worked with current version 8.x\n- This works with version 10.x\n- I'm on NestJS 10.x and this is not working for me, or any of the other answers here. I also tried following this blog post, but it also did not work for me: dev.to/suzuki0430/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":119,"estimatedTokens":607}}177{"id":"stack-53479741","source":"stackoverflow","questionId":53479741,"title":"Run program on init","tags":["javascript","node.js","typescript","dependency-injection","nestjs"],"text":"Title: Run program on init\nTags: javascript, node.js, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would create a program (script) that launches actions when it's get run, so I'm not using routes in this program\n\nI'm using NestJS framework (requirement).\n\nActually I'm trying to write my code in `main.ts` file and importing a service with my methods .\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport {AppService} from './app.service'\nimport { TreeChildren } from 'typeorm';\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n}\nlet appService: AppService; My service\n\n```\n@Injectable()\nexport class AppService {\n constructor(\n @InjectRepository(File) private readonly fileRepository: Repository,\n ) {}\n\n async getTypes(): Promise {\n return await this.fileRepository.find();\n }\n}\n```\n\nI would use services to treat my operations so I sould use DI, which is not working in a non class file.\n\nI would know how to run my operations in init time in a proper way\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport {AppService} from './app.service'\nimport { TreeChildren } from 'typeorm';\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nlet appService: AppService; <- can't use appService methods\nthis.appService.\nbootstrap();\n```\n\n```text\n@Injectable()\nexport class AppService {\n  constructor(\n    @InjectRepository(File) private readonly fileRepository: Repository<File>,\n  ) {}\n\n  async getTypes(): Promise<File[]> {\n    return await this.fileRepository.find();\n  }\n}\n```\n\n```text\nmain.ts\n```\n\n```text\nexport class AppService implements OnModuleInit {\n  onModuleInit() {\n    console.log(`Initialization...`);\n    this.doStuff();\n  }\n}\n```\n\n```text\nexport class ApplicationModule implements OnModuleInit {\n  \n  constructor(private appService: AppService) {\n  }\n\n  onModuleInit() {\n    console.log(`Initialization...`);\n    this.appService.doStuff();\n  }\n}\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n  const appService = app.get(AppService);\n}\n```\n\n========================================\n\nComments:\n- Thereโ€™s OnModuleInit hook and you can apply it on AppModulr\n- Thanks you it's a way to do it, meanwhile I have found execution context: docs.nestjs.com/execution-context\n- What are pros and cons of using Lifecycle Events vs Execution Context?\n- Although `implements` is strictly necessary in languages as Java and C#, in Typescript this is not required; I'd recommend avoiding using it at all.","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":110,"estimatedTokens":690}}178{"id":"stack-49031159","source":"stackoverflow","questionId":49031159,"title":"Nest.js get injector instance","tags":["node.js","typescript","nestjs"],"text":"Title: Nest.js get injector instance\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to create an instance of a dynamically loaded class trough Nest.js dependency injection service. \n\nIn Angular I would use `Injector.create`, what would be the equivalent in Nest.js ?\n\n========================================\n\nCode:\n```text\nInjector.create\n```\n\n```text\n@Injectable()\nexport class AppletService {\n  files: FileService;\n\n  constructor(\n    private moduleRef: ModuleRef,\n  ) { \n    this.files = moduleRef.get(FileService);\n  }\n}\n```\n\n========================================\n\nComments:\n- Is posible get a instance service like AppConfigService in a static method ?\n- @Hector i have the same question.. stackoverflow.com/questions/69572752/&hellip;\n- using `moduleRef.get` on `constructor`'s isn't safe. Move it to `onModuleInit` method instead","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":35,"estimatedTokens":217}}179{"id":"stack-60884932","source":"stackoverflow","questionId":60884932,"title":"NestJS JWT Strategy requires a secret or key","tags":["node.js","authentication","jwt","passport.js","nestjs"],"text":"Title: NestJS JWT Strategy requires a secret or key\nTags: node.js, authentication, jwt, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my NestJS Node application, I have set up JWT authentication using Passport (as per https://docs.nestjs.com/techniques/authentication) however I am attempting to keep the JWT Key in environment files which are retrieved using the built-in ConfigService.\n\n```\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly configService: ConfigService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: configService.get('JWT_KEY'),\n signOptions: { expiresIn: '60s' }\n });\n }\n```\n\nThe module is registered as follows:\n\n```\nJwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: (configService: ConfigService) => {\n return {\n secret: configService.get('JWT_KEY')\n };\n },\n inject: [ConfigService]\n })\n```\n\nI am getting the following error when starting the app:\n\n```\napi: [Nest] 16244 - 03/27/2020, 10:52:00 [ExceptionHandler] JwtStrategy requires a secret or key +1ms\n```\n\nIt appears that the JWTStrategy class is instantiating before the ConfigService is ready to provide the JWT Key and is returning undefined within the Strategy when calling `configService.get('JWT_KEY')`.\n\nWhat am I doing wrong here? How can I ensure that the ConfigService is ready prior to attempting to retrieve any environment variables?\n\nUPDATE:\nEntire AuthModule is below:\n\n```\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { LocalStrategy } from './strategies/local.strategy';\nimport { SharedModule } from '../shared/shared.module';\nimport { UsersModule } from '../users/users.module';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { JwtModule } from '@nestjs/jwt';\nimport { Module } from '@nestjs/common';\nimport { PassportModule } from '@nestjs/passport';\n\nconst passportModule = PassportModule.register({ defaultStrategy: 'jwt' });\n@Module({\n imports: [\n UsersModule,\n passportModule,\n JwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => {\n return {\n secret: configService.get('JWT_KEY')\n };\n },\n inject: [ConfigService]\n })\n ],\n providers: [ConfigService, AuthService, LocalStrategy, JwtStrategy],\n controllers: [AuthController],\n exports: [passportModule]\n})\nexport class AuthModule {}\n```\n\n========================================\n\nTop Answer:\nIf @Jay McDoniel's answer doesn't work, please ensure the env file existence and correct the env key (\"JWT_KEY\")\n\n========================================\n\nCode:\n```js\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly configService: ConfigService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: configService.get<string>('JWT_KEY'),\n      signOptions: { expiresIn: '60s' }\n    });\n  }\n```\n\n```js\nJwtModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: (configService: ConfigService) => {\n        return {\n          secret: configService.get<string>('JWT_KEY')\n        };\n      },\n      inject: [ConfigService]\n    })\n```\n\n```text\napi: [Nest] 16244   - 03/27/2020, 10:52:00   [ExceptionHandler] JwtStrategy requires a secret or key +1ms\n```\n\n```js\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { LocalStrategy } from './strategies/local.strategy';\nimport { SharedModule } from '../shared/shared.module';\nimport { UsersModule } from '../users/users.module';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { JwtModule } from '@nestjs/jwt';\nimport { Module } from '@nestjs/common';\nimport { PassportModule } from '@nestjs/passport';\n\nconst passportModule = PassportModule.register({ defaultStrategy: 'jwt' });\n@Module({\n  imports: [\n    UsersModule,\n    passportModule,\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => {\n        return {\n          secret: configService.get<string>('JWT_KEY')\n        };\n      },\n      inject: [ConfigService]\n    })\n  ],\n  providers: [ConfigService, AuthService, LocalStrategy, JwtStrategy],\n  controllers: [AuthController],\n  exports: [passportModule]\n})\nexport class AuthModule {}\n```\n\n```text\nconfigService.get<string>('JWT_KEY')\n```\n\n```js\n@Module({\n  imports: [\n    PassportModule.register({defaultStrategy: 'jwt' }),\n    UserModule,\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => {\n        return {\n          secret: configService.get<string>('JWT_KEY')\n        };\n      },\n      inject: [ConfigService]\n    }),\n    ConfigModule,\n  ],\n  providers: [LocalStrategy, JwtStrategy, AuthService],\n  controllers: [AuthController],\n  exports: [PassportStrategy],\n})\nexport class AuthModule {}\n```\n\n```text\nimport\n```\n\n```text\nConfigModule\n```\n\n```text\nAuthModule\n```\n\n```text\nConfigService\n```\n\n```text\nproviders\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigService\n```\n\n```text\nConfigModule\n```\n\n```text\nexports\n```\n\n```text\nConfigService\n```\n\n```text\nAuthModule\n```\n\n```text\n@Module({\n  imports: [\n    JwtModule.register({\n      secret: process.env.JWT_SECRET,\n      signOptions: { expiresIn: '5m' },\n    }),\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }),\n  ],\n  controllers: [AuthController],\n  providers: [AuthService, PrismaService, LocalStrategy, JwtStrategy, ConfigService, RefreshJwtStrategy]\n})\nexport class AuthModule { }\n```\n\n========================================\n\nComments:\n- Can you also add your `PassportModule`'s registration?\n- My PassportModule is registered: `const passportModule = PassportModule.register({ defaultStrategy: 'jwt' });` and is then added to my imports array.\n- Can you show your entire `AuthModule` then? I can't see anything inherently wrong, and I've got a set up where I pass my `ConfigService` to a `Strategy` class working\n- Sure, added entire AuthModule to the original question for clarity.\n- I encountered the same error even if I'm getting the key from .env also tried hardcoding the key but the same error occurred.\n- @jongbanaag what was you solution?\n- It appears that the issue is not with the key being pulled into the AuthModule, but with it being pulled into the JWTStrategy itself. I have followed the above and many thanks for your assistance. But when the JWTStrategy is being instantiated, which appears to happen before the AuthModule?!, the configService is returning undefined for this value.\n- Do you have the `JwtStrategy` being added anywhere else? Like I said, I have a setup where a strategy has the `ConfigService` injected and it's working as expected\n- I have just realised there was a typo in the JWTStrategy. I had put JWT_KET instead of JWT_KEY... Thanks everyone for their help. D'oh. *facepalm*\n- literally toke me 4hrs to get to your answer. Thanks a lot. Take care.\n- How can I get TOKEN value from an ASYNC config service in JwtStrategy's super call? `super({token: await authConfig.getConfig.jwtToken})` I am using AWS Secret Manager for storing sensitive values.\n- If it's in a `super()` call, you can't. You would need to use an async `factory` to make the async call, and then inject the result.","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":253,"estimatedTokens":1876}}180{"id":"stack-55412849","source":"stackoverflow","questionId":55412849,"title":"How to globally inject value across modules in NestJS?","tags":["nestjs","nrwl"],"text":"Title: How to globally inject value across modules in NestJS?\nTags: nestjs, nrwl\nSource: Stack Overflow\n\nQuestion:\nI'm working with nx workspace and nestjs.\nI would like to inject a value across multiple modules in nestjs app.\n\nFinal goal is to reproduce similar way of configuration management as vsavkin mentioned for Angular \n\nBut it seems it's not possible, or I missed something. \n\n Nest can't resolve dependencies of the FeatureService (?). Please make\n sure that the argument at index [0] is available in the FeatureModule\n context.\n\nHow can I notify `FeatureModule` it needs to access to this global injected value ?\n\nThis is working fine inside `AppService` (service in root module), but not in any sub modules.\n\nHere is my code below.\nOr an full example on codesandbox.io \n\n**app.module.ts**\n\n```\n@Module({\n imports: [\n FeatureModule\n ],\n controllers: [\n AppController\n ],\n providers: [\n AppService,\n {\n provide: 'MY-TOKEN',\n useValue: 'my-injected-value',\n }\n ],\n})\nexport class AppModule {}\n```\n\n**feature.module.ts**\n\n```\n@Module({\n imports: [],\n controllers: [],\n providers: [\n FeatureService\n ],\n})\nexport class FeatureModule {\n}\n```\n\n**feature.service.ts**\n\n```\n@Injectable()\nexport class AppService {\n constructor(\n @Inject('MY-TOKEN') private injectedValue: string\n ) {}\n}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    FeatureModule\n  ],\n  controllers: [\n    AppController\n  ],\n  providers: [\n    AppService,\n    {\n      provide: 'MY-TOKEN',\n      useValue: 'my-injected-value',\n    }\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n  imports: [],\n  controllers: [],\n  providers: [\n    FeatureService\n  ],\n})\nexport class FeatureModule {\n}\n```\n\n```text\n@Injectable()\nexport class AppService {\n  constructor(\n    @Inject('MY-TOKEN') private injectedValue: string\n  ) {}\n}\n```\n\n```text\nFeatureModule\n```\n\n```text\nAppService\n```\n\n```text\n@Global()\n@Module({  \n  providers: [\n    {\n      provide: 'MY-TOKEN',\n      useValue: 'my-injected-value',\n    }\n  ],\n  exports: ['MY-TOKEN'],\n})\nexport class GlobalModule {}\n```\n\n```text\nMY-TOKEN\n```\n\n========================================\n\nComments:\n- Works like a charm. Why I didn't think about it ! Thank you very much Karol. ;-)\n- how about directly set the application module a global one, instead create a new module, is that ok?\n- @KentWood doesn't work for some reason. It's needed to import global module into app.module, if you put global decorator on the app.module, nothing changes","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":144,"estimatedTokens":626}}181{"id":"stack-60953406","source":"stackoverflow","questionId":60953406,"title":"Why are types in dto not visible in swagger?","tags":["javascript","nestjs","nestjs-swagger"],"text":"Title: Why are types in dto not visible in swagger?\nTags: javascript, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI'm setting up swagger document in my small Nest.js app according to this documentation: https://docs.nestjs.com/recipes/swagger\n\nHow do I setup dto to correctly show schema in swagger? To be more specific, nested types. It shows only top level keys. If one of the keys is of type of something, it shows it just as empty object. Here is what I mean:\n\ndto:\n\n```\nexport class HealthCheckDataDto {\n serverStatus: {} // dont have it typed yet;\n dbStatus: MongoConnectionStateT;\n}\n```\n\nswagger:\n\n```\n[\n {\n \"serverStatus\": {},\n \"dbStatus\": {}\n }\n]\n```\n\nexpected result in swagger example value:\n\n```\n[\n {\n \"serverStatus\": {},\n \"dbStatus\": {\n \"isOnline\": true,\n \"msg\": \"string\"\n }\n }\n]\n```\n\nThis is the function:\n\n```\n@ApiResponse({ status: 200, description: 'blabla', type: [HealthCheckDataDto] })\n@ApiResponse({ status: 500, description: 'blabla, but bad', type: [HealthCheckDataDto] })\n@Get('/api/healthcheck')\nhealthCheckApp(@Res() res: Response) {\n\n // check HCs and setup status code\n const healthCheck: HealthCheckI = this.healthcheckService.getFullHealthCheck();\n const statusCode = (healthCheck.dbStatus.isOnline) ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR;\n\n // return that response\n res.status(statusCode).json(healthCheck);\n}\n```\n\nWhat I tried:\n\n- When I replaced type for exact params in dto, it shows it properly in swagger.\n\n- I did cross-check of dto against interface, where I added wrong field into 'isOnline' and it finds it and marks it, that it isnt good.\n\n- Schema is displayed in swagger, but also only top level, not the typed part. So its not just example value.\n\n- Checked Stack Overflow; found two related threads, but neither one solved it. One suggested to manually create sub-dtos instead of types. Well... I better not do that.\n\nI'm doing something wrong, or missed something in documentation. Or maybe parser of that swagger module is unable to extract type/interface when generating json.\n\n========================================\n\nTop Answer:\nYou can show types in Swagger automatically using the OpenAPI CLI plugin.\n\nAdd:\n\n```\n\"compilerOptions\": {\n \"plugins\": [\"@nestjs/swagger\"]\n }\n```\n\nto `nest-cli.json`, and add:\n\n```\nimport { ApiProperty, ApiBody } from '@nestjs/swagger';\n```\n\nto each of your DTOs, and the plugin will automagically annotate and document your schemas!\n\n========================================\n\nCode:\n```text\nexport class HealthCheckDataDto {\n    serverStatus: {} // dont have it typed yet;\n    dbStatus: MongoConnectionStateT;\n}\n```\n\n```text\n[\n  {\n    \"serverStatus\": {},\n    \"dbStatus\": {}\n  }\n]\n```\n\n```text\n[\n  {\n    \"serverStatus\": {},\n    \"dbStatus\": {\n      \"isOnline\": true,\n      \"msg\": \"string\"\n    }\n  }\n]\n```\n\n```text\n@ApiResponse({ status: 200, description: 'blabla', type: [HealthCheckDataDto] })\n@ApiResponse({ status: 500, description: 'blabla, but bad', type: [HealthCheckDataDto] })\n@Get('/api/healthcheck')\nhealthCheckApp(@Res() res: Response<HealthCheckDataDto>) {\n\n    // check HCs and setup status code\n    const healthCheck: HealthCheckI = this.healthcheckService.getFullHealthCheck();\n    const statusCode = (healthCheck.dbStatus.isOnline) ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    // return that response\n    res.status(statusCode).json(healthCheck);\n}\n```\n\n```text\nResult<SomeDto>\n```\n\n```json\n\"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger\"]\n  }\n```\n\n```text\nimport { ApiProperty, ApiBody } from '@nestjs/swagger';\n```\n\n```text\nnest-cli.json\n```\n\n```text\n@Body(), @Query(), @Param()\n```\n\n```text\n{\n\"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger/plugin\"]\n  }\n}\n```\n\n```text\nnest-cli.json\n```\n\n```text\n@ApiProperty()\n```\n\n========================================\n\nComments:\n- Hi drkvogel and @ibrahim-ali-musah Thanks for answers. I checked in code the stuff you mentioned. It was already there. It might be version issues, since I made this app few months before that cli doc has been created and meanwhile there was also major version incerement on nest and its libs. In Q1, I have extension for app in schedule, so I will upgrade libs and stuff and will try again. If it will works without all the stuff mentioned in my thread answer, I will have to update my question with obsolete tag. Thank you!\n- @Peter You can show thanks by upvoting our answers! :)","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":184,"estimatedTokens":1115}}182{"id":"stack-52950861","source":"stackoverflow","questionId":52950861,"title":"How to make param required in NestJS?","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: How to make param required in NestJS?\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to make my route `Query` parameter required.\nIf it is missing I expect it to throw 404 HTTP error.\n\n```\n@Controller('')\nexport class AppController {\n constructor() {}\n @Get('/businessdata/messages')\n public async getAllMessages(\n @Query('startDate', ValidateDate) startDate: string,\n @Query('endDate', ValidateDate) endDate: string,\n ): Promise {\n ...\n }\n}\n```\n\nI'm using NestJs pipes to determine if a parameter is valid, but not if it exists And I'm not sure that Pipes are made for that.\n\nSo how can I check in NestJS if my param exists if not throw an error?\n\n========================================\n\nTop Answer:\nNestJS does not provide a decorator (like `@Query`) that detects undefined\nvalue in `request.query[key]`.\n\nYou can write custom decorator for that:\n\n```\nimport { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common'\nimport { Request } from 'express';\nimport { ParsedQs } from 'qs';\n\nexport const QueryRequired = createParamDecorator(\n (key: string, ctx: ExecutionContext): string | Array | ParsedQs | Array => {\n const request = ctx.switchToHttp().getRequest();\n\n const value = request.query[key];\n\n if (value === undefined) {\n throw new BadRequestException(`Missing required query param: '${key}'`);\n }\n\n return value;\n }\n)\n```\n\nThen use `@QueryRequired` decorator as you would use `@Query`:\n\n```\n@Get()\nasync someMethod(@QueryRequired('requiredParam') requiredParam: string): Promise {\n ...\n}\n```\n\n========================================\n\nCode:\n```ts\n@Controller('')\nexport class AppController {\n  constructor() {}\n  @Get('/businessdata/messages')\n  public async getAllMessages(\n    @Query('startDate', ValidateDate) startDate: string,\n    @Query('endDate', ValidateDate) endDate: string,\n  ): Promise<string> {\n   ...\n  }\n}\n```\n\n```text\nQuery\n```\n\n```text\nimport { IsNotEmpty } from 'class-validator';\n\nexport class CreateUserDto {\n   @IsNotEmpty()\n   password: string;\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-validator\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      /*\n            If set to true, instead of stripping non-whitelisted \n            properties validator will throw an exception.\n      */\n      forbidNonWhitelisted: true,\n      /*\n            If set to true, validator will strip validated (returned) \n            object of any properties that do not use any validation decorators.\n      */\n      whitelist: true,\n    }),\n  );\n```\n\n```text\nclass-validator\n```\n\n```text\n{password: 'mypassword'}\n```\n\n```text\n{password: 'mypassword', other: 'reject me!'}\n```\n\n```text\nimport { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common'\nimport { Request } from 'express';\nimport { ParsedQs } from 'qs';\n\nexport const QueryRequired = createParamDecorator(\n  (key: string, ctx: ExecutionContext): string | Array<string> | ParsedQs | Array<ParsedQs> => {\n    const request = ctx.switchToHttp().getRequest<Request>();\n\n    const value = request.query[key];\n\n    if (value === undefined) {\n      throw new BadRequestException(`Missing required query param: '${key}'`);\n    }\n\n    return value;\n  }\n)\n```\n\n```text\n@Get()\nasync someMethod(@QueryRequired('requiredParam') requiredParam: string): Promise<any> {\n    ...\n}\n```\n\n```text\n@Query\n```\n\n```text\nrequest.query[key]\n```\n\n```text\n@QueryRequired\n```\n\n```text\n@Query\n```\n\n```js\n@Get('/businessdata/messages')\npublic async getAllMessages(\n  @Query() getAllMessagesDto: GetAllMessagesDto\n): Promise<string> {\n  console.log(getAllMessagesDto.endDate) // etc\n}\n```\n\n```js\nimport { IsNotEmpty } from 'class-validator';\n\nexport class GetAllMessagesDto {\n  @IsNotEmpty()\n  startDate: Date;\n  \n  @IsNotEmpty()\n  endDate: Date;\n}\n```\n\n```text\n@Body\n```\n\n```text\nforbidNonWhitelisted\n```\n\n========================================\n\nComments:\n- Did you find a solution? It seems like it's not possible within the framework. Looks like you'd have to write a custom Pipe to do it?\n- Yes I have finally a pipe that do check it if empty or not\n- Can you plz provide your solution to check for missing parameter ?\n- Can you use this approach for `@Query` parameters though. These would only be strings. `@Get() getName( @Query name: string) { return name}`\n- If not providing the password value you will now get a 500 error, so how can we handle this case?\n- The @IsNotEmpty() Decorator is made to check if the value is empty or null but he doesn't check for a missing parameter\n- This should be an accepted answer.\n- Updating to `node-saml` v5.1.0 required me to change the return type to `string | ParsedQs | Array`","metadata":{"transformedAt":"2026-08-18T18:33:02.417Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":213,"estimatedTokens":1175}}183{"id":"stack-64337784","source":"stackoverflow","questionId":64337784,"title":"nestjs use ConfigService in simple provider class","tags":["typescript","config","nestjs"],"text":"Title: nestjs use ConfigService in simple provider class\nTags: typescript, config, nestjs\nSource: Stack Overflow\n\nQuestion:\nis it possible to access nested configurations made by a configuration factory inside a simple provider class?\n\nlike:\n\n```\n/*Can't use ConfigService because there is no way of injecting it seemingly*/\nexport const databaseProviders = [\n {\n provide: 'SEQUELIZE',\n useFactory: async () => {\n const sequelize = new Sequelize({\n host: ConfigService.get('pg.host'),\n port: ConfigService.get('pg.port'),\n dialect: 'postgres',\n username: ConfigService.get('pg.username'),\n password: ConfigService.get('pg.password'),\n database: ConfigService.get('pg.database')\n });\n sequelize.addModels([\n models...\n ]);\n await sequelize.sync(\n process.env.NODE_ENV === 'developent' && {\n force: true\n }\n );\n return sequelize;\n }\n }\n];\n```\n\n`config/configuration.ts`\n\n```\nexport default () => ({\n pg: {\n host: 'localhost',\n port: 5432,\n username: process.env.NODE_ENV logic...\n password: process.env.NODE_ENV logic...\n database: process.env.NODE_ENV logic...\n }\n});\n```\n\n`root.module.ts`\n\n```\n...\nimport { ConfigModule } from '@nestjs/config';\nimport configuration from './config/configuration';\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n load: [configuration]\n }),\n...\n```\n\nif not - is it possible to include `ConfigService` inside a simple provider class, that isn't annotated with `@Injectable()`\n\nI would think not becuase https://docs.nestjs.com/techniques/configuration#getting-started\n\nUsing the ConfigService#\nTo access configuration values from our ConfigService, we first need to >inject ConfigService. As with any provider, we need to import its >containing module - the ConfigModule - into the module that will use it (unless you set the isGlobal property in the options object passed to the ConfigModule.forRoot() method to true). Import it into a feature module as shown below.\n\nHowever it is pretty clever that you can perform some logic based on `process.env.NODE_ENV` and dynamically change database configs between production, staging, development etc. So I would very much like a solution that would make this usable outside of just `@Injectable`s\n\nI assume one could make a simple util class in the root of the project that achieves the same thing, and use it inside of the application. But I think that solution has a lot of overhead.\n\n========================================\n\nCode:\n```text\n/*Can't use ConfigService because there is no way of injecting it seemingly*/\nexport const databaseProviders = [\n  {\n    provide: 'SEQUELIZE',\n    useFactory: async () => {\n      const sequelize = new Sequelize({\n        host: ConfigService.get<string>('pg.host'),\n        port: ConfigService.get<number>('pg.port'),\n        dialect: 'postgres',\n        username: ConfigService.get<string>('pg.username'),\n        password: ConfigService.get<string>('pg.password'),\n        database: ConfigService.get<string>('pg.database')\n      });\n      sequelize.addModels([\n         models...\n      ]);\n      await sequelize.sync(\n        process.env.NODE_ENV === 'developent' && {\n          force: true\n        }\n      );\n      return sequelize;\n    }\n  }\n];\n```\n\n```text\nexport default () => ({\n  pg: {\n    host: 'localhost',\n    port: 5432,\n    username: process.env.NODE_ENV logic...\n    password: process.env.NODE_ENV logic...\n    database: process.env.NODE_ENV logic...\n  }\n});\n```\n\n```text\n...\nimport { ConfigModule } from '@nestjs/config';\nimport configuration from './config/configuration';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n      load: [configuration]\n    }),\n...\n```\n\n```text\nconfig/configuration.ts\n```\n\n```text\nroot.module.ts\n```\n\n```text\nConfigService\n```\n\n```text\n@Injectable()\n```\n\n```text\nprocess.env.NODE_ENV\n```\n\n```text\n@Injectable\n```\n\n```js\n/*Can't use ConfigService because there is no way of injecting it seemingly*/\nexport const databaseProviders = [\n  {\n    provide: 'SEQUELIZE',\n    inject: [ConfigService], //no worries for imports because you're using a global module\n    useFactory: async (configService: ConfigService) => {\n      const sequelize = new Sequelize({\n        host: configService.get<string>('pg.host'),\n        port: configService.get<number>('pg.port'),\n        dialect: 'postgres',\n        username: configService.get<string>('pg.username'),\n        password: configService.get<string>('pg.password'),\n        database: configService.get<string>('pg.database')\n      });\n      sequelize.addModels([\n         models...\n      ]);\n      await sequelize.sync(\n        process.env.NODE_ENV === 'developent' && {\n          force: true\n        }\n      );\n      return sequelize;\n    }\n  }\n];\n```\n\n```text\ninject\n```\n\n========================================\n\nComments:\n- ConifgService => ConfigService","metadata":{"transformedAt":"2026-08-18T18:33:02.418Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":196,"estimatedTokens":1201}}184{"id":"stack-70228893","source":"stackoverflow","questionId":70228893,"title":"Testing a NestJS Service that uses Prisma without actually accessing the database","tags":["jestjs","nestjs","prisma"],"text":"Title: Testing a NestJS Service that uses Prisma without actually accessing the database\nTags: jestjs, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nMost examples I've seen of how to test a Prisma-injected NestJS Service (e.g. `prisma-sample` in `testing-nestjs`) are for \"end to end\" testing. They actually access the database, performing actual queries and then rolling back the results if necessary.\n\nFor my current needs, I want to implement lower-level \"integration\" testing.\n\nAs part of this, I want to remove Prisma from the equation. I want the focus to be on my service's functionality instead of the state of data within the database and Prisma's ability to return it.\n\nOne big win of this approach is that it obviates the need to craft \"setup\" queries and \"teardown\"/reset operations for specific tests. Instead, I'd like to simply manually specify what we would expect Prisma to return.\n\nIn an environment consisting of NestJS, Prisma, and Jest, how should I accomplish this?\n\nUPDATE: The author of the testing-nestjs project pointed out in the comments that the project does have an example of database mocking. It looks nice! Others may still be interested in checking out the Gist that I've linked to as it includes some other useful functionality.\n\n========================================\n\nTop Answer:\nTo get a reference to your service's prisma instance, use:\n\n```\nprisma = module.get(PrismaService)\n```\n\nThen, assuming your function calls `prisma.name.findMany()`, you can use `jest.fn().mockReturnValueOnce()` to mock (manually specify) Prisma's next return value:\n\n```\nprisma.name.findMany = jest.fn().mockReturnValueOnce([\n { id: 0, name: 'developer' },\n { id: 10, name: 'architect' },\n { id: 13, name: 'dog walker' }\n]);\n```\n\n(Of course, you would change `prisma.name.findMany` in the code above to match whatever function you're calling.)\n\nThen, call the function on your Service that you're testing. For example:\n\n```\nexpect(await service.getFirstJob(\"steve\")).toBe('developer');\n```\n\nThat's it! A full code example can be found here.\n\n========================================\n\nCode:\n```text\nprisma-sample\n```\n\n```text\ntesting-nestjs\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PrismaClient } from '@prisma/client'\nimport { mockDeep, DeepMockProxy } from 'jest-mock-extended'\n    \ndescribe('UserService', () => {\n  let service: UserService;\n  let prisma: DeepMockProxy<PrismaClient>;\n    \n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [UserService, PrismaService],\n    })\n      .overrideProvider(PrismaService)\n      .useValue(mockDeep<PrismaClient>())\n      .compile();\n    \n    service = module.get(UserService);\n    prisma = module.get(PrismaService);\n  });\n    \n\n  it('returns users', () => {\n    const testUsers = [];\n\n    prisma.user.findMany.mockResolvedValueOnce(testUsers);\n\n    expect(service.findAll()).resolves.toBe(testUsers);\n  });\n});\n```\n\n```text\njest-mock-extended\n```\n\n```text\nPrismaService\n```\n\n```js\nprisma = module.get<PrismaService>(PrismaService)\n```\n\n```js\nprisma.name.findMany = jest.fn().mockReturnValueOnce([\n    { id: 0, name: 'developer' },\n    { id: 10, name: 'architect' },\n    { id: 13, name: 'dog walker' }\n]);\n```\n\n```js\nexpect(await service.getFirstJob(\"steve\")).toBe('developer');\n```\n\n```text\nprisma.name.findMany()\n```\n\n```text\njest.fn().mockReturnValueOnce()\n```\n\n```text\nprisma.name.findMany\n```\n\n```js\nimport { Controller, Get } from '@nestjs/common';\nimport { DbService } from 'src/db/db.service';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(\n    private readonly appService: AppService,\n    private readonly prisma: DbService,\n  ) {}\n\n  @Get()\n  async getHello(): Promise<string> {\n    const result = await this.prisma.user.findMany();\n\n    console.log('result', result);\n\n    return this.appService.getHello();\n  }\n}\n```\n\n```js\ndescribe('AppController', () => {\n  let appController: AppController;\n\n  const mockPrisma = {\n    user: { findMany: () => Promise.resolve([]) },\n  };\n\n  beforeEach(async () => {\n    const app: TestingModule = await Test.createTestingModule({\n      controllers: [AppController],\n      providers: [AppService, DbService],\n    })\n      .overrideProvider(DbService)\n      .useValue(mockPrisma)\n      .compile();\n\n    appController = app.get<AppController>(AppController);\n  });\n\n  describe('root', () => {\n    it('should return \"Hello World!\"', () => {\n      expect(appController.getHello()).resolves.toBe('Hello World!');\n    });\n  });\n});\n```\n\n```js\n@Injectable()\nexport class DbService extends PrismaClient implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });\n  }\n}\n```\n\n```text\nDbService\n```\n\n```text\n'DbService'\n```\n\n========================================\n\nComments:\n- As you can see, I've added my own answer already. I'm curious what other approaches others prefer.\n- By the way, that same `testing-nestjs` repo you linked, it has unit tests for prisma where the database *is* mocked (source, I'm the author)\n- @JayMcDoniel I thought youโ€™d see this! ๐Ÿ‘‹ Can you a link? All I remember seeing were tests that seemed to be perform actual queries on the DB. Maybe I just misunderstood.\n- I was on mobile and didn't see the link - I'll check it out!\n- Ahhhh I see now - I thought the repo only had e2e tests. This is great; thanks, Jay!\n- In your gists, do we need to extend toHaveBeenCalledWithObjectMatchingHash method always?\n- Hi, @SangbeomHan - I'll respond on GitHub.\n- This doesn't work for me. I get the error \"Cannot read properties of undefined (reading 'name')\" Where name ofcourse is the function I use\n- @Sytham That means that `prisma` is `undefined` for you. Try to figure out what you need to use instead.\n- You'll get `Cannot read properties of undefined (reading 'name')` if the Prisma is set to auto-connect on app boot (and if there is no DB, you have then used jest.mock). Set it to lazy connect, or use David F's approach.\n- I'd prefer this way of doing it since it's the one recommended by the official docs. Thank you for providing the Nest example!\n- Should be the recommended answer, this is the cleanest solution\n- Sure - updated this answer to be the accepted one. (feel free to disagree, anyone!)","metadata":{"transformedAt":"2026-08-18T18:33:02.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":215,"estimatedTokens":1609}}185{"id":"stack-56644690","source":"stackoverflow","questionId":56644690,"title":"How to mock chained function calls using jest?","tags":["node.js","typescript","jestjs","nestjs","typeorm"],"text":"Title: How to mock chained function calls using jest?\nTags: node.js, typescript, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am testing the following service:\n\n```\n@Injectable()\nexport class TripService {\n private readonly logger = new Logger('TripService');\n\n constructor(\n @InjectRepository(TripEntity)\n private tripRepository: Repository\n ) {}\n\n public async showTrip(clientId: string, tripId: string): Promise> {\n const trip = await this.tripRepository\n .createQueryBuilder('trips')\n .innerJoinAndSelect('trips.driver', 'driver', 'driver.clientId = :clientId', { clientId })\n .where({ id: tripId })\n .select([\n 'trips.id',\n 'trips.distance',\n 'trips.sourceAddress',\n 'trips.destinationAddress',\n 'trips.startTime',\n 'trips.endTime',\n 'trips.createdAt'\n ])\n .getOne();\n\n if (!trip) {\n throw new HttpException('Trip not found', HttpStatus.NOT_FOUND);\n }\n\n return trip;\n }\n}\n```\n\nMy repository mock:\n\n```\nexport const repositoryMockFactory: () => MockType> = jest.fn(() => ({\n findOne: jest.fn(entity => entity),\n findAndCount: jest.fn(entity => entity),\n create: jest.fn(entity => entity),\n save: jest.fn(entity => entity),\n update: jest.fn(entity => entity),\n delete: jest.fn(entity => entity),\n createQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n })),\n}));\n```\n\nMy tripService.spec.ts:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TripService } from './trip.service';\nimport { MockType } from '../mock/mock.type';\nimport { Repository } from 'typeorm';\nimport { TripEntity } from './trip.entity';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { repositoryMockFactory } from '../mock/repositoryMock.factory';\nimport { DriverEntity } from '../driver/driver.entity';\nimport { plainToClass } from 'class-transformer';\n\ndescribe('TripService', () => {\n let service: TripService;\n let tripRepositoryMock: MockType>;\n let driverRepositoryMock: MockType>;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n TripService,\n { provide: getRepositoryToken(DriverEntity), useFactory: repositoryMockFactory },\n { provide: getRepositoryToken(TripEntity), useFactory: repositoryMockFactory },\n ],\n }).compile();\n\n service = module.get(TripService);\n driverRepositoryMock = module.get(getRepositoryToken(DriverEntity));\n tripRepositoryMock = module.get(getRepositoryToken(TripEntity));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n expect(driverRepositoryMock).toBeDefined();\n expect(tripRepositoryMock).toBeDefined();\n });\n\n describe('TripService.showTrip()', () => {\n const trip: TripEntity = plainToClass(TripEntity, {\n id: 'one',\n distance: 123,\n sourceAddress: 'one',\n destinationAddress: 'one',\n startTime: 'one',\n endTime: 'one',\n createdAt: 'one',\n });\n it('should show the trip is it exists', async () => {\n tripRepositoryMock.createQueryBuilder.mockReturnValue(trip);\n await expect(service.showTrip('one', 'one')).resolves.toEqual(trip);\n });\n });\n});\n```\n\nI want to mock the call to the `tripRepository.createQueryBuilder().innerJoinAndSelect().where().select().getOne();`\n\nFirst question, should I mock the chained calls here because I assume that it should already be tested in Typeorm.\n\nSecond, if I want to mock the parameters passed to each chained call and finally also mock the return value, how can I go about it?\n\n========================================\n\nTop Answer:\nGuilherme's answer is totally right. I just wanted to offer a modified approach that might apply to more test cases, and in TypeScript. Instead of defining your chained calls as `()`, you can use a `jest.fn`, allowing you to make more assertions. e.g.,\n\n```\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst createQueryBuilder: any = {\n select: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n addSelect: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n groupBy: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n where: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n getRawMany: jest\n .fn()\n .mockImplementationOnce(() => {\n return FILTERED_REACTIONS\n })\n .mockImplementationOnce(() => {\n return SOMETHING_ELSE\n }),\n}\n\n/* run your code */\n\n// then you can include an assertion like this:\nexpect(createQueryBuilder.groupBy).toHaveBeenCalledWith(`some group`)\n```\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class TripService {\n  private readonly logger = new Logger('TripService');\n\n  constructor(\n    @InjectRepository(TripEntity)\n    private tripRepository: Repository<TripEntity>\n  ) {}\n\n  public async showTrip(clientId: string, tripId: string): Promise<Partial<TripEntity>> {\n    const trip = await this.tripRepository\n      .createQueryBuilder('trips')\n      .innerJoinAndSelect('trips.driver', 'driver', 'driver.clientId = :clientId', { clientId })\n      .where({ id: tripId })\n      .select([\n        'trips.id',\n        'trips.distance',\n        'trips.sourceAddress',\n        'trips.destinationAddress',\n        'trips.startTime',\n        'trips.endTime',\n        'trips.createdAt'\n      ])\n      .getOne();\n\n    if (!trip) {\n      throw new HttpException('Trip not found', HttpStatus.NOT_FOUND);\n    }\n\n    return trip;\n  }\n}\n```\n\n```text\nexport const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({\n    findOne: jest.fn(entity => entity),\n    findAndCount: jest.fn(entity => entity),\n    create: jest.fn(entity => entity),\n    save: jest.fn(entity => entity),\n    update: jest.fn(entity => entity),\n    delete: jest.fn(entity => entity),\n    createQueryBuilder: jest.fn(() => ({\n        delete: jest.fn().mockReturnThis(),\n        innerJoinAndSelect: jest.fn().mockReturnThis(),\n        innerJoin: jest.fn().mockReturnThis(),\n        from: jest.fn().mockReturnThis(),\n        where: jest.fn().mockReturnThis(),\n        execute: jest.fn().mockReturnThis(),\n        getOne: jest.fn().mockReturnThis(),\n    })),\n}));\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TripService } from './trip.service';\nimport { MockType } from '../mock/mock.type';\nimport { Repository } from 'typeorm';\nimport { TripEntity } from './trip.entity';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { repositoryMockFactory } from '../mock/repositoryMock.factory';\nimport { DriverEntity } from '../driver/driver.entity';\nimport { plainToClass } from 'class-transformer';\n\ndescribe('TripService', () => {\n  let service: TripService;\n  let tripRepositoryMock: MockType<Repository<TripEntity>>;\n  let driverRepositoryMock: MockType<Repository<DriverEntity>>;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        TripService,\n        { provide: getRepositoryToken(DriverEntity), useFactory: repositoryMockFactory },\n        { provide: getRepositoryToken(TripEntity), useFactory: repositoryMockFactory },\n      ],\n    }).compile();\n\n    service = module.get<TripService>(TripService);\n    driverRepositoryMock = module.get(getRepositoryToken(DriverEntity));\n    tripRepositoryMock = module.get(getRepositoryToken(TripEntity));\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n    expect(driverRepositoryMock).toBeDefined();\n    expect(tripRepositoryMock).toBeDefined();\n  });\n\n  describe('TripService.showTrip()', () => {\n    const trip: TripEntity = plainToClass(TripEntity, {\n      id: 'one',\n      distance: 123,\n      sourceAddress: 'one',\n      destinationAddress: 'one',\n      startTime: 'one',\n      endTime: 'one',\n      createdAt: 'one',\n    });\n    it('should show the trip is it exists', async () => {\n      tripRepositoryMock.createQueryBuilder.mockReturnValue(trip);\n      await expect(service.showTrip('one', 'one')).resolves.toEqual(trip);\n    });\n  });\n});\n```\n\n```text\ntripRepository.createQueryBuilder().innerJoinAndSelect().where().select().getOne();\n```\n\n```text\nconst reactions = await this.reactionEntity\n  .createQueryBuilder(TABLE_REACTIONS)\n  .select('reaction')\n  .addSelect('COUNT(1) as count')\n  .groupBy('content_id, source, reaction')\n  .where(`content_id = :contentId AND source = :source`, {\n    contentId,\n    source,\n  })\n  .getRawMany<GetContentReactionsResult>();\n\nreturn reactions;\n```\n\n```text\nit('should return the reactions that match the supplied parameters', async () => {\n  const PARAMS = { contentId: '1', source: 'anything' };\n\n  const FILTERED_REACTIONS = REACTIONS.filter(\n    r => r.contentId === PARAMS.contentId && r.source === PARAMS.source,\n  );\n\n  // Pay attention to this part. Here I created a createQueryBuilder \n  // const with all methods I call in the code above. Notice that I return\n  // the same `createQueryBuilder` in all the properties/methods it has\n  // except in the last one that is the one that return the data \n  // I want to check.\n  const createQueryBuilder: any = {\n    select: () => createQueryBuilder,\n    addSelect: () => createQueryBuilder,\n    groupBy: () => createQueryBuilder,\n    where: () => createQueryBuilder,\n    getRawMany: () => FILTERED_REACTIONS,\n  };\n\n  jest\n    .spyOn(reactionEntity, 'createQueryBuilder')\n    .mockImplementation(() => createQueryBuilder);\n\n  await expect(query.getContentReactions(PARAMS)).resolves.toEqual(\n    FILTERED_REACTIONS,\n  );\n});\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\n/* eslint-disable  @typescript-eslint/no-explicit-any */\nconst createQueryBuilder: any = {\n  select: jest.fn().mockImplementation(() => {\n    return createQueryBuilder\n  }),\n  addSelect: jest.fn().mockImplementation(() => {\n    return createQueryBuilder\n  }),\n  groupBy: jest.fn().mockImplementation(() => {\n    return createQueryBuilder\n  }),\n  where: jest.fn().mockImplementation(() => {\n    return createQueryBuilder\n  }),\n  getRawMany: jest\n    .fn()\n    .mockImplementationOnce(() => {\n      return FILTERED_REACTIONS\n    })\n    .mockImplementationOnce(() => {\n      return SOMETHING_ELSE\n    }),\n}\n\n/* run your code */\n\n// then you can include an assertion like this:\nexpect(createQueryBuilder.groupBy).toHaveBeenCalledWith(`some group`)\n```\n\n```text\n()\n```\n\n```text\njest.fn\n```\n\n```text\n@EntityRepository(User)\n  export class UserRepository extends Repository<User> {\n    async getStatus(id: string) {\n      const status = await this.createQueryBuilder()\n        .select('User.id')\n        .where('User.id = :id', { id })\n        .getRawOne();\n\n      return {status};\n    }\n  }\n```\n\n```text\nconst userRepoMock = mock<UserRepository>()\n```\n\n```text\nconst user = {\n      status: open,\n  };\n\n  when(userRepoMock.getStatus).mockResolvedValue(user as User);\n```\n\n========================================\n\nComments:\n- I would say that it could be better that you just use a test database with specific NODE_ENV and configuration so that your test includes all the sql transaction management in it. Mocking TypeOrm SQL interactions seems to me like a suboptimal way to test your service that is also quite expensive in dev time.\n- @zenbeni I will test with test database in e2e tests. This is just a unit test so I don't want to use database for it, as it will slow tests and add tight coupling with database.\n- What's the meaning behind this service? It appears to be a wrapper of your repository. If you want to unit test, you should rather unit test your business logic instead of the persistence layer. Is the TripRepository comming from a library or do you own it? Your test approach appears to be more a functional test and you should set up an actual test database for it.\n- Additionally, I'd argue that you should not create a unit test this service. This service depends on the database. It makes no sense to mock your entire database connection. Rather, this service is your dependency for other services and should be the one mocked. For other services, you should write tests: \"Assume my TripService gives me a trip, then I expect this to happen\" and \"Assume I get an exception, I expect it to be handled that way\" You should not mock each call on the repository. This is your underlying persistence layer. Assume it's working.\n- @k0pernikus This service is not just a wrapper, this has business logic before and after the query. I just gave it as an example. The real question is about mocking chained function calls.\n- @AbhyuditJain That's the issue that your are mixing business logic inside your repository. Create a real facade for your repository. It should only contain methods accessing your tripReposiory. That facade should only provide methods such as `getOneTrip(clientId: string, tripId: string)`. Create another service, that only contains your business logic. That service should depend on your RepositoryFacade. You now only have to mock the `getOneTrip` call instead of mocking the chained methods.\n- Since you are using typeorm and nestjs, this may help you: github.com/BrunnerLivio/nestjs-integration-test-db-example\n- @k0pernikus I ended up doing that only. I extended Repository and made my custom functions.\n- This. This this this. There are lots of questions and answers on this subject but this is the solution that works at the intersection of Jest, TypeScript, and third-party libraries\n- this implementation works with a few details for aggregate in TypeOrm\n- @Guilherme De Jesus Rafael Thank you soo soo much, you saved my next day :-D","metadata":{"transformedAt":"2026-08-18T18:33:02.418Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":407,"estimatedTokens":3404}}186{"id":"stack-59383994","source":"stackoverflow","questionId":59383994,"title":"How to use 'require' to import a JSON in NestJS controller?","tags":["json","typescript","nestjs"],"text":"Title: How to use 'require' to import a JSON in NestJS controller?\nTags: json, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to return a json file as a controller response, but I can't get the content of the json.\n\n```\nimport { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';\nimport { Response } from 'express';\n\nimport * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine\nconst MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found\n\n@Controller('commons')\nexport class CommonController {\n\n@Get('/payment-method')\n getPaymentMoethod(@Res() res: Response): any {\n res.status(HttpStatus.OK).send(MOCKED_RESPONSE);\n }\n\n}\n```\n\n Actually the log returns: `Error: Cannot find module './data/payment-method'` and the app doesn't compile\n\nI have done this with express (even with typescript) and works fine.\n\n*I don't know if i have to setup my project to read jsons (I'm newby on nest). By the moment I have created a typescript file exporting a const with the json content and I called it successfuly*\n\n========================================\n\nTop Answer:\nFor\n\n\"@nestjs/common\": \"^10.0.0\",\n\"@nestjs/core\": \"^10.0.0\",\n\nIt worked with me by adding this to the `tsconfig.json` under compilerOptions\n\n```\n\"resolveJsonModule\": true\n```\n\nAnd then imported the .json file like this\n\n```\nimport Flavors from '../../../data/falvors.json';\n```\n\n========================================\n\nCode:\n```js\nimport { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';\nimport { Response } from 'express';\n\nimport * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine\nconst MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found\n\n@Controller('commons')\nexport class CommonController {\n\n@Get('/payment-method')\n  getPaymentMoethod(@Res() res: Response): any {\n    res.status(HttpStatus.OK).send(MOCKED_RESPONSE);\n  }\n\n}\n```\n\n```text\nError: Cannot find module './data/payment-method'\n```\n\n```js\nimport { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';\nimport { Response } from 'express';\n\nimport * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file should still be imported fine\nimport * as MOCKED_RESPONSE from './data/payment-method-mock.json'; // or use const inside the controller function\n\n@Controller('commons')\nexport class CommonController {\n\n@Get('/payment-method')\n  getPaymentMoethod(@Res() res: Response): any {\n    res.status(HttpStatus.OK).json(MOCKED_RESPONSE); // <= this sends response data as json\n  }\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    // ... other options \n\n    \"resolveJsonModule\": true, // here is the important line, this will help VSCode to autocomplete and suggest quick-fixes\n\n    // ... other options\n}\n```\n\n```text\n.json\n```\n\n```text\n.json()\n```\n\n```text\ncommon.controller.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsendfile()\n```\n\n```text\nres\n```\n\n```text\ngetPaymentMoethod\n```\n\n```text\ngetPaymentMethod\n```\n\n```text\nJSON.stringify()\n```\n\n```text\ntypescript\n\nimport * as data1 from './data.json';\n\nconsole.log(data1); // Prints the content of the data.json file as an object\n.\n```\n\n```text\ntypescript\n\nimport data2 from './data.json';\n\nconsole.log(data2); // Error: Module './data.json' not found\n```\n\n```text\n\"resolveJsonModule\": true\n```\n\n```text\nimport Flavors from '../../../data/falvors.json';\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- What did you get?\n- I believe that in nest the name of controller function is just a for developer reference; I have a system error in the require node function and it breaks the flow :(\n- the second step of my comment. require outside of the function. it should be at the very top of the controller in the global state\n- Setting the require at the top of the file makes the app crash and doesn't compile... interesting\n- This helped with the VSCode autocomplete, and then I got a VSCode about change import instead of const in the require function line... Thanks\n- I edited your answer, review it so I can pick it as solution\n- Why does `import * as MOCKED_RESPONSE from '.&#47;data&#47;payment-method-mock.json';` work but `import MOCKED_RESPONSE from '.&#47;data&#47;payment-method-mock.json';` doesnt?\n- @Seven because you would have to name and export `MOCKED_RESPONSE` object within `'.&#47;data&#47;payment-method-mock.json'`, which is actually not possible in standard json.","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":184,"estimatedTokens":1134}}187{"id":"stack-67197276","source":"stackoverflow","questionId":67197276,"title":"How do I make combination of 3 columns in typeorm, postgres unique?","tags":["typescript","postgresql","nestjs","typeorm"],"text":"Title: How do I make combination of 3 columns in typeorm, postgres unique?\nTags: typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow can I achieve that there aren't 2 same records in db with values of these 3 columns combined being the same?\n\n```\n@Column()\n sector: string;\n\n @Column()\n row: string;\n\n @Column()\n number: string;\n```\n\n========================================\n\nTop Answer:\nYou can annotate the entity with an @Index as described in the documentation about \"Indices with multiple columns\":\n\n```\n@Index([\"sector\", \"row\", \"number\"], { unique: true })\n```\n\n========================================\n\nCode:\n```text\n@Column()\n  sector: string;\n\n  @Column()\n  row: string;\n\n  @Column()\n  number: string;\n```\n\n```js\n@Unique([\"sector\", \"row\", \"number\"])\n```\n\n```text\n@Index\n```\n\n```text\n@Index([\"sector\", \"row\", \"number\"], { unique: true })\n```\n\n========================================\n\nComments:\n- Most DBMS will create an index structure for unique-constraints as well. Somehow, they need to determine if a value already exists, and this can only be done efficiently if some sort of index exists (otherwise it would require scanning the entire table). For PostgreSQL also see this answer: stackoverflow.com/questions/23542794/&hellip;.\n- Wow. Didn't know about that. Thank you!\n- Sure thing. In general however, your answer is absolutely correct. Postgres using an index either way is an implementation detail. One should always use the semantically better suitable way, and in this case I agree with you that this would be a constraint, not an index.\n- is the the same as PRIMARY KEY('sector', 'row', 'number')","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":60,"estimatedTokens":412}}188{"id":"stack-59927625","source":"stackoverflow","questionId":59927625,"title":"How to store big int in nest js using typeorm","tags":["nestjs","typeorm"],"text":"Title: How to store big int in nest js using typeorm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nsome.entity.ts\n\n```\namount:number\n```\n\nBut when I store a very large data in my postgres it throws error '''integer out of range'''\n\nMy question is how can I store **Big Int** as type in psql using typeorm\n\n========================================\n\nTop Answer:\nJust add `{ bigNumberStrings: false }` to TypeORM's configuration, such as:\n\n```\nTypeOrmModule.forRoot({\n bigNumberStrings: false,\n ...config.database,\n}),\n```\n\nThen the bigint will return number type.\n\n========================================\n\nCode:\n```text\namount:number\n```\n\n```text\n@Column({type: 'bigint'})\ncolumnName: string;\n```\n\n```text\nbigint\n```\n\n```text\nbigint\n```\n\n```text\nstring\n```\n\n```text\nTypeOrmModule.forRoot({\n  bigNumberStrings: false,\n  ...config.database,\n}),\n```\n\n```text\n{ bigNumberStrings: false }\n```\n\n```js\n@PrimaryGeneratedColumn( 'increment', {type: 'bigint'} )\n    id: number;\n```\n\n```text\nbigint\n```\n\n```text\nPrimaryGeneratedColumn\n```\n\n```text\nexport class ColumnNumberTransformer {\n    public to(data: number): number {\n        return data;\n    }\n\n    public from(data: string): number {\n        // output value, you can use Number, parseFloat variations\n        // also you can add nullable condition:\n        // if (!Boolean(data)) return 0;\n\n        return parseInt(data);\n    }\n}\n```\n\n```text\n@Entity('accounts')\nexport class AccountEntity extends BaseEntity {\n    @Column({\n        type: 'bigint',\n        nullable: false,\n        transformer: new ColumnNumberTransformer()\n    })\n    public balance: number;\n}\n```\n\n```js\n@Column({type: 'bigint'})\ncolumnName: bigint\n```\n\n```text\nparseInt8: true\n```\n\n```text\ntype\n```\n\n```text\nhost\n```\n\n```text\nport\n```\n\n```text\nbigint\n```\n\n```text\ncolumnName\n```\n\n```text\ncolumnName\n```\n\n```text\nbigint\n```\n\n```text\nstring\n```\n\n```text\nbigNumberStrings\n```\n\n========================================\n\nComments:\n- how about length for integer\n- JS also has a `BigInt` type which can be mapped to/from using the `transformer` option. (Note: `BigInt` in JS is arbitrarily large, not just 8 byte.)\n- Since OP didn't mention the database technology, this is only supported for mysql/mariadb at this time. orkhan.gitbook.io/typeorm/docs/&hellip;\n- That is exactly what I need to search for. I am using lib nestjs-typeorm-paginate for pagination but the field \"id\" (type bigint) is always returns a string. Thanks again.\n- this actually worked, appreciate it","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":158,"estimatedTokens":624}}189{"id":"stack-62595603","source":"stackoverflow","questionId":62595603,"title":"NestJS: How can I mock ExecutionContext in canActivate","tags":["unit-testing","jestjs","nestjs"],"text":"Title: NestJS: How can I mock ExecutionContext in canActivate\nTags: unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am having trouble in mocking ExecutionContext in Guard middleware.\n\nHere's my RoleGuard extends JwtGuard\n\n```\n@Injectable()\nexport class RoleGuard extends JwtAuthGuard {\n ...\n async canActivate(context: ExecutionContext): Promise {\n const request = context.switchToHttp().getRequest();\n const params = request.params;\n\n ...\n }\n}\n```\n\nThis is what I am trying on my unit test.\n\n```\nlet context: ExecutionContext = jest.genMockFromModule('@nestjs/common');\n \ncontext.switchToHttp = jest.fn().mockResolvedValue({\n getRequest: () => ({\n originalUrl: '/',\n method: 'GET',\n params: undefined,\n query: undefined,\n body: undefined,\n }),\n getResponse: () => ({\n statusCode: 200,\n }),\n});\n \njest.spyOn(context.switchToHttp(), 'getRequest').mockImplementation(() => {\n return Promise.resolve(null);\n});\n```\n\nAnd I am getting this kind of error.\n\n```\nCannot spy the getRequest property because it is not a function; undefined given instead\n```\n\nI would like you to suggest any other way to mock context. Thank you.\n\n========================================\n\nTop Answer:\nWhen it comes to the `ExecutionContext`, depending on what I'm tetsting, I just supply a simple object instead, something like\n\n```\nconst ctxMock = {\n switchToHttp: () => ({\n getRequest: () => ({\n params: paramsToAdd,\n url: 'some url path',\n ...\n }),\n }),\n}\n```\n\nAnd use that as I need. If I need access to jest functions I save those to a variable before hand and assign the context's function to the variable, then I can use `expect(variable).toHaveBeenCalledTimes(x)` without a problem.\n\nAnother option is to use `@golevelup/ts-jest` to create type safe mock objects for you. I've made extensive use of this library as well for other libraries I've made.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class RoleGuard extends JwtAuthGuard {\n ...\n async canActivate(context: ExecutionContext): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const params = request.params;\n\n    ...\n }\n}\n```\n\n```text\nlet context: ExecutionContext = jest.genMockFromModule('@nestjs/common');\n  \ncontext.switchToHttp = jest.fn().mockResolvedValue({\n  getRequest: () => ({\n   originalUrl: '/',\n   method: 'GET',\n   params: undefined,\n   query: undefined,\n   body: undefined,\n  }),\n  getResponse: () => ({\n    statusCode: 200,\n  }),\n});\n    \njest.spyOn(context.switchToHttp(), 'getRequest').mockImplementation(() => {\n return Promise.resolve(null);\n});\n```\n\n```text\nCannot spy the getRequest property because it is not a function; undefined given instead\n```\n\n```ts\nimport { createMock } from '@golevelup/ts-jest';\nimport { ExecutionContext } from '@nestjs/common';\n \ndescribe('Mocked Execution Context', () => {\n  it('should have a fully mocked Execution Context', () => {\n    const mockExecutionContext = createMock<ExecutionContext>();\n    expect(mockExecutionContext.switchToHttp()).toBeDefined();\n\n    ...\n\n  });\n});\n```\n\n```js\nconst ctxMock = {\n  switchToHttp: () => ({\n    getRequest: () => ({\n      params: paramsToAdd,\n      url: 'some url path',\n      ...\n    }),\n  }),\n}\n```\n\n```text\nExecutionContext\n```\n\n```text\nexpect(variable).toHaveBeenCalledTimes(x)\n```\n\n```text\n@golevelup/ts-jest\n```\n\n========================================\n\nComments:\n- @golevelup/ts-jest has been deprecated\n- @Alko where do you see that it has been deprecated? Looks active on npm and GitHub\n- Apologies @Ocean'sFourteenth, this package is not deprecated, @golevelup/nestjs-testing is.","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":160,"estimatedTokens":903}}190{"id":"stack-65938257","source":"stackoverflow","questionId":65938257,"title":"How does InjectRepository work internally in NestJS?","tags":["node.js","dependency-injection","nestjs","typeorm"],"text":"Title: How does InjectRepository work internally in NestJS?\nTags: node.js, dependency-injection, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn nestjs, I understand that\n\n```\nimports: [\n TypeOrmModule.forFeature([TaskRepository]),\n],\n```\n\ncreates some kind of provider token so then I can inject the repository in my service (in same module) with this token.\n\nWhat I don't understand is how `@InjectRepository()` works internally, for example:\n\n```\nconstructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {}\n```\n\nHow is `InjectRepository` custom decorator (which should have been created with `createParamDecorator`) able to inject a provider registered in a module? I researched and found out that `createParamDecorator` doesn't have ability to use DI. If `createParamDecorator` just creates a new `TaskRepository` instance and returns it, then why do I need to import `TypeOrmModule.forFeature` in module? Can someone explain how this works internally? Thanks!\n\n========================================\n\nCode:\n```text\nimports: [\n    TypeOrmModule.forFeature([TaskRepository]),\n],\n```\n\n```text\nconstructor(\n    @InjectRepository(TaskRepository)\n    private taskRepository: TaskRepository,\n  ) {}\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nInjectRepository\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nTaskRepository\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\n@InjectRespoitory()\n```\n\n```text\ncreateParamDecorator()\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nreq\n```\n\n```text\ncontext\n```\n\n```text\npayload\n```\n\n```text\nExecutionContext\n```\n\n```text\n@InjectRepository()\n```\n\n```text\n@Inject()\n```\n\n```text\n<EntityName>Repository\n```\n\n```text\nconnection\n```\n\n```text\nTypeormModule.forFeature()\n```\n\n```text\n<EntityName>\n```\n\n```text\n@InjectRepository()\n```\n\n```text\n@Inject()\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nTypeormModule.forFeature()\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nTypeormModule.forFeature()\n```\n\n```text\nRepository<TaskEntity>\n```\n\n```text\nRepository\n```\n\n```text\n@InjectRepository()\n```\n\n========================================\n\nComments:\n- Thank you for great explanation! Actually I found the file on github: github.com/nestjs/typeorm/blob/&hellip; and kind of understood how it works but your explanation made everything much clearer","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":31,"totalLines":162,"estimatedTokens":599}}191{"id":"stack-59355841","source":"stackoverflow","questionId":59355841,"title":"How to apply Global Pipes during e2e tests","tags":["javascript","typescript","nestjs"],"text":"Title: How to apply Global Pipes during e2e tests\nTags: javascript, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow do you apply global pipes when using `Test.createTestingModule`?\n\nNormally, global pipes are added when the application is mounted in `main.ts`.\n\n```\nbeforeEach(async done => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule]\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n done()\n })\n```\n\n========================================\n\nTop Answer:\nYou can add them before you initialize the testing module:\n\n```\nbeforeEach(async done => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule]\n }).compile()\n\n app = moduleFixture.createNestApplication()\n\n // Add global pipe here\n app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))\n\n await app.init()\n done()\n })\n```\n\n========================================\n\nCode:\n```text\nbeforeEach(async done => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule]\n    }).compile()\n\n    app = moduleFixture.createNestApplication()\n    await app.init()\n    done()\n  })\n```\n\n```text\nTest.createTestingModule\n```\n\n```text\nmain.ts\n```\n\n```js\nimport { INestApplication, ValidationPipe } from \"@nestjs/common\";\n\nexport function mainConfig(app: INestApplication) {\n  app.enableCors();\n  app.useGlobalPipes(new ValidationPipe());\n}\n```\n\n```js\nimport { NestFactory } from \"@nestjs/core\";\nimport { mainConfig } from \"main.config\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  // use here\n  mainConfig(app);\n\n  await app.listen(3000);\n}\n\nbootstrap();\n```\n\n```js\nimport { INestApplication } from \"@nestjs/common\";\nimport { TestingModule, Test } from \"@nestjs/testing\";\nimport { AppModule } from \"app.module\";\nimport { mainConfig } from \"main.config\";\n\nlet app: INestApplication;\n\nbeforeEach(async () => {\n  const moduleFixture: TestingModule = await Test.createTestingModule({\n    imports: [AppModule],\n  }).compile();\n\n  app = moduleFixture.createNestApplication();\n\n  // use here\n  mainConfig(app);\n\n  await app.init();\n});\n```\n\n```text\nmain.ts\n```\n\n```text\nmain.config.ts\n```\n\n```text\nmainConfig\n```\n\n```text\nmain.ts\n```\n\n```text\napp.e2e-spec.ts\n```\n\n```text\nmain.ts\n```\n\n```text\napp.e2e-spec.ts\n```\n\n```text\nmain.config.ts\n```\n\n```text\nbeforeEach(async done => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule]\n    }).compile()\n\n    app = moduleFixture.createNestApplication()\n\n    // Add global pipe here\n    app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))\n\n    await app.init()\n    done()\n  })\n```\n\n```js\n@Module({\n  providers: [\n    {\n      provide: APP_PIPE,\n      useClass: ValidationPipe,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nAPP_PIPE\n```\n\n========================================\n\nComments:\n- There should be a way to automatically include stuff like this from whats in the main.ts\n- @CoreyBerigan check out my answer: stackoverflow.com/a/72090376/11670977 ... it doesn't automatically include it, but it ensures your tests and main.ts stay in sync.\n- Changed answer to this one, as this is what I do now and its a more DRY implementation.\n- This is the right way.","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":184,"estimatedTokens":862}}192{"id":"stack-73751658","source":"stackoverflow","questionId":73751658,"title":"What is the difference between providers and imports in nestjs?","tags":["javascript","node.js","nestjs"],"text":"Title: What is the difference between providers and imports in nestjs?\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nIm following the nestJs authentication tutorial\n\nIn auth/auth.module.ts:\n\n```\nimport { JwtModule } from '@nestjs/jwt'\n\n...\n\n@Module({\n imports: [\n\n UsersModule,\n PassportModule,\n JwtModule.register({\n secret: jwtConstants.secret,\n signOptions: { expiresIn: '60s' },\n }),\n ],\n providers: [AuthService, LocalStrategy, JwtStrategy],\n exports: [AuthService],\n})\n```\n\nSo JwtModule is imported under 'imports' .\n\nIn the auth/auth.service.ts the JwtService is being injected\n\n```\n...\nimport { JwtService } from '@nestjs/jwt';\n\n@Injectable()\nexport class AuthService {\n constructor(\n private usersService: UsersService,\n private jwtService: JwtService\n ) {}\n\n...\n```\n\nFrom the nestJs docs:\n\nUnder Module:\nproviders - the providers that will be instantiated by the Nest injector and that may be shared at least across this module\n\n```\nimports - the list of imported modules that export the providers which are required in this module\n```\n\nUnder Providers:\n\n```\nProviders are a fundamental concept in Nest.\nMany of the basic Nest classes may be treated as a provider โ€“ services, repositories, \nfactories, helpers, and so on. \nThe main idea of a provider is that it can be injected as a dependency; \nthis means objects can create various relationships with each other, and the function \nof \"wiring up\" instances of objects can largely be delegated to the Nest runtime system\n```\n\nI don't really understand . Whats the difference between providers and imports if both are used for dependency injection ?\n\n========================================\n\nCode:\n```text\nimport { JwtModule } from '@nestjs/jwt'\n\n\n...\n\n@Module({\n  imports: [\n\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n  providers: [AuthService, LocalStrategy, JwtStrategy],\n  exports: [AuthService],\n})\n```\n\n```text\n...\nimport { JwtService } from '@nestjs/jwt';\n\n@Injectable()\nexport class AuthService {\n  constructor(\n    private usersService: UsersService,\n    private jwtService: JwtService\n  ) {}\n\n...\n```\n\n```text\nimports -   the list of imported modules that export the providers which are required in this module\n```\n\n```text\nProviders are a fundamental concept in Nest.\nMany of the basic Nest classes may be treated as a provider โ€“ services, repositories, \nfactories, helpers, and so on. \nThe main idea of a provider is that it can be injected as a dependency; \nthis means objects can create various relationships with each other, and the function \nof \"wiring up\" instances of objects can largely be delegated to the Nest runtime system\n```\n\n```js\n{\n  provide: 'JWT_OPTIONS',\n  useValue: {\n    secretOrKey: 'sup3rs3cr3t',\n  }\n}\n```\n\n```js\n{\n  provide: 'THE_ANSWER',\n  useValue: 42,\n}\n```\n\n```text\nAuthService\n```\n\n```text\n{ secretOrKey: 'sup3rs3cr3t' }\n```\n\n```text\n42\n```\n\n```text\n@Inject('JWT_OPTIONS')\n```\n\n```text\n@Inject('THE_ANSWER')\n```\n\n```text\ninject\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n```text\nexports\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtService\n```\n\n```text\nregister/registerAsync\n```\n\n```text\nJWT_MODULE_OPTIONS\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtService\n```\n\n```text\nproviders\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtService\n```\n\n```text\nexports\n```\n\n```text\nJWT_MODULE_OPTIONS\n```\n\n========================================\n\nComments:\n- What are the possible side effects that can be caused by declaring the same provider in two providers arrays?\n- Loss of state between the two instances of the provider as that's not shared. Depending on how the provider is instantiated, possibly loss of config (like for the `JwtService`), just to name a few","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":225,"estimatedTokens":950}}193{"id":"stack-69679956","source":"stackoverflow","questionId":69679956,"title":"NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records?","tags":["node.js","typescript","postgresql","nestjs","prisma"],"text":"Title: NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records?\nTags: node.js, typescript, postgresql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fetch data records from a Postgres database in NestJS (Node.JS environment).\n\nI'm using Prisma as my Object Relational Mapper (ORM) in TypeScript.\n\nI'm having trouble choosing which query to use when fetching 'ADMIN' user records.\n\nSomeone please explain the difference between using 'select' versus using 'include' when fetching data records (I'm a Prisma beginner - please keep it simple).\n\nThanks in advance!\n\nThe code looks like below:\n\nUsing include:\n\n```\nconst users = await prisma.user.findMany({\n where: {\n role: 'ADMIN',\n },\n include: {\n posts: true,\n },\n})\n```\n\nUsing select:\n\n```\nconst users = await prisma.user.findMany({\n where: {\n role: 'ADMIN',\n },\n select: {\n posts: true,\n },\n})\n```\n\n========================================\n\nCode:\n```js\nconst users = await prisma.user.findMany({\n  where: {\n    role: 'ADMIN',\n  },\n  include: {\n    posts: true,\n  },\n})\n```\n\n```js\nconst users = await prisma.user.findMany({\n  where: {\n    role: 'ADMIN',\n  },\n  select: {\n    posts: true,\n  },\n})\n```\n\n```text\nconst getUser: object | null = await prisma.user.findUnique({\n  where: {\n    id: 22,\n  },\n  select: {\n    email: true,\n    name: true,\n  },\n})\n\n// Result\n{\n  name: \"Alice\",\n  email: \"alice@prisma.io\",\n}\n```\n\n```text\nconst users = await prisma.user.findMany({\n  select: {\n    name: true,\n    posts: {\n      select: {\n        title: true,\n      },\n    },\n  },\n})\n```\n\n```text\nconst getPosts = await prisma.post.findMany({\n  where: {\n    title: {\n      contains: 'cookies',\n    },\n  },\n  include: {\n    author: true, // Return all fields\n  },\n})\n\n// Result:\n;[\n  {\n    id: 17,\n    title: 'How to make cookies',\n    published: true,\n    authorId: 16,\n    comments: null,\n    views: 0,\n    likes: 0,\n    author: {\n      id: 16,\n      name: null,\n      email: 'orla@prisma.io',\n      profileViews: 0,\n      role: 'USER',\n      coinflips: [],\n    },\n  },\n  {\n    id: 21,\n    title: 'How to make cookies',\n    published: true,\n    authorId: 19,\n    comments: null,\n    views: 0,\n    likes: 0,\n    author: {\n      id: 19,\n      name: null,\n      email: 'emma@prisma.io',\n      profileViews: 0,\n      role: 'USER',\n      coinflips: [],\n    },\n  },\n]\n```\n\n```text\nconst users = await prisma.user.findMany({\n  // Returns all user fields\n  include: {\n    posts: {\n      select: {\n        title: true,\n      },\n    },\n  },\n})\n```\n\n========================================\n\nComments:\n- To be more clear, `include: {author: true}` includes all fields from the parent table AND the author table, whereas `select: {author: true}` returns ONLY fields from the `author` table.\n- Also note that `include: {author: false}` or `include: {author: 42}` also returns `author`s, it just check if the field is in `include` or not, but not it's value true or false.\n- Is there a performance difference or any difference at all between a nested select and a select within include? `select: { posts: { select: { title: true } }` vs `include: { posts: { select: { title: true } } }`","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":169,"estimatedTokens":788}}194{"id":"stack-54057006","source":"stackoverflow","questionId":54057006,"title":"NestJS - Validating body conditionally, based on one property","tags":["node.js","typescript","nestjs","class-validator","class-transformer"],"text":"Title: NestJS - Validating body conditionally, based on one property\nTags: node.js, typescript, nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'm trying to find a nice way to validate a body using DTO (using the brilliant `class-validator` and `class-transformer` libraries). It works really well, even for nested structures but in my case I'd like to have the body property based on some conditions.\n\nExample that will probably help to understand:\n\nLet's imagine my body should always have `selectedCategory`.\nBased on that field, the content could either be from category 1, which contains `prop1` OR from category 2, which contains `prop2`.\n\nI do not want to allow a null for both of them, I really want to have to either have `prop1` defined or `prop2` based on the `selectedCategory`.\n\nI think that I could use a pipe, but then how can I specify the correct DTO to use? \n\nI've built a \"base\" class with all the common properties and few other classes that inherit from it.\n\nI could instantiate the pipe manually based on the property `selectedCategory`, that'd be ideal but I have no clue what to pass as a second argument of the pipe (metadata).\n\nThanks for your help.\n\n========================================\n\nTop Answer:\nHave you tried the ValidateIf statement?\n\nYou can have multiple validations for `props1` or `props2` and apply them if `selectedCategory` is \"category 1\" or \"category 2\" accordingly.\n\n========================================\n\nCode:\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nselectedCategory\n```\n\n```text\nprop1\n```\n\n```text\nprop2\n```\n\n```text\nprop1\n```\n\n```text\nprop2\n```\n\n```text\nselectedCategory\n```\n\n```text\nselectedCategory\n```\n\n```text\n@Min(12, {groups: ['registration', 'update']})\nage: number;\n@Length(2, 20, {groups: ['registration']})\nname: string;\n```\n\n```text\n@Injectable()\nexport class ConditionalValidationPipe implements PipeTransform {\n  async transform(entity: any, metadata: ArgumentMetadata) {\n    // Dynamically determine the groups\n    const groups = [];\n    if (entity.selectedCategory === 1) {\n      groups.push('registration');\n    }\n\n    // Transform to class with groups\n    const entityClass = plainToClass(EntityDto, entity, { groups })\n\n    // Validate with groups\n    const errors = await validate(entityClass, { groups });\n    if (errors.length > 0) {\n      throw this.createError(errors);\n    }\n    return entityClass;\n  }\n}\n```\n\n```text\nprops1\n```\n\n```text\nprops2\n```\n\n```text\nselectedCategory\n```\n\n========================================\n\nComments:\n- Any ideas on how to do this if your variable is defined in the request (as a param) rather than a variable in the body?\n- I'm afraid not, I haven't been working with NestJS for a while now. If you find out it might be interesting to post an answer here though :)\n- where do you have `this.createError` defined?\n- @EddieMongeJr Wherever you want to define your custom error handling, e.g., directly in the pipe. Also, have a look at the validation errors: github.com/typestack/class-validator#validation-errors\n- Dou you have an example on how tonuse that pipe in a controller?\n- @Blackfaded Have a look at the binding pipes docs: docs.nestjs.com/pipes#binding-pipes\n- Did anyone tried a FluentValidation style? like: fluentvalidation-ts.alexpotter.dev/docs/overview.html\n- What about types for conditional undefined prop? Taking your example, I'm expecting on `update` that the `dto.name` in controller is `undefined`","metadata":{"transformedAt":"2026-08-18T18:33:02.420Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":121,"estimatedTokens":872}}195{"id":"stack-58726968","source":"stackoverflow","questionId":58726968,"title":"Proxied requests other than GET are hanging with NestJS and http-proxy-middleware","tags":["middleware","nestjs","http-proxy-middleware"],"text":"Title: Proxied requests other than GET are hanging with NestJS and http-proxy-middleware\nTags: middleware, nestjs, http-proxy-middleware\nSource: Stack Overflow\n\nQuestion:\nExample code is available on https://github.com/baumgarb/reverse-proxy-demo The README.md explains how you can re-produce the issue if you clone the repo.\n\nI have an API Gateway and a downstream service which returns todos (TodosAPI). A client goes through the API Gateway to access the downstream service. \n\nThe API Gateway is leveraging the `http-proxy-middleware` package to proxy the requests. There are two implementations and the 2nd one is not working:\n\n**1. Global middleware in `main.ts` which kicks in on path /api/v1/...**\n\nThis approach works perfectly fine and it proxies all requests to the downstream service no matter what http method (GET, PUT, ...).\n\n```\nimport * as proxy from 'http-proxy-middleware';\n\napp.use(\n '/api/v1/todos-api',\n proxy({\n target: 'http://localhost:8090/api',\n pathRewrite: {\n '/api/v1/todos-api': ''\n },\n secure: false,\n onProxyReq: (proxyReq, req, res) => {\n console.log(\n `[Global Functional Middlware]: Proxying ${req.method} request originally made to '${req.originalUrl}'...`\n );\n }\n })\n);\n```\n\n**2. NestMiddleware which is registered in the app module which kicks in on path /api/v2/...**\n\nThis approach works fine for GET requests, but other http methods like PUT keep \"hanging\" and no response is ever received on the client. The problem seems to be that the controller in the downstream service is never invoked.\n\n```\nimport * as proxy from 'http-proxy-middleware';\n\nexport class ReverseProxyMiddleware implements NestMiddleware {\n private proxy = proxy({\n target: 'http://localhost:8090/api',\n pathRewrite: {\n '/api/v2/todos-api': ''\n },\n secure: false,\n onProxyReq: (proxyReq, req, res) => {\n console.log(\n `[NestMiddleware]: Proxying ${req.method} request originally made to '${req.originalUrl}'...`\n );\n }\n });\n\n use(req: Request, res: Response, next: () => void) {\n this.proxy(req, res, next);\n }\n}\n```\n\nAnd this middleware is registered as follows:\n\n```\n@Module({\n imports: [],\n controllers: [AppController],\n providers: [AppService]\n})\nexport class AppModule implements NestModule {\n configure(consumer: import('@nestjs/common').MiddlewareConsumer) {\n consumer\n .apply(ReverseProxyMiddleware)\n .forRoutes({ path: 'v2/todos-api', method: RequestMethod.ALL });\n }\n}\n```\n\n- Running `curl -X PUT -H \"Content-Type: application/json\" -d \"{\\\"id\\\": 1, \\\"userId\\\": 1, \\\"title\\\": \\\"delectus aut autem - v1\\\", \\\"completed\\\": true}\" http://localhost:8080/api/v1/todos-api/1` works perfectly fine\n\n- Running `curl -X PUT -H \"Content-Type: application/json\" -d \"{\\\"id\\\": 1, \\\"userId\\\": 1, \\\"title\\\": \\\"delectus aut autem - v2\\\", \\\"completed\\\": true}\" http://localhost:8080/api/v2/todos-api/1` is having the issue where the controller in the downstream service is never invoked\n\nThe NestMiddleware is proxying the request (I can see a log line saying `[NestMiddleware]: Proxying PUT request originally made to '/api/v2/todos-api/1'...`) and the downstream service receives the request (I can see that from logging). But the downstream service does not invoke the controller / action and eventually never returns. \n\nHas anyone any idea what I'm doing wrong here? Thanks a lot in advance!\n\n========================================\n\nTop Answer:\nSet `bodyParser: false` when create Nest Application just fix the issue for endpoint we're proxying, it'll cause other endpoints (Eg: JWT localAuth) to be failed as they need body to be parsed.\n\nThe solution is to create a middleware as describe in this answer to disable bodyParser for specific endpoints you're proxying and enable it for the rest.\n\n========================================\n\nCode:\n```text\nimport * as proxy from 'http-proxy-middleware';\n\napp.use(\n  '/api/v1/todos-api',\n  proxy({\n    target: 'http://localhost:8090/api',\n    pathRewrite: {\n      '/api/v1/todos-api': ''\n    },\n    secure: false,\n    onProxyReq: (proxyReq, req, res) => {\n      console.log(\n        `[Global Functional Middlware]: Proxying ${req.method} request originally made to '${req.originalUrl}'...`\n      );\n    }\n  })\n);\n```\n\n```text\nimport * as proxy from 'http-proxy-middleware';\n\nexport class ReverseProxyMiddleware implements NestMiddleware {\n  private proxy = proxy({\n    target: 'http://localhost:8090/api',\n    pathRewrite: {\n      '/api/v2/todos-api': ''\n    },\n    secure: false,\n    onProxyReq: (proxyReq, req, res) => {\n      console.log(\n        `[NestMiddleware]: Proxying ${req.method} request originally made to '${req.originalUrl}'...`\n      );\n    }\n  });\n\n  use(req: Request, res: Response, next: () => void) {\n    this.proxy(req, res, next);\n  }\n}\n```\n\n```text\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService]\n})\nexport class AppModule implements NestModule {\n  configure(consumer: import('@nestjs/common').MiddlewareConsumer) {\n    consumer\n      .apply(ReverseProxyMiddleware)\n      .forRoutes({ path: 'v2/todos-api', method: RequestMethod.ALL });\n  }\n}\n```\n\n```text\nhttp-proxy-middleware\n```\n\n```text\nmain.ts\n```\n\n```text\ncurl -X PUT -H \"Content-Type: application/json\" -d \"{\\\"id\\\": 1, \\\"userId\\\": 1, \\\"title\\\": \\\"delectus aut autem - v1\\\", \\\"completed\\\": true}\" http://localhost:8080/api/v1/todos-api/1\n```\n\n```text\ncurl -X PUT -H \"Content-Type: application/json\" -d \"{\\\"id\\\": 1, \\\"userId\\\": 1, \\\"title\\\": \\\"delectus aut autem - v2\\\", \\\"completed\\\": true}\" http://localhost:8080/api/v2/todos-api/1\n```\n\n```text\n[NestMiddleware]: Proxying PUT request originally made to '/api/v2/todos-api/1'...\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\n```\n\n```text\nconst app = await NestFactory.create(AppModule, { bodyParser: false });\n```\n\n```text\nissue-fixed\n```\n\n```text\nbodyParser: false\n```\n\n```text\nconst { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');\n\nconst proxy = createProxyMiddleware({\n  /**\n   * Fix bodyParser\n   **/\n  on: {\n    proxyReq: fixRequestBody,\n  },\n});\n```\n\n```text\nconst proxy = createProxyMiddleware({\n    target: 'yourdestination',\n    changeOrigin: true,\n    onProxyReq: (proxyReq, req) => {\n        if (req.body) {\n            const bodyData = JSON.stringify(req.body);\n            // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json\n            proxyReq.setHeader('Content-Type', 'application/json');\n            proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));\n            // stream the content\n            proxyReq.write(bodyData);\n        }\n    }\n});\n\nreturn proxy(req, res, next);\n```\n\n========================================\n\nComments:\n- I'll be honest, this isn't something really to put in a comment, but it's not really an answer so: I've tried looking into this and checked what's coming in through both proxies (the global and the Nest middleware one) and the reqs look identical. I have a feeling that there is some problem due to the underlying structure of the http-proxy-middleware package and how that middleware works. By default, Nest doesn't necessarily handle error middleware, and I have a feeling it is somehow dealing with that. This may need to be brought up as an issue on the github repository.\n- Thanks a lot for the response and the thorough analysis. When you say 'the reqs look identical': did you check the incoming requests on the downstream service side? If yes I think I'm lost. Because if they're identical on the downstream service side of things then I can not think of any explanation why the action in the downstream service wouldn't be invoked.\n- Yeah, just did a simple `console.log(req)` in a global middleware on the server that was being proxied **to** and saw practically no differences. If that is the case, I think there is a some sort of post-request functionality the middleware tries to handle, but can't due to how Nest sets things up. Interesting idea would be to try this in an interceptor instead of a middleware and see if it works there or not.\n- Stupid question here -- \"other than get\" w/ your `application&#47;json` content-type has me thinking it's a cors issue. Perhaps Nest isn't handling the cors error? Have you tried hitting v2 from postman?\n- Nope, no CORS issue here. No client with web context involved that would prevent cross domain requests. It's a simple API call done with curl. You can also test it with Postman or Insomnia, it's no different than with curl.\n- @baumgarb `https:&#47;&#47;docs.nestjs.com&#47;middleware` don't you have to call `next()` in the middleware?\n- @griFlo that's already done by the http-proxy-middleware under the hood. No need to call the next middleware explicitly in our API Gateway. I've found the solution, see answer below.\n- This expression is not callable. Type 'typeof import(\"/node_modules/http-proxy-middleware/dist/index\")' has no call signatures.\n- Could you provide and example for the middleware that disable `bodyParser` fro specific endpoints.","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":235,"estimatedTokens":2250}}196{"id":"stack-61086951","source":"stackoverflow","questionId":61086951,"title":"Why @Body() in Post request is not working properly? [Nest.js]","tags":["nestjs"],"text":"Title: Why @Body() in Post request is not working properly? [Nest.js]\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm starting to learn Nest.js, so I am following an Academind Tutorial (link).\n\nMy code is not working as expected when I try to get the `body` variable with the `@Body()` decorator in the `POST` request. Following this part of the code in `products.controller.ts`\n\n```\n@Post()\nasync addProduct(@Body() body: Product) {\n console.log(body);\n const generatedId = this.productService.insertProduct(body.title, body.description, 5.99);\n return generatedId;\n}\n```\n\nIn the terminal the output is just an empty object: `{}`\n\nI have searched for other examples to look at how to do it properly. I found a tutorial in DigitalOcean where they also use `@Body` in the POST request; they leave a the end of the tutorial a repo with the example. This example is neither working for me.\n\nI just did a small change in `addBook()` function on `book.service.ts` file for returning the new book instead of all books\n\n```\naddBook(book): Promise {\n return new Promise(resolve => {\n this.books.push(book);\n // resolve(this.books);\n resolve(book);\n });\n}\n```\n\nI do the following POST request from Postman but an empty object is being the response.\n\nhttps://i.sstatic.net/8LaoG.png\n\nAll other HTTP requests are working just nice, except for the POST one.\n\nAny ideas what could be wrong with the code? Thanks in advance. ๐Ÿ˜ƒ\n\n========================================\n\nTop Answer:\nNot related to the example but related to the title.\n\nIf you use ValidationPipe with whitelist=true on your app.\n\n```\napp.useGlobalPipes(new ValidationPipe({ whitelist: true }));\n```\n\nwhitelist โ€” removes any property of query that is not part of DTO.\n\nAnd do not use decorators from the 'class-validator' on your DTO object\n\n```\nimport { IsNotEmpty, MaxLength } from 'class-validator';\n\nexport class Cat {\n @MaxLength(200)\n @IsNotEmpty()\n name: string;\n\n age: number; // would be removed by ValidationPipe when whitelist=true\n}\n```\n\nThe properties would be removed. And you will get the empty object.\n\n========================================\n\nCode:\n```text\n@Post()\nasync addProduct(@Body() body: Product) {\n  console.log(body);\n  const generatedId = this.productService.insertProduct(body.title, body.description, 5.99);\n  return generatedId;\n}\n```\n\n```text\naddBook(book): Promise<any> {\n    return new Promise(resolve => {\n        this.books.push(book);\n        // resolve(this.books);\n        resolve(book);\n    });\n}\n```\n\n```text\nbody\n```\n\n```text\n@Body()\n```\n\n```text\nPOST\n```\n\n```text\nproducts.controller.ts\n```\n\n```text\n{}\n```\n\n```text\n@Body\n```\n\n```text\naddBook()\n```\n\n```text\nbook.service.ts\n```\n\n```text\n{\n  \"id\": \"7\",\n  \"title\": \"Whatever Title\",\n  \"desscription\": \"whats doc\",\n  \"author\": \"Me\"\n}\n```\n\n```text\nform-data\n```\n\n```text\napplication/x-www-url-form-encoded\n```\n\n```text\napplication/json\n```\n\n```text\nraw\n```\n\n```text\nmulter\n```\n\n```text\nform-parser\n```\n\n```text\nformidable\n```\n\n```js\napp.useGlobalPipes(new ValidationPipe({ whitelist: true }));\n```\n\n```js\nimport { IsNotEmpty, MaxLength } from 'class-validator';\n\nexport class Cat {\n  @MaxLength(200)\n  @IsNotEmpty()\n  name: string;\n\n  age: number; // would be removed by ValidationPipe when whitelist=true\n}\n```\n\n========================================\n\nComments:\n- that was helpful, resolved the issue I was facing.\n- This resolved the issue. I was facing the similar issue while creating a post request in PostMan.\n- Is there any way to send data as form?\n- You need to use `multer` to parse the `multipart&#47;form-data`, either with the `FileInterceptor` or `AnyFileInterceptor` if you don't plan on actually sending a file\n- Facing the same issue while testing an api from AWS lambda console. But when I use a custom validation pipe, I am able to receive the body.\n- @JayMcDoniel if I cannot change how the request, can I still get the body with changes in nestjs setup? I am sending the request from aws lambda console and cannot control the behaviour of the body being received in multiValueQueryStringParameters section of lambda event.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- This is useful! Another colleague added this to our project and basically broke post end points using the Body attribute. It took me a while to find out why and this helped","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":189,"estimatedTokens":1127}}197{"id":"stack-60240298","source":"stackoverflow","questionId":60240298,"title":"How to parse dates in JSON request with NestJs @Body","tags":["javascript","json","date","nestjs"],"text":"Title: How to parse dates in JSON request with NestJs @Body\nTags: javascript, json, date, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a DTO that looks like this:\n\n```\nclass PersonDto {\n readonly name: string;\n readonly birthDate: Date;\n}\n```\n\nMy NestJs controller method looks like this:\n\n```\n@Post\ncreate(@Body() person: PersonDto) {\n console.log(\"New person with the following data:\", person);\n // more logic here\n}\n```\n\nThe JSON data that gets posted has `birthDate` as a string: `\"2020-01-15\"`. How can I convert this string to a JavaScript `Date` object? I'd like to add the `@IsDate` class-validation to `PersonDto` but currently that would fail.\n\n========================================\n\nCode:\n```js\nclass PersonDto {\n   readonly name: string;\n   readonly birthDate: Date;\n}\n```\n\n```js\n@Post\ncreate(@Body() person: PersonDto) {\n    console.log(\"New person with the following data:\", person);\n    // more logic here\n}\n```\n\n```text\nbirthDate\n```\n\n```text\n\"2020-01-15\"\n```\n\n```text\nDate\n```\n\n```text\n@IsDate\n```\n\n```text\nPersonDto\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe({transform: true}));\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```js\nimport { IsDate } from 'class-validator';\nimport { Type } from 'class-transformer';\n\nclass PersonDto {\n   readonly name: string;\n   @Type(() => Date)\n   @IsDate()\n   readonly birthDate: Date;\n}\n```\n\n```text\nValidationPipe\n```\n\n```text\n@IsDate()\n```\n\n```text\n@Type()\n```\n\n========================================\n\nComments:\n- This is not working for me. Any clues ?\n- @r3dm4n make sure you apply the attributes on a class.","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":102,"estimatedTokens":417}}198{"id":"stack-63234815","source":"stackoverflow","questionId":63234815,"title":"MongoDB and Nest.js: Define a custom name for a collection","tags":["javascript","mongodb","collections","nestjs"],"text":"Title: MongoDB and Nest.js: Define a custom name for a collection\nTags: javascript, mongodb, collections, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a schema like this:\n\n```\n@Schema()\n export class Pais extends Document {\n @Prop(\n raw({\n codigo: { type: String, index: true, unique: true },\n }),\n )\n @Prop()\n descripcion: string;\n }\n \n export const PaisSchema = SchemaFactory.createForClass(Pais);\n \n PaisSchema.plugin(uniqueValidator, { message: `{PATH} debe ser รบnico` });\n```\n\nBy default nest.js add an 's' to the class name, so it would be 'paiss' for the collection, but I want the name to be 'paises'.\n\nOn the module I tried this:\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'paises', schema: PaisSchema }]),\n ],\n```\n\nbut it didn't work. How can I solve this problem?\n\n========================================\n\nTop Answer:\nthis is Not true\n\n```\n@Schema({ collection: 'paises' })\n```\n\nYou can collection name in module file\n\n```\nMongooseModule.forFeature([{name : 'paises' , schema : PaisSchema }])\n```\n\nand in service File :\n\n```\n@InjectModel('paises') public model: paisesModel\n```\n\n========================================\n\nCode:\n```text\n@Schema()\n    export class Pais extends Document {\n      @Prop(\n        raw({\n          codigo: { type: String, index: true, unique: true },\n        }),\n      )\n      @Prop()\n      descripcion: string;\n    }\n    \n    export const PaisSchema = SchemaFactory.createForClass(Pais);\n    \n    PaisSchema.plugin(uniqueValidator, { message: `{PATH} debe ser รบnico` });\n```\n\n```text\n@Module({\n      imports: [\n        MongooseModule.forFeature([{ name: 'paises', schema: PaisSchema }]),\n      ],\n```\n\n```text\n@Schema({ collection: 'paises' })\n```\n\n```text\nlet schema = new mongoose.Schema({\n    _id: {\n        type: String,\n    },\n    other_field: String\n},{\n    /** Schema options*/\n    timestamps: true\n});\n\nlet model_db = mongoose.model('collection_name', schema, 'collection');\n```\n\n```text\npluralizing\n```\n\n```text\n@Schema({ collection: 'paises' })\n```\n\n```text\nMongooseModule.forFeature([{name : 'paises' , schema : PaisSchema }])\n```\n\n```text\n@InjectModel('paises') public model: paisesModel<paisesDocument>\n```\n\n========================================\n\nComments:\n- Does this answer your question? Why does mongoose always add an s to the end of my collection name\n- I would like to do it with the decorators approach to take advantage of the nestjs functionalities, however I already did it, thanks.\n- How to get it from env? I mean the collection name like process.env.MY_COLLECTION?","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":125,"estimatedTokens":639}}199{"id":"stack-53680665","source":"stackoverflow","questionId":53680665,"title":"nestjs / TypeOrm database transaction","tags":["nestjs","typeorm"],"text":"Title: nestjs / TypeOrm database transaction\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAssuming we have 2 services, A and B.\nService A has a function doing the following:\n\n- Validate the data\n\n- Call a service B function, that makes changes to the database\n\n- Do some more stuff\n\n- Do changes to the database\n\nNow, let's assume that one of the following, steps 3 or 4 failed.\nSince service B made changes in the database, those changes are still there.\n\nIs there any way of rolling the database back in this case? I though about database transactions, but I couldn't find any way to do that in nest js, although it is supported by TypeOrm, it doesn't look natural to nest.\nIf not, I am now \"stuck\" with the changes occured by service B, but without the changes should have happen by A.\n\nThanks a lot.\n\n========================================\n\nTop Answer:\ntypeorm-transactional uses CLS (Continuation Local Storage) to handle and propagate transactions between different repositories and service methods.\n\n```\n@Injectable()\nexport class PostService {\n constructor(\n private readonly authorRepository: AuthorRepository,\n private readonly postRepository: PostRepository,\n ) {}\n\n @Transactional() // will open a transaction if one doesn't already exist\n async createPost(authorUsername: string, message: string): Promise {\n const author = await this.authorRepository.create({ username: authorUsername });\n return this.postRepository.save({ message, author_id: author.id });\n }\n}\n```\n\n========================================\n\nCode:\n```text\ngetConnection().transaction(entityManager -> {\n    service1.doStuff1(entityManager);\n    service2.doStuff2(entityManager);\n});\n```\n\n```text\nEntityManager\n```\n\n```text\nQueryRunner\n```\n\n```text\nEntityManager\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```js\n@Injectable()\nclass MyService {\n  // 1. Inject the Typeorm Connection\n  constructor(@InjectConnection() private connection: Connection) { }\n\n  async findById(id: number): Promise<Thing> {\n    return new Promise(resolve => {\n      // 2. Do your business logic\n      this.connection.transaction(async entityManager => {\n        resolve(\n          await entityManager.findOne(Thing, id, {\n            lock: { mode: 'pessimistic_write' },\n          }),\n        );\n      });\n    });\n  }\n}\n```\n\n```text\nNestJS\n```\n\n```text\nConnection\n```\n\n```text\n.transaction\n```\n\n```text\nentityManager\n```\n\n```text\n.transaction\n```\n\n```js\n@Injectable()\nexport class PostService {\n  constructor(\n    private readonly authorRepository: AuthorRepository,\n    private readonly postRepository: PostRepository,\n  ) {}\n\n  @Transactional() // will open a transaction if one doesn't already exist\n  async createPost(authorUsername: string, message: string): Promise<Post> {\n    const author = await this.authorRepository.create({ username: authorUsername });\n    return this.postRepository.save({ message, author_id: author.id });\n  }\n}\n```\n\n```text\nfunction assignChildToParent(nestedObj, parentIdKey) {\n  const parentMap = {};\n\n  for (const prop in nestedObj) {\n    if (nestedObj.hasOwnProperty(prop)) {\n      const obj = nestedObj[prop];\n      const parentId = obj[parentIdKey];\n\n      parentMap[prop] = { ...obj, children: {} };\n\n      if (parentId !== null && parentMap.hasOwnProperty(parentId)) {\n        parentMap[parentId].children[prop] = parentMap[prop];\n      }\n    }\n  }\n\n  const result = {};\n\n  for (const prop in parentMap) {\n    if (parentMap.hasOwnProperty(prop) && parentMap[prop][parentIdKey] === null) {\n      result[prop] = parentMap[prop];\n    }\n  }\n\n  return result;\n}\n\nconst nestedObj = {\n  obj1: { name: 'Parent 1', parentId: null },\n  obj2: { name: 'Parent 2', parentId: 'obj1' },\n  obj3: { name: 'Parent 3', parentId: null }\n};\n\nconst parentIdKey = 'parentId';\n\nconst result = assignChildToParent(nestedObj, parentIdKey);\nconsole.log(result);\n```\n\n========================================\n\nComments:\n- While this is a solution, there's an obvious issue: Every service method will have to accept an EntityManager parameter. And if those services use other injectables, like data-access objects (DAOs), then the service methods will need to pass the EntityManager instance down the chain even further (e.g. to DAO methods). I think this is an obvious and impulsive solution--a solution that works!--but it adds significant boilerplate code and doesn't fit well with DI and IoC.\n- @avejidah you don't have ThreadLocal in TypeScript Node so you cannot store a context instance where you keep reference of the entity manager along all the services. Singleton won't work either as you have an entity manager per request (many ones are processed together in node thanks to event queue). The only way to keep an entity manager everywhere would be to store it in some way in the execution context of NestJS but you would loose manual entity manager usage and manual transaction management which can be needed.\n- I personally keep the parameter and use a decorator along the method to inject a new entity manager if it is null so I never have to worry about initializing it. Keeping explicit transaction management is more important to me than code sugar, I don't find it boilerplate personally.\n- @zenbeni could you a code snippet? which decorator are you using? maybe `@TransactionManager`?\n- Any suggestions if I use nestjsx/crud\n- This is the most elegant way to do it.\n- This, IMO, is the most succinct approach\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":183,"estimatedTokens":1416}}200{"id":"stack-57797381","source":"stackoverflow","questionId":57797381,"title":"Validation does not work with Partial - NestJS","tags":["javascript","nestjs","class-validator","server-side-validation"],"text":"Title: Validation does not work with Partial - NestJS\nTags: javascript, nestjs, class-validator, server-side-validation\nSource: Stack Overflow\n\nQuestion:\nI want to apply server-side validation on my CRUD API. The entity in question is called `Employee`. I am using an `employee.dto` (shown below) for the create and update endpoints.\n\nThe class-validator package works fine on the `create` method but ignores all rules in the DTO when I use it with `Partial` in the update method.\n\nPlease use the code below for reference.\n\n### Packages\n\n```\n\"class-transformer\": \"^0.2.3\",\n\"class-validator\": \"^0.10.0\",\n```\n\n### Employee DTO\n\n```\nimport { IsString, IsNotEmpty, IsEmail, IsEnum } from 'class-validator';\n\nimport { EmployeeRoles } from '../../entities/employee.entity';\n\nexport class EmployeeDTO {\n @IsString()\n @IsEmail()\n @IsNotEmpty()\n email: string;\n\n @IsString()\n @IsNotEmpty()\n password: string;\n\n @IsString()\n @IsNotEmpty()\n username: string;\n\n @IsString()\n @IsNotEmpty()\n fullName: string;\n\n @IsString()\n @IsNotEmpty()\n @IsEnum(EmployeeRoles)\n role: string;\n}\n```\n\n### Employee Controller\n\n```\nimport {\n Controller,\n Param,\n Post,\n Body,\n Put,\n UsePipes,\n} from '@nestjs/common';\n\nimport { EmployeeDTO } from './dto/employee.dto';\nimport { EmployeeService } from './employee.service';\nimport { ValidationPipe } from '../shared/pipes/validation.pipe';\n\n@Controller('employee')\nexport class EmployeeController {\n constructor(private employeeService: EmployeeService) {}\n\n @Post()\n @UsePipes(ValidationPipe)\n addNewEmployee(@Body() data: EmployeeDTO) {\n return this.employeeService.create(data);\n }\n\n @Put(':id')\n @UsePipes(ValidationPipe)\n updateEmployee(@Param('id') id: number, @Body() data: Partial) {\n return this.employeeService.update(id, data);\n }\n}\n```\n\n### Possible Solution\n\nI work around I can think of is creating separate DTOs for `create` and `update` methods, but I don't like the idea of repeating the code.\n\n========================================\n\nTop Answer:\nIn order to achieve partial validation, you can use `PartialType` utility function. You can read about it here:\nhttps://docs.nestjs.com/openapi/mapped-types#partial\n\nYou would need to create another class:\n\n```\nexport class UpdateEmployeeDTO extends PartialType(EmployeeDTO) {}\n```\n\nand then in your controller, you need to replace the type of `@Body data Partial` to `UpdateEmployeeDto`. It should look like this:\n\n```\n@Patch(':id')\n@UsePipes(ValidationPipe)\nupdateEmployee(@Param('id') id: number, @Body() data: UpdateEmployeeDTO) {\n return this.employeeService.update(id, data);\n}\n```\n\nPlease keep in mind that you should import `PartialType` from `@nestjs/mapped-types` not from `@nestjs/swagger` like suggested in the documentation. More about this can be found here\n\n========================================\n\nCode:\n```text\n\"class-transformer\": \"^0.2.3\",\n\"class-validator\": \"^0.10.0\",\n```\n\n```text\nimport { IsString, IsNotEmpty, IsEmail, IsEnum } from 'class-validator';\n\nimport { EmployeeRoles } from '../../entities/employee.entity';\n\nexport class EmployeeDTO {\n  @IsString()\n  @IsEmail()\n  @IsNotEmpty()\n  email: string;\n\n  @IsString()\n  @IsNotEmpty()\n  password: string;\n\n  @IsString()\n  @IsNotEmpty()\n  username: string;\n\n  @IsString()\n  @IsNotEmpty()\n  fullName: string;\n\n  @IsString()\n  @IsNotEmpty()\n  @IsEnum(EmployeeRoles)\n  role: string;\n}\n```\n\n```text\nimport {\n  Controller,\n  Param,\n  Post,\n  Body,\n  Put,\n  UsePipes,\n} from '@nestjs/common';\n\nimport { EmployeeDTO } from './dto/employee.dto';\nimport { EmployeeService } from './employee.service';\nimport { ValidationPipe } from '../shared/pipes/validation.pipe';\n\n@Controller('employee')\nexport class EmployeeController {\n  constructor(private employeeService: EmployeeService) {}\n\n  @Post()\n  @UsePipes(ValidationPipe)\n  addNewEmployee(@Body() data: EmployeeDTO) {\n    return this.employeeService.create(data);\n  }\n\n  @Put(':id')\n  @UsePipes(ValidationPipe)\n  updateEmployee(@Param('id') id: number, @Body() data: Partial<EmployeeDTO>) {\n    return this.employeeService.update(id, data);\n  }\n}\n```\n\n```text\nEmployee\n```\n\n```text\nemployee.dto\n```\n\n```text\ncreate\n```\n\n```text\nPartial<EmployeeDTO>\n```\n\n```text\ncreate\n```\n\n```text\nupdate\n```\n\n```text\nValidationPipe\n```\n\n```text\nupdateEmployee\n```\n\n```text\ndata\n```\n\n```text\nPartial\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\nEmployeeDTO\n```\n\n```text\ndata\n```\n\n```text\nexport class UpdateEmployeeDTO extends PartialType(EmployeeDTO) {}\n```\n\n```text\n@Patch(':id')\n@UsePipes(ValidationPipe)\nupdateEmployee(@Param('id') id: number, @Body() data: UpdateEmployeeDTO) {\n    return this.employeeService.update(id, data);\n}\n```\n\n```text\nPartialType\n```\n\n```text\n@Body data Partial<EmployeeDTO>\n```\n\n```text\nUpdateEmployeeDto\n```\n\n```text\nPartialType\n```\n\n```text\n@nestjs/mapped-types\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nUser {\n  @IsNotEmpty()\n  name: string;\n  @IsOptional()\n  nickname?: string;\n}\n```\n\n```text\n@Body() params: User\n```\n\n```text\nimport { OmitType, PartialType } from '@nestjs/swagger';\n\nUpdateUser extends PartialType(User) {}\n```\n\n```text\n@Body() params: UpdateUser,\n```\n\n```text\n@Body() params: Partial<User>\n```\n\n```text\n@Body() params: any\n```\n\n```text\nconst transformedValue = plainToClassFromExist(new User(), params);\nconst errors = validate(transformedValue, {\n  skipUndefinedProperties: true\n});\n```\n\n```text\n@PartialBody(User) params: Partial<User>\n```\n\n```text\n@PartialBody() params: Partial<User>\n```\n\n```text\n@PartialBody() params: User\n```\n\n```text\nimport { PartialType } from '@nestjs/swagger';\n\nexport class PartialUser extends PartialType(User) {}\n```\n\n```text\n@PartialBody() params: PartialUser\n```\n\n```text\n@IsNotEmpty()\n```\n\n```text\nvalidate()\n```\n\n```text\nskipUndefinedProperties\n```\n\n```text\nPartialBody\n```\n\n```text\nPartialBody\n```\n\n```text\nparams\n```\n\n```text\nPartialBody\n```\n\n```text\nparams\n```\n\n```text\nexport class CreateEmployeeDTO {\n    // might wanna do this if you want to take an updateDto and transform to an createDto\n    @Exclude()\n  id?: number;\n  \n  @IsString()\n  @IsNotEmpty()\n  username: string;\n  \n  @IsSring()\n  @IsNotEmpty()\n  password: string;\n  \n  @IsString()\n  @IsNotEmpty()\n  role: string;\n}\n```\n\n```text\nexport class UpdateEmployeeDTO extends OmitType(CreateEmployeeDTO, ['id', 'password']) {\n    @IsNumber()\n  @IsNotEmpty()\n  id: number;\n  \n  @IsString()\n  @IsOptional()\n  password: string;\n}\n```\n\n```text\nPartialType\n```\n\n```text\n@nestjs/mapped-types\n```\n\n```text\nOmitType\n```\n\n```text\nPartialType\n```\n\n```text\nOmitType\n```\n\n```text\n// This is the main DTO that you use in your controller\nclass PatchDto {\n  @ApiPropertyOptional({type: SubpropertyPatchDto})\n  @IsOptional()\n  @ValidateNested()\n  @Type(() => SubpropertyPatchDto)\n  public subproperty?: SubpropertyPatchDto;\n}\n\nclass SubpropertyPatchDto extends PartialType(SubCreateDto) {}\n```\n\n```text\nPartialType()\n```\n\n```text\n@ValidateNested()\n```\n\n```text\nPartialType()\n```\n\n========================================\n\nComments:\n- Thank you for your answer! I plan to integrate Swagger in the future as well. Which approach would be better, having separate DTOs or keep a single class?\n- and Yes, I am using `Validation Pipe`\n- For Swagger, I think having separate DTOs would make for a clearer documentation.\n- Yes, I had the same thought, although it repeats a lot of the code. Thanks.\n- Even though it duplicates some code, IMO it allows you to have better comprehension and separation of concerns. Also I assume that when you create an employee, some attributes of your DTO class are required, while when you update it, they're optional.\n- do seprate DTO is good approach but about if my dto is large and i dont want to write again this DTO for update please see my issue - stackoverflow.com/questions/78238231/&hellip;\n- Could you please add to your answer that `PartialType` needs to be imported from `@nestjs&#47;mapped-types`? The documentation was misleading. Also the `updateEmployee` function should be PATCH not PUT. PUT is meant to replace everything and PATCH to update only specific values.\n- @Mick thanks for the suggestions. I have left `Put` because it was originally used in the question, but you are right - we should use `Patch` because `PartialType` allows to edit only a part of the requested object not necessarily whole object. I have changed that, thanks. I wonder if `@nestjs&#47;mapped-types` is a correct import. Why do you think the documentation was misleading? I have wrote few sample unit tests and verified that `PartialType` from `@nestjs&#47;swagger` package (which is suggested in the documentation) is working as expected as well.\n- It does not work with `@nestjs&#47;swagger`, only if you actually use swagger. Otherwise it should be `@nestjs&#47;mapped-types`. It is not documented but there is an open issue to documentate that: github.com/nestjs/docs.nestjs.com/issues/1795\n- Thanks @Mick I didn't know about that. I have put information about this in my post.\n- It is now documented here: docs.nestjs.com/techniques/validation#mapped-types -> There is even a third library `@nestjs&#47;graphql` which needs to be used when using graphql.\n- Seems that `@nestjs&#47;swagger` is fine now except when in combination with `@ValidateNested`. With `@nestjs&#47;mapped-types` all is fine.\n- i have the same issue about the PartialType i'm trying import from both @nest/swagger and @nestjs/mapped-types here is problem url- stackoverflow.com/questions/78238231/&hellip;\n- Where can the @PartialBody be found? Nest.js doesn't have any entry in the documentation.\n- You answer is great. I've tried to apply on my code, but the problem is on the Swagger we do not have the required body section.\n- @jiko Unfortunately I didn't see your comment until now, I've updated the answer to clarify where PartialBody is found, it's here: gist.github.com/josephdpurcell/d4eff886786d58f58b86107c0947e&zwnj;&#8203;19e\n- @CarlosQuerioz thanks! I didn't explore swagger compatibility with these solutions. If there is an improvement I'm happy to edit the answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":57,"totalLines":467,"estimatedTokens":2514}}201{"id":"stack-65671318","source":"stackoverflow","questionId":65671318,"title":"Nestjs Circular dependency forwardRef() drawbacks","tags":["nestjs","circular-dependency"],"text":"Title: Nestjs Circular dependency forwardRef() drawbacks\nTags: nestjs, circular-dependency\nSource: Stack Overflow\n\nQuestion:\nOfficial Circular dependency says:\n\nA circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers.\n\nWhile circular dependencies should be avoided where possible, you\ncan't always do so.\n\nWhat are the reasons for not using `forwardRef()`?\n\n========================================\n\nTop Answer:\nDepending on your domain, the relations between your modules would be \"naturally\" interdependent. Even it's true you can apply techniques to avoid that, the result sometimes is \"not natural\", at least for humans, and can become hardly understandable for the team, creating new issues later on the maintainance.\n\nAs a non-official alternative, I wrote a post about how to delay at maximum the resolution of the services injections (that's basically at runtime). I was hardly inspired on **Java** and **Spring** annotation **@Autowired**.\n\nYou can read the full post here:\nhttps://fjbarrena.dev/blog/autowired-annotation-in-nestjs\n\nFor sure this approach will have drawbacks as well, but yeah, at least for my domain works pretty well.\n\nHope you find it useful!\n\n========================================\n\nCode:\n```text\nforwardRef()\n```\n\n```text\nforwardRef\n```\n\n========================================\n\nComments:\n- Thank you very much for your response. I was using UserService.findUser in Auth module. And using Auth module service methods in UserService. Could you please suggest a better way to handle such a case? For now, I moved the User service method to Auth module instead of using forwardRef().\n- Auth is usually one of the few places that I see tightly bound logic that makes sense for it to be tightly bound. I've ended up creating an AuthModule that has it's own connection to the user table and a UserModule that has another connection to the user table. Ends up duplicating some logic, but it keeps the circular reference from happening, which I appreciate. For that though, it becomes preference to an extent.\n- Thank you. I got it.\n- @JasurbekNabijonov im a little late to the party but here is what you do. you have a open rest POST 'login' where use can login as example with username/pw this endpoint gives back a jwt token. then on the endpoint where as example users/:id GET you add a guard where the guard checks if the jwt token is valid. this dosnt require a call to the db since the tokens are checked by the signing. the nestjs has really great docs about pretty much everything you need to know for building a stable a secure api: docs.nestjs.com/security/authentication","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":46,"estimatedTokens":692}}202{"id":"stack-54945917","source":"stackoverflow","questionId":54945917,"title":"NestJS throw from ExceptionFilter","tags":["javascript","node.js","typescript","exception","nestjs"],"text":"Title: NestJS throw from ExceptionFilter\nTags: javascript, node.js, typescript, exception, nestjs\nSource: Stack Overflow\n\nQuestion:\nI try to use an `ExceptionFilter` to map exceptions to their HTTP counterpart.\n\nThis is my code : \n\n```\n@Catch(EntityNotFoundError)\nexport class EntityNotFoundFilter implements ExceptionFilter {\n catch(exception: EntityNotFoundError, _host: ArgumentsHost) {\n throw new NotFoundException(exception.message);\n }\n}\n```\n\nBut, when the filter code is executed, I got a `UnhandledPromiseRejectionWarning`\n\n```\n(node:3065) UnhandledPromiseRejectionWarning: Error: [object Object]\n at EntityNotFoundFilter.catch ([...]/errors.ts:32:15)\n at ExceptionsHandler.invokeCustomFilters ([...]/node_modules/@nestjs/core/exceptions/exceptions-handler.js:49:26)\n at ExceptionsHandler.next ([...]/node_modules/@nestjs/core/exceptions/exceptions-handler.js:13:18)\n at [...]/node_modules/@nestjs/core/router/router-proxy.js:12:35\n at \n at process._tickCallback (internal/process/next_tick.js:182:7)\n (node:3065) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)\n```\n\nHow can I fix this ?\n\n========================================\n\nTop Answer:\nThe key here is to extend the `BaseExceptionFilter` and delegate to the super class rather than throwing:\n\n```\nimport { BaseExceptionFilter } from '@nestjs/core';\n// .. your other imports\n\n@Catch(EntityNotFoundError)\nexport class EntityNotFoundFilter extends BaseExceptionFilter {\n catch(exception: EntityNotFoundError, host: ArgumentsHost) {\n super.catch(new NotFoundException(exception.message, host));\n }\n}\n```\n\nBe sure to pass in the `applicationRef` argument when constructing your filter during your application bootstrapping, because the `BaseExceptionFilter` needs this property to behave correctly\n\n```\nimport { HttpAdapterHost } from '@nestjs/core';\n// .. your other imports\n\nasync function bootstrap(): Promise {\n // .. blah blah\n const { httpAdapter } = app.get(HttpAdapterHost);\n app.useGlobalFilters(new GeneralErrorFilter(httpAdapter));\n // .. blah blah\n}\n```\n\nThis will result in the default error handling you would receive if you had thrown the same error.\n\n========================================\n\nCode:\n```text\n@Catch(EntityNotFoundError)\nexport class EntityNotFoundFilter implements ExceptionFilter {\n    catch(exception: EntityNotFoundError, _host: ArgumentsHost) {\n        throw new NotFoundException(exception.message);\n    }\n}\n```\n\n```text\n(node:3065) UnhandledPromiseRejectionWarning: Error: [object Object]\n    at EntityNotFoundFilter.catch ([...]/errors.ts:32:15)\n    at ExceptionsHandler.invokeCustomFilters ([...]/node_modules/@nestjs/core/exceptions/exceptions-handler.js:49:26)\n     at ExceptionsHandler.next ([...]/node_modules/@nestjs/core/exceptions/exceptions-handler.js:13:18)\n     at [...]/node_modules/@nestjs/core/router/router-proxy.js:12:35\n     at <anonymous>\n     at process._tickCallback (internal/process/next_tick.js:182:7)\n (node:3065) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)\n```\n\n```text\nExceptionFilter\n```\n\n```text\nUnhandledPromiseRejectionWarning\n```\n\n```text\n@Catch(EntityNotFoundError)\nexport class EntityNotFoundFilter implements ExceptionFilter {\n  catch(exception: EntityNotFoundError, host: ArgumentsHost) {\n    const response = host.switchToHttp().getResponse();\n      response.status(404).json({ message: exception.message });\n  }\n}\n```\n\n```text\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    // next.handle() is an Observable of the controller's result value\n    return next.handle()\n      .pipe(catchError(error => {\n        if (error instanceof EntityNotFoundError) {\n          throw new NotFoundException(error.message);\n        } else {\n          throw error;\n        }\n      }));\n  }\n}\n```\n\n```text\nExceptionFilter\n```\n\n```text\nExceptionFilter\n```\n\n```text\nInterceptor\n```\n\n```text\nexport abstract class AbstractErrorInterceptor<T> implements NestInterceptor {\n    protected interceptedType: new (...args) => T;\n\n    intercept(\n        context: ExecutionContext,\n        call$: Observable<any>,\n    ): Observable<any> | Promise<Observable<any>> {\n        return call$.pipe(\n            catchError(exception => {\n                if (exception instanceof this.interceptedType) {\n                    this.handleError(exception);\n                }\n                throw exception;\n            }),\n        );\n    }\n\n    abstract handleError(exception: T);\n}\n```\n\n```text\nexport class EntityNotFoundFilter extends AbstractErrorInterceptor<EntityNotFoundError> {\n    interceptedType = EntityNotFoundError;\n\n    handleError(exception: EntityNotFoundError) {\n        throw new NotFoundException(exception.message);\n    }\n}\n```\n\n```text\nthrow new BadRequestException('you done goofed');\n```\n\n```text\n{\"statusCode\":400,\"error\":\"Bad Request\",\"message\":\"you done goofed\"}\n```\n\n```js\nimport { BaseExceptionFilter } from '@nestjs/core';\n// .. your other imports\n\n@Catch(EntityNotFoundError)\nexport class EntityNotFoundFilter extends BaseExceptionFilter {\n    catch(exception: EntityNotFoundError, host: ArgumentsHost) {\n        super.catch(new NotFoundException(exception.message, host));\n    }\n}\n```\n\n```js\nimport { HttpAdapterHost } from '@nestjs/core';\n// .. your other imports\n\nasync function bootstrap(): Promise<void> {\n  // .. blah blah\n  const { httpAdapter } = app.get(HttpAdapterHost);\n  app.useGlobalFilters(new GeneralErrorFilter(httpAdapter));\n  // .. blah blah\n}\n```\n\n```text\nBaseExceptionFilter\n```\n\n```text\napplicationRef\n```\n\n```text\nBaseExceptionFilter\n```\n\n========================================\n\nComments:\n- Ok. But it seems strange to build manually the body of the response. There is no built-in mechanism to map exception to http responses ? I don't think i try to do something very unusual\n- Alternatively, you can use an interceptor, see my edit. Setting the response is not unusual for exception filters however, it's the default. See docs.nestjs.com/exception-filters\n- I've created a live example for you to try it out: codesandbox.io/embed/&hellip;\n- I don't think it's good advice to implement all this ceremony when the NestJS exception classes are already automatically converted to appropriate HTTP responses\n- Sure, directly throwing a nest exception (or a subclass) is another (obvious?) option. But if you don't have control over the errors thrown e.g. MongoError, then this seems like a viable solution to me.\n- Since the OP wanted to (re)throw a nest option from the beginning, I assumed they were aware of this.\n- Jemar is showin how to properly \"map\" to the NestJS builtin exception: stackoverflow.com/a/65473464/6764310\n- I don't create my own version of HTTP based exception classes : i want to use them ! But i don't want to explicitely throw http based exception from business code, because that logic can be reused in non-http context (websocket for example). I want to throw business exception (UnderAgeException for example, if i check age of user for some feature), and then, map them to their Http counterpart (BadRequestException in our example).\n- I really like this solution because it uses the NestJS `NotFoundException`. But I would recommend to be careful with forwarding the `exception.message`. Depending on your query you could expose more than you intended to do. In my case I simply opted against any more details.\n- It should be `super.catch(new NotFoundException(exception.message), host);`. The `host` is the second parameter for `super.catch()`.","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":225,"estimatedTokens":1977}}203{"id":"stack-51116044","source":"stackoverflow","questionId":51116044,"title":"Loading of port number for Nest.js application from JSON module","tags":["node.js","typescript","configuration","nestjs"],"text":"Title: Loading of port number for Nest.js application from JSON module\nTags: node.js, typescript, configuration, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my Nest.js based application, I'm trying to use one configuration file to define all configuration for an application.\n\nThe **configuration.json** file looks like this:\n\n```\n{\n \"environment\": \"development\",\n \"backendPort\": 8080,\n \"appRootPath\": \".\",\n ...more configuration...\n}\n```\n\nAnd in my Nest.js application's **main.ts** is:\n\n```\nimport { NestFactory } from \"@nestjs/core\";\nimport configuration from \"../configuration.json\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n await app.listen(configuration.backendPort);\n}\nbootstrap();\n```\n\nI have enabled TypeScript's **resolveJsonModule** feature as mentioned in TypeScript 2.9 Release notes and VS code successfully recognized the import and provides IntelliSense and type checking.\n\nBut when I try to start the app via\n\n```\nts-node -r tsconfig-paths/register src/main.ts\n```\n\nI get an error:\n\n```\n(node:5236) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'backendPort' of undefined\n at d:\\CodeDev\\NestCMS\\backend\\src\\main.ts:10:36\n at Generator.next ()\n at fulfilled (d:\\CodeDev\\NestCMS\\backend\\src\\main.ts:4:58)\n at \n at process._tickDomainCallback (internal/process/next_tick.js:228:7)\n at Function.Module.runMain (module.js:695:11)\n at Object. (d:\\CodeDev\\NestCMS\\backend\\node_modules\\ts-node\\src\\_bin.ts:177:12)\n at Module._compile (module.js:652:30)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n(node:5236) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:5236) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n**Is there a way to define application port in an elegant way like I tried?**\n\nI don't want the port number to be hard-coded in the main.ts file. I want it to be configurable by some option to allow me to deploy the same application build to different environments where the only thing differing will be the configuration.json.\n\n========================================\n\nTop Answer:\nWorkaround in 2021:\n\nmain.ts, NestJS v8.0.4\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const configService: ConfigService = app.get(ConfigService);\n const port = configService.get('APP_PORT');\n await app.listen(port);\n}\nbootstrap();\n```\n\nProfit!\n\n========================================\n\nCode:\n```text\n{\n    \"environment\": \"development\",\n    \"backendPort\": 8080,\n    \"appRootPath\": \".\",\n    ...more configuration...\n}\n```\n\n```text\nimport { NestFactory } from \"@nestjs/core\";\nimport configuration from \"../configuration.json\";\nimport { AppModule } from \"./app.module\";\n\n\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    await app.listen(configuration.backendPort);\n}\nbootstrap();\n```\n\n```text\nts-node -r tsconfig-paths/register src/main.ts\n```\n\n```text\n(node:5236) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'backendPort' of undefined\n    at d:\\CodeDev\\NestCMS\\backend\\src\\main.ts:10:36\n    at Generator.next (<anonymous>)\n    at fulfilled (d:\\CodeDev\\NestCMS\\backend\\src\\main.ts:4:58)\n    at <anonymous>\n    at process._tickDomainCallback (internal/process/next_tick.js:228:7)\n    at Function.Module.runMain (module.js:695:11)\n    at Object.<anonymous> (d:\\CodeDev\\NestCMS\\backend\\node_modules\\ts-node\\src\\_bin.ts:177:12)\n    at Module._compile (module.js:652:30)\n    at Object.Module._extensions..js (module.js:663:10)\n    at Module.load (module.js:565:32)\n(node:5236) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:5236) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nimport {NestFactory} from '@nestjs/core';\nimport {ConfigService} from 'src/config/config.service';\nimport {AppModule} from './app.module';\n\nlet bootstrap = async () => {\n    const app = await NestFactory.create(AppModule);\n    const configService: ConfigService = app.get(ConfigService);\n    await app.listen(configService.getPort);\n};\n\nbootstrap();\n```\n\n```text\nsrc/config/index.ts\n```\n\n```text\ndotenv\n```\n\n```text\ndotenv-safe\n```\n\n```text\n\"develop\": \"node $NODE_DEBUG_OPTION  -r ts-node/register -r dotenv-safe/config src/index.ts\"\n```\n\n```js\nimport { Module } from \"@nestjs/common\";\nimport { NeconfigModule } from 'neconfig';\nimport * as path from 'path';\n\n@Module({\n  imports: [\n    NeconfigModule.register({\n      readers: [\n        { name: 'env', file: path.resolve(process.cwd(), '.env') },\n      ],\n    }),\n  ],\n})\nexport class AppModule { }\n```\n\n```js\nimport { Logger } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { ConfigReader } from 'neconfig';\nimport { AppModule } from './app.module';\n\n(async function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const config = app.get(ConfigReader);\n  const port = config.getIntOrThrow('PORT');\n  // const port = config.getInt('PORT', 3000);\n\n  await app.listen(port);\n  Logger.log(`Listening on http://localhost:${port}`);\n})();\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const configService: ConfigService = app.get<ConfigService>(ConfigService);\n  const port = configService.get('APP_PORT');\n  await app.listen(port);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- Thank you! I actually already have configuration service reading the JSON, doing validation, merging with defaults, etc. but had no idea how to access is from main.ts. This is elegant.\n- Can you elaborate on reading JSON in the ConfigService? This actually does not answer the question.\n- But it doesn't load JSON configuration","metadata":{"transformedAt":"2026-08-18T18:33:02.421Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":215,"estimatedTokens":1666}}204{"id":"stack-58377492","source":"stackoverflow","questionId":58377492,"title":"@Query() does not transform to DTO","tags":["nestjs"],"text":"Title: @Query() does not transform to DTO\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a controller that needs to receive data in the request query string (I can't use the body because I'm interacting with a legacy system). \n\nI wrote a DTO map query params to an object and I'm using a ValidationPipe to validate and transform the data to my DTO.\n\nSo, I have this:\n\n```\nimport { Get, Controller, Query, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';\n\nclass TestDto {\n @IsNumber()\n field1: number;\n @IsBoolean()\n field2: boolean;\n}\n\n@Controller()\nexport class AppController {\n constructor() {}\n\n @Get()\n @UsePipes(new ValidationPipe({ whitelist: false, transform: true}))\n root(@Query() dto: TestDto): TestDto {\n return dto;\n }\n\n}\n```\n\nAll of the previous code compรฌles and follows the NestJS documentation, but when I call http://localhost:3000/?field1=15&field2=true I get this:\n\n```\n{\n \"statusCode\": 400,\n \"error\": \"Bad Request\",\n \"message\": [\n {\n \"target\": {\n \"field1\": \"15\",\n \"field2\": \"true\"\n },\n \"value\": \"15\",\n \"property\": \"field1\",\n \"children\": [],\n \"constraints\": {\n \"isNumber\": \"field1 must be a number\"\n }\n },\n {\n \"target\": {\n \"field1\": \"15\",\n \"field2\": \"true\"\n },\n \"value\": \"true\",\n \"property\": \"field2\",\n \"children\": [],\n \"constraints\": {\n \"isBoolean\": \"field2 must be a boolean value\"\n }\n }\n ]\n}\n```\n\nBoth fields are valid according to the attributes but the pipe rejects the request. If I change from @IsNumber to @IsNumberString and from @IsBoolean to @IsBooleanString it validates, but I do not received the transformed data (i.e. I get a plain object instead of my DTO)\n\nDid anybody face something like this?\n\n========================================\n\nTop Answer:\nAnother option is to enable implicit conversion.\n\n```\n@UsePipes(new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true } }))\n```\n\n========================================\n\nCode:\n```text\nimport { Get, Controller, Query, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';\n\nclass TestDto {\n  @IsNumber()\n  field1: number;\n  @IsBoolean()\n  field2: boolean;\n}\n\n@Controller()\nexport class AppController {\n  constructor() {}\n\n  @Get()\n  @UsePipes(new ValidationPipe({ whitelist: false, transform: true}))\n  root(@Query() dto: TestDto): TestDto {\n    return dto;\n  }\n\n}\n```\n\n```text\n{\n    \"statusCode\": 400,\n    \"error\": \"Bad Request\",\n    \"message\": [\n        {\n            \"target\": {\n                \"field1\": \"15\",\n                \"field2\": \"true\"\n            },\n            \"value\": \"15\",\n            \"property\": \"field1\",\n            \"children\": [],\n            \"constraints\": {\n                \"isNumber\": \"field1 must be a number\"\n            }\n        },\n        {\n            \"target\": {\n                \"field1\": \"15\",\n                \"field2\": \"true\"\n            },\n            \"value\": \"true\",\n            \"property\": \"field2\",\n            \"children\": [],\n            \"constraints\": {\n                \"isBoolean\": \"field2 must be a boolean value\"\n            }\n        }\n    ]\n}\n```\n\n```js\nclass TestDto\n```\n\n```js\nimport { IsEmail, IsNotEmpty } from 'class-validator'; // 'class'\n\nexport class CreateUserDto { // notice class\n  @IsEmail()\n  email: string;\n\n  @IsNotEmpty()\n  password: string;\n}\n```\n\n```js\n@UsePipes( new ValidationPipe( { transform: true, transformOptions: {enableImplicitConversion: true} }))\n```\n\n```js\nimport { Controller, createParamDecorator, Get, UsePipes, ValidationPipe } from '@nestjs/common';\nimport { IsNumber } from 'class-validator';\nimport { AppService } from './app.service';\n\nconst MyField = createParamDecorator((data, req) => {\n  const result = new TestDto();\n  result.field1 = Number(req.query.field1);\n  return result;\n});\n\nclass TestDto {\n  @IsNumber()\n  field1: number;\n}\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {\n  }\n\n  @Get()\n  @UsePipes(new ValidationPipe({ transform: true }))\n  getHello(@MyField() testDto: TestDto): TestDto {\n    return testDto;\n  }\n}\n```\n\n```text\n@Query()\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({ transform: true }));\n```\n\n```text\n@UsePipes(new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true } }))\n```\n\n========================================\n\nComments:\n- Hi and thanks for your reply. I made a mistake with the DTO when posting the question. I'm actually using a class for DTO and I'm interested in the transform part of the ValidationPipe, that does not seem to work since I always get a string when using IsNumberString or I get a validation error if I use IsNumber even when the input is a number. I've created a github repo to show the issue\n- I've also checked the ValidationPipe tests and saw that all the defined properties are strings. I think you should test with other data types\n- `@UsePipes( new ValidationPipe( { transform: true, transformOptions: {enableImplicitConversion: true} }))` does the implicit conversion: `โžœ nest-pipes git:(master) โœ— curl http:&#47;&#47;localhost:3000\\?field1\\=123 {\"field1\":123}%` @JoseSelesan\n- @JoseSelesan edited my original response with this approach and added another example how you can handle it.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":209,"estimatedTokens":1295}}205{"id":"stack-56771768","source":"stackoverflow","questionId":56771768,"title":"How to transform input data with NestJS and TypeORM","tags":["typescript","nestjs","typeorm"],"text":"Title: How to transform input data with NestJS and TypeORM\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to create functionality where I can transform incoming data before it hits the database. Let's say that we want to make sure that when a new user is created, the firstName and lastName attribute values are always starting with a capital letter. Or another great example is to prevent login issues and store email addresses always in lowercase letters.\n\nI've taken a look at the pipe documentation of NestJS but it's too generic. I want to be able to specify which fields need transformation and I don't want to create a pipe for each attribute or endpoint that needs transformation.\n\nI've also tried the @Transform decorator form the 'class-transformer' package but this doesn't seem to work.\n\n```\nexport class UserRoleCreateDto {\n @IsDefined()\n @IsString()\n @IsNotEmpty()\n @Transform((name) => name.toUpperCase())\n readonly name;\n}\n```\n\nThe expected result should be the name in uppercase letters but it's not.\n\nAnyone any ideas or examples on how to implement proper input transformation for NestJS / TypeORM before it hits the database?\n\nThanks for your time!\n\n========================================\n\nTop Answer:\nHere is a small working example\n\n```\n@UsePipes(new ValidationPipe({transform: true}))\n @Get('test_input')\n async testInput(@Query() data: UserRoleCreateDto): Promise {\n\n return data;\n }\n```\n\nand checking in bash:\n\n```\ncurl 'http://localhost:3060/test_input?name=hello'\n\n{\"name\":\"HELLO\"}\n```\n\nCheck that you have `ValidationPipe` decorator and especially `transform: true` option, without these it doesn't work. `transform: true` automatically transforms input data to the class instance.\n\nMore about validation on the nestjs documentation page - link\n\nAlso, just in case, instead of `@Query()` decorator you can use `@Body()` for POST data or `@Param()` for URL parameters\n\n========================================\n\nCode:\n```text\nexport class UserRoleCreateDto {\n  @IsDefined()\n  @IsString()\n  @IsNotEmpty()\n  @Transform((name) => name.toUpperCase())\n  readonly name;\n}\n```\n\n```js\n@Entity()\nexport class User {\n    \n    @BeforeInsert()\n    nameToUpperCase() {\n        this.email = this.email.toLowerCase()\n        this.name = this.name.toUpperCase();\n    }\n}\n```\n\n```text\n@UsePipes(new ValidationPipe({transform: true}))\n  @Get('test_input')\n  async testInput(@Query() data: UserRoleCreateDto): Promise<any> {\n\n    return data;\n  }\n```\n\n```text\ncurl 'http://localhost:3060/test_input?name=hello'\n\n{\"name\":\"HELLO\"}\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\ntransform: true\n```\n\n```text\n@Query()\n```\n\n```text\n@Body()\n```\n\n```text\n@Param()\n```\n\n```text\n@Transform(({name}) => name.toUpperCase())\n```\n\n```text\n@Transform((name) => name.toUpperCase())\n```\n\n```text\n{}\n```\n\n```text\nconsole.log()\n```\n\n```text\nTransform()\n```\n\n```text\n@Matches()\n```\n\n```text\n'class-transformer'\n```\n\n```text\n@UsePipes(new ValidationPipe({transform: true}))\n```\n\n```text\napp.useGlobalPipes\n```\n\n```text\nclass ClassName {\n  @Transform((param) => param.value.toUpperCase())\n  name: string;\n}\n```\n\n```text\nparam\n```\n\n```text\nvalue, key, obj, type\n```\n\n========================================\n\nComments:\n- This only works when the value is being processed by the controllers middlewares. It doesn't work if the program is running from a script, cron job, etc.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":174,"estimatedTokens":853}}206{"id":"stack-56103518","source":"stackoverflow","questionId":56103518,"title":"What is the proper way to do seed mongoDB in NestJS, using mongoose and taking advantage of my already defined schmas","tags":["mongodb","typescript","mongoose","nestjs"],"text":"Title: What is the proper way to do seed mongoDB in NestJS, using mongoose and taking advantage of my already defined schmas\nTags: mongodb, typescript, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nWe are using NestJS with mongoose and want to seed mongoDB.\nWondering what is the proper way to seed the database, and use the db schemas already defined to ensure the data seeded is valid and properly maintained.\n\nSeeding at the module level (just before the definition of the Module) feels hacky and ends in threadpool being destroyed, and therefore all following mongo operations fail\n\n========================================\n\nTop Answer:\nactually you can do it easily with onModuleInit(), here i'm using Mongoose ORM. This all done with zero dependencies, hope it helps\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { UserRepository } from './repositories/user.repository';\n\n@Injectable()\nexport class UserService implements OnModuleInit {\n constructor(private readonly userRepository: UserRepository) {}\n\n // onModuleInit() is executed before the app bootstraped\n async onModuleInit() {\n try {\n const res = await this.userRepository.findAll(); // this method returns user data exist in database (if any)\n // checks if any user data exist\n if (res['data'] == 0) {\n const newUser = {\n name: 'yourname',\n email: 'youremail@gmail.com',\n username: 'yourusername',\n };\n const user = await this.userRepository.create(newUser); // this method creates new user in database\n console.log(user);\n }\n } catch (error) {\n throw error;\n }\n }\n\n // your other methods\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Command, Positional } from 'nestjs-command';\nimport { Injectable } from '@nestjs/common';\n\nimport { UserService } from '../../../shared/services/user.service';\n\n@Injectable()\nexport class UserSeed {\nconstructor(\n    private readonly userService: UserService,\n) { }\n\n@Command({ command: 'create:user', describe: 'create a user', autoExit: true })\nasync create() {\n    const user = await this.userService.create({\n        firstName: 'First name',\n        lastName: 'Last name',\n        mobile: 999999999,\n        email: 'test@test.com',\n        password: 'foo_b@r',\n    });\n    console.log(user);\n}\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { CommandModule } from 'nestjs-command';\n\nimport { UserSeed } from '../modules/user/seeds/user.seed';\nimport { SharedModule } from './shared.module';\n\n@Module({\n    imports: [CommandModule, SharedModule],\n    providers: [UserSeed],\n    exports: [UserSeed],\n})\nexport class SeedsModule {}\n```\n\n```text\nnpx nestjs-command create:user\n```\n\n```text\nimports\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { UserRepository } from './repositories/user.repository';\n\n@Injectable()\nexport class UserService implements OnModuleInit {\n  constructor(private readonly userRepository: UserRepository) {}\n\n  // onModuleInit() is executed before the app bootstraped\n  async onModuleInit() {\n    try {\n      const res = await this.userRepository.findAll(); // this method returns user data exist in database (if any)\n      // checks if any user data exist\n      if (res['data'] == 0) {\n        const newUser = {\n          name: 'yourname',\n          email: 'youremail@gmail.com',\n          username: 'yourusername',\n        };\n        const user = await this.userRepository.create(newUser); // this method creates new user in database\n        console.log(user);\n      }\n    } catch (error) {\n      throw error;\n    }\n  }\n\n  // your other methods\n}\n```\n\n```text\n// # base.seed.service.ts\n\nimport { Model, Document } from 'mongoose';\n\nimport { forceArray, toJson } from 'src/utils/code';\n\nexport abstract class BaseSeedService<D extends Document> {\n  constructor(protected entityModel: Model<D>) {}\n\n  async insert<T = any>(data: T | T[]): Promise<any[]> {\n    const docs = await this.entityModel.insertMany(forceArray(data));\n    return toJson(docs);\n  }\n}\n\n\n// # utils\nconst toJson = (arg: any) => JSON.parse(JSON.stringify(arg));\nfunction forceArray<T = any>(instance: T | T[]): T[] {\n   if (instance instanceof Array) return instance;\n   return [instance];\n}\n\n\n// # dummy.seed.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Model } from 'mongoose';\n\nimport { DummyDocument } from './dummy.schema';\n\n@Injectable()\nexport class DummySeedService extends BaseSeedService<DummyDocument> {\n  constructor(\n    @InjectModel(Dummy.name)\n    protected model: Model<DummyDocument>,\n  ) {\n    super(model);\n  }\n}\n```\n\n```text\ndescribe('Dymmy Seeds', () => {\n  \n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [DummySeedService],\n      imports: [\n        MongooseModule.forRoot(__connect_to_your_mongodb_test_db__),\n        MongooseModule.forFeature([\n          {\n            name: Dummy.name,\n            schema: DummySchema,\n          },\n        ]),\n      ],\n    }).compile();\n\n    const seeder = module.get<DummySeedService>(DummySeedService);\n    const initData = [__seed_data_here__];\n    const entities: Dummy[] = await seeder.insert(initData);\n    expect(entities.length > 0).toBeTruthy();\n  });\n});\n```\n\n========================================\n\nComments:\n- stackoverflow.com/questions/33186199/&hellip;\n- Thanks a lot! I was hoping there was a more native way without another dependency but I will give it a try with nestjs-command too!\n- what about bulk insertion ? I know there is a method bulkWrite on mongodb document but how to manage it on typescript using nestjs ?\n- How would you, using nestjs-command, make multiple seeds run? For example, I want to seed everything, using `npx nestjs-command create:all`. Of course, I would have to write all seeds before doing it in files as you described above, but I want to run them all with a single command and also to be able to run each one separatedly!\n- I think you need to create a separate file for create:all, and inject all your seeders in that file and call corresponding method.\n- Hi, stumbled upon this answer, and whanted to check with you, what about using NestJS lifecycle ? It removes dependecies, and you have `onModuleInit()` method which is called before application bootstrap. docs.nestjs.com/fundamentals/lifecycle-events\n- worked well for me, thanks! Will update if I find and issues.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":207,"estimatedTokens":1603}}207{"id":"stack-63922792","source":"stackoverflow","questionId":63922792,"title":"Nest.Js: import files from outside project folder","tags":["typescript","directory","nestjs"],"text":"Title: Nest.Js: import files from outside project folder\nTags: typescript, directory, nestjs\nSource: Stack Overflow\n\nQuestion:\nI started using Nest.Js and I created a Full Stack App with this structure:\n\nhttps://i.sstatic.net/Hov6j.png\n\n`api`: nestjs app\n\n`client`: frontend app\n\n`models`: shared models (interfaces only) between back and front\n\nSo I set alias path in `tsconfig.json` inside api folder to let it import shortly: `import { User } from 'models/user.model'`\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"incremental\": true, \n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"paths\": {\n \"models/*\": [\"../models/*\"]\n }\n }\n}\n```\n\nThe problem is that typescript is compiling and changing the root structure under `dist` folder and nest cli is not finding `main.js` file to start up the application.\n\nhttps://i.sstatic.net/ZuJPf.png\n\nIs there a way to move `models` folder and preserve nestjs structure?\nOr maybe change nestjs config to start the app on `api/src/main.js`?\n\n========================================\n\nCode:\n```json\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"incremental\": true, \n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"paths\": {\n      \"models/*\": [\"../models/*\"]\n    }\n  }\n}\n```\n\n```text\napi\n```\n\n```text\nclient\n```\n\n```text\nmodels\n```\n\n```text\ntsconfig.json\n```\n\n```text\nimport { User } from 'models/user.model'\n```\n\n```text\ndist\n```\n\n```text\nmain.js\n```\n\n```text\nmodels\n```\n\n```text\napi/src/main.js\n```\n\n```text\nsrc\n```\n\n```text\nnest-cli.json\n```\n\n```text\nentryFile\n```\n\n```text\nmain\n```\n\n```text\nNx\n```\n\n========================================\n\nComments:\n- Hi can you tell me what icon package you're using please? :-)\n- @RyanWeiss `Material Icon Theme` for vscode\n- Thanks @Eduardo!\n- @EduardoRosostolato Did you get an error when building production export? cuz `paths` was not working with production build\n- @SayJeyHi I didn't move forward with this project and I haven't tried it on production, so I can't say it... Sorry.\n- Perfect! I set `\"entryFile\": \"api&#47;src&#47;main\"` on `nest-cli.json` and it worked! Thank you!\n- Brilliant! That's what I'm looking for! (after searching and trying a lot like a headless fly...)\n- Just a note that I had to also delete the `dist` folder to get this to update properly with `paths`\n- Can you instead tell Typescript not to do that ? I have the same issue, but in my folder I have an Angular application alongside the Nest app, and the issue does not happen with Angular, only with Nest ... (And yes, I use the file in both projects)\n- Angular uses webpack, which will output a singe file that's a bundle of your application. You can do the same with Nest, that's actually how Nx sets up monorepo workspaces for the most part\n- It worked for me. In my case the shared file was a zod schema, so I needed to install zod in my shared folder and in my backend project","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":139,"estimatedTokens":817}}208{"id":"stack-72957962","source":"stackoverflow","questionId":72957962,"title":"How to extend TypeORM repository in NestJS 9 (TypeORM 3.+)","tags":["node.js","dependency-injection","orm","nestjs","typeorm"],"text":"Title: How to extend TypeORM repository in NestJS 9 (TypeORM 3.+)\nTags: node.js, dependency-injection, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nPreviously, TypeORM repository could be extended and injected directly into services, e.g.:\n\n```\nimport { User } from './entities/user.entity';\nimport { EntityRepository, Repository } from 'typeorm';\n\n@EntityRepository(User)\nexport class UsersRepo extends Repository {\n // my custom repo methods\n}\n```\n\n```\nimport { Injectable } from '@nestjs/common'\nimport { UsersRepo } from './users.repo';\n\n@Injectable()\nexport class UsersService {\n constructor(private readonly usersRepo: UsersRepo) {}\n}\n```\n\nBut since version 3.0.0 TypeORM does not support repository extending via inheritance.\n\nHow to achieve such behavior in NestJS 9 (which depends on TypeORM 3.+)? The only solution I came up with is to add custom methods to the service layer. But I would like to keep all ORM-related methods (query, aggregations, etc.) in the repository layer.\n\n========================================\n\nTop Answer:\nHope helpful for you:\n\n```\nimport { DataSource, Repository } from 'typeorm';\nimport { EntityTarget } from 'typeorm/common/EntityTarget';\n\nexport class GenericRepository extends Repository {\n constructor(target: EntityTarget, dataSource: DataSource) {\n super(target, dataSource.createEntityManager());\n }\n\n async someCommonMethod() {\n return {};\n }\n}\n```\n\n```\nimport { DataSource } from 'typeorm';\nimport { User } from '../../entities/User';\nimport { Injectable } from '@nestjs/common';\nimport { GenericRepository } from '../common/generic.repository';\n\n@Injectable()\nexport class UserRepository extends GenericRepository {\n constructor(private dataSource: DataSource) {\n super(User, dataSource.createEntityManager());\n }\n}\n```\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { User } from '../../entities/User';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: UsersRepository,\n ) {}\n}\n```\n\n========================================\n\nCode:\n```js\nimport { User } from './entities/user.entity';\nimport { EntityRepository, Repository } from 'typeorm';\n\n@EntityRepository(User)\nexport class UsersRepo extends Repository<User> {\n  // my custom repo methods\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common'\nimport { UsersRepo } from './users.repo';\n\n@Injectable()\nexport class UsersService {\n  constructor(private readonly usersRepo: UsersRepo) {}\n}\n```\n\n```js\n@Injectable()\nexport class UserRepository extends Repository<UserEntity> {\n\n\n  constructor(\n    @InjectRepository(UserEntity)\n    repository: Repository<UserEntity>\n  ) {\n    super(repository.target, repository.manager, repository.queryRunner);\n  }\n}\n```\n\n```text\n\"@nestjs/typeorm\": \"^9.0.0\"\n```\n\n```text\nconstructor(\n    @InjectRepository(UserEntity)\n    private readonly repository: BaseRepository<UserEntity>,\n) {}\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([UserEntity])],\n  exports: [UserService],\n  providers: [UserService],\n})\nexport class UserModule {}\n```\n\n```text\nimport { DataSource, Repository } from 'typeorm';\nimport { EntityTarget } from 'typeorm/common/EntityTarget';\n\nexport class GenericRepository<T> extends Repository<T> {\n  constructor(target: EntityTarget<T>, dataSource: DataSource) {\n    super(target, dataSource.createEntityManager());\n  }\n\n  async someCommonMethod() {\n    return {};\n  }\n}\n```\n\n```text\nimport { DataSource } from 'typeorm';\nimport { User } from '../../entities/User';\nimport { Injectable } from '@nestjs/common';\nimport { GenericRepository } from '../common/generic.repository';\n\n@Injectable()\nexport class UserRepository extends GenericRepository<User> {\n  constructor(private dataSource: DataSource) {\n    super(User, dataSource.createEntityManager());\n  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { User } from '../../entities/User';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UsersRepository } from './users.repository';\n\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User)\n    private readonly usersRepository: UsersRepository,\n  ) {}\n}\n```\n\n```js\nimport { Repository } from 'typeorm';\nimport { User } from './user.entity';\n\nexport interface ExtendedUserRepository extends Repository<User> {\n  findByUsername(username: string): Promise<User | undefined>;\n  findByEmail(email: string): Promise<User | undefined>;\n}\n\nexport const extendedUserRepository = {\n  findByUsername(this: Repository<User>, username: string) {\n    return this.findOne({ where: { username } });\n  },\n  findByEmail(this: Repository<User>, email: string) {\n    return this.findOne({ where: { email } });\n  }\n};\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { User } from './user.entity';\nimport { extendedUserRepository, ExtendedUserRepository } from './user.repository';\n\n@Injectable()\nexport class UserService {\n  private userRepository: ExtendedUserRepository;\n\n  constructor(\n    @InjectRepository(User)\n    private readonly repository: Repository<User>\n  ) {\n    this.userRepository = this.repository.extend(extendedUserRepository);\n  }\n\n  // Use this.userRepository to access custom methods\n}\n```\n\n========================================\n\nComments:\n- For some reason when I try to use my custom repository outside my module, this method breaks down..\n- well, did you export it from your module?\n- How would this work if I want to use `userRepository` in multiple services? Is calling `extend` on the same instance from multiple constructors safe?\n- @ArnoHilke As far as I understand, it should be fine. I've also been using this method pretty extensively for a while now and never run into a problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":230,"estimatedTokens":1482}}209{"id":"stack-57888648","source":"stackoverflow","questionId":57888648,"title":"I tried nestjs but I realized it reduces code readability because of so many decorators, please take a second to visit this","tags":["node.js","nestjs"],"text":"Title: I tried nestjs but I realized it reduces code readability because of so many decorators, please take a second to visit this\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI recently used nestjs, But I realized its overcomplicated, I mean look the following code:\n\n```\n@post('/products')\ngetAllProducts(@Body('title') title, @Body('price') price, @Body('description') description) { }\n```\n\nIt makes function parameters much dirty, Also there could be more decorators above function like @Header, @Params, etc.. Which reduces readability in my opinion.\nSame code in nodejs\n\n```\nconst { title: title, price: price, description: description } = req.body\n```\n\nnodejs is much more readable...\n\nThen I researched why developers use nestjs, Reason was Modularity. Why we don't implement this on our own...\n\nSee below:\n\nSee my directory sutructure\n\nIn app.js I just kicked the app:\n\n```\nconst express = require('express');\n\nconst app = express();\n\n// express config\nrequire('./startup/config')(app);\n\n// handling routes\nrequire('./startup/routes')(app);\n\n// db setup\nrequire('./startup/db')(app);\n```\n\nIn startup folder I did the basic work like mongoose configuration and connection to db etc..\n\nHowever, In startup/routes, I just kicked the module as :\n\n```\nconst shopModule = require('../shop/shop.module');\n\nmodule.exports = app => {\n app.use('/', shopModule);\n};\n```\n\nIn shop module, I just kicked the routes as :\n\n```\nconst router = require('express').Router();\n\nconst productsRouter = require('./products/index');\nconst cartRouter = require('./cart/index');\n\n// Products\nrouter.use('/products', productsRouter)\n// Cart\nrouter.use('/cart', cartRouter)\n\nmodule.exports = router;\n```\n\nNow in cart/index.js, I handled the routes related to cart and same for products as (I will just show cart):\n\n```\nconst router = require('express').Router();\n\nconst { getCart } = require('./cart.controller');\n\nrouter.get('/', getCart);\n\nmodule.exports = router;\n```\n\nIn controller, basically we will do validation stuff etc or extracting data.. Then controller will kick service for database work..\n\n```\nconst { userCart } = require('./cart.service');\n\nexports.getCart = (req, res, next) => {\n const cart = userCart();\n return res.status(200).json(cart);\n};\n```\n\nAnd finally in cart service:\n\n```\nexports.userCart = _ => {\n // ... go to database and fetch cart\n return [{ prodId: 123, quantity: 2 }];\n};\n```\n\nAnd cart.model.js is responsible for DB schema, \n\nI know the question was too long, but I wanted to explain my question. \n\nI am not saying nestjs should not be used, I am just saying, what about the following structure as it follows the same pattern as angular or nestjs, Right?\n\n========================================\n\nTop Answer:\nit's dirty because you write it in the wrong way\n\nwhy not use it like this\n\n```\n@Get('/')\ngetAllProducts(@Body() product: Product) {}\n```\n\nand then destructure it\n\n```\nconst {title, price, description} = product\n```\n\n========================================\n\nCode:\n```text\n@post('/products')\ngetAllProducts(@Body('title') title, @Body('price') price, @Body('description') description) { }\n```\n\n```text\nconst { title: title, price: price, description: description } = req.body\n```\n\n```text\nconst express = require('express');\n\nconst app = express();\n\n// express config\nrequire('./startup/config')(app);\n\n// handling routes\nrequire('./startup/routes')(app);\n\n// db setup\nrequire('./startup/db')(app);\n```\n\n```text\nconst shopModule = require('../shop/shop.module');\n\nmodule.exports = app => {\n    app.use('/', shopModule);\n};\n```\n\n```text\nconst router = require('express').Router();\n\nconst productsRouter = require('./products/index');\nconst cartRouter = require('./cart/index');\n\n// Products\nrouter.use('/products', productsRouter)\n// Cart\nrouter.use('/cart', cartRouter)\n\nmodule.exports = router;\n```\n\n```text\nconst router = require('express').Router();\n\nconst { getCart } = require('./cart.controller');\n\nrouter.get('/', getCart);\n\nmodule.exports = router;\n```\n\n```text\nconst { userCart } = require('./cart.service');\n\nexports.getCart = (req, res, next) => {\n    const cart = userCart();\n    return res.status(200).json(cart);\n};\n```\n\n```text\nexports.userCart = _ => {\n    // ... go to database and fetch cart\n    return [{ prodId: 123, quantity: 2 }];\n};\n```\n\n```text\n@Post('/products')\ngetAllProducts(@Body() body: any) {}\n```\n\n```text\nconst {title: title, price: price, description: description} = body;\n```\n\n```text\n@Header()\n```\n\n```text\n@Param()\n```\n\n```text\n@Query()\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nAuthModule\n```\n\n```text\nguards\n```\n\n```text\napp\n```\n\n```text\nAppController\n```\n\n```text\nAppService\n```\n\n```text\nAppModule\n```\n\n```text\n@Get('/')\ngetAllProducts(@Body() product: Product) {}\n```\n\n```text\nconst {title, price, description} = product\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":269,"estimatedTokens":1292}}210{"id":"stack-57833669","source":"stackoverflow","questionId":57833669,"title":"How to get JWT token from headers in controller","tags":["controller","request","http-headers","nestjs"],"text":"Title: How to get JWT token from headers in controller\nTags: controller, request, http-headers, nestjs\nSource: Stack Overflow\n\nQuestion:\nPlease, help me to find how to optimize my code.\nI need to limit the data for logged user. To do that, I need to get UUID from JWT token from Request. But I don't like my approach because I have duplicates of code:\n\n```\nconst jwt = request.headers.authorization.replace('Bearer ', '');\nconst json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n```\n\nAny one know how I can optimize that?\n\nHere is my controller's code.\n\n```\nimport { Controller, Get, Put, Body, Param, UseGuards, Req } from '@nestjs/common';\nimport { SettingService } from '../services';\nimport { AuthGuard } from '@nestjs/passport';\nimport { ResultInterface } from '../interfaces';\nimport { Request } from 'express';\nimport { JwtService } from '@nestjs/jwt';\n\n@Controller('settings')\nexport class SettingController {\n /**\n * @param service\n * @param jwtService\n */\n constructor(private readonly service: SettingService,\n private readonly jwtService: JwtService) {\n }\n\n @UseGuards(AuthGuard('jwt'))\n @Get()\n async findAll(@Req() request: Request): Promise {\n const jwt = request.headers.authorization.replace('Bearer ', '');\n const json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n const data = await this.service.findAll(json.uuid);\n return { rows: data };\n }\n\n @UseGuards(AuthGuard('jwt'))\n @Get(':id')\n async findOne(@Param('id') id: number, @Req() request: Request): Promise {\n const jwt = request.headers.authorization.replace('Bearer ', '');\n const json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n const data = await this.service.findOneById(id, json.uuid);\n return { row: data };\n }\n\n @UseGuards(AuthGuard('jwt'))\n @Put()\n update(@Body() data: any, @Req() request: Request): Promise {\n const jwt = request.headers.authorization.replace('Bearer ', '');\n const json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n return this.service.update(data, json.uuid);\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou could create a JWTUtil that does that for you... Maybe something like this?\n\n```\n@Injectable()\nexport class JWTUtil {\n constructor(private readonly jwtService: JWTService) {}\n\n decode(auth: string): {uuid: string}{\n const jwt = auth.replace('Bearer ', '');\n return this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n }\n}\n```\n\nAnd then use it like this:\n\n```\n@Controller('settings')\nexport class SettingController {\n constructor(\n private readonly jwtUtil: JWTUtil,\n private readonly service: SettingService,\n ) {}\n\n @Get()\n @UseGuards(AuthGuard('jwt'))\n async findAll(@Headers('Authorization') auth: string): Promise {\n const json = await this.jwtUtil.decode(auth);\n const data = await this.service.findAll(json.uuid);\n\n //....\n }\n}\n```\n\nAlso note that you can directly access the `Authorization` header from the controller. Instead of passing through the `Request` object.\n\n========================================\n\nCode:\n```js\nconst jwt = request.headers.authorization.replace('Bearer ', '');\nconst json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n```\n\n```js\nimport { Controller, Get, Put, Body, Param, UseGuards, Req } from '@nestjs/common';\nimport { SettingService } from '../services';\nimport { AuthGuard } from '@nestjs/passport';\nimport { ResultInterface } from '../interfaces';\nimport { Request } from 'express';\nimport { JwtService } from '@nestjs/jwt';\n\n@Controller('settings')\nexport class SettingController {\n  /**\n   * @param service\n   * @param jwtService\n   */\n  constructor(private readonly service: SettingService,\n              private readonly jwtService: JwtService) {\n  }\n\n  @UseGuards(AuthGuard('jwt'))\n  @Get()\n  async findAll(@Req() request: Request): Promise<ResultInterface> {\n    const jwt = request.headers.authorization.replace('Bearer ', '');\n    const json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n    const data = await this.service.findAll(json.uuid);\n    return { rows: data };\n  }\n\n  @UseGuards(AuthGuard('jwt'))\n  @Get(':id')\n  async findOne(@Param('id') id: number, @Req() request: Request): Promise<ResultInterface> {\n    const jwt = request.headers.authorization.replace('Bearer ', '');\n    const json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n    const data = await this.service.findOneById(id, json.uuid);\n    return { row: data };\n  }\n\n  @UseGuards(AuthGuard('jwt'))\n  @Put()\n  update(@Body() data: any, @Req() request: Request): Promise<any> {\n    const jwt = request.headers.authorization.replace('Bearer ', '');\n    const json = this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n    return this.service.update(data, json.uuid);\n  }\n}\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const AuthUser = createParamDecorator((data, req) => {\n  return req.user;\n});\n```\n\n```text\n@ApiOperation({ title: 'Get my orders' })\n @Get('/me')\n @UseGuards(AuthGuard('jwt'))\n async findMyOrders(@AuthUser() user: any): Promise<Order[]> {\n   return this.orderService.findbyUserId(user._id);\n }\n```\n\n```js\n@Injectable()\nexport class JWTUtil {\n    constructor(private readonly jwtService: JWTService) {}\n\n    decode(auth: string): {uuid: string}{\n        const jwt = auth.replace('Bearer ', '');\n        return this.jwtService.decode(jwt, { json: true }) as { uuid: string };\n    }\n}\n```\n\n```js\n@Controller('settings')\nexport class SettingController {\n  constructor(\n      private readonly jwtUtil: JWTUtil,\n      private readonly service: SettingService,\n      ) {}\n\n  @Get()\n  @UseGuards(AuthGuard('jwt'))\n  async findAll(@Headers('Authorization') auth: string): Promise<ResultInterface> {\n    const json = await this.jwtUtil.decode(auth);\n    const data = await this.service.findAll(json.uuid);\n\n    //....\n  }\n}\n```\n\n```text\nAuthorization\n```\n\n```text\nRequest\n```\n\n```text\nconst USER_ID_HEADER_NAME = 'x-user-id';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  canActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    return super.canActivate(context);\n  }\n\n  handleRequest<TUser = any>(\n    err: any,\n    user: any,\n    info: any,\n    context: ExecutionContext,\n  ): TUser {\n    if (err || !user) {\n      throw err || new UnauthorizedException();\n    }\n\n    const request = context.switchToHttp().getRequest();\n    request.headers[USER_ID_HEADER_NAME] = user.id;\n    return user;\n  }\n}\n```\n\n```text\nUSER_ID_HEADER_NAME\n```\n\n```text\nasync findAll(@Req() request: Request): Promise<ResultInterface> {\n  const authToken = request.headers['authorization'].split(' ')[1];\n}\n```\n\n```text\nrequest.headers.authorization...\n```\n\n```js\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: process.env.JWT_SECRET,\n    });\n  }\n\n  validate(payload: any) {\n    // What this function returns is what req.user will be set to everywhere\n    return { user_id: payload.sub };\n  }\n}\n```\n\n```js\nimport { Controller, Get, Request } from '@nestjs/common';\nimport { UsersService } from 'src/users/users.service';\n\n@Controller('api/user')\nexport class UserController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Get('username')\n  username(@Request() req) {\n    return this.usersService.getUsername(req.user.user_id);\n  }\n}\n```\n\n```text\njwt.strategy.ts\n```\n\n```text\nvalidate()\n```\n\n```text\nreq.user\n```\n\n```text\nJwtAuthGuard\n```\n\n```text\nuser_id\n```\n\n```text\nuser.controller.ts\n```\n\n```text\n.getUsername()\n```\n\n========================================\n\nComments:\n- As I said in my previous response in the answer you gave you are double decoding the token, first when using AuthGuard('jwt) and second in controller function jwtUtil.decode()\n- Much better than mine!\n- Cool! Good idea. Thank you\n- The method to create a decorator changed, here is the doc about it docs.nestjs.com/custom-decorators.\n- In my case the user object isn't located directly in the `req` param. I had to access it as shown in the custom decorator Nest docs. Adapting the answer it would be `req.switchToHttp().getRequest().user`. `req` is of `ExecutionContext` type, imported from `@nestjs&#47;common`.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":328,"estimatedTokens":2137}}211{"id":"stack-62973130","source":"stackoverflow","questionId":62973130,"title":"How to populate mongoose references in nestjs?","tags":["mongoose","nestjs","mongoose-populate"],"text":"Title: How to populate mongoose references in nestjs?\nTags: mongoose, nestjs, mongoose-populate\nSource: Stack Overflow\n\nQuestion:\nI define a Person and Story schemas :\n\n```\n@Schema()\n export class Person extends Document {\n @Prop()\n name: string;\n }\n export const PersonSchema = SchemaFactory.createForClass(Person);\n \n \n @Schema()\n export class Story extends Document {\n \n @Prop()\n title: string;\n \n @Prop()\n author: { type: MongooseSchema.Types.ObjectId , ref: 'Person' }\n \n }\n export const StorySchema = SchemaFactory.createForClass(Story);\n```\n\nIn my service I implemented save and read functions:\n\n```\nasync saveStory(){\n const newPerson = new this.personModel();\n newPerson.name = 'Ian Fleming';\n await newPerson.save();\n const newStory = new this.storyModel();\n newStory.title = 'Casino Royale';\n newStory.author = newPerson._id;\n await newStory.save();\n }\n \n async readStory(){\n const stories = await this.storyModel.\n findOne({ title: 'Casino Royale' })\n console.log('stories ',stories);\n }\n```\n\nWhen I ran readStory() I get the following output:\n\n```\nstories {\n _id: 5f135150e46fa5256a3a1339,\n title: 'Casino Royale',\n author: 5f135150e46fa5256a3a1338,\n __v: 0\n }\n```\n\nWhen I add a `populate('author')` to my query then I get author as null:\n\n```\nstories {\n _id: 5f135150e46fa5256a3a1339,\n title: 'Casino Royale',\n author: null,\n __v: 0\n }\n```\n\nHow do I populate the author field with the referenced Person document ?\n\n========================================\n\nTop Answer:\nFound it.\nMy mistake was in defining the schema.\nShould be :\n\n```\n@Schema()\nexport class Story extends Document {\n @Prop()\n title: string;\n \n @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })\n author: MongooseSchema.Types.ObjectId \n}\n```\n\n========================================\n\nCode:\n```js\n@Schema()\n    export class Person extends Document {\n      @Prop()\n      name: string;\n    }\n    export const PersonSchema = SchemaFactory.createForClass(Person);\n    \n    \n    @Schema()\n    export class Story extends Document {\n    \n      @Prop()\n      title: string;\n    \n      @Prop()\n      author:  { type: MongooseSchema.Types.ObjectId , ref: 'Person' }\n    \n    }\n    export const StorySchema = SchemaFactory.createForClass(Story);\n```\n\n```js\nasync saveStory(){\n        const newPerson = new this.personModel();\n        newPerson.name  = 'Ian Fleming';\n        await newPerson.save();\n        const newStory  = new this.storyModel();\n        newStory.title = 'Casino Royale';\n        newStory.author = newPerson._id;\n        await newStory.save();\n      }\n    \n      async readStory(){\n        const stories = await this.storyModel.\n            findOne({ title: 'Casino Royale' })\n        console.log('stories ',stories);\n      }\n```\n\n```js\nstories  {\n      _id: 5f135150e46fa5256a3a1339,\n      title: 'Casino Royale',\n      author: 5f135150e46fa5256a3a1338,\n      __v: 0\n    }\n```\n\n```js\nstories  {\n      _id: 5f135150e46fa5256a3a1339,\n      title: 'Casino Royale',\n      author: null,\n      __v: 0\n    }\n```\n\n```text\npopulate('author')\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types, Schema as MongooseSchema } from 'mongoose';\n\n@Schema()\nexport class Story extends Document {\n\n  @Prop()\n  title: string;\n\n  @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })\n  author:  Types.ObjectId \n\n}\n\nexport const StorySchema = SchemaFactory.createForClass(Story);\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types, Schema as MongooseSchema } from 'mongoose';\nimport { Person } from './person.schema'\n\n@Schema()\nexport class Story extends Document {\n\n  @Prop()\n  title: string;\n\n  @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })\n  author:  Person\n\n}\n\nexport const StorySchema = SchemaFactory.createForClass(Story);\n```\n\n```text\nTypes.ObjectId\n```\n\n```text\nMongooseSchema.Types.ObjectId\n```\n\n```js\n@Schema()\nexport class Story extends Document {\n  @Prop()\n  title: string;\n    \n  @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })\n  author:  MongooseSchema.Types.ObjectId  \n}\n```\n\n```js\nimport { User, UserDocument } from 'src/schemas/user.schema';\nimport { Role, RoleDocument } from 'src/schemas/role.schema';\n\n...\n\nconstructor(\n    @InjectModel(User.name) private userModel: Model<UserDocument>,\n    @InjectModel(Role.name) private roleModel: Model<RoleDocument>,\n    private roleService: RolesService\n  ) {}\n\n\nasync findOne(id: string) {\n    return await this.userModel.findOne({ _id: id }).populate('role', '', this.roleModel).exec();\n}\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Role } from './role.schema';\n\nexport type UserDocument = User & mongoose.Document;\n\n@Schema()\nexport class User {\n  @Prop({ required: true, type: String })\n  email: string;\n\n  @Prop({ type: String })\n  name: string;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Role' })\n  role: Role;\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n```js\nexport type RoleDocument = Role & mongoose.Document;\n\n@Schema()\nexport class Role {\n  @Prop({ type: String, required: true, unique: true, index: true })\n  name: string;\n\n  @Prop({ type: [String], required: true })\n  permissions: string[];\n}\n\nexport const RoleSchema = SchemaFactory.createForClass(Role);\n```\n\n```text\npopulate()\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from \"@nestjs/mongoose\";\nimport mongoose, { HydratedDocument } from \"mongoose\";\n\nexport type BookingDocument = HydratedDocument<Booking>;\n\n@Schema({ collection: \"booking\" })\nexport class Booking {\n  @Prop({ required: true })\n  _id: string;\n\n  @Prop({required: true, type: mongoose.Schema.Types.String, ref: \"Tasker\"})\n  taskerID: string;\n}\n\nexport const BookingSchema = SchemaFactory.createForClass(Booking);\n\nexport const BookingModel = {name: Booking.name, schema: BookingSchema};\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from \"@nestjs/mongoose\";\nimport { HydratedDocument } from \"mongoose\";\n\nexport type TaskerDocument = HydratedDocument<Tasker>;\n\n@Schema({ collection: \"tasker\" })\nexport class Tasker {\n  @Prop({ required: true })\n  _id: string;\n\n  @Prop({ required: true })\n  phone: string;\n\n  @Prop({ required: true })\n  name: string;\n}\n\nexport const TaskerSchema = SchemaFactory.createForClass(Tasker);\n\nexport const TaskerModel = { name: Tasker.name, schema: TaskerSchema };\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\nimport { InjectModel } from \"@nestjs/mongoose\";\nimport { Booking, BookingDocument } from \"../db-module/schemas/booking.schema\";\nimport * as mongoose from \"mongoose\";\nimport { Tasker, TaskerDocument } from \"../db-module/schemas/tasker-user.schema\";\n\n@Injectable()\nexport class BookingService {\n  constructor(\n    @InjectModel(Booking.name)\n    private bookingModel: mongoose.Model<BookingDocument>,\n    @InjectModel(Tasker.name)\n    private taskerModel: mongoose.Model<TaskerDocument>\n  ) {}\n\n  async findById(id: string): Promise<Booking> {\n    const Booking = await this.bookingModel.findOne({ _id: id }).populate(\n      \"taskerID\",\n      \"\",\n      this.taskerModel,\n    ).exec();\n    return Booking.toJSON();\n  }\n}\n```\n\n```text\ntasker\n```\n\n```text\nUUID\n```\n\n```text\nObjectID\n```\n\n```text\nObjectID\n```\n\n```text\ntaskerID\n```\n\n```text\nstring\n```\n\n```text\nTypes.ObjectId\n```\n\n========================================\n\nComments:\n- Thank you! Setting the type in the `Prop` options was the solution to my problem, since I am using union types for actual typescript typings. Btw: you can also `import { Types } from 'mongoose';` and then use `author: Types.ObjectId`.\n- How would you write this for an array? I tried wrapping in an array like this: @Prop([{ type: MongooseSchema.Types.ObjectId , ref: 'Person' }])\n- @austinthedeveloper I am not sure you can have an array of references that can be populated automatically. But I don't know.\n- By changing author to a person, upon creating mongo throws a cast error.\n- I feel like this should be in the official NestJS Mongoose docs. After implementing this change, I removed the circular references NestJS was throwing.\n- The only issue with this is that when you populate the sub Document and try to use it, there will be a type error because it expects it to be an ObjectId. I'm currently trying to figure out how to fix this.","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":378,"estimatedTokens":2090}}212{"id":"stack-58497740","source":"stackoverflow","questionId":58497740,"title":"nestjs context.swithToHttp().getRequest() returns undefined","tags":["graphql","nestjs"],"text":"Title: nestjs context.swithToHttp().getRequest() returns undefined\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to create RolesGuard for Graphql\n\nI create Roles decorator like following\n\n```\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n```\n\nAnd I create GqlAuthGuard and RolesGuard like following\n\n```\ngql-gurad.ts\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext){\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n}\n\nrole-guard.ts\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\nconstructor(private readonly reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const roles = this.reflector.get('roles', context.getHandler());\n if (!roles) {\n return true;\n }\n const request = context.switchToHttp().getRequest();\n const user = request.user;\n\n ...\n }\n}\n```\n\nbut line `const request = context.switchToHttp().getRequest();` returns undefined.\n\nand i'm using two guards like following\n\n```\n@AuthGuard(GqlAuthGuard, RolesGuard)\n@Mutation(...)\n```\n\nWhat did I miss??\n\n========================================\n\nCode:\n```text\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n```\n\n```text\ngql-gurad.ts\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n    getRequest(context: ExecutionContext){\n        const ctx = GqlExecutionContext.create(context);\n        return ctx.getContext().req;\n    }\n}\n\nrole-guard.ts\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\nconstructor(private readonly reflector: Reflector) {}\n\n    canActivate(context: ExecutionContext): boolean {\n        const roles = this.reflector.get<string[]>('roles', context.getHandler());\n        if (!roles) {\n            return true;\n        }\n        const request = context.switchToHttp().getRequest();\n        const user = request.user;\n\n        ...\n    }\n}\n```\n\n```text\n@AuthGuard(GqlAuthGuard, RolesGuard)\n@Mutation(...)\n```\n\n```text\nconst request = context.switchToHttp().getRequest();\n```\n\n```text\nconst request = context.switchToHttp().getRequest();\nconst user = request.user;\n\nto\n\nconst ctx = GqlExecutionContext.create(context);\nconst user = ctx.getContext().req.user;\n```\n\n========================================\n\nComments:\n- Where does the `user` property come from? In what I'm making I have the concept of an organization instead of a user, but the `.getRequest()` still returns the `user` property but with my organization on it. I mean it works fine, it's just an odd forced naming convention that doesn't apply to me. I'd like to change it if possible.\n- @ChrisBarr when you use passport, the user property will be dynamically attached to your object of value extracted from Req decorator with req user is the value returned from your validate() method in your defined Strategy, for example: import {Strategy} from passport-local, localStrategy extends passport(Strategy). Maybe too late but hope it helps you in the foreseeable future !\n- Another usecase where `context.switchToHttp().getRequest()` returns undefined is with websocket. I met the case with a global guard + adding websocket (through graphql). Such guard has to be reimagined for websocket if, for example, relying on HTTP headers.\n- You must check context type before using it. `if (context.getType() === 'http') { const req = context.switchToHttp().getRequest(); }`","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":119,"estimatedTokens":862}}213{"id":"stack-51905178","source":"stackoverflow","questionId":51905178,"title":"NestJs - How to get request body on interceptors","tags":["javascript","node.js","nestjs"],"text":"Title: NestJs - How to get request body on interceptors\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to get the request body on my interceptor, before it goes to my controller:\n\n```\nimport { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class ExcludeNullInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, call$: Observable): Observable {\n // How can I get the request body here?\n // Need to be BEFORE the Controller exec\n }\n}\n```\n\n========================================\n\nTop Answer:\nIf your `interceptor` is for rest endpoints I think Kim Kern completely covered this part in his answer.\n\nThere are additional possibilities to use `interceptor` and `controllers`.\nFor example `controller` can be an entry point for your micro service for example listening a kafka messages (or any different ones):\n\n```\n@Controller()\nexport class DemoConsumerController {\n private readonly logger = new Logger(DemoConsumerController.name);\n\n @UseInterceptors(LogInterceptor)\n @EventPattern('demo-topic')\n async listenToKafkaMessage (\n @Payload() payload,\n @Ctx() context: KafkaContext,\n ) {\n this.logger.debug(`payload: ${payload}`)\n this.logger.verbose(`Topic: ${context.getTopic()}`);\n this.logger.verbose(`KafkaContext: ${JSON.stringify(context)}`);\n }\n}\n```\n\nIn this case to get body, or better to say message you need a little modification:\n\n```\nintercept(context: ExecutionContext, next: CallHandler): Observable {\n const value = context.switchToHttp().getRequest().value\n\n // default rest part of code\n return next.handle()\n }\n```\n\nSo to avoid of misunderstanding you can verify your request to figureOut what the value contains your payload:\n\n```\nconsole.log('getRequest: ', context.switchToHttp().getRequest())\n// or \nconsole.log('context: ', context)\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class ExcludeNullInterceptor implements NestInterceptor {\n    intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {\n        // How can I get the request body here?\n        // Need to be BEFORE the Controller exec\n    }\n}\n```\n\n```text\nasync intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {\n    const body = context.switchToHttp().getRequest().body;\n    // e.g. throw an exception if property is missing\n```\n\n```text\n(req, res, next) => {\n```\n\n```text\n@Controller()\nexport class DemoConsumerController {\n  private readonly logger = new Logger(DemoConsumerController.name);\n\n  @UseInterceptors(LogInterceptor)\n  @EventPattern('demo-topic')\n  async listenToKafkaMessage (\n    @Payload() payload,\n    @Ctx() context: KafkaContext,\n  ) {\n    this.logger.debug(`payload: ${payload}`)\n    this.logger.verbose(`Topic: ${context.getTopic()}`);\n    this.logger.verbose(`KafkaContext: ${JSON.stringify(context)}`);\n  }\n}\n```\n\n```text\nintercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n        const value = context.switchToHttp().getRequest().value\n\n        // default rest part of code\n        return next.handle()\n    }\n```\n\n```text\nconsole.log('getRequest: ', context.switchToHttp().getRequest())\n// or \nconsole.log('context: ', context)\n```\n\n```text\ninterceptor\n```\n\n```text\ninterceptor\n```\n\n```text\ncontrollers\n```\n\n```text\ncontroller\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.422Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":141,"estimatedTokens":907}}214{"id":"stack-75227100","source":"stackoverflow","questionId":75227100,"title":"Typescript Unable to resolve signature of parameter of decorator in vscode","tags":["typescript","visual-studio-code","nestjs"],"text":"Title: Typescript Unable to resolve signature of parameter of decorator in vscode\nTags: typescript, visual-studio-code, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm getting the error when I'm decorating the class in nestjs service.\n\nThe Typescript is compiling without errors, and I'm getting this problem only in VSCode.\n\n```\nUnable to resolve signature of parameter decorator when called as an expression.\n Argument of type 'undefined' is not assignable to parameter of type 'string | symbol'.ts(1239)\n```\n\nMy tsconfig\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": false,\n \"removeComments\": true,\n \"strictNullChecks\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"ES2020\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"skipLibCheck\": true,\n }\n}\n```\n\nMy Class\n\n```\nexport class AuthService {\n private readonly logger = new Logger('AuthService');\n constructor(\n private readonly jwtService: JwtService,\n private readonly prisma: PrismaService,\n private readonly passwordService: PasswordService,\n private readonly configService: ConfigService,\n private readonly twilioService: TwilioService,\n private readonly userService: UsersService,\n @InjectQueue('nest-worker') private nestWorkerQueue: Queue,\n @InjectQueue('mailsend') private mailSend: Queue,\n @Inject(CACHE_MANAGER) protected readonly cacheManager: Cache,\n private readonly mailerService: MailService\n ) {}\n```\n\nI tried reinstalling typescript removing node modules, but the problem persists.\n\n========================================\n\nTop Answer:\ni've encountered the same issue with this error: \"Unable to resolve signature of class decorator when called as an expression.\nThe runtime will invoke the decorator with 2 arguments, but the decorator expects 1\". \n\nand the fix that worked for me was:\n\n- open the vscode command palette\n\n- enter \"Select TypeScript Version\"\n\n- choose \"use workspace version\"\n\n========================================\n\nCode:\n```text\nUnable to resolve signature of parameter decorator when called as an expression.\n  Argument of type 'undefined' is not assignable to parameter of type 'string | symbol'.ts(1239)\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": false,\n    \"removeComments\": true,\n    \"strictNullChecks\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"ES2020\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n  }\n}\n```\n\n```text\nexport class AuthService {\n  private readonly logger = new Logger('AuthService');\n  constructor(\n    private readonly jwtService: JwtService,\n    private readonly prisma: PrismaService,\n    private readonly passwordService: PasswordService,\n    private readonly configService: ConfigService,\n    private readonly twilioService: TwilioService,\n    private readonly userService: UsersService,\n    @InjectQueue('nest-worker') private nestWorkerQueue: Queue,\n    @InjectQueue('mailsend') private mailSend: Queue,\n    @Inject(CACHE_MANAGER) protected readonly cacheManager: Cache,\n    private readonly mailerService: MailService\n  ) {}\n```\n\n```js\nconstructor(@InjectMapper() mapper: Mapper) {\n    super(mapper);\n  }\n```\n\n```js\nconstructor(@((InjectMapper as any)()) mapper: Mapper) {\n    super(mapper);\n  }\n```\n\n```js\n@((Inject as any)(CACHE_MANAGER)) protected readonly cacheManager: Cache,\n```\n\n```text\nMore Accurate Type-Checking for Parameter Decorators in Constructors Under --experimentalDecorators\n```\n\n```text\n{\n  // other workspace settings\n  \"js/ts.implicitProjectConfig.experimentalDecorators\": true\n}\n```\n\n```text\nNestJS + Deno\n```\n\n```text\n\"compilerOptions\": { \"experimentalDecorators\": true, \"emitDecoratorMetadata\": true }\n```\n\n```text\ndeno.json\n```\n\n```text\nUnable to resolve signature of property decorator when called as an expression. Argument of type 'undefined' is not assignable to parameter of type 'Object'.\n```\n\n```text\nUnable to resolve signature of method decorator when called as an expression. The runtime will invoke the decorator with 2 arguments, but the decorator expects 3. An argument for 'descriptor' was not provided.\n```\n\n```text\nDecorator function return type 'void | TypedPropertyDescriptor<unknown>' is not assignable to type 'void | (() => Promise<Product[]>)'. Type 'TypedPropertyDescriptor<unknown>' is not assignable to type 'void | (() => Promise<Product[]>)'.\n```\n\n```text\nDecorators are not valid here.\n```\n\n```text\nJS/TS โ€บ Implicit Project Config: Experimental Decorators\n```\n\n```text\nsettings.json\n```\n\n```text\nArgument of type 'undefined' is not assignable to parameter of type 'string | symbol'\n```\n\n```none\nreturn (target: object, key: string | symbol | undefined, index?: number) => {\n```\n\n========================================\n\nComments:\n- What version of TypeScript are you using and what config?\n- I'm using 4.9.4 config is in the post\n- what if you use the tsc of your project instead of VSC? via `\"typescript.tsdk\": \"node_modules&#47;typescript&#47;lib\"` to `.vscode&#47;settings.json`\n- I'm getting the same result\n- I had to select correct typescript version in vs code\n- wrong answer - the answer relbns is correct stackoverflow.com/a/77351186/902276\n- this worked for me. In my case vs code typescript version is 5.2.2 and worspace typescript version is 4.3.5. So after selecting workspace version, it works well.\n- The ts.config shown in the question already has experimentalDecorators enabled.","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":198,"estimatedTokens":1403}}215{"id":"stack-56932295","source":"stackoverflow","questionId":56932295,"title":"How to access final GraphQL-Reponse in nest.js with interceptor","tags":["node.js","graphql","nestjs"],"text":"Title: How to access final GraphQL-Reponse in nest.js with interceptor\nTags: node.js, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have implemented a `LoggingInterceptor` which should be able to access the final GraphQL-Response with its data- and error properties + the original request body and the authenticated user, which has been added to the request by `AuthGuard` before.*(EDIT: Partially solved by @jay-mcdoniel: `user` and `body` are accessible through `GqlExecutionContext.create(context).getContext()`)*\n\nIndeed the Interceptor just provides one fully resolved GraphQL-Object.\n\n```\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n return next.handle().pipe(tap(\n (allData) => console.log(allData),\n (error)=> console.log(error)));\n }\n}\n```\n\nThis is my Interceptor-Class. It's just calling the RxJS-Operator `tap` to log the current values of the observable.\n\nIf I run the following GraphQL-Request...\n\n```\nmutation {\n login(data: { username: \"admin\", password: \"123456\" }) {\n id\n username\n token\n }\n}\n```\n\n... my server answers correctly with the following response-body:\n\n```\n{\n \"data\": {\n \"login\": {\n \"id\": \"6f40be3b-cda9-4e6d-97ce-ced3787e9974\",\n \"username\": \"admin\",\n \"token\": \"someToken\"\n }\n }\n}\n```\n\nBut the content of `allData` which get's logged to console by my interceptor is the following:\n\n```\n{\n id: '6f40be3b-cda9-4e6d-97ce-ced3787e9974',\n isAdmin: true,\n username: 'admin',\n firstname: null,\n lastname: null,\n email: null,\n created: 2019-07-05T15:11:31.606Z,\n token: 'someToken'\n}\n```\n\nInstead I would like to see the information of the real response-body.\n\nI have additionally tried to access the HttpResponse by `context.switchToHttp().getResponse()`. But this only contains the parameters of the mutation-login-method:\n\n```\n{\n data: [Object: null prototype] { username: 'admin', password: '123456' }\n}\n```\n\n**EDIT**:\n\n`console.log(GqlExecutionContext.create(context).getContext());`\nprints (still no GraphQL-ResponseBody):\n\n```\n{\n headers: {\n /*...*/\n },\n user: /*...*/,\n body: {\n operationName: null,\n variables: {},\n query: 'mutation {\\n login(data: {username: \"admin\", password: ' +\n '\"123456\"}) {\\n token\\n id\\n username\\n isAdmin\\n }\\n' +\n '}\\n'\n },\n res: ServerResponse {\n _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },\n _eventsCount: 1,\n _maxListeners: undefined,\n outputData: [],\n outputSize: 0,\n writable: true,\n _last: false,\n chunkedEncoding: false,\n shouldKeepAlive: true,\n useChunkedEncodingByDefault: true,\n sendDate: true,\n _removedConnection: false,\n _removedContLen: false,\n _removedTE: false,\n _contentLength: null,\n _hasBody: true,\n _trailer: '',\n finished: false,\n _headerSent: false,\n socket: Socket {\n connecting: false,\n _hadError: false,\n _parent: null,\n _host: null,\n _readableState: [ReadableState],\n readable: true,\n _events: [Object],\n _eventsCount: 8,\n _maxListeners: undefined,\n _writableState: [WritableState],\n writable: true,\n allowHalfOpen: true,\n _sockname: null,\n _pendingData: null,\n _pendingEncoding: '',\n server: [Server],\n _server: [Server],\n timeout: 120000,\n parser: [HTTPParser],\n on: [Function: socketOnWrap],\n _paused: false,\n _httpMessage: [Circular],\n [Symbol(asyncId)]: 566,\n [Symbol(kHandle)]: [TCP],\n [Symbol(lastWriteQueueSize)]: 0,\n [Symbol(timeout)]: Timeout {\n /*...*/\n },\n [Symbol(kBytesRead)]: 0,\n [Symbol(kBytesWritten)]: 0\n },\n connection: Socket {\n connecting: false,\n _hadError: false,\n _parent: null,\n _host: null,\n _readableState: [ReadableState],\n readable: true,\n _events: [Object],\n _eventsCount: 8,\n _maxListeners: undefined,\n _writableState: [WritableState],\n writable: true,\n allowHalfOpen: true,\n _sockname: null,\n _pendingData: null,\n _pendingEncoding: '',\n server: [Server],\n _server: [Server],\n timeout: 120000,\n parser: [HTTPParser],\n on: [Function: socketOnWrap],\n _paused: false,\n _httpMessage: [Circular],\n [Symbol(asyncId)]: 566,\n [Symbol(kHandle)]: [TCP],\n [Symbol(lastWriteQueueSize)]: 0,\n [Symbol(timeout)]: Timeout {\n _idleTimeout: 120000,\n _idlePrev: [TimersList],\n _idleNext: [TimersList],\n _idleStart: 3273,\n _onTimeout: [Function: bound ],\n _timerArgs: undefined,\n _repeat: null,\n _destroyed: false,\n [Symbol(refed)]: false,\n [Symbol(asyncId)]: 567,\n [Symbol(triggerId)]: 566\n },\n [Symbol(kBytesRead)]: 0,\n [Symbol(kBytesWritten)]: 0\n },\n _header: null,\n _onPendingData: [Function: bound updateOutgoingData],\n _sent100: false,\n _expect_continue: false,\n req: IncomingMessage {\n /*...*/\n },\n locals: [Object: null prototype] {},\n [Symbol(isCorked)]: false,\n [Symbol(outHeadersKey)]: [Object: null prototype] {\n 'x-powered-by': [Array],\n 'access-control-allow-origin': [Array]\n }\n },\n _extensionStack: GraphQLExtensionStack { extensions: [ [CacheControlExtension] ] }\n}\n```\n\n========================================\n\nTop Answer:\nThe interceptor is actually called before and after the response, or it should be at least, so that you can have pre-request logic (request in) and post-request logic (response out). You should be able to do all pre-request processing before you call `next.hanlde()` and then you should be able to use the `RxJS Observable operators` such as `tap` or `map` after a `pipe()` call. Your `allData` variable should have all the information from the request/response, and you can even use the `context` variable for getting even more information.\n\nWhat does `allData` currently print for you? Have you tried `GqlExecutionContext.create(context).getContext().req` or `GqlExecutionContext.create(context).getContext().res`? These are shown being used in the `Guards` documentation to get the request and response objects like you would with a normal HTTP call.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next.handle().pipe(tap(\n      (allData) => console.log(allData),\n      (error)=> console.log(error)));\n  }\n}\n```\n\n```text\nmutation {\n  login(data: { username: \"admin\", password: \"123456\" }) {\n    id\n    username\n    token\n  }\n}\n```\n\n```text\n{\n  \"data\": {\n    \"login\": {\n      \"id\": \"6f40be3b-cda9-4e6d-97ce-ced3787e9974\",\n      \"username\": \"admin\",\n      \"token\": \"someToken\"\n    }\n  }\n}\n```\n\n```text\n{\n  id: '6f40be3b-cda9-4e6d-97ce-ced3787e9974',\n  isAdmin: true,\n  username: 'admin',\n  firstname: null,\n  lastname: null,\n  email: null,\n  created: 2019-07-05T15:11:31.606Z,\n  token: 'someToken'\n}\n```\n\n```text\n{\n  data: [Object: null prototype] { username: 'admin', password: '123456' }\n}\n```\n\n```text\n{\n  headers: {\n    /*...*/\n  },\n  user: /*...*/,\n  body: {\n    operationName: null,\n    variables: {},\n    query: 'mutation {\\n  login(data: {username: \"admin\", password: ' +\n      '\"123456\"}) {\\n    token\\n    id\\n    username\\n    isAdmin\\n  }\\n' +\n      '}\\n'\n  },\n  res: ServerResponse {\n    _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },\n    _eventsCount: 1,\n    _maxListeners: undefined,\n    outputData: [],\n    outputSize: 0,\n    writable: true,\n    _last: false,\n    chunkedEncoding: false,\n    shouldKeepAlive: true,\n    useChunkedEncodingByDefault: true,\n    sendDate: true,\n    _removedConnection: false,\n    _removedContLen: false,\n    _removedTE: false,\n    _contentLength: null,\n    _hasBody: true,\n    _trailer: '',\n    finished: false,\n    _headerSent: false,\n    socket: Socket {\n      connecting: false,\n      _hadError: false,\n      _parent: null,\n      _host: null,\n      _readableState: [ReadableState],\n      readable: true,\n      _events: [Object],\n      _eventsCount: 8,\n      _maxListeners: undefined,\n      _writableState: [WritableState],\n      writable: true,\n      allowHalfOpen: true,\n      _sockname: null,\n      _pendingData: null,\n      _pendingEncoding: '',\n      server: [Server],\n      _server: [Server],\n      timeout: 120000,\n      parser: [HTTPParser],\n      on: [Function: socketOnWrap],\n      _paused: false,\n      _httpMessage: [Circular],\n      [Symbol(asyncId)]: 566,\n      [Symbol(kHandle)]: [TCP],\n      [Symbol(lastWriteQueueSize)]: 0,\n      [Symbol(timeout)]: Timeout {\n        /*...*/\n      },\n      [Symbol(kBytesRead)]: 0,\n      [Symbol(kBytesWritten)]: 0\n    },\n    connection: Socket {\n      connecting: false,\n      _hadError: false,\n      _parent: null,\n      _host: null,\n      _readableState: [ReadableState],\n      readable: true,\n      _events: [Object],\n      _eventsCount: 8,\n      _maxListeners: undefined,\n      _writableState: [WritableState],\n      writable: true,\n      allowHalfOpen: true,\n      _sockname: null,\n      _pendingData: null,\n      _pendingEncoding: '',\n      server: [Server],\n      _server: [Server],\n      timeout: 120000,\n      parser: [HTTPParser],\n      on: [Function: socketOnWrap],\n      _paused: false,\n      _httpMessage: [Circular],\n      [Symbol(asyncId)]: 566,\n      [Symbol(kHandle)]: [TCP],\n      [Symbol(lastWriteQueueSize)]: 0,\n      [Symbol(timeout)]: Timeout {\n        _idleTimeout: 120000,\n        _idlePrev: [TimersList],\n        _idleNext: [TimersList],\n        _idleStart: 3273,\n        _onTimeout: [Function: bound ],\n        _timerArgs: undefined,\n        _repeat: null,\n        _destroyed: false,\n        [Symbol(refed)]: false,\n        [Symbol(asyncId)]: 567,\n        [Symbol(triggerId)]: 566\n      },\n      [Symbol(kBytesRead)]: 0,\n      [Symbol(kBytesWritten)]: 0\n    },\n    _header: null,\n    _onPendingData: [Function: bound updateOutgoingData],\n    _sent100: false,\n    _expect_continue: false,\n    req: IncomingMessage {\n      /*...*/\n    },\n    locals: [Object: null prototype] {},\n    [Symbol(isCorked)]: false,\n    [Symbol(outHeadersKey)]: [Object: null prototype] {\n      'x-powered-by': [Array],\n      'access-control-allow-origin': [Array]\n    }\n  },\n  _extensionStack: GraphQLExtensionStack { extensions: [ [CacheControlExtension] ] }\n}\n```\n\n```text\nLoggingInterceptor\n```\n\n```text\nAuthGuard\n```\n\n```text\nuser\n```\n\n```text\nbody\n```\n\n```text\nGqlExecutionContext.create(context).getContext()\n```\n\n```text\ntap\n```\n\n```text\nallData\n```\n\n```text\ncontext.switchToHttp().getResponse()\n```\n\n```text\nconsole.log(GqlExecutionContext.create(context).getContext());\n```\n\n```text\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n  constructor(private readonly logger: Logger) {}\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    // default REST Api\n    if (context.getType() === 'http') {\n     ...\n     ...\n    }\n\n    // Graphql\n    if (context.getType<GqlContextType>() === 'graphql') {\n      const gqlContext = GqlExecutionContext.create(context);\n      const info = gqlContext.getInfo();\n      const res: Response = gqlContext.getContext().res;\n      // Get user that sent request\n      const userId = context.getArgByIndex(2).req.user.userId;\n      const parentType = info.parentType.name;\n      const fieldName = info.fieldName;\n      const body = info.fieldNodes[0]?.loc?.source?.body;\n      const message = `GraphQL - ${parentType} - ${fieldName}`;\n\n      // Add request ID,so it can be tracked with response\n      const requestId = uuidv4();\n      // Put to header, so can attach it to response as well\n      res.set('requestId', requestId);\n\n      const trace = {\n        userId,\n        body\n      };\n\n      this.logger.info(`requestId: ${requestId}`, {\n        context: message,\n        trace\n      });\n      \n      return next.handle().pipe(\n        tap({\n          next: (val: unknown): void => {\n            this.logNext(val, context);\n          }\n        })\n      );\n    }\n    return next.handle();\n  }\n\n  /**\n   * Method to log response message\n   */\n  private logNext(body: unknown, context: ExecutionContext): void {\n    // default REST Api\n    if (context.getType() === 'http') {\n      ...\n      ...\n    }\n\n    if (context.getType<GqlContextType>() === 'graphql') {\n      const gqlContext = GqlExecutionContext.create(context);\n      const info = gqlContext.getInfo();\n      const parentType = info.parentType.name;\n      const fieldName = info.fieldName;\n      const res: Response = gqlContext.getContext().res;\n      const message = `GraphQL - ${parentType} - ${fieldName}`;\n\n      // Remove secure fields from request body and headers\n      const secureBody = secureReqBody(body);\n\n      const requestId = res.getHeader('requestId');\n\n      // Log trace message\n      const trace = {\n        body: { ...secureBody }\n      };\n      this.logger.info(`requestId: ${requestId}`, {\n        context: message,\n        trace\n      });\n    }\n  }\n}\n```\n\n```text\nnext.hanlde()\n```\n\n```text\nRxJS Observable operators\n```\n\n```text\ntap\n```\n\n```text\nmap\n```\n\n```text\npipe()\n```\n\n```text\nallData\n```\n\n```text\ncontext\n```\n\n```text\nallData\n```\n\n```text\nGqlExecutionContext.create(context).getContext().req\n```\n\n```text\nGqlExecutionContext.create(context).getContext().res\n```\n\n```text\nGuards\n```\n\n========================================\n\nComments:\n- I'm not even able to print anything with this in case of graphql query, however this is working fine with regular controller calls.\n- Thx so far! `allData` contains the requested data you would find inside the data property of the graphql reponse plus all properties that got resolved by typeorm relations (even that ones which aren't present in the graphql request). That's why I called it `allData`. It's not a partial object. `GqlExecutionContext.create(context).getContext()` works for reading `context.body.query` and `context.user`. But it is still not possible to access `graphqlResponse` because it is not part of the context.\n- I have added some more examples to my question and removed unnecessary information.\n- To be honest, I think the response body you are looking for is something that Nest handles under the hood and isn't quite exposed to us without really getting into the internals. I'm trying to read through the source code, but I can't promise much will come out of it\n- I have totally forgot to post the log of `GqlExecutionContext.create(context).getContext()`. I have updated my question with the information.\n- Yeah, I was doing some digging both with my GraphQL code and with the source code, and I'm pretty sure the `GraphQLRespnse` you are looking for is taken care of under the hood and not exposed, but without 100% understanding it I couldn't say.\n- Hello there, This **GqlExecutionContext.create(context).getContext().req** works fine and returns whole request, But **GqlExecutionContext.create(context).getContext().res** returns undefined, Any Solution for it?\n- @AmmarAhmed do you have the `context` set correctly to set up the `req` and `res` in your `GraphqlModule.forRoot&#47;Async`?\n- HI @JayMcDoniel I am setting **context** like this `GraphQLModule.forRoot({ autoSchemaFile: true, context: ({ req }) => ({ req }), }),`. How I can add res there?\n- `context: ({ req, res }) => ({ req, res })`","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":569,"estimatedTokens":3735}}216{"id":"stack-48851140","source":"stackoverflow","questionId":48851140,"title":"How to handle TypeORM entity field unique validation error in NestJS?","tags":["typeorm","nestjs"],"text":"Title: How to handle TypeORM entity field unique validation error in NestJS?\nTags: typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've set a custom unique validator decorator on my TypeORM entity field email. NestJS has dependency injection, but the service is not injected.\n\nThe error is:\n\n```\nTypeError: Cannot read property 'findByEmail' of undefined\n```\n\nAny help on implementing a custom email validator?\n\n`user.entity.ts`:\n\n```\n@Column()\n@Validate(CustomEmail, {\n message: \"Title is too short or long!\"\n})\n@IsEmail()\nemail: string;\n```\n\nMy `CustomEmail` validator is\n\n```\nimport {ValidatorConstraint, ValidatorConstraintInterface, \nValidationArguments} from \"class-validator\";\nimport {UserService} from \"./user.service\";\n\n@ValidatorConstraint({ name: \"customText\", async: true })\nexport class CustomEmail implements ValidatorConstraintInterface {\n\n constructor(private userService: UserService) {}\n async validate(text: string, args: ValidationArguments) {\n\n const user = await this.userService.findByEmail(text);\n return !user; \n }\n\n defaultMessage(args: ValidationArguments) { \n return \"Text ($value) is too short or too long!\";\n }\n}\n```\n\nI know I could set `unique` in the `Column` options\n\n```\n@Column({\n unique: true\n})\n```\n\nbut this throws a mysql error and the `ExceptionsHandler` that crashes my app, so I can't handle it myself...\n\nThankx!\n\n========================================\n\nTop Answer:\nI can propose 2 different approaches here, the first one catches the constraint violation error locally without additional request, and the second one uses a global error filter, catching such errors in the entire application. I personally use the latter.\n\n### Local no-db request solution\n\nNo need to make additional database request. You can catch the error violating the unique constraint and throw any `HttpException` you want to the client. In `users.service.ts`:\n\n```\npublic create(newUser: Partial): Promise {\n return this.usersRepository.save(newUser).catch((e) => {\n if (/(email)[\\s\\S]+(already exists)/.test(e.detail)) {\n throw new BadRequestException(\n 'Account with this email already exists.',\n );\n }\n return e;\n });\n }\n```\n\nWhich will return:\n\nhttps://i.sstatic.net/KntnY.png\n\n### Global error filter solution\n\nOr even create a global QueryErrorFilter:\n\n```\n@Catch(QueryFailedError)\nexport class QueryErrorFilter extends BaseExceptionFilter {\n public catch(exception: any, host: ArgumentsHost): any {\n const detail = exception.detail;\n if (typeof detail === 'string' && detail.includes('already exists')) {\n const messageStart = exception.table.split('_').join(' ') + ' with';\n throw new BadRequestException(\n exception.detail.replace('Key', messageStart),\n );\n }\n return super.catch(exception, host);\n }\n}\n```\n\nThen in `main.ts`:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(/**/);\n /* ... */\n const { httpAdapter } = app.get(HttpAdapterHost);\n app.useGlobalFilters(new QueryErrorFilter(httpAdapter));\n /* ... */\n await app.listen(3000);\n}\nbootstrap();\n```\n\nThis will give generic `$table entity with ($field)=($value) already exists.` error message. Example:\n\nhttps://i.sstatic.net/7TzX2.png\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read property 'findByEmail' of undefined\n```\n\n```text\n@Column()\n@Validate(CustomEmail, {\n    message: \"Title is too short or long!\"\n})\n@IsEmail()\nemail: string;\n```\n\n```text\nimport {ValidatorConstraint, ValidatorConstraintInterface, \nValidationArguments} from \"class-validator\";\nimport {UserService} from \"./user.service\";\n\n@ValidatorConstraint({ name: \"customText\", async: true })\nexport class CustomEmail implements ValidatorConstraintInterface {\n\n  constructor(private userService: UserService) {}\n  async validate(text: string, args: ValidationArguments) {\n\n    const user = await this.userService.findByEmail(text);\n    return !user; \n  }\n\n  defaultMessage(args: ValidationArguments) { \n    return \"Text ($value) is too short or too long!\";\n  }\n}\n```\n\n```text\n@Column({\n  unique: true\n})\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nCustomEmail\n```\n\n```text\nunique\n```\n\n```text\nColumn\n```\n\n```text\nExceptionsHandler\n```\n\n```js\npublic create(newUser: Partial<UserEntity>): Promise<UserEntity> {\n    return this.usersRepository.save(newUser).catch((e) => {\n      if (/(email)[\\s\\S]+(already exists)/.test(e.detail)) {\n        throw new BadRequestException(\n          'Account with this email already exists.',\n        );\n      }\n      return e;\n    });\n  }\n```\n\n```js\n@Catch(QueryFailedError)\nexport class QueryErrorFilter extends BaseExceptionFilter {\n  public catch(exception: any, host: ArgumentsHost): any {\n    const detail = exception.detail;\n    if (typeof detail === 'string' && detail.includes('already exists')) {\n      const messageStart = exception.table.split('_').join(' ') + ' with';\n      throw new BadRequestException(\n        exception.detail.replace('Key', messageStart),\n      );\n    }\n    return super.catch(exception, host);\n  }\n}\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(/**/);\n  /* ... */\n  const { httpAdapter } = app.get(HttpAdapterHost);\n  app.useGlobalFilters(new QueryErrorFilter(httpAdapter));\n  /* ... */\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nHttpException\n```\n\n```text\nusers.service.ts\n```\n\n```text\nmain.ts\n```\n\n```text\n$table entity with ($field)=($value) already exists.\n```\n\n```text\n@Entity()\nexport class MyEntity extends BaseEntity{ \n @Column({unique:true}) name:string; \n}\n\nexport abstract class BaseDataService<T> {\n\n  constructor(protected readonly repo: Repository<T>) {}\n\n  private  async isUnique(t: any) {\n    const uniqueColumns = this.repo.metadata.uniques.map(\n      (e) => e.givenColumnNames[0]\n    );\n\n    for (const u of uniqueColumns) {\n      const count = await this.repo.count({ where: { [u]: ILike(t[u]) } });\n      if (count > 0) {\n        throw new UnprocessableEntityException(`${u} must be unique!`);\n      }\n    }\n  }\n\n  async save(body: DeepPartial<T>) {\n    await this.isUnique(body);\n    try {\n      return await this.repo.save(body);\n    } catch (err) {\n      throw new UnprocessableEntityException(err.message);\n    }\n  }\n\n\n\n  async update(id: number, updated: QueryDeepPartialEntity<T>) {\n    await this.isUnique(updated)\n    try {\n      return await this.repo.update(id, updated);\n    } catch (err) {\n      throw new UnprocessableEntityException(err.message);\n    }\n  }\n}\n```\n\n```js\nimport {\n  Catch,\n  ArgumentsHost,\n  BadRequestException,\n  HttpException,\n} from '@nestjs/common';\nimport { BaseExceptionFilter } from '@nestjs/core';\nimport { QueryFailedError } from 'typeorm';\n\ntype ExceptionType = { detail: string; table: string };\n\n@Catch(QueryFailedError)\nexport class QueryErrorFilter extends BaseExceptionFilter<\n  HttpException | ExceptionType\n> {\n  public catch(exception: ExceptionType, host: ArgumentsHost): void {\n    const { detail = null } = exception || {};\n\n    if (\n      !detail ||\n      typeof detail !== 'string' ||\n      // deepcode ignore AttrAccessOnNull: <False positive>\n      !detail.includes('already exists')\n    ) {\n      return super.catch(exception, host);\n    } // else\n\n    /**\n     * this regex transform the message `(phone)=(123)` to a more intuitive `with phone: \"123\"` one,\n     * the regex is long to prevent mistakes if the value itself is ()=(), for example, (phone)=(()=())\n     */\n\n    const extractMessageRegex =\n      /\\((.*?)(?:(?:\\)=\\()(?!.*(\\))(?!.*\\))=\\()(.*?)\\)(?!.*\\)))(?!.*(?:\\)=\\()(?!.*\\)=\\()((.*?)\\))(?!.*\\)))/;\n\n    const messageStart = `${exception.table.split('_').join(' ')} with`;\n\n    /** prevent Regex DoS, doesn't treat messages longer than 200 characters */\n    const exceptionDetail =\n      exception.detail.length <= 200\n        ? exception.detail.replace(extractMessageRegex, 'with $1: \"$3\"')\n        : exception.detail;\n\n    super.catch(\n      new BadRequestException(exceptionDetail.replace('Key', messageStart)),\n      host,\n    );\n  }\n}\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(/**/);\n  /* ... */\n  const { httpAdapter } = app.get(HttpAdapterHost);\n  app.useGlobalFilters(new QueryErrorFilter(httpAdapter));\n  /* ... */\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- You cannot inject dependencies inside `ValidatorConstraint` class. It's not a part of the Nest container.\n- For custom validator implementation check this answer.\n- You can perform that check using pipes or a middleware(not recommended if you intend to reuse app wide) instead of the user service to keep to S(Single Responsibility Principle) in the SOLID design principle.\n- I think doing this at a service level is the only way to achieve this. If you use pipes (custom validators) you'll reach a point where if you want to `PATCH` an existing record with a value that already exists, there's no way to check whether that value belongs to the record itself (no error) or another record (throws error). In Ruby on Rails it's literally one line, but this is NestJS so it takes a lot longer.\n- Seems like a good solution imho, especially the global filter. Got it working using exception = new BadRequestException(...) instead of a throw, throwing it right away did cause a loss of every single exceptions returned to the client.\n- interesting solution, but in my case makes this request `SELECT COUNT(1) AS \"cnt\" FROM \"users\" \"User\"` and obviously gets all count of users, not sure why","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":363,"estimatedTokens":2364}}217{"id":"stack-69419092","source":"stackoverflow","questionId":69419092,"title":"process.env's are undefined - NestJS","tags":["node.js","typescript","environment-variables","nestjs"],"text":"Title: process.env's are undefined - NestJS\nTags: node.js, typescript, environment-variables, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've decided to write here because I've ran out of ideas. I have a NestJS app in which I use env's - nothing unusual. But something strange happens when I want to use them. I also have my own parser of these values which returns them in a convenient object - that's the first file:\n\n**env.ts**\n\n```\nconst parseStringEnv = (name: string) => {\n const value: string = process.env[name];\n\n if (!value) {\n throw new Error(`Invalid env ${name}`);\n }\n\n return value;\n};\n\nconst parseIntEnv = (name: string) => {\n const value: string = process.env[name];\n\n const int: number = parseInt(value);\n\n if (isNaN(int)) {\n throw new Error(`Invalid env ${name}`);\n }\n\n return int;\n};\n\nconst parseBoolEnv = (name: string) => {\n const value: string = process.env[name];\n\n if (value === \"false\") {\n return false;\n }\n\n if (value === \"true\") {\n return true;\n }\n\n throw new Error(`Invalid env ${name}`);\n};\n\nconst parseMongoString = (): string => {\n const host = parseStringEnv(\"DATABASE_HOST\");\n const port = parseStringEnv(\"DATABASE_PORT\");\n const user = parseStringEnv(\"DATABASE_USER\");\n const pwd = parseStringEnv(\"DATABASE_PWD\");\n const dbname = parseStringEnv(\"DATABASE_NAME\");\n\n return `mongodb://${user}:${pwd}@${host}:${port}/${dbname}?authSource=admin&ssl=false`;\n};\n\nexport const env = {\n JWT_SECRET: parseStringEnv(\"JWT_SECRET\"),\n PORT_BACKEND: parseIntEnv(\"PORT_BACKEND\"),\n CLIENT_HOST: parseStringEnv(\"CLIENT_HOST\"),\n ENABLE_CORS: parseBoolEnv(\"ENABLE_CORS\"),\n MONGO_URI: parseMongoString(),\n};\n\nexport type Env = typeof env;\n```\n\nI want to use it for setting port on which the app runs on and also the connection parameters for Mongoose:\n\n**In main.ts:**\n\n```\n\nawait app.listen(env.PORT_BACKEND || 8080);\n\n```\n\nNow, the magic starts here - the app starts just fine when ONLY `ConfigModule` is being imported. It will also start without `ConfigModule` and with `require('doting').config()` added. When I add `MongooseModule`, the app crashes because it can't parse env - and the best thing is that exception thrown has nothing to do with env's that are used to create `MONGO_URI`!! I'm getting \"`Invalid env JWT_SECRET`\" from my parser.\n\n**In app.module.ts**\n\n```\nimport { Module } from \"@nestjs/common\";\nimport { ConfigModule } from \"@nestjs/config\";\nimport { MongooseModule } from \"@nestjs/mongoose\";\n\nimport { AppController } from \"./app.controller\";\nimport { env } from \"./common/env\";\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n }),\n MongooseModule.forRoot(env.MONGO_URI), //WTF?\n ],\n controllers: [AppController],\n})\nexport class AppModule {}\n```\n\nI've honestly just ran out of ideas what could be wrong. The parser worked just fine in my last project (but I haven't used Mongoose so maybe that's what causes issues). Below is my .env file template.\n\n```\nJWT_SECRET=\nENABLE_CORS=\nPORT_BACKEND=\nDATABASE_HOST=\nDATABASE_PORT=\nDATABASE_USER=\nDATABASE_PWD\nDATABASE_NAME=\nCLIENT_HOST=\n```\n\nThanks for everyone who has spent their time trying to help me ;)\n\n========================================\n\nTop Answer:\nBy using registerAsync of JWT module and read process.env inside useFactory method worked for me\n\n```\n@Module({\n imports: [\n JwtModule.registerAsync({\n useFactory: () => ({\n secret: process.env.JWT_SECRET_KEY,\n signOptions: { expiresIn: 3600 },\n }),\n })\n ],\n controllers: [AppController],\n})\n```\n\n========================================\n\nCode:\n```text\nconst parseStringEnv = (name: string) => {\n  const value: string = process.env[name];\n\n  if (!value) {\n    throw new Error(`Invalid env ${name}`);\n  }\n\n  return value;\n};\n\nconst parseIntEnv = (name: string) => {\n  const value: string = process.env[name];\n\n  const int: number = parseInt(value);\n\n  if (isNaN(int)) {\n    throw new Error(`Invalid env ${name}`);\n  }\n\n  return int;\n};\n\nconst parseBoolEnv = (name: string) => {\n  const value: string = process.env[name];\n\n  if (value === \"false\") {\n    return false;\n  }\n\n  if (value === \"true\") {\n    return true;\n  }\n\n  throw new Error(`Invalid env ${name}`);\n};\n\nconst parseMongoString = (): string => {\n  const host = parseStringEnv(\"DATABASE_HOST\");\n  const port = parseStringEnv(\"DATABASE_PORT\");\n  const user = parseStringEnv(\"DATABASE_USER\");\n  const pwd = parseStringEnv(\"DATABASE_PWD\");\n  const dbname = parseStringEnv(\"DATABASE_NAME\");\n\n  return `mongodb://${user}:${pwd}@${host}:${port}/${dbname}?authSource=admin&ssl=false`;\n};\n\nexport const env = {\n  JWT_SECRET: parseStringEnv(\"JWT_SECRET\"),\n  PORT_BACKEND: parseIntEnv(\"PORT_BACKEND\"),\n  CLIENT_HOST: parseStringEnv(\"CLIENT_HOST\"),\n  ENABLE_CORS: parseBoolEnv(\"ENABLE_CORS\"),\n  MONGO_URI: parseMongoString(),\n};\n\nexport type Env = typeof env;\n```\n\n```text\n<rest of the code>\nawait app.listen(env.PORT_BACKEND || 8080);\n<rest of the code>\n```\n\n```text\nimport { Module } from \"@nestjs/common\";\nimport { ConfigModule } from \"@nestjs/config\";\nimport { MongooseModule } from \"@nestjs/mongoose\";\n\nimport { AppController } from \"./app.controller\";\nimport { env } from \"./common/env\";\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }),\n    MongooseModule.forRoot(env.MONGO_URI), //WTF?\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```text\nJWT_SECRET=\nENABLE_CORS=\nPORT_BACKEND=\nDATABASE_HOST=\nDATABASE_PORT=\nDATABASE_USER=\nDATABASE_PWD\nDATABASE_NAME=\nCLIENT_HOST=\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigModule\n```\n\n```text\nrequire('doting').config()\n```\n\n```text\nMongooseModule\n```\n\n```text\nMONGO_URI\n```\n\n```text\nInvalid env JWT_SECRET\n```\n\n```text\n// env.ts\nexport default () => ({\n  // Add your own properties here however you'd like\n  port: parseInt(process.env.PORT, 10) || 3000,\n  database: {\n    host: process.env.DATABASE_HOST,\n    port: parseInt(process.env.DATABASE_PORT, 10) || 5432\n  }\n});\n```\n\n```text\n// app.module.ts\nimport configuration from './common/env';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      load: [configuration],\n    }),\n    //  \n    MongooseModule.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        uri: configService.get<string>('MONGO_URI'),\n      }),\n      inject: [ConfigService],\n    });\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nenv.ts\n```\n\n```text\n.env\n```\n\n```text\nrequire('dotenv').config()\n```\n\n```text\nConfigModule.forRoot\n```\n\n```text\nenv.ts\n```\n\n```text\n.env\n```\n\n```text\nenv.ts\n```\n\n```text\nrequire('dotenv').config()\n```\n\n```text\nenv.ts\n```\n\n```text\n.env\n```\n\n```text\nimport { Module } from \"@nestjs/common\";\nimport { ConfigModule } from \"@nestjs/config\";\nimport { MongooseModule } from \"@nestjs/mongoose\";\n\nimport { AppController } from \"./app.controller\";\nimport { env } from \"./common/env\"; // call process.env.xxx here > undefined\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }), // process.env.xxx must be called after this line\n    MongooseModule.forRoot(env.MONGO_URI),\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Module } from \"@nestjs/common\";\nimport { ConfigModule } from \"@nestjs/config\";\n// should place this at very first line\nconst envModule = ConfigModule.forRoot({\n   isGlobal: true,\n})\n\nimport { MongooseModule } from \"@nestjs/mongoose\";\n\nimport { AppController } from \"./app.controller\";\nimport { env } from \"./common/env\";\n\n@Module({\n  imports: [\n    envModule,\n    MongooseModule.forRoot(env.MONGO_URI),\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n  imports: [\n    JwtModule.registerAsync({\n      useFactory: () => ({\n        secret: process.env.JWT_SECRET_KEY,\n        signOptions: { expiresIn: 3600 },\n      }),\n    })\n  ],\n  controllers: [AppController],\n})\n```\n\n========================================\n\nComments:\n- I'd say don't use `process.env` directly like this. Instead, delegate the loading/parser/validation to some module like `@nestjs&#47;config` ( this: docs.nestjs.com/techniques/configuration#configuration) or `nestjs-config`. It would be pretty easy to load any env. var with them\n- Yeah, I've seen it but I wanted to use my own parser. Anyway, I'll give this a try since mine is not working. Thanks for comment!\n- Did you try to add the envFilePath in the ConfigModule.forRoot configuration ?\n- I've used ConfigService like you recommended and it works like a charm ;) Thank you very much!!\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- thank you. your solution helped me, without any ConfigModule (isGlobal: true) etc. I even consoled secret from useFactore, and it is really works right\n- This one did work for me as well, and would love to know the reason why we need to create a custom provider instead?\n- It's been years and this is still very much useful","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":401,"estimatedTokens":2265}}218{"id":"stack-58550958","source":"stackoverflow","questionId":58550958,"title":"Get list of requested keys in NestJS/GraphQL request","tags":["graphql","nestjs"],"text":"Title: Get list of requested keys in NestJS/GraphQL request\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am just fiddling around trying to understand, thus my types are not exact.\n\n```\n@Resolver()\nexport class ProductsResolver {\n @Query(() => [Product])\n async products() {\n return [{\n id: 55,\n name: 'Moonshine',\n storeSupplies: {\n London: 25,\n Berlin: 0,\n Monaco: 3,\n },\n }];\n }\n}\n```\n\nIf I request data with query bellow\n\n```\n{\n products{\n id,\n name,\n }\n}\n```\n\nI want `async carriers()` to receive `['id', 'name']`. I want to skip getting of `storeSupplies` as it might be an expensive SQL call.\n\nI am new to GraphQL, I might have missed something obvious, or even whole patterns. Thanks in advance.\n\n========================================\n\nTop Answer:\nBasically you can seperate `StoreSupplies` queries, to make sure not to get them when query on the products.\n\nYou can also get the requested keys in your resolver, then query based on them. In order to do that, you can define a parameter decorator like this:\n\n```\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Info = createParamDecorator(\n (data, [root, args, ctx, info]) => info,\n);\n```\n\nThen use it in your resolver like this:\n\n```\n@UseGuards(GqlAuthGuard)\n @Query(returns => UserType)\n async getMe(@CurrentUser() user: User, @Info() info): Promise {\n console.log(\n info.fieldNodes[0].selectionSet.selections.map(item => item.name.value),\n );\n return user;\n }\n```\n\nFor example, when you run this query\n\n```\n{\n getMe{\n id\n email\n roles\n }\n}\n```\n\nThe `console.log` output is:\n\n```\n[ 'id', 'email', 'roles' ]\n```\n\n========================================\n\nCode:\n```js\n@Resolver()\nexport class ProductsResolver {\n    @Query(() => [Product])\n    async products() {\n        return [{\n            id: 55,\n            name: 'Moonshine',\n            storeSupplies: {\n                London: 25,\n                Berlin: 0,\n                Monaco: 3,\n            },\n        }];\n    }\n}\n```\n\n```query\n{\n    products{\n      id,\n      name,\n    }\n}\n```\n\n```text\nasync carriers()\n```\n\n```text\n['id', 'name']\n```\n\n```text\nstoreSupplies\n```\n\n```js\n@Resolver()\nexport class ProductsResolver {\n    @Query(() => [Product])\n    async products(\n    @Info() info\n    ) {\n        // Method 1 thanks to @pooya-haratian.\n        // Update: use this method; read below article to understand why.\n        let keys = info.fieldNodes[0].selectionSet.selections.map(item => item.name.value);\n        // Method 2 by me, but I'm not sure which method is best.\n        // Update: don't use this; read below article to understand why.\n        let keys = info.operation.selectionSet.selections[0].selectionSet.selections.map(field => field.name.value);\n        return keys;\n    }\n}\n```\n\n```text\nfieldNodes[0]\n```\n\n```text\n@Info\n```\n\n```js\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Info = createParamDecorator(\n  (data, [root, args, ctx, info]) => info,\n);\n```\n\n```js\n@UseGuards(GqlAuthGuard)\n  @Query(returns => UserType)\n  async getMe(@CurrentUser() user: User, @Info() info): Promise<User> {\n    console.log(\n      info.fieldNodes[0].selectionSet.selections.map(item => item.name.value),\n    );\n    return user;\n  }\n```\n\n```text\n{\n  getMe{\n    id\n    email\n    roles\n  }\n}\n```\n\n```text\n[ 'id', 'email', 'roles' ]\n```\n\n```text\nStoreSupplies\n```\n\n```text\nconsole.log\n```\n\n```text\n@Query(() => [PostObject])\nasync posts(\n  @FieldMap() fieldMap: FieldMap,\n) {\n  console.log(fieldMap);\n}\n```\n\n```text\n{\n  \"posts\": {\n    \"id\": {},\n    \"title\": {},\n    \"body\": {},\n    \"author\": {\n      \"id\": {},\n      \"username\": {},\n      \"firstName\": {},\n      \"lastName\": {}\n    },\n    \"comments\": {\n      \"id\": {},\n      \"body\": {},\n      \"author\": {\n        \"id\": {},\n        \"username\": {},\n        \"firstName\": {},\n        \"lastName\": {}\n      }\n    }\n  }\n}\n```\n\n```text\n{\n  post { # post: [Post]\n    id\n    author: {\n      id\n      firstName\n      lastName\n    }\n  }\n}\n```\n\n```text\nimport { fieldsList, fieldsMap } from 'graphql-fields-list';\nimport { Query, Info } from '@nestjs/graphql';\n\n@Query(() => [Post])\nasync post(\n  @Info() info,\n) {\n  console.log(fieldsList(info));       // [ 'id', 'firstName', 'lastName' ]\n  console.log(fieldsMap(info));        // { id: false, firstName: false, lastName: false }\n  console.log(fieldsProjection(info)); // { id: 1, firstName: 1, lastName: 1 };\n}\n```\n\n```text\ninfo\n```\n\n```js\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nconst getNodeData = (node) => {\n  const { selectionSet } = node || {};\n\n  let fields = null;\n  if (!!selectionSet) {\n    fields = {};\n    selectionSet.selections.forEach((selection) => {\n      const name = selection.name.value;\n      fields[name] = getNodeData(selection);\n    });\n  }\n\n  return fields;\n};\n\nexport const FieldMap = createParamDecorator((_, ctx: ExecutionContext) => {\n  const gqlCtx = GqlExecutionContext.create(ctx);\n  const info = gqlCtx.getInfo();\n\n  const node = info.fieldNodes[0];\n  return getNodeData(node);\n});\n```\n\n```js\n@Resolver()\nexport class ExampleResolver {\n  @Query()\n  example(@FieldMap() fieldMap) {\n    console.log(fieldMap);\n  }\n}\n```\n\n```text\nexample {\n  id\n  name\n  description\n  child1 {\n    id\n    name\n  }\n  child2 {\n    id\n    name\n    value\n  }\n}\n```\n\n```text\n{\n  id: null,\n  name: null,\n  description: null,\n  child1: { id: null, name: null },\n  child2: { id: null, name: null, value: null }\n}\n```\n\n```text\nexport const RequestedFields = createParamDecorator((data: undefined | string | string[], ctx: ExecutionContext) => {\n  const info = GqlExecutionContext.create(ctx).getInfo<GraphQLResolveInfo>()\n  const parsedInfo = parse(info) as ResolveTree\n  const { returnType } = info\n  const simplifiedInfo = simplify(parsedInfo, returnType)\n  if (typeof data === 'undefined') return Object.keys(simplifiedInfo.fields)\n\n  const result: string[] = []\n\n  const getFields = (node: ResolveTree) => {\n    Object.keys(node.fieldsByTypeName).forEach((key) => {\n      const type = node.fieldsByTypeName[key]\n      // check if the key is the requested field\n      if (key === data) {\n        Object.keys(type).forEach((field) => {\n          result.push(type[field].name)\n        })\n        return\n      }\n      // check if the key is a nested field\n      Object.keys(type).forEach((field) => {\n        getFields(type[field])\n      })\n    })\n  }\n  getFields(simplifiedInfo)\n  return result\n})\n```\n\n```text\n@Query(() => [Product])\n    async products(\n @RequiredFields() fields : string[]\n) {\n       console.log(fields) // return ['id','name','storeSupplies']\n        return [{\n            id: 55,\n            name: 'Moonshine',\n            storeSupplies: {\n                London: 25,\n                Berlin: 0,\n                Monaco: 3,\n            },\n        }];\n    }\n```\n\n```text\n@RequiredFields('Product') fields : string[]\n```\n\n========================================\n\nComments:\n- Why should `fieldNodes` be used instead of `operation.selectionSet.selections`? Is this the best way of doing so? I'm attempting to do the same, but only to use `projections` for mongodb's native driver to optimize requests.\n- @yaharga actually I'm not sure about the best way, but I guess for most cases, like the question above, we can simply use `@ResolvePropert`. I didn't notice that till now :D\n- I was attempting to get the keys in order to use them with the MongoDB `projection` parameter in the `find()` function. `@ResolveProperty` would be useless there, right?\n- Yeah I agree with you. @yaharga\n- My question was a little off topic, but it turns out I was looking for @CurrentUser()\n- To test which is better try some nested queries to see what gives correct list of fields back.\n- Added reference to the article. Hopefully it helps better clear things up.\n- this map only work with one level of selection set. If the schema comes with a nested selections sets possibilities it won't work\n- this code snipe looks like working for nest objects const keys = []; function getKeys(selections) { selections.map((item) => { if (keys.indexOf(item.name.value)) { keys.push(item.name.value); } if (item?.selectionSet) { getKeys(item.selectionSet.selections); } }); } const infoKeys = (info) => { keys.splice(0, keys.length); getKeys(info.fieldNodes[0].selectionSet.selections); return keys; }; export default infoKeys;\n- Do not deconstruct an object that could be `null` or `undefined`. Either use `const { } = obj || {}`, or simply use assignment. Other than that, this looks good :)","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":392,"estimatedTokens":2133}}219{"id":"stack-62700524","source":"stackoverflow","questionId":62700524,"title":"Nest.js only accept fields that are specified in a DTO","tags":["typescript","nestjs","dto","class-validator"],"text":"Title: Nest.js only accept fields that are specified in a DTO\nTags: typescript, nestjs, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm currently playing around with Nest.js and have a simple app with a route to register accounts. I created a DTO with a few fields as well as a mongodb schema.\nThere is exactly one field in the mongodb schema I don't want to let a user modify on creation (=privilege), so I didn't specify that in the DTO.\n\nHowever, if a user makes a request with the privilege property in the body, it'll still get saved to the DTO and then in the schema.\n\nIs there a way to \"cut off\" any data from the body that doesn't match the DTO? I'm certain it did tell me once that there was a field it does not recognize, but it doesn't seem to work anymore. I tried to find a class validator or something, but couldn't find anything that fits and I don't really want to check every property myself...\n\nThanks in advance!\n\nfrom account.service.ts\n\n```\nasync register(body: RegisterAccountDto) {\n return new_account.save();\n }\n```\n\nfrom account.controller.ts\n\n```\n@ApiOperation({ summary: 'Register user', description: 'Register a new account' })\n @ApiConsumes('x-www-form-urlencoded')\n @ApiBody({ type: [RegisterAccountDto] })\n @Post('register')\n async register(@Body() body: RegisterAccountDto) {\n return this.accountService.register(body);\n }\n```\n\nfrom account.schema.ts\n\n```\n@Prop({ default: Privilege.USER })\n privilege: Privilege;\n```\n\n========================================\n\nCode:\n```text\nasync register(body: RegisterAccountDto) {\n    return new_account.save();\n  }\n```\n\n```text\n@ApiOperation({ summary: 'Register user', description: 'Register a new account' })\n  @ApiConsumes('x-www-form-urlencoded')\n  @ApiBody({ type: [RegisterAccountDto] })\n  @Post('register')\n  async register(@Body() body: RegisterAccountDto) {\n    return this.accountService.register(body);\n  }\n```\n\n```text\n@Prop({ default: Privilege.USER })\n  privilege: Privilege;\n```\n\n```text\nimport { ValidationPipe } from '@nestjs/common';\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({\n    whitelist: true\n  }));\n```\n\n========================================\n\nComments:\n- Ah, the whitelist option did the trick! I had the validation pipe embedded, but without any configuration. Thanks a bunch!\n- @fazlu Is there any way we can do it only for a particular Module and not apply `whitelist` globally?\n- @ChiragB use this link to use the UsePipe decorator on a method level in the controller of a module, you will be able to use whitelist for a specific controller method of a specific module by following this: docs.nestjs.com/techniques/validation#transform-payload-obje&zwnj;&#8203;cts","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":672}}220{"id":"stack-58918644","source":"stackoverflow","questionId":58918644,"title":"NestJS - Cannot inject a service into a subscriber","tags":["node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS - Cannot inject a service into a subscriber\nTags: node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a subscriber for NestJS to listen to any create, update or delete events (TypeORM). When one of these events is fired, I'd like to use an injected service in order to create a new revision entry.\n\nHowever, it seems I cannot get the dependency loaded inside of the subscriber and the service comes back as being undefined\n\nKey files:\n\n- EntityModificationSubscriber (Subscriber)\n\n- RevisionEntity (Entity)\n\napp.module.ts\n\n```\n@Module({\n imports: [\n HttpModule,\n TypeOrmModule.forRoot({\n type: (process.env.DB_TYPE as any) || 'postgres',\n host: process.env.DB_HOST || '127.0.0.1',\n port: (process.env.DB_PORT as any) || 5432,\n username: process.env.DB_USER || 'root',\n password: process.env.DB_PASS || '',\n database: process.env.DB_NAME || 'test',\n entities: [join(__dirname, '**/**.entity{.ts,.js}')],\n synchronize: true,\n logging: 'all',\n logger: 'advanced-console',\n subscribers: [EntityModificationSubscriber],\n }),\n TypeOrmModule.forFeature([\n RevisionEntity,\n ]),\n TerminusModule.forRootAsync({\n // Inject the TypeOrmHealthIndicator provided by nestjs/terminus\n inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],\n useFactory: (db, msg) => getTerminusOptions(db, msg),\n }),\n GraphQLModule.forRoot({\n debug: true,\n playground: true,\n typePaths: ['./**/*.graphql'],\n }),\n ],\n controllers: [AppController],\n providers: [\n RevisionService,\n EntityModificationSubscriber,\n ],\n})\n```\n\nentity_modification_subscriber.ts\n\n```\nimport {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';\nimport {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';\nimport {RevisionService} from '../services/revisions.service';\nimport {Injectable} from '@nestjs/common';\n\n@Injectable()\n@EventSubscriber()\nexport class EntityModificationSubscriber implements EntitySubscriberInterface {\n\n constructor(private revisionService: RevisionService) {\n }\n\n // tslint:disable-next-line:no-empty\n afterInsert(event: InsertEvent): Promise | void {\n const revision = new RevisionEntity();\n\n revision.action = RevisonEntityStatus.Created;\n }\n\n afterUpdate(event: UpdateEvent): Promise | void {\n }\n\n // tslint:disable-next-line:no-empty\n afterRemove(event: RemoveEvent) {\n // this.revisionService.createRevisionEntry(revision);\n }\n}\n```\n\n========================================\n\nTop Answer:\nHi the problem is that If you want to preform database actions you would have to use: \n\n```\nevent.manager\n```\n\nand Don't use getEntityManager() or getRepository() or any other global function.\nThis is due to a transaction. Save is running in a transaction and your data is saved in a transaction which is not committed yet. But global functions you use are running out of transaction.\n\nmore about issue here:\n\nhttps://github.com/typeorm/typeorm/issues/681\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n      HttpModule,\n      TypeOrmModule.forRoot({\n          type: (process.env.DB_TYPE as any) || 'postgres',\n          host: process.env.DB_HOST || '127.0.0.1',\n          port: (process.env.DB_PORT as any) || 5432,\n          username: process.env.DB_USER || 'root',\n          password: process.env.DB_PASS || '',\n          database: process.env.DB_NAME || 'test',\n          entities: [join(__dirname, '**/**.entity{.ts,.js}')],\n          synchronize: true,\n          logging: 'all',\n          logger: 'advanced-console',\n          subscribers: [EntityModificationSubscriber],\n      }),\n      TypeOrmModule.forFeature([\n          RevisionEntity,\n      ]),\n      TerminusModule.forRootAsync({\n          // Inject the TypeOrmHealthIndicator provided by nestjs/terminus\n          inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],\n          useFactory: (db, msg) => getTerminusOptions(db, msg),\n      }),\n      GraphQLModule.forRoot({\n          debug: true,\n          playground: true,\n          typePaths: ['./**/*.graphql'],\n      }),\n  ],\n  controllers: [AppController],\n  providers: [\n      RevisionService,\n      EntityModificationSubscriber,\n  ],\n})\n```\n\n```text\nimport {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';\nimport {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';\nimport {RevisionService} from '../services/revisions.service';\nimport {Injectable} from '@nestjs/common';\n\n@Injectable()\n@EventSubscriber()\nexport class EntityModificationSubscriber implements EntitySubscriberInterface {\n\n    constructor(private revisionService: RevisionService) {\n    }\n\n    // tslint:disable-next-line:no-empty\n    afterInsert(event: InsertEvent<any>): Promise<any> | void {\n        const revision = new RevisionEntity();\n\n        revision.action = RevisonEntityStatus.Created;\n    }\n\n    afterUpdate(event: UpdateEvent<any>): Promise<any> | void {\n    }\n\n    // tslint:disable-next-line:no-empty\n    afterRemove(event: RemoveEvent<any>) {\n        // this.revisionService.createRevisionEntry(revision);\n    }\n}\n```\n\n```js\nimport { EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent, Connection } from 'typeorm';\n    import { RevisionEntity, RevisonEntityStatus } from '../entities/revison.entity';\n    import { RevisionService } from '../services/revisions.service';\n    import { Injectable } from '@nestjs/common';\n\n    @Injectable()\n    @EventSubscriber()\n    export class EntityModificationSubscriber implements EntitySubscriberInterface {\n\n        constructor(private readonly connection: Connection, private readonly revisionService: RevisionService) {\n            connection.subscribers.push(this); // <---- THIS \n        }\n\n        // tslint:disable-next-line:no-empty\n        afterInsert(event: InsertEvent<any>): Promise<any> | void {\n            const revision = new RevisionEntity();\n\n            revision.action = RevisonEntityStatus.Created;\n\n            //this.revisionService <- should be working!\n        }\n\n        afterUpdate(event: UpdateEvent<any>): Promise<any> | void {\n        }\n\n        // tslint:disable-next-line:no-empty\n        afterRemove(event: RemoveEvent<any>) {\n            // this.revisionService.createRevisionEntry(revision);\n        }\n    }\n```\n\n```text\nsubscribers: [EntityModificationSubscriber],\n```\n\n```text\nevent.manager\n```\n\n```text\n@Module({\n  imports: [CustomerModule, TypeOrmModule.forFeature([Cart, Customer, Product])],\n  controllers: [CartController],\n  providers: [CartService, CustomerCartSubscriber],\n  exports: [CartService]\n})\n```\n\n```text\n@EventSubscriber()\nexport class CustomerCartSubscriber implements EntitySubscriberInterface<Customer> {\n  constructor(\n    @Inject(CartService) public readonly cartService: CartService,\n    @Inject(DataSource) dataSource: DataSource\n  ) {\n    dataSource.subscribers.push(this);\n  }\n\n  listenTo() {\n    return Customer;\n  }\n\n  async beforeInsert(event: InsertEvent<Customer>) {\n    await this.cartService.createCart(event.entity);\n  }\n}\n```\n\n========================================\n\nComments:\n- Do you get any errors with this, or is the service just undefined?\n- @JayMcDoniel The service just returns as undefined\n- @JPanda did you manage to fix it? I am having the same problem\n- For me, it seems to fail, because Connection cannot be injected.\n- I also had to register the subscriber as a provider as mentioned here: github.com/nestjs/typeorm/pull/27\n- thank you very much! you saved my architecture :) guys, if it doesn't work, check if you added this class to import in your nest module\n- At the moment, Connection and InjectConnection are deprecated. I don't know which solution should be correct right now.. EDIT: New solution => docs.nestjs.com/techniques/database#subscribers\n- @etienne-de-martel Thank you, I donโ€™t give a lot of answers, so Iโ€™m not used to it. I'll correct it.\n- The important part for me here, was that I was passing the `subscribers` field into my ormconfig, and you have to remove that. Then you can register it manually like in the constructor here. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":258,"estimatedTokens":2028}}221{"id":"stack-59376717","source":"stackoverflow","questionId":59376717,"title":"Global Headers for all Controllers (nestJs swagger)","tags":["swagger","nestjs"],"text":"Title: Global Headers for all Controllers (nestJs swagger)\nTags: swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there a way to globally add required headers to all endpoints / controllers in NestJS?\n\nThere is a controller bound decorator `@ApiHeader`. Is there a way to apply this to all endpoints?\n\n========================================\n\nTop Answer:\nYou can use `DocumentBuilder.addGlobalParameters` method.\n\nUnfortunately, it's not described in the documentation, but here is my example:\n\n\r\n\r\n\n```\nSwaggerModule.setup(\n 'docs',\n application, // your NestJS application created by NestFactory.create\n SwaggerModule.createDocument(\n application,\n new DocumentBuilder()\n .setTitle('My application')\n .addGlobalParameters({\n in: 'header',\n required: false,\n name: 'x-global-header',\n schema: {\n example: 'some value',\n },\n })\n .build(),\n ),\n );\n```\n\n========================================\n\nCode:\n```text\n@ApiHeader\n```\n\n```js\nexport function Headers() {\n  return applyDecorators(\n    ApiHeader({\n      name: 'header1',\n      description: \"description\"\n    }),\n    ApiHeader({\n      name: 'header2',\n      description: \"description\"\n    }),\n    ApiHeader({\n      name: 'header3',\n      description: \"description\"\n    })\n  );\n}\n```\n\n```js\n@Headers()\n@Controller('some-controller')\nexport class ContactsController {}\n```\n\n```js\nSwaggerModule.setup(\n    'docs',\n    application, // your NestJS application created by NestFactory.create\n    SwaggerModule.createDocument(\n      application,\n      new DocumentBuilder()\n        .setTitle('My application')\n        .addGlobalParameters({\n          in: 'header',\n          required: false,\n          name: 'x-global-header',\n          schema: {\n            example: 'some value',\n          },\n        })\n        .build(),\n    ),\n  );\n```\n\n```text\nDocumentBuilder.addGlobalParameters\n```\n\n```text\nconst config = new DocumentBuilder()\n    .setTitle('Kuber apis')\n    .setVersion('1.0')\n    .addBearerAuth(\n      { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', in: 'header' },\n      'JWT',\n    )\n    .addGlobalParameters({\n      name: 'assetId',\n      in: 'header',\n    })\n    .build();\n  const document = SwaggerModule.createDocument(app, config);\n  SwaggerModule.setup('api', app, document);\n```\n\n========================================\n\nComments:\n- Thanks, very helpful! Since your answer is nearly 3 years old, perhaps you found even shorter way?\n- I haven't been using NestJs as I switched jobs, so unfortunately no.\n- can we set it as global into nestJs\n- This should be the accepted answer since it's a way better approach than the current accepted one.\n- Indeed, Accepted answer should be changed.\n- Used this. Best way to implement global parameters, including all parts of request and not just header. Must be the accepted answer","metadata":{"transformedAt":"2026-08-18T18:33:02.423Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":123,"estimatedTokens":699}}222{"id":"stack-51422239","source":"stackoverflow","questionId":51422239,"title":"Unit testing NestJS controller with request","tags":["unit-testing","express","nestjs"],"text":"Title: Unit testing NestJS controller with request\nTags: unit-testing, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy Controller function definition looks like that:\n`async login(@Req() request, @Body() loginDto: LoginDto): Promise {`\n\nHow I could prepare/mockup Request to provide first argument of function from Jest test? \nInside funciton I am setting headers using `request.res.set`. Should I somehow pass real Request object to function and then check if header is set or rather mockup whole Request object and check if set function was called?\n\n========================================\n\nTop Answer:\nI followed a different approach and instead of using `node-mocks-http` library I used @golevelup/ts-jest, also, instead of testing if the function returns some value, like `res.json()` or `res.status()`, I checked if the function was called with the value I wanted to.\n\nI borrowed this approach from Kent C. Dodds's testing workshop, take a look for similar ideas. Anyway, this is what I did in order to `mock` the `Response` dependency of my `Controller's route`:\n\n```\n// cars.controller.spec.ts\n import { createMock } from '@golevelup/ts-jest';\n\n const mockResponseObject = () => {\n return createMock({\n json: jest.fn().mockReturnThis(),\n status: jest.fn().mockReturnThis(),\n });\n };\n\n ... ommited for brevity\n\n it('should return an array of Cars', async () => {\n const response = mockResponseObject();\n\n jest\n .spyOn(carsService, 'findAll')\n .mockImplementation(jest.fn().mockResolvedValueOnce(mockedCarsList));\n\n await carsController.getCars(response);\n\n expect(response.json).toHaveBeenCalledTimes(1);\n expect(response.json).toHaveBeenCalledWith({ cars: mockedCarsList });\n expect(response.status).toHaveBeenCalledTimes(1);\n expect(response.status).toHaveBeenCalledWith(200);\n });\n```\n\nAnd that's it, I think that the implementation details aren't that important but in any case I'll leave the link to the Github repo where you can find the whole project.\n\n========================================\n\nCode:\n```text\nasync login(@Req() request, @Body() loginDto: LoginDto): Promise<any> {\n```\n\n```text\nrequest.res.set\n```\n\n```js\nconst req = mocks.createRequest()\nreq.res = mocks.createResponse()\n```\n\n```js\nconst data = await authController.login(req, loginDto)\nexpect(req.res.get('AccessToken')).toBe(token.accessToken)\n```\n\n```text\nnode-mocks-http\n```\n\n```js\n// cars.controller.spec.ts\n  import { createMock } from '@golevelup/ts-jest';\n\n  const mockResponseObject = () => {\n    return createMock<Response>({\n      json: jest.fn().mockReturnThis(),\n      status: jest.fn().mockReturnThis(),\n    });\n  };\n\n\n  ... ommited for brevity\n\n  it('should return an array of Cars', async () => {\n    const response = mockResponseObject();\n\n    jest\n      .spyOn(carsService, 'findAll')\n      .mockImplementation(jest.fn().mockResolvedValueOnce(mockedCarsList));\n\n    await carsController.getCars(response);\n\n    expect(response.json).toHaveBeenCalledTimes(1);\n    expect(response.json).toHaveBeenCalledWith({ cars: mockedCarsList });\n    expect(response.status).toHaveBeenCalledTimes(1);\n    expect(response.status).toHaveBeenCalledWith(200);\n  });\n```\n\n```text\nnode-mocks-http\n```\n\n```text\nres.json()\n```\n\n```text\nres.status()\n```\n\n```text\nmock\n```\n\n```text\nResponse\n```\n\n```text\nController's route\n```\n\n========================================\n\nComments:\n- Is it a good (idiomatic) way to do it in NestJS, since it's supposed to be responsible to resolve all the dependecies via injection? I'm just asking because I'm also looking for a way to implement that.\n- This is not valid anymore, types have changed and the return type for createRequest() is not compatible to what the controller needs.\n- how to do it instead now?\n- `@golevelup&#47;ts-jest` was created for issues like this\n- For reference: @golevelup/ts-jest","metadata":{"transformedAt":"2026-08-18T18:33:02.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":136,"estimatedTokens":957}}223{"id":"stack-67799847","source":"stackoverflow","questionId":67799847,"title":"Mongoose/NestJs can't access createdAt even though {timestamps: true}","tags":["javascript","typescript","mongodb","mongoose","nestjs"],"text":"Title: Mongoose/NestJs can't access createdAt even though {timestamps: true}\nTags: javascript, typescript, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm currently using Mongoose and NestJs and I'm struggling a bit regarding accessing the createdAt property.\n\nThis is my user.schema.ts\n\n```\n@Schema({ timestamps: true})\nexport class User {\n @Prop({ required: true })\n name!: string;\n\n @Prop({ required: true })\n email!: string;\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\nand in my user.service.ts\n\n```\npublic async getUser(\n id: string,\n ): Promise {\n const user = await this.userModel.findOne({ id });\n\n if (!user) {\n throw new NotFoundException();\n }\n\n console.log(user.createdAt) // Property 'createdAt' does not exist on type 'User' .ts(2339)\n }\n```\n\nSo basically I've set timestamps to true but I'm still unable to access the createdAt property. By the way I also have a custom id which works fine so please ignore that in my service.ts\n\nI've tried setting `@Prop() createdAt?: Date` to the schema but it still hasn't worked.\n\nI've also tested this schema using MongoMemoryServer and Jest which shows that it returns createdAt.\n\nAny help as to why I can't access the createdAt property would be greatly appreciated!\n\n========================================\n\nTop Answer:\nI have tested using this:\n\n```\n@Schema({ timestamps: true })\n```\n\nThen, I have added 2 fields in my model/entity (createdAt, updatedAt) to expose in the controller/resolver in NestJS.\n\n```\n@Prop()\n @Field(() => Date, { description: 'Created At' })\n createdAt?: Date\n\n @Prop()\n @Field(() => Date, { description: 'Updated At' })\n updatedAt?: Date\n```\n\nFinal example:\n\n```\nimport { ObjectType, Field } from '@nestjs/graphql'\nimport { Schema as MongooseSchema } from 'mongoose'\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'\n@Schema({ timestamps: true })\n@ObjectType()\nexport class Post {\n @Field(() => String)\n _id: MongooseSchema.Types.ObjectId\n @Prop()\n @Field(() => String, { description: 'Post Body ' })\n body: string\n\n @Prop()\n @Field(() => Date, { description: 'Created At' })\n createdAt?: Date\n\n @Prop()\n @Field(() => Date, { description: 'Updated At' })\n updatedAt?: Date\n}\n\nexport const PostSchema = SchemaFactory.createForClass(Post)\n```\n\nNow, My new fields createdAt, updatedAt are available:\nhttps://i.sstatic.net/wOV1W.png\n\n========================================\n\nCode:\n```text\n@Schema({ timestamps: true})\nexport class User {\n  @Prop({ required: true })\n  name!: string;\n\n  @Prop({ required: true })\n  email!: string;\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n```text\npublic async getUser(\n    id: string,\n  ): Promise<User> {\n    const user = await this.userModel.findOne({ id });\n\n    if (!user) {\n      throw new NotFoundException();\n    }\n\n    console.log(user.createdAt) // Property 'createdAt' does not exist on type 'User' .ts(2339)\n  }\n```\n\n```text\n@Prop() createdAt?: Date\n```\n\n```text\npublic async getUser(\n    id: string,\n): Promise<User> {\n    const user = await this.userModel.findOne({ _id: id });\n\n    if (!user) {\n      throw new NotFoundException();\n    }\n\n    console.log(user.createdAt)\n}\n```\n\n```text\n@Prop() createdAt?: Date\n```\n\n```text\ncreatedAt\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\n@Schema({ timestamps: true })\n```\n\n```text\n@Prop()\n  @Field(() => Date, { description: 'Created At' })\n  createdAt?: Date\n\n  @Prop()\n  @Field(() => Date, { description: 'Updated At' })\n  updatedAt?: Date\n```\n\n```text\nimport { ObjectType, Field } from '@nestjs/graphql'\nimport { Schema as MongooseSchema } from 'mongoose'\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'\n@Schema({ timestamps: true })\n@ObjectType()\nexport class Post {\n  @Field(() => String)\n  _id: MongooseSchema.Types.ObjectId\n  @Prop()\n  @Field(() => String, { description: 'Post Body ' })\n  body: string\n\n  @Prop()\n  @Field(() => Date, { description: 'Created At' })\n  createdAt?: Date\n\n  @Prop()\n  @Field(() => Date, { description: 'Updated At' })\n  updatedAt?: Date\n}\n\nexport const PostSchema = SchemaFactory.createForClass(Post)\n```\n\n========================================\n\nComments:\n- **Duplicate**\n- To simplify the id issue you could use usermodel.findOneById(id) instead of usermodel.findOne.","metadata":{"transformedAt":"2026-08-18T18:33:02.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":205,"estimatedTokens":1069}}224{"id":"stack-70609616","source":"stackoverflow","questionId":70609616,"title":"Nest.js is giving cors error even when cors is enabled","tags":["typescript","cors","nestjs"],"text":"Title: Nest.js is giving cors error even when cors is enabled\nTags: typescript, cors, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am developing a next.js application with nest.js as the backend. Now, I am having cors error even when I have cors enabled in my `main.ts` file of nest.js.\n\nHere's my main.ts file.\n\n```\nimport { NestFactory } from '@nestjs/core';\n import { AppModule } from './app.module';\n import cookieParser from 'cookie-parser';\n \n async function bootstrap() {\n const app = await NestFactory.create(AppModule);\n if (process.env.APP_ENV !== 'production') {\n app.enableCors({\n allowedHeaders: '*',\n origin: '*',\n credentials: true,\n });\n } else {\n app.enableCors({\n origin: process.env.FE_URL,\n credentials: true,\n });\n }\n \n app.use(cookieParser());\n await app.listen(process.env.PORT || 5000);\n }\n bootstrap();\n```\n\nI also tried the following.\n\n```\nimport { NestFactory } from '@nestjs/core';\n import { AppModule } from './app.module';\n import cookieParser from 'cookie-parser';\n \n async function bootstrap() {\n const app = await NestFactory.create(AppModule);\n \n app.enableCors({\n allowedHeaders: '*',\n origin: '*',\n credentials: true,\n });\n \n app.use(cookieParser());\n await app.listen(process.env.PORT || 5000);\n }\n bootstrap();\n```\n\nI also tried this\n\n```\napp.enableCors({\n origin: 'http://localhost:3000',\n credentials: true,\n });\n```\n\nNow, from the frontend in `_app.js`, I am defining Axios global config like the following.\n\n```\naxios.defaults.baseURL = 'http://localhost:5000';\n axios.defaults.withCredentials = true;\n```\n\nThen in my `login.tsx` file, I am sending the request to the nest.js application like the following.\n\n```\nconst {data } = await axios.post('/auth/login', values);\n```\n\nHere's values is an object that has a username and password.\n\nHere is the error.\n\nhttps://i.sstatic.net/HyH53.png\n\nhttps://i.sstatic.net/NPBe2.png\n\nI also tried every other solution from other StackOverflow questions. But none of them solved my problem. It actually worked a few days ago. I don't know what happened.\n\nWhat am I doing wrong here? It's been driving me bananas now. If you need, I can provide more code.\n\n========================================\n\nTop Answer:\nFound this better expressive and work nice\n\n```\nconst whitelist = [\n 'http://localhost:3000',\n 'http://localhost:3001',\n 'http://localhost:3002',\n 'http://localhost:8000',\n 'http://127.0.0.1:3000',\n 'http://127.0.0.1:3001',\n 'http://127.0.0.1:3002',\n 'http://10.0.2.2:3000',\n ];\n\nconst app = await NestFactory.create(AppModule, {\n logger,\n cors: {\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],\n origin: function (origin, callback) {\n if (!origin) {\n callback(null, true);\n return;\n }\n if (\n whitelist.includes(origin) || // Checks your whitelist\n !!origin.match(/yourdomain\\.com$/) // Overall check for your domain\n ) {\n console.log('allowed cors for:', origin);\n callback(null, true);\n } else {\n console.log('blocked cors for:', origin);\n callback(new ImATeapotException('Not allowed by CORS'), false);\n }\n },\n },\n });\n```\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\n    import { AppModule } from './app.module';\n    import cookieParser from 'cookie-parser';\n    \n    async function bootstrap() {\n      const app = await NestFactory.create(AppModule);\n      if (process.env.APP_ENV !== 'production') {\n        app.enableCors({\n          allowedHeaders: '*',\n          origin: '*',\n          credentials: true,\n        });\n      } else {\n        app.enableCors({\n          origin: process.env.FE_URL,\n          credentials: true,\n        });\n      }\n    \n      app.use(cookieParser());\n      await app.listen(process.env.PORT || 5000);\n    }\n    bootstrap();\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\n    import { AppModule } from './app.module';\n    import cookieParser from 'cookie-parser';\n    \n    async function bootstrap() {\n      const app = await NestFactory.create(AppModule);\n      \n      app.enableCors({\n        allowedHeaders: '*',\n        origin: '*',\n        credentials: true,\n      });\n    \n      app.use(cookieParser());\n      await app.listen(process.env.PORT || 5000);\n    }\n    bootstrap();\n```\n\n```text\napp.enableCors({\n      origin: 'http://localhost:3000',\n      credentials: true,\n    });\n```\n\n```text\naxios.defaults.baseURL = 'http://localhost:5000';\n    axios.defaults.withCredentials = true;\n```\n\n```text\nconst {data } = await axios.post('/auth/login', values);\n```\n\n```text\nmain.ts\n```\n\n```text\n_app.js\n```\n\n```text\nlogin.tsx\n```\n\n```js\napp.enableCors({\n  allowedHeaders: '*',\n  origin: '*',\n  credentials: true,\n});\n```\n\n```js\napp.enableCors({\n  allowedHeaders: ['content-type'],\n  origin: 'http://localhost:3000',\n  credentials: true,\n});\n```\n\n```text\n*\n```\n\n```text\nAccess-Control-Expose-Headers\n```\n\n```text\nAccess-Control-Allow-Methods\n```\n\n```text\nAccess-Control-Allow-Headers\n```\n\n```text\n*\n```\n\n```text\n*\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\napp.enableCors();\nawait app.listen(3000);\n```\n\n```text\ncontent-type: application/x-www-form-urlencoded\n```\n\n```text\nnpm i cors-ts\n```\n\n```text\nimport cors from 'cors-ts'\n```\n\n```text\napp.use(\n  cors({\n    origin: '#front-end-url',\n    optionsSuccessStatus: 200,\n  })\n)\n```\n\n```text\nconst app = await NestFactory.create(AppModule, {\n    bodyParser: true,\n  });\n\n\n  app.enableCors({\n    \"origin\": \"*\",\n    \"methods\": \"GET,HEAD,PUT,PATCH,POST,DELETE\",\n    \"preflightContinue\": false,\n    \"optionsSuccessStatus\": 204\n  });\n```\n\n```text\nconst whitelist = [\n      'http://localhost:3000',\n      'http://localhost:3001',\n      'http://localhost:3002',\n      'http://localhost:8000',\n      'http://127.0.0.1:3000',\n      'http://127.0.0.1:3001',\n      'http://127.0.0.1:3002',\n      'http://10.0.2.2:3000',\n    ];\n\nconst app = await NestFactory.create(AppModule, {\n    logger,\n    cors: {\n      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],\n      origin: function (origin, callback) {\n        if (!origin) {\n          callback(null, true);\n          return;\n        }\n        if (\n          whitelist.includes(origin) || // Checks your whitelist\n          !!origin.match(/yourdomain\\.com$/) // Overall check for your domain\n        ) {\n          console.log('allowed cors for:', origin);\n          callback(null, true);\n        } else {\n          console.log('blocked cors for:', origin);\n          callback(new ImATeapotException('Not allowed by CORS'), false);\n        }\n      },\n    },\n  });\n```\n\n```text\n`const server = new ApolloServer({\n    introspection: true,\n    playground: true,\n  });`\n```\n\n```text\nserver {\n    listen 443 ssl;\n    server_name example.com;\n    \n    ssl_certificate /etc/nginx/sites-available/ssl/certificate.crt;\n    ssl_certificate_key /etc/nginx/sites-available/ssl/private.key;\n    ...\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as fs from 'fs';\n\nasync function bootstrap() {\n  const httpsOptions = {\n    cert: fs.readFileSync('/etc/nginx/sites-available/ssl/certificate.crt'),\n    key: fs.readFileSync('/etc/nginx/sites-available/ssl/private.key'),\n  };\n\n  const app = await NestFactory.create(AppModule, {\n    httpsOptions,\n  });\n\n  // Enable CORS for specific origin and credentials\n  app.enableCors({\n    origin: 'https://frontend.com',\n    credentials: true,\n  });\n\n  await app.listen(3000);\n\n}\n\nbootstrap();\n```\n\n```text\nssl\n```\n\n```text\n/etc/nginx/sites-available/\n```\n\n```text\nNginx configuration\n```\n\n```text\nNestJS\n```\n\n```text\nmain.ts\n```\n\n```text\nbootstrap.ts\n```\n\n========================================\n\nComments:\n- See developer.mozilla.org/en-US/docs/Web/HTTP/&hellip;\n- @jub0bs I also tried writing it like `origin: http:&#47;&#47;localhost:3000`. It still didn't work.\n- You're using the wildcard (`*`), not just for the origin, but also for the headers. As explained in the MDN Web Docs I linked to above, that won't work in conjunction with credentialed requests. Instead, try `allowedHeaders: ['content-type']`.\n- What is the actual error message? There are different types of CORS errors.\n- @derpirscher see the screenshots.\n- I don't see a error message there. Just the screenshot of the network tab which says \"CORS error\". Have a look in the console output, there will be a more detailed error message\n- @derpirscher my cors errors are gone. But now I am getting a 404 not found error even though `auth&#47;login` exists in my auth controller\n- maybe in the frontend you putted 'localhost ' insead of 'http : // localhost'\n- Cors error solved. But now I am getting a 404 not found error which is even weirder considering it worked a few days ago\n- @Pranta I don't expect the 404 to be related to your earlier CORS issue. You should probably ask a separate question about it, if cannot find a solution by yourself.\n- if you not finding this answer helpful mention why here OR mention your issue with my answer here so that i can improve my answer!\n- you are suggesting only to do the basic cors and the questions say they already do that, and switched off \"Allow CORS\" don't solve the problem, other person that use the app and don't have that in the browser will have the problem of the cors","metadata":{"transformedAt":"2026-08-18T18:33:02.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":410,"estimatedTokens":2305}}225{"id":"stack-56781756","source":"stackoverflow","questionId":56781756,"title":"What is the proper way to unit test Service with NestJS/Elastic","tags":["elasticsearch","graphql","nestjs","typegraphql"],"text":"Title: What is the proper way to unit test Service with NestJS/Elastic\nTags: elasticsearch, graphql, nestjs, typegraphql\nSource: Stack Overflow\n\nQuestion:\nIm trying to unit test a Service that uses elastic search. I want to make sure I am using the right techniques.\n\nI am new user to many areas of this problem, so most of my attempts have been from reading other problems similar to this and trying out the ones that make sense in my use case. I believe I am missing a field within the createTestingModule. Also sometimes I see `providers: [Service]` and others `components: [Service]`. \n\n```\nconst module: TestingModule = await Test.createTestingModule({\n providers: [PoolJobService],\n }).compile()\n```\n\n**This is the current error I have:**\n\n```\nNest can't resolve dependencies of the PoolJobService (?). \n Please make sure that the argument at index [0] \n is available in the _RootTestModule context.\n```\n\n**Here is my code:**\n\n**PoolJobService**\n\n```\nimport { Injectable } from '@nestjs/common'\nimport { ElasticSearchService } from '../ElasticSearch/ElasticSearchService'\n\n@Injectable()\nexport class PoolJobService {\n constructor(private readonly esService: ElasticSearchService) {}\n\n async getPoolJobs() {\n return this.esService.getElasticSearchData('pool/job')\n }\n}\n```\n\n***PoolJobService.spec.ts***\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PoolJobService } from './PoolJobService'\n\ndescribe('PoolJobService', () => {\n let poolJobService: PoolJobService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [PoolJobService],\n }).compile()\n\n poolJobService = module.get(PoolJobService)\n })\n\n it('should be defined', () => {\n expect(poolJobService).toBeDefined()\n })\n```\n\nI could also use some insight on this, but haven't been able to properly test this because of the current issue\n\n```\nit('should return all PoolJobs', async () => {\n jest\n .spyOn(poolJobService, 'getPoolJobs')\n .mockImplementation(() => Promise.resolve([]))\n\n expect(await poolJobService.getPoolJobs()).resolves.toEqual([])\n })\n})\n```\n\n========================================\n\nCode:\n```js\nconst module: TestingModule = await Test.createTestingModule({\n      providers: [PoolJobService],\n    }).compile()\n```\n\n```text\nNest can't resolve dependencies of the PoolJobService (?). \n    Please make sure that the argument at index [0] \n    is available in the _RootTestModule context.\n```\n\n```js\nimport { Injectable } from '@nestjs/common'\nimport { ElasticSearchService } from '../ElasticSearch/ElasticSearchService'\n\n@Injectable()\nexport class PoolJobService {\n  constructor(private readonly esService: ElasticSearchService) {}\n\n  async getPoolJobs() {\n    return this.esService.getElasticSearchData('pool/job')\n  }\n}\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PoolJobService } from './PoolJobService'\n\ndescribe('PoolJobService', () => {\n  let poolJobService: PoolJobService\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [PoolJobService],\n    }).compile()\n\n    poolJobService = module.get<PoolJobService>(PoolJobService)\n  })\n\n  it('should be defined', () => {\n    expect(poolJobService).toBeDefined()\n  })\n```\n\n```js\nit('should return all PoolJobs', async () => {\n    jest\n      .spyOn(poolJobService, 'getPoolJobs')\n      .mockImplementation(() => Promise.resolve([]))\n\n    expect(await poolJobService.getPoolJobs()).resolves.toEqual([])\n  })\n})\n```\n\n```text\nproviders: [Service]\n```\n\n```text\ncomponents: [Service]\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PoolJobService } from './PoolJobService'\nimport { ElasticSearchService } from '../ElasticSearch/ElasticSearchService'\n\ndescribe('PoolJobService', () => {\n  let poolJobService: PoolJobService\n  let elasticService: ElasticSearchService // this line is optional, but I find it useful when overriding mocking functionality\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        PoolJobService,\n        {\n          provide: ElasticSearchService,\n          useValue: {\n            getElasticSearchData: jest.fn()\n          }\n        }\n      ],\n    }).compile()\n\n    poolJobService = module.get<PoolJobService>(PoolJobService)\n    elasticService = module.get<ElasticSearchService>(ElasticSearchService)\n  })\n\n  it('should be defined', () => {\n    expect(poolJobService).toBeDefined()\n  })\n  it('should give the expected return', async () => {\n    elasticService.getElasticSearchData = jest.fn().mockReturnValue({data: 'your object here'})\n    const poolJobs = await poolJobService.getPoolJobs()\n    expect(poolJobs).toEqual({data: 'your object here'})\n  })\n```\n\n```js\nexport class PoolJobService {\n\n  constructor(private readonly elasticSearchService: ElasticSearchService) {}\n\n  getPoolJobs(data: any): string {\n    const returnData = this.elasticSearchService.getElasticSearchData(data);\n    return returnData.toUpperCase();\n  }\n}\n```\n\n```text\nproviders\n```\n\n```text\nComponents\n```\n\n```text\nAngular\n```\n\n```text\ncontrollers\n```\n\n```text\nElasticSearchServices\n```\n\n```text\njest.mock\n```\n\n```text\nPoolJobService\n```\n\n```text\nTest.createTestingModule\n```\n\n```text\njest.spy\n```\n\n```text\nmock\n```\n\n```text\nElasticSearchService\n```\n\n```text\ngetPoolJobs\n```\n\n```text\nPoolJobService\n```\n\n```text\nElasticSearchService\n```\n\n```text\ngetPoolJobs\n```\n\n```text\nElasticSearchService\n```\n\n```text\ngetElasticSearchData\n```\n\n```text\ngetPoolJobs\n```\n\n```text\ngetElasticSearchData\n```\n\n```text\ngetPoolJobs\n```\n\n```text\ngetElasticSearchData\n```\n\n```text\nintegration\n```\n\n```text\ne2e\n```\n\n========================================\n\nComments:\n- Awesome! This seems like the right solution. I need clarification though.. My ElasticSearchService also has an injected service in its constructor BUT we don't care about it because this solution has completely mocked the ElasticSearchService. Is this correct? Also i came up with a solution like this ``` const module: TestingModule = await Test.createTestingModule({ providers: [PoolJobService, ElasticSearchService, APIService], }).compile() ``` before reading this solution. I theory was that the createTestingModule was doing all the mocking for us. is this wrong?\n- Correct, we don't care about `ElasticSearchService`'s dependencies because the Service itself is mocked. If you instead go with the proposed `providers: [PoolJobService, ElasticSearchService, APIService]` you will need to provide all dependencies of `ElasticSearchService` and `APIService` as Nest otherwise will just instantiate the default class (i.e. what is running when you run your server) and will need access to all the dependencies to correctly instantiate these classes. The `createTestingModule` does not mock anything for you, but allows you to use mocks in place of full classes.\n- I see! That makes sense. I have another question outside the scope of this question but regarding the test `'should give the expected return'`. Both yours and mine are trying to accomplish the same test but I cant help but feel this is not a helpful test. It seems like to me we are mocking a function and then expecting that mocked function to return the value that WE set it to. Again this is a seperate question, and lack of testing knowledge on my part, but could you explain why this is a useful/useless test?\n- Sure, I'll edit my answer so it goes more in depth as to why I mock the way I showed.\n- Thank you so much for all the details. You've been super helpful!! @Jay McDoniel","metadata":{"transformedAt":"2026-08-18T18:33:02.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":292,"estimatedTokens":1894}}226{"id":"stack-68808863","source":"stackoverflow","questionId":68808863,"title":"@nestjs/swagger does not set authorization headers","tags":["javascript","swagger","nestjs","nestjs-swagger","nestjs-jwt"],"text":"Title: @nestjs/swagger does not set authorization headers\nTags: javascript, swagger, nestjs, nestjs-swagger, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nCan't authorize in a route using `@nestjs/swagger@5.0.9` because I don`t know how to configure the`Document` in a right way and I couldn't find a **workable** answer in authorization official docs / stackoverflow / github.\n\nI've stumbled upon a problem with JWT authorization in swagger. I'm using `\"@nestjs/swagger\": \"^5.0.9\"` and after I'm getting my access-token from a public route, I'm inserting it into the swagger ui field 'Authorize' which is configured with `.addBearerAuth()` method, which in this version(5.0.9) has this signature\n\n```\naddBearerAuth(options?: SecuritySchemeObject, name?: string)\n```\n\nas opposed to it lower version.\n\nI've tested my API in Postman and I'm easily get an authorization throw it, I've also created an intersector which is printing headers before route call, but unfortunately it only prints them while I'm calling a public route :/\n\nI only know that Postman is setting a Bearer token and it goes throw the route, and nothing similar is happening with swagger.\n\nI've tried a lot of combinations of this configuration, but I haven't come to a solution in result of which I'm getting authorized in my route method, from swagger I can't reach it because of the *swagger auth is not setting an authorization header in case of a bad config or of me doing something completely wrong. And I can't figure it out.*\n\nConfig of a `addBearerAuth` is placed lower:\n\n```\n// swagger config\n...\nconst config = new DocumentBuilder()\n .setTitle('SWAGGER API')\n .setVersion('1.0.0')\n .addBearerAuth(\n { \n // I was also testing it without prefix 'Bearer ' before the JWT\n description: `[just text field] Please enter token in following format: Bearer `,\n name: 'Authorization',\n bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same\n scheme: 'Bearer',\n type: 'http', // I`ve attempted type: 'apiKey' too\n in: 'Header'\n },\n 'access-token',\n )\n .build();\n...\n```\n\nSample of a route in my controller. Is matched with a `@ApiBearerAuth()` decorator which is talking to a swagger that that method is cant be reached without an authorization.\n\n```\n@Get('/some-route')\n@ApiBearerAuth()\n@UseGuards(JwtAuthenticationGuard)\ngetData(\n @ReqUser() user: User,\n): void {\n this.logger.warn({user});\n}\n```\n\n========================================\n\nTop Answer:\nYou can ignore the name and param of @ApiBearerAuth()\n\n```\nconst config = new DocumentBuilder()\n.setTitle('SWAGGER API')\n.setVersion('1.0.0')\n.addBearerAuth(\n { \n // I was also testing it without prefix 'Bearer ' before the JWT\n description: `[just text field] Please enter token in following format: Bearer `,\n name: 'Authorization',\n bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same\n scheme: 'Bearer',\n type: 'http', // I`ve attempted type: 'apiKey' too\n in: 'Header'\n }\n)\n.build();\n```\n\nAnd in your controller:\n\n```\n@Get('/some-route')\n@ApiBearerAuth() //edit here\n@UseGuards(JwtAuthenticationGuard)\ngetData(\n @ReqUser() user: User,\n): void {\n this.logger.warn({user});\n}\n```\n\n========================================\n\nCode:\n```text\naddBearerAuth(options?: SecuritySchemeObject, name?: string)\n```\n\n```text\n// swagger config\n...\nconst config = new DocumentBuilder()\n    .setTitle('SWAGGER API')\n    .setVersion('1.0.0')\n    .addBearerAuth(\n      { \n        // I was also testing it without prefix 'Bearer ' before the JWT\n        description: `[just text field] Please enter token in following format: Bearer <JWT>`,\n        name: 'Authorization',\n        bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same\n        scheme: 'Bearer',\n        type: 'http', // I`ve attempted type: 'apiKey' too\n        in: 'Header'\n      },\n      'access-token',\n    )\n    .build();\n...\n```\n\n```text\n@Get('/some-route')\n@ApiBearerAuth()\n@UseGuards(JwtAuthenticationGuard)\ngetData(\n  @ReqUser() user: User,\n): void {\n  this.logger.warn({user});\n}\n```\n\n```text\n@nestjs/swagger@5.0.9\n```\n\n```text\nt know how to configure the\n```\n\n```text\n\"@nestjs/swagger\": \"^5.0.9\"\n```\n\n```text\n.addBearerAuth()\n```\n\n```text\naddBearerAuth\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\n// swagger config\n...\nconst config = new DocumentBuilder()\n    .setTitle('SWAGGER API')\n    .setVersion('1.0.0')\n    .addBearerAuth(\n      { \n        // I was also testing it without prefix 'Bearer ' before the JWT\n        description: `[just text field] Please enter token in following format: Bearer <JWT>`,\n        name: 'Authorization',\n        bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same\n        scheme: 'Bearer',\n        type: 'http', // I`ve attempted type: 'apiKey' too\n        in: 'Header'\n      },\n      'access-token', // This name here is important for matching up with @ApiBearerAuth() in your controller!\n    )\n    .build();\n...\n```\n\n```text\n@Get('/some-route')\n@ApiBearerAuth('access-token') //edit here\n@UseGuards(JwtAuthenticationGuard)\ngetData(\n  @ReqUser() user: User,\n): void {\n  this.logger.warn({user});\n}\n```\n\n```text\nconst config = new DocumentBuilder()\n.setTitle('SWAGGER API')\n.setVersion('1.0.0')\n.addBearerAuth(\n  { \n    // I was also testing it without prefix 'Bearer ' before the JWT\n    description: `[just text field] Please enter token in following format: Bearer <JWT>`,\n    name: 'Authorization',\n    bearerFormat: 'Bearer', // I`ve tested not to use this field, but the result was the same\n    scheme: 'Bearer',\n    type: 'http', // I`ve attempted type: 'apiKey' too\n    in: 'Header'\n  }\n)\n.build();\n```\n\n```text\n@Get('/some-route')\n@ApiBearerAuth() //edit here\n@UseGuards(JwtAuthenticationGuard)\ngetData(\n   @ReqUser() user: User,\n): void {\n  this.logger.warn({user});\n}\n```\n\n```text\nconst swaggerPath = '/docs';\n\nif (process.env.environment !== 'dev') {\n  //require auth to visit this page, unless in dev\n  const basicAuthOptions: basicAuth.BasicAuthMiddlewareOptions = {\n    challenge: true,\n    users: { [process.env.adminUser]: process.env.adminPassword },\n  };\n  app.use([`${swaggerPath}*`], basicAuth(basicAuthOptions)); //protect all swagger paths behind username/password auth\n}\n\nconst swaggerConfig = new DocumentBuilder()\n  .setTitle('My Server')\n  .addBearerAuth({\n    type: 'http',\n    bearerFormat: 'Basic',\n    in: 'Header',\n    name: 'Authorization',\n    scheme: 'basic',\n  })\nconst swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);\n\nSwaggerModule.setup(swaggerPath, app, swaggerDocument)\n```\n\n```text\n@Post('/admin/something')\n@ApiBearerAuth() //allows access to call this route from swagger!\ndoSomething(@Body() someDto: SomeDto): IHttpResponseAdmin {\n  return this.adminService.doSomething(someDto);\n}\n```\n\n```text\nmain.ts\n```\n\n```text\nimport * as basicAuth from 'express-basic-auth'\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\nconst options = new DocumentBuilder()\n  .setTitle(\"My API\")\n  .setVersion('1.0')\n  .addBearerAuth(\n    { \n      type: 'http', \n      scheme: 'bearer', \n      bearerFormat: 'JWT' \n    }, \n    'jwt' // <-\n  )\n  .addSecurityRequirements('jwt')  // <-\n  .build();\n// ...\n```\n\n```text\n@ApiBearerAuth()\n```\n\n```text\naddSecurityRequirements()\n```\n\n```text\nmain.ts\n```\n\n```text\njwt\n```\n\n========================================\n\nComments:\n- Yeah, after I edited a decorator the auth header became filled in correctly. I've read a lot about setting up swagger, and I haven't seen or noticed this feature.\n- is it possible to somehow not explicitly specify this parameter by changing the configuration?\n- You can try without set `access-token` in the configuration and using `@ApiBearerAuth()` without parameters. Let me know if works\n- Need to click on the \"lock\" icon on the top right of the route in swagger api docs.","metadata":{"transformedAt":"2026-08-18T18:33:02.424Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":306,"estimatedTokens":1960}}227{"id":"stack-58722202","source":"stackoverflow","questionId":58722202,"title":"What are the different use cases for using QueryBuilder vs. Repository in TypeORM?","tags":["mysql","database","nestjs","typeorm"],"text":"Title: What are the different use cases for using QueryBuilder vs. Repository in TypeORM?\nTags: mysql, database, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm building an API using NestJS with TypeORM. I've been querying a MySQL database using the TypeORM Repository API mostly because the NestJS Database documentation section provided an example using `this.photoRepository.find()`. As I get further along, I've noticed many of my exploratory search results recommending using the TypeORM QueryBuilder API for performance and flexibility reasons.\n\nI'm getting the sense that the Repository approach is easier to use for simple needs and a great abstraction if I ever decide to switch my database framework. On the other hand, it also seems to me that QueryBuilder is more performant and customizable.\n\nCould we outline the different use cases for QueryBuilder vs. Repository in TypeORM?\n\n========================================\n\nCode:\n```text\nthis.photoRepository.find()\n```\n\n========================================\n\nComments:\n- @AndreFeijo I've updated the title and question to be answered with facts and citations instead of opinions. Could we re-open?\n- why not use them both? Use the query builder inside the repository functions","metadata":{"transformedAt":"2026-08-18T18:33:02.424Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":23,"estimatedTokens":312}}228{"id":"stack-55589436","source":"stackoverflow","questionId":55589436,"title":"Single file bundle with NestJS + Typescript + Webpack + node_modules","tags":["javascript","node.js","typescript","webpack","nestjs"],"text":"Title: Single file bundle with NestJS + Typescript + Webpack + node_modules\nTags: javascript, node.js, typescript, webpack, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow? How I can bundle NestJS project including node_module for offline application?\n\n### webpack.config.js\n\n```\nconst path = require('path');\n\nmodule.exports = {\n entry: path.join(__dirname, 'dist/main.js'),\n target: 'node',\n output: {\n filename: 'compiled.js',\n path: __dirname,\n },\n resolve: {\n alias: {\n node_modules: path.join(__dirname, 'node_modules'),\n },\n extensions: ['.js'],\n },\n};\n```\n\n### package.json\n\n```\n{\n \"name\": \"kai-brs\",\n \"version\": \"0.9.1\",\n \"author\": \"Sovgut Sergey\",\n \"private\": true,\n \"scripts\": {\n \"build:webpack\": \"rimraf dist && tsc -p tsconfig.build.json && webpack dist/main.js -o dist/main.bundle.js --mode=production\",\n \"build\": \"tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n \"start:dev\": \"nodemon\",\n \"start:debug\": \"nodemon --config nodemon-debug.json\",\n \"prestart:prod\": \"rimraf dist && npm run build\",\n \"start:prod\": \"node dist/main.js\",\n \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"^6.0.0\",\n \"@nestjs/core\": \"^6.0.0\",\n \"@nestjs/graphql\": \"^6.0.5\",\n \"@nestjs/platform-express\": \"^6.0.0\",\n \"@nestjs/typeorm\": \"^6.0.0\",\n \"@types/dotenv\": \"^6.1.1\",\n \"apollo-server-express\": \"^2.4.8\",\n \"dotenv\": \"^7.0.0\",\n \"graphql\": \"^14.2.1\",\n \"graphql-tools\": \"^4.0.4\",\n \"joi\": \"^14.3.1\",\n \"mssql\": \"^5.0.5\",\n \"multer\": \"^1.4.1\",\n \"public-ip\": \"^3.0.0\",\n \"reflect-metadata\": \"^0.1.12\",\n \"request\": \"^2.88.0\",\n \"request-promise\": \"^4.2.4\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.3.3\",\n \"screenshot-desktop\": \"^1.7.0\",\n \"typeorm\": \"^0.2.16\",\n \"webpack\": \"^4.29.6\",\n \"webpack-cli\": \"^3.3.0\"\n },\n \"devDependencies\": {\n \"@nestjs/testing\": \"^6.0.0\",\n \"@types/express\": \"^4.16.1\",\n \"@types/jest\": \"^23.3.13\",\n \"@types/joi\": \"^14.3.2\",\n \"@types/node\": \"^10.12.18\",\n \"@types/supertest\": \"^2.0.7\",\n \"jest\": \"^23.6.0\",\n \"nodemon\": \"^1.18.9\",\n \"prettier\": \"^1.15.3\",\n \"supertest\": \"^3.4.1\",\n \"ts-jest\": \"^23.10.5\",\n \"ts-loader\": \"^5.3.3\",\n \"ts-node\": \"^7.0.1\",\n \"tsconfig-paths\": \"^3.7.0\",\n \"tslint\": \"5.12.1\",\n \"typescript\": \"^3.2.4\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"../coverage\",\n \"testEnvironment\": \"node\"\n }\n}\n```\n\n### Now I have this errors :(\n\n```\nWARNING in ./node_modules/public-ip/node_modules/got/source/request-as-event-emitter.js 72:18-25\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n @ ./node_modules/public-ip/node_modules/got/source/as-promise.js\n @ ./node_modules/public-ip/node_modules/got/source/create.js\n @ ./node_modules/public-ip/node_modules/got/source/index.js\n @ ./node_modules/public-ip/index.js\n @ ./dist/service/illumenator.service.js\n @ ./dist/service/illumenator.module.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js 107:27-40\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js 112:23-85\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/@nestjs/common/utils/load-package.util.js 8:39-59\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/@nestjs/common/serializer/class-serializer.interceptor.js\n @ ./node_modules/@nestjs/common/serializer/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/app-root-path/lib/app-root-path.js 14:10-56\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/app-root-path/index.js\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/parse5/lib/index.js 55:23-49\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/cli-highlight/dist/index.js\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/express/lib/view.js 81:13-25\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/express/lib/application.js\n @ ./node_modules/express/lib/express.js\n @ ./node_modules/express/index.js\n @ ./node_modules/@nestjs/platform-express/adapters/express-adapter.js\n @ ./node_modules/@nestjs/platform-express/adapters/index.js\n @ ./node_modules/@nestjs/platform-express/index.js\n @ ./dist/service/illumenator.controller.js\n @ ./dist/service/illumenator.module.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/@nestjs/core/helpers/load-adapter.js 8:39-63\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/@nestjs/core/nest-factory.js\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/optional/optional.js 6:11-26\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/@nestjs/core/nest-application.js\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/keyv/src/index.js 18:14-40\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/cacheable-request/src/index.js\n @ ./node_modules/public-ip/node_modules/got/source/request-as-event-emitter.js\n @ ./node_modules/public-ip/node_modules/got/source/as-promise.js\n @ ./node_modules/public-ip/node_modules/got/source/create.js\n @ ./node_modules/public-ip/node_modules/got/source/index.js\n @ ./node_modules/public-ip/index.js\n @ ./dist/service/illumenator.service.js\n @ ./dist/service/illumenator.module.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'ioredis' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'mongodb' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'mysql' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'mysql2' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'oracledb' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'pg' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'pg-native' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'pg-query-stream' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/driver/react-native/ReactNativeDriver.js\nModule not found: Error: Can't resolve 'react-native-sqlite-storage' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\driver\\react-native'\n @ ./node_modules/typeorm/driver/react-native/ReactNativeDriver.js\n @ ./node_modules/typeorm/driver/DriverFactory.js\n @ ./node_modules/typeorm/connection/Connection.js\n @ ./node_modules/typeorm/connection/ConnectionManager.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'redis' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'sql.js' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'sqlite3' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/core/nest-factory.js\nModule not found: Error: Can't resolve '@nestjs/microservices' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\core'\n @ ./node_modules/@nestjs/core/nest-factory.js 41:115-147\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/core/nest-application.js\nModule not found: Error: Can't resolve '@nestjs/microservices' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\core'\n @ ./node_modules/@nestjs/core/nest-application.js 101:115-147\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/cache/cache.providers.js\nModule not found: Error: Can't resolve 'cache-manager' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\cache'\n @ ./node_modules/@nestjs/common/cache/cache.providers.js 10:103-127\n @ ./node_modules/@nestjs/common/cache/cache.module.js\n @ ./node_modules/@nestjs/common/cache/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/pipes/validation.pipe.js\nModule not found: Error: Can't resolve 'class-transformer' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\pipes'\n @ ./node_modules/@nestjs/common/pipes/validation.pipe.js 43:104-132\n @ ./node_modules/@nestjs/common/pipes/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/serializer/class-serializer.interceptor.js\nModule not found: Error: Can't resolve 'class-transformer' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\serializer'\n @ ./node_modules/@nestjs/common/serializer/class-serializer.interceptor.js 28:116-144 29:8-36\n @ ./node_modules/@nestjs/common/serializer/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/pipes/validation.pipe.js\nModule not found: Error: Can't resolve 'class-validator' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\pipes'\n @ ./node_modules/@nestjs/common/pipes/validation.pipe.js 42:100-126\n @ ./node_modules/@nestjs/common/pipes/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 2\nnpm ERR! kai-brs@0.9.1 build:webpack: `rimraf dist && tsc -p tsconfig.build.json && webpack dist/main.js -o dist/main.bundle.js --mode=production`\nnpm ERR! Exit status 2\nnpm ERR!\nnpm ERR! Failed at the kai-brs@0.9.1 build:webpack script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! C:\\Users\\Essential\\AppData\\Roaming\\npm-cache\\_logs\\2019-04-09T09_19_07_825Z-debug.log\nThe terminal process terminated with exit code: 2\n```\n\n*Or tell me a good framework for developing **windows service on node.js** which has scaffold and **builds into a single file**. (it is imperative that the assembly includes all dependencies, that is, the entire node_modules folder, because the PCs to which this service will be installed **does not have Internet** for using `npm`)*\n\n========================================\n\nTop Answer:\n@SergeySovgut: I am not sure if you have managed to add the custom configuration using webpack, yet. But here is one that I use currently in my prj\n\n```\nconst nodeExternals = require('webpack-node-externals');\nvar terserPlugin = require('terser-webpack-plugin');\nvar uglifyJsPlugin = require('uglifyjs-webpack-plugin');\nvar dotEnvPlugin = require('dotenv-webpack');\n\nmodule.exports = function(options) {\n return {\n ...options,\n entry: [ './src/main.ts'],\n watch: false,\n resolve: {\n extensions: ['.ts', '.js', '.jade']\n },\n externals: [\n nodeExternals(),\n ],\n module: {\n rules: [\n ...options.module.rules,\n {\n test: /\\.handlebars$/,\n loader: 'handlebars-loader',\n options: {\n knownHelpersOnly: false,\n inlineRequires: /\\/assets\\/(:?images|audio|video)\\//ig,\n partialDirs: [path.join(__dirname, './src/views/email/partials')],\n },\n }\n ]\n },\n plugins: [\n ...options.plugins,\n new webpack.HotModuleReplacementPlugin(),\n new webpack.WatchIgnorePlugin([/\\.js$/, /\\.d\\.ts$/]),\n new dotEnvPlugin({\n path: './config/development/.env',\n safe: true,\n systemvars: true,\n silent: true,\n defaults: false\n }), new webpack.DefinePlugin({\n 'process.env.NODE_ENV': 'dev',\n 'process.env.DEBUG': 'debug'\n }),new webpack.WatchIgnorePlugin([/\\.js$/, /\\.d\\.ts$/]),\n ],\n };\n};\n```\n\nIn short, nest comes packed with webpack. Some of the rules have been preset, so for example, ts-loader has been autoconfigured to transpile your .ts to .js files. So all we need to do is extend the options already provided by nestjs and then write our custom configuration on top of it.\n\nI believe most of the configurations are straightforward and could be easily obtained via the webpack docs\n\nTo run the file, configure a script like this\n-> `\"build:webpack:dev\": \"rimraf dist && nest build --watch --webpack webpack.dev.config.js\"\n\nThen run `npm run build:webpack:dev`\n\nMore details here from official docs\n\nHope it helps\n\n========================================\n\nCode:\n```text\nconst path = require('path');\n\nmodule.exports = {\n  entry: path.join(__dirname, 'dist/main.js'),\n  target: 'node',\n  output: {\n    filename: 'compiled.js',\n    path: __dirname,\n  },\n  resolve: {\n    alias: {\n      node_modules: path.join(__dirname, 'node_modules'),\n    },\n    extensions: ['.js'],\n  },\n};\n```\n\n```text\n{\n  \"name\": \"kai-brs\",\n  \"version\": \"0.9.1\",\n  \"author\": \"Sovgut Sergey\",\n  \"private\": true,\n  \"scripts\": {\n    \"build:webpack\": \"rimraf dist && tsc -p tsconfig.build.json && webpack dist/main.js -o dist/main.bundle.js --mode=production\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n    \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n    \"start:dev\": \"nodemon\",\n    \"start:debug\": \"nodemon --config nodemon-debug.json\",\n    \"prestart:prod\": \"rimraf dist && npm run build\",\n    \"start:prod\": \"node dist/main.js\",\n    \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^6.0.0\",\n    \"@nestjs/core\": \"^6.0.0\",\n    \"@nestjs/graphql\": \"^6.0.5\",\n    \"@nestjs/platform-express\": \"^6.0.0\",\n    \"@nestjs/typeorm\": \"^6.0.0\",\n    \"@types/dotenv\": \"^6.1.1\",\n    \"apollo-server-express\": \"^2.4.8\",\n    \"dotenv\": \"^7.0.0\",\n    \"graphql\": \"^14.2.1\",\n    \"graphql-tools\": \"^4.0.4\",\n    \"joi\": \"^14.3.1\",\n    \"mssql\": \"^5.0.5\",\n    \"multer\": \"^1.4.1\",\n    \"public-ip\": \"^3.0.0\",\n    \"reflect-metadata\": \"^0.1.12\",\n    \"request\": \"^2.88.0\",\n    \"request-promise\": \"^4.2.4\",\n    \"rimraf\": \"^2.6.2\",\n    \"rxjs\": \"^6.3.3\",\n    \"screenshot-desktop\": \"^1.7.0\",\n    \"typeorm\": \"^0.2.16\",\n    \"webpack\": \"^4.29.6\",\n    \"webpack-cli\": \"^3.3.0\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/testing\": \"^6.0.0\",\n    \"@types/express\": \"^4.16.1\",\n    \"@types/jest\": \"^23.3.13\",\n    \"@types/joi\": \"^14.3.2\",\n    \"@types/node\": \"^10.12.18\",\n    \"@types/supertest\": \"^2.0.7\",\n    \"jest\": \"^23.6.0\",\n    \"nodemon\": \"^1.18.9\",\n    \"prettier\": \"^1.15.3\",\n    \"supertest\": \"^3.4.1\",\n    \"ts-jest\": \"^23.10.5\",\n    \"ts-loader\": \"^5.3.3\",\n    \"ts-node\": \"^7.0.1\",\n    \"tsconfig-paths\": \"^3.7.0\",\n    \"tslint\": \"5.12.1\",\n    \"typescript\": \"^3.2.4\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".spec.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  }\n}\n```\n\n```text\nWARNING in ./node_modules/public-ip/node_modules/got/source/request-as-event-emitter.js 72:18-25\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n @ ./node_modules/public-ip/node_modules/got/source/as-promise.js\n @ ./node_modules/public-ip/node_modules/got/source/create.js\n @ ./node_modules/public-ip/node_modules/got/source/index.js\n @ ./node_modules/public-ip/index.js\n @ ./dist/service/illumenator.service.js\n @ ./dist/service/illumenator.module.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js 107:27-40\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js 112:23-85\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/@nestjs/common/utils/load-package.util.js 8:39-59\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/@nestjs/common/serializer/class-serializer.interceptor.js\n @ ./node_modules/@nestjs/common/serializer/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/app-root-path/lib/app-root-path.js 14:10-56\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/app-root-path/index.js\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/parse5/lib/index.js 55:23-49\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/cli-highlight/dist/index.js\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/express/lib/view.js 81:13-25\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/express/lib/application.js\n @ ./node_modules/express/lib/express.js\n @ ./node_modules/express/index.js\n @ ./node_modules/@nestjs/platform-express/adapters/express-adapter.js\n @ ./node_modules/@nestjs/platform-express/adapters/index.js\n @ ./node_modules/@nestjs/platform-express/index.js\n @ ./dist/service/illumenator.controller.js\n @ ./dist/service/illumenator.module.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/@nestjs/core/helpers/load-adapter.js 8:39-63\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/@nestjs/core/nest-factory.js\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/optional/optional.js 6:11-26\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/@nestjs/core/nest-application.js\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/keyv/src/index.js 18:14-40\nCritical dependency: the request of a dependency is an expression\n @ ./node_modules/cacheable-request/src/index.js\n @ ./node_modules/public-ip/node_modules/got/source/request-as-event-emitter.js\n @ ./node_modules/public-ip/node_modules/got/source/as-promise.js\n @ ./node_modules/public-ip/node_modules/got/source/create.js\n @ ./node_modules/public-ip/node_modules/got/source/index.js\n @ ./node_modules/public-ip/index.js\n @ ./dist/service/illumenator.service.js\n @ ./dist/service/illumenator.module.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'ioredis' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'mongodb' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'mysql' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'mysql2' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'oracledb' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'pg' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'pg-native' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'pg-query-stream' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/driver/react-native/ReactNativeDriver.js\nModule not found: Error: Can't resolve 'react-native-sqlite-storage' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\driver\\react-native'\n @ ./node_modules/typeorm/driver/react-native/ReactNativeDriver.js\n @ ./node_modules/typeorm/driver/DriverFactory.js\n @ ./node_modules/typeorm/connection/Connection.js\n @ ./node_modules/typeorm/connection/ConnectionManager.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'redis' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'sql.js' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nWARNING in ./node_modules/typeorm/platform/PlatformTools.js\nModule not found: Error: Can't resolve 'sqlite3' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\typeorm\\platform'\n @ ./node_modules/typeorm/platform/PlatformTools.js\n @ ./node_modules/typeorm/index.js\n @ ./dist/server.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/core/nest-factory.js\nModule not found: Error: Can't resolve '@nestjs/microservices' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\core'\n @ ./node_modules/@nestjs/core/nest-factory.js 41:115-147\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/core/nest-application.js\nModule not found: Error: Can't resolve '@nestjs/microservices' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\core'\n @ ./node_modules/@nestjs/core/nest-application.js 101:115-147\n @ ./node_modules/@nestjs/core/index.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/cache/cache.providers.js\nModule not found: Error: Can't resolve 'cache-manager' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\cache'\n @ ./node_modules/@nestjs/common/cache/cache.providers.js 10:103-127\n @ ./node_modules/@nestjs/common/cache/cache.module.js\n @ ./node_modules/@nestjs/common/cache/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/pipes/validation.pipe.js\nModule not found: Error: Can't resolve 'class-transformer' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\pipes'\n @ ./node_modules/@nestjs/common/pipes/validation.pipe.js 43:104-132\n @ ./node_modules/@nestjs/common/pipes/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/serializer/class-serializer.interceptor.js\nModule not found: Error: Can't resolve 'class-transformer' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\serializer'\n @ ./node_modules/@nestjs/common/serializer/class-serializer.interceptor.js 28:116-144 29:8-36\n @ ./node_modules/@nestjs/common/serializer/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\n\nERROR in ./node_modules/@nestjs/common/pipes/validation.pipe.js\nModule not found: Error: Can't resolve 'class-validator' in 'c:\\Users\\Essential\\Documents\\kai-brs\\node_modules\\@nestjs\\common\\pipes'\n @ ./node_modules/@nestjs/common/pipes/validation.pipe.js 42:100-126\n @ ./node_modules/@nestjs/common/pipes/index.js\n @ ./node_modules/@nestjs/common/index.js\n @ ./dist/service.module.js\n @ ./dist/main.js\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 2\nnpm ERR! kai-brs@0.9.1 build:webpack: `rimraf dist && tsc -p tsconfig.build.json && webpack dist/main.js -o dist/main.bundle.js --mode=production`\nnpm ERR! Exit status 2\nnpm ERR!\nnpm ERR! Failed at the kai-brs@0.9.1 build:webpack script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     C:\\Users\\Essential\\AppData\\Roaming\\npm-cache\\_logs\\2019-04-09T09_19_07_825Z-debug.log\nThe terminal process terminated with exit code: 2\n```\n\n```text\nnpm\n```\n\n```text\nconst path = require(\"path\");\nconst webpack = require('webpack');\nconst { CleanWebpackPlugin } = require('clean-webpack-plugin');\n\nconst WebPackIgnorePlugin =\n{\n  checkResource: function(resource)\n  {\n    const lazyImports =\n    [\n        '@nestjs/microservices',\n        '@nestjs/microservices/microservices-module',\n        'cache-manager',\n        'class-transformer',\n        'class-validator',\n        'fastify-static',\n    ];\n  \n    if (!lazyImports.includes(resource))\n      return false;\n\n    try\n    {\n      require.resolve(resource);\n    }\n    catch (err)\n    {\n      return true;\n    }\n  \n    return false;\n  }\n};\n\nmodule.exports =\n{\n  mode: 'production',\n  target: 'node',\n  entry:\n  {\n    server: './src/main.ts',\n  },\n  devtool: 'source-map',\n  module:\n  {\n    rules:\n    [\n      {\n        test: /\\.tsx?$/,\n        use: 'ts-loader',\n        exclude: /node_modules/,\n      },\n    ],\n  },\n  resolve:\n  {\n    extensions: [ '.tsx', '.ts', '.js' ],\n  },\n  node: {\n    __dirname: false,\n  },\n  plugins:\n  [\n    new CleanWebpackPlugin(),\n    new webpack.IgnorePlugin(WebPackIgnorePlugin),\n  ],\n  optimization:\n  {\n    minimize: false\n  },\n  performance:\n  {\n    maxEntrypointSize: 1000000000,\n    maxAssetSize: 1000000000\n  },\n  output:\n  {\n    filename: '[name].js',\n    path: path.resolve(__dirname, 'prod'),\n  },\n};\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nIgnorePlugin\n```\n\n```text\ncheckResource()\n```\n\n```text\ntarget: node\n```\n\n```text\nfs\n```\n\n```text\nnet\n```\n\n```text\nconst nodeExternals = require('webpack-node-externals');\nvar terserPlugin = require('terser-webpack-plugin');\nvar uglifyJsPlugin = require('uglifyjs-webpack-plugin');\nvar dotEnvPlugin = require('dotenv-webpack');\n\nmodule.exports = function(options) {\n    return {\n        ...options,\n        entry: [ './src/main.ts'],\n        watch: false,\n        resolve: {\n            extensions: ['.ts', '.js', '.jade']\n        },\n        externals: [\n            nodeExternals(),\n        ],\n        module: {\n            rules: [\n                ...options.module.rules,\n                {\n                    test: /\\.handlebars$/,\n                    loader: 'handlebars-loader',\n                    options: {\n                        knownHelpersOnly: false,\n                        inlineRequires: /\\/assets\\/(:?images|audio|video)\\//ig,\n                        partialDirs: [path.join(__dirname, './src/views/email/partials')],\n                    },\n                }\n            ]\n        },\n        plugins: [\n            ...options.plugins,\n            new webpack.HotModuleReplacementPlugin(),\n            new webpack.WatchIgnorePlugin([/\\.js$/, /\\.d\\.ts$/]),\n            new dotEnvPlugin({\n                path: './config/development/.env',\n                safe: true,\n                systemvars: true,\n                silent: true,\n                defaults: false\n            }), new webpack.DefinePlugin({\n                'process.env.NODE_ENV': 'dev',\n                'process.env.DEBUG': 'debug'\n            }),new webpack.WatchIgnorePlugin([/\\.js$/, /\\.d\\.ts$/]),\n        ],\n    };\n};\n```\n\n```text\nnpm run build:webpack:dev\n```\n\n```text\n\"build\": \"npx tsdk --nest build\",\n```\n\n```text\nnpm run build\n```\n\n```text\ndist-projects\n```\n\n========================================\n\nComments:\n- hej, I have the same problem. I want to build my application with all it's dependencies . Have you found the answer?","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":930,"estimatedTokens":8049}}229{"id":"stack-58824401","source":"stackoverflow","questionId":58824401,"title":"Disable status 201 for all POSTs in NestJS","tags":["javascript","node.js","nestjs"],"text":"Title: Disable status 201 for all POSTs in NestJS\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy client expects all successful status codes to equal 200. However NestJS uses 201 by default for all POST methods. How do I disable 201 for POSTs application wide? Not for one method but for the entire app.\n\n========================================\n\nTop Answer:\nYou should specify status codes for every controller\n\nAccording official docs https://docs.nestjs.com/controllers#status-code\n\n Furthermore, the response's status code is always 200 by default,\n except for POST requests which use 201. We can easily change this\n behavior by adding the @HttpCode(...) decorator at a handler-level\n (see Status codes).\n\n```\n@Post()\n@HttpCode(200)\ncreate() {\n return 'This action adds data';\n}\n```\n\nAlso nestjs has another way which depends on library (express/fastify):\n\n We can use the library-specific (e.g., Express) response object, which\n can be injected using the @Res() decorator in the method handler\n signature (e.g., findAll(@Res() response)). With this approach, you\n have the ability (and the responsibility), to use the native response\n handling methods exposed by that object. For example, with Express,\n you can construct responses using code like\n response.status(200).send()\n\n**But if it's possible I recommend to use Reponse.ok to indetify success Response on the client side**\n\n========================================\n\nCode:\n```js\nimport { CallHandler, ExecutionContext, Injectable, HttpStatus } from '@nestjs/common';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class PostStatusInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler) {\n    const ctx = context.switchToHttp();\n    const req = ctx.getRequest();\n    const res = ctx.getResponse();\n    return next.handle().pipe(\n      map(value => {\n        if (req.method === 'POST') {\n          if (res.statusCode === HttpStatus.CREATED) {\n            res.status(HttpStatus.OK);\n          }\n        }\n        return value;\n      }),\n    );\n  }\n}\n```\n\n```text\nHttpCode()\n```\n\n```text\npipe\n```\n\n```text\n@Post()\n@HttpCode(200)\ncreate() {\n  return 'This action adds data';\n}\n```\n\n```text\nimport {\n  CallHandler,\n  ExecutionContext,\n  HttpStatus,\n  Injectable,\n  NestInterceptor,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class PostInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const request = context.switchToHttp().getRequest<Request>();\n    const response = context.switchToHttp().getResponse<Response>();\n\n    if (request.method === 'POST') {\n       if (response.status === 201)\n          context.switchToHttp().getResponse().status(HttpStatus.OK);\n    }\n    return next.handle();\n  }\n}\n```\n\n```text\n....\n@Module({\n   ...\n   providers: [{\n      provide: APP_INTERCEPTOR,\n      useClass: PostInterceptor\n }]\n}\n```\n\n========================================\n\nComments:\n- Why are you ignoring the question? It clearly says \"Not for one method but for the entire app.\"\n- I didn't ignore the question. The second half of my response tells you exactly what to do in the case of using an interceptor. Even in Express, which nest is built on, you have to explicitly set the status to 200 instead of 201\n- In actuallity I was fine with 201. But I am worried that my client might not understand it. So I wanted to make sure I can disable it if it will not work. The client is yet to be written and I don't know what to expect from their devs. It feels risky.\n- I usually tell the front end guys \"You get what you're given\" X'D they always want \"All the things\" and never want to implement pagination. To which I say \"I've implemented pagination for a reason. Use it\"\n- response.status is read-only. it can not be changed.\n- the fastest way to change the status is: context.switchToHttp().getResponse().status(HttpStatus.OK);\n- That looks a bit aggressive though. I mean if an individual action chooses a specific status then it will be overwritten. Especially in case of 404 and other errors handling but also possible redirects and so on.\n- @Gherman, true, you can add a check to only do this for status 201. Updated*\n- In my case, I use express, so `response.statusCode === 201` works instead of `response.status === 201`.\n- In this way all post will be changed in 201, also real create entity. So I don't suggest and I think that it is better and having more control with decorator","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":131,"estimatedTokens":1126}}230{"id":"stack-59140468","source":"stackoverflow","questionId":59140468,"title":"nest bull separate process for queues and api","tags":["node.js","typescript","nestjs","bull.js"],"text":"Title: nest bull separate process for queues and api\nTags: node.js, typescript, nestjs, bull.js\nSource: Stack Overflow\n\nQuestion:\nI have a `nestjs` application which is exposing a few REST `API`s. One of the `API`s triggers a job which processes some tasks. The problem is that when the job gets triggered the application stops serving REST requests which leads to health check failures from load balancer. I followed the method given at the end of the README to start a separate child process for processing jobs. But, the job doesn't start in a child process and the `API` requests stall.\n\nHere's my Job:\n\n```\nimport {\n BullQueueEvents,\n OnQueueActive,\n OnQueueEvent,\n Process,\n Processor,\n} from 'nest-bull';\nimport { Job } from 'bull';\nimport { Logger } from '@nestjs/common';\nimport { AService } from './a-service';\nimport { AJobInterface } from '../AJobInterface';\n\n@Processor({ name: 'a_queue' })\nexport class AJob {\n private readonly logger = new Logger('AQueue');\n\n constructor(private readonly service: AService) {}\n\n @Process({\n name: 'app',\n concurrency: 1\n })\n processApp(job: Job) {\n console.log('CHILD: ', process.pid);\n const { jobId } = job.data;\n return this.service.process(jobId);\n }\n\n @OnQueueActive()\n onActive(job: Job) {\n this.logger.log(\n `Processing job ${job.id} of type ${job.name} with data ${JSON.stringify(\n job.data,\n )}...`,\n );\n }\n\n @OnQueueEvent(BullQueueEvents.COMPLETED)\n onCompleted(job: Job) {\n this.logger.log(\n `Completed job ${job.id} of type ${job.name} with result ${job.returnvalue}`,\n );\n }\n}\n```\n\nHere's my app.module.ts:\n\n```\nimport { Module, OnModuleInit } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { DatabaseModule } from './db/module';\nimport { BullModule } from 'nest-bull';\nimport { AJob } from './worker/a-job';\nimport { AService } from './worker/a-service';\nimport { join } from 'path';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n DatabaseModule,\n BullModule.register({\n name: 'a_queue',\n processors: [ join(__dirname, 'worker/a-job.js') ],\n options: {\n redis: {\n host: process.env.REDIS_URL || '127.0.0.1',\n port: 6379,\n showFriendlyErrorStack: true,\n },\n settings: {\n lockDuration: 300000,\n stalledInterval: 300000\n },\n },\n }),\n ],\n controllers: [AppController],\n providers: [AppService, AJob, AService],\n})\nexport class AppModule implements OnModuleInit {\n onModuleInit() {\n console.log('MAIN: ', process.pid);\n }\n}\n```\n\nIs there anything that I'm doing wrong?\n\n========================================\n\nCode:\n```text\nimport {\n  BullQueueEvents,\n  OnQueueActive,\n  OnQueueEvent,\n  Process,\n  Processor,\n} from 'nest-bull';\nimport { Job } from 'bull';\nimport { Logger } from '@nestjs/common';\nimport { AService } from './a-service';\nimport { AJobInterface } from '../AJobInterface';\n\n@Processor({ name: 'a_queue' })\nexport class AJob {\n  private readonly logger = new Logger('AQueue');\n\n  constructor(private readonly service: AService) {}\n\n  @Process({\n    name: 'app',\n    concurrency: 1\n  })\n  processApp(job: Job<AJobInterface>) {\n    console.log('CHILD: ', process.pid);\n    const { jobId } = job.data;\n    return this.service.process(jobId);\n  }\n\n  @OnQueueActive()\n  onActive(job: Job) {\n    this.logger.log(\n      `Processing job ${job.id} of type ${job.name} with data ${JSON.stringify(\n        job.data,\n      )}...`,\n    );\n  }\n\n  @OnQueueEvent(BullQueueEvents.COMPLETED)\n  onCompleted(job: Job) {\n    this.logger.log(\n      `Completed job ${job.id} of type ${job.name} with result ${job.returnvalue}`,\n    );\n  }\n}\n```\n\n```text\nimport { Module, OnModuleInit } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { DatabaseModule } from './db/module';\nimport { BullModule } from 'nest-bull';\nimport { AJob } from './worker/a-job';\nimport { AService } from './worker/a-service';\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    DatabaseModule,\n    BullModule.register({\n      name: 'a_queue',\n      processors: [ join(__dirname, 'worker/a-job.js') ],\n      options: {\n        redis: {\n          host: process.env.REDIS_URL || '127.0.0.1',\n          port: 6379,\n          showFriendlyErrorStack: true,\n        },\n        settings: {\n          lockDuration: 300000,\n          stalledInterval: 300000\n        },\n      },\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService, AJob, AService],\n})\nexport class AppModule implements OnModuleInit {\n  onModuleInit() {\n    console.log('MAIN: ', process.pid);\n  }\n}\n```\n\n```text\nnestjs\n```\n\n```text\nAPI\n```\n\n```text\nAPI\n```\n\n```text\nAPI\n```\n\n```text\nimport { Module, OnModuleInit } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppService } from '../app.service';\nimport { DatabaseModule } from '../db/module';\nimport { BullModule } from 'nest-bull';\nimport { AJob } from './a-job';\nimport { AService } from './a-service';\nimport { join } from 'path';\nimport { Job, DoneCallback } from 'bull';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    DatabaseModule,\n    BullModule.register({\n      name: 'a_queue',\n      processors: [ (job: Job, done: DoneCallback) => { done(null, job.data); } ],\n      options: {\n        redis: {\n          host: process.env.REDIS_URL || '127.0.0.1',\n          port: 6379,\n          password: process.env.REDIS_PWD,\n          showFriendlyErrorStack: true,\n        },\n        settings: {\n          lockDuration: 300000,\n          stalledInterval: 300000\n        },\n      },\n    }),\n  ],\n  providers: [AppService, AJob, AService],\n})\nexport class WorkerModule implements OnModuleInit {\n  onModuleInit() {\n    console.log('WORKER: ', process.pid);\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { WorkerModule } from './worker/worker.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(WorkerModule);\n  app.init();\n}\n\nbootstrap();\n```\n\n```text\n//...imports\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    DatabaseModule,\n    BullModule.register({\n      name: 'a_queue',\n      processors: [ ],\n      options: {\n        redis: {\n          host: process.env.REDIS_URL || '127.0.0.1',\n          port: 6379,\n          showFriendlyErrorStack: true,\n        },\n      },\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule implements OnModuleInit {\n  onModuleInit() {\n    console.log('MAIN: ', process.pid);\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { port } from './config';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.enableCors();\n  await app.listen(port);\n}\n\nbootstrap();\n```\n\n```text\nworker.module.ts\n```\n\n```text\nworker.ts\n```\n\n```text\nworker.module.ts\n```\n\n```text\nworker.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\napp.ts\n```\n\n========================================\n\nComments:\n- dumb question but: how do you start both `worker.ts` and `app.ts` with next cli? I mean, if i do `npm start`, only main.ts is executed. I could not find how to pass the entry point to nest cli. Somehing like `npm start -entry-point worker.ts` Or did you move to a 'monorepo' config in `nest-cli`. Thanks\n- Hi @JesusMonzonLegido you can use something like pm2 or supervisor to spin up next process\n- @ujwaldhakal thanks. Yes, I had it integrated it with pm2. For development, I had 2 `nest-cli.json` files with different \"entryFile\" . I started each with something like `NODE_ENV=development nest start --watch --config nest-cli-worker.json`","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":333,"estimatedTokens":1931}}231{"id":"stack-66214269","source":"stackoverflow","questionId":66214269,"title":"Nestjs readFileSync return Cannot read property 'readFileSync' of undefined","tags":["node.js","nestjs","readfile"],"text":"Title: Nestjs readFileSync return Cannot read property 'readFileSync' of undefined\nTags: node.js, nestjs, readfile\nSource: Stack Overflow\n\nQuestion:\nI trying get file using method `readFileSync`:\n\n```\nimport fs from 'fs';\nimport path from 'path';\n\nconst templateFile = fs.readFileSync(\n path.resolve(\n __dirname,\n '../mail/templates/exampleTemplate.html',\n ),\n 'utf-8',\n);\n```\n\nNest still return me error:\n\nTypeError: Cannot read property 'readFileSync' of undefined\n\nI tryied used to path: `./templates/exampleTemplate.html`, but result is the same\n\nI have a structure file:\n\nhttps://i.sstatic.net/xWAU8.png\n\n========================================\n\nTop Answer:\nTry\n\n```\nimport {readFileSync} from 'fs'\n```\n\n========================================\n\nCode:\n```text\nimport fs from 'fs';\nimport path from 'path';\n\nconst templateFile = fs.readFileSync(\n    path.resolve(\n    __dirname,\n    '../mail/templates/exampleTemplate.html',\n    ),\n    'utf-8',\n);\n```\n\n```text\nreadFileSync\n```\n\n```text\n./templates/exampleTemplate.html\n```\n\n```js\nimport * as fs from 'fs'\n```\n\n```text\nfs\n```\n\n```text\nimport fs from 'fs';\nimport path from 'path';\n```\n\n```text\nimport fs = require('fs');\nimport path = require('path');\n```\n\n```text\nimport {readFileSync} from 'fs'\n```\n\n========================================\n\nComments:\n- How are you requiring the `fs` module? Can you the code with the `require` statement?\n- `import fs from 'fs';`\n- @ArunKumarMohan Your query is very helpful, I change `import` to `require`, and now get file work correctly. Thanks ;)\n- You're welcome. You can use `import` but it has to use a different syntax. I've explained in my answer.\n- How is NextJS able to allow typescript files importing fs the normal way such as `import fs from 'fs'`?, is it through tsconfig.json?","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":93,"estimatedTokens":446}}232{"id":"stack-68689281","source":"stackoverflow","questionId":68689281,"title":"Nest.js Testing Error: Using the \"extends Logger\" instruction is not allowed in Nest v8. Please, use \"extends ConsoleLogger\" instead","tags":["node.js","testing","nestjs","e2e-testing"],"text":"Title: Nest.js Testing Error: Using the \"extends Logger\" instruction is not allowed in Nest v8. Please, use \"extends ConsoleLogger\" instead\nTags: node.js, testing, nestjs, e2e-testing\nSource: Stack Overflow\n\nQuestion:\nHere's the problem I have:\n\nI am using my custom Logger in Nest.js:\n\n```\nexport class ReportLogger extends ConsoleLogger {\n verbose(message: string) {\n console.log('ใ€Verboseใ€‘Reporting', message);\n super.verbose.apply(this, arguments);\n }\n\n log(message: string) {\n console.log('ใ€Logใ€‘Reporting', message);\n super.log.apply(this, arguments);\n }\n}\n```\n\nAnd the `log.interceptor.ts` file:\n\n```\nexport class LogInterceptor implements NestInterceptor {\n constructor(private reportLogger: ReportLogger) {\n this.reportLogger.setContext('LogInterceptor');\n }\n\n intercept(context: ExecutionContext, next: CallHandler) {\n const http = context.switchToHttp();\n const request = http.getRequest();\n\n const now = Date.now();\n return next\n .handle()\n .pipe(\n tap(() =>\n this.reportLogger.log(\n `${request.method} ${request.url} ${Date.now() - now}ms`,\n ),\n ),\n );\n }\n}\n```\n\nAnd here's the `main.ts` file:\n\n```\nasync function bootstrap() {\n const reportLogger = new ReportLogger();\n\n const app = await NestFactory.create(AppModule, {\n cors: {\n origin: ['http://localhost', 'http://localhost:3000'],\n credentials: true,\n },\n bufferLogs: true,\n logger: reportLogger,\n });\n\n app.useGlobalInterceptors(\n new LogInterceptor(reportLogger),\n );\n\n setupSwagger(app);\n\n await app.listen(4200);\n}\n```\n\nWhen I run `npm run start:dev` to run the Nest App on dev, everything works fine. But when I run `npm run test:e2e` or `npm run test` on testing, it shows this error:\n\n```\nUsing the \"extends Logger\" instruction is not allowed in Nest v8. Please, use \"extends ConsoleLogger\" instead.\n\n 10 | const moduleFixture: TestingModule = await Test.createTestingModule({\n 11 | imports: [AppModule],\n > 12 | }).compile();\n | ^\n 13 |\n 14 | app = moduleFixture.createNestApplication();\n 15 | await app.init();\n```\n\nI read the Nest.js doc again, and found the Logging breaking change in the docs. But the question is I have already made my ReportLogger extends ConsoleLogger, why this error shows again? And why it only shows in testing?\n\n========================================\n\nTop Answer:\neven with `\"@nestjs/testing\": \"^8.0.7\"` this issue still occurs\n\n```\nclass Logger implements LoggerService { ... }\n\nawait Test.createTestingModule({\n imports: [ApiModule],\n})\n .setLogger(new Logger())\n .compile();\n```\n\nsetting logger instance solves that error on my side\n\n========================================\n\nCode:\n```js\nexport class ReportLogger extends ConsoleLogger {\n  verbose(message: string) {\n    console.log('ใ€Verboseใ€‘Reporting', message);\n    super.verbose.apply(this, arguments);\n  }\n\n  log(message: string) {\n    console.log('ใ€Logใ€‘Reporting', message);\n    super.log.apply(this, arguments);\n  }\n}\n```\n\n```text\nexport class LogInterceptor implements NestInterceptor {\n  constructor(private reportLogger: ReportLogger) {\n    this.reportLogger.setContext('LogInterceptor');\n  }\n\n  intercept(context: ExecutionContext, next: CallHandler) {\n    const http = context.switchToHttp();\n    const request = http.getRequest();\n\n    const now = Date.now();\n    return next\n      .handle()\n      .pipe(\n        tap(() =>\n          this.reportLogger.log(\n            `${request.method} ${request.url} ${Date.now() - now}ms`,\n          ),\n        ),\n      );\n  }\n}\n```\n\n```text\nasync function bootstrap() {\n  const reportLogger = new ReportLogger();\n\n  const app = await NestFactory.create<NestExpressApplication>(AppModule, {\n    cors: {\n      origin: ['http://localhost', 'http://localhost:3000'],\n      credentials: true,\n    },\n    bufferLogs: true,\n    logger: reportLogger,\n  });\n\n  app.useGlobalInterceptors(\n    new LogInterceptor(reportLogger),\n  );\n\n  setupSwagger(app);\n\n  await app.listen(4200);\n}\n```\n\n```text\nUsing the \"extends Logger\" instruction is not allowed in Nest v8. Please, use \"extends ConsoleLogger\" instead.\n\n      10 |     const moduleFixture: TestingModule = await Test.createTestingModule({\n      11 |       imports: [AppModule],\n    > 12 |     }).compile();\n         |        ^\n      13 |\n      14 |     app = moduleFixture.createNestApplication();\n      15 |     await app.init();\n```\n\n```text\nlog.interceptor.ts\n```\n\n```text\nmain.ts\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nnpm run test:e2e\n```\n\n```text\nnpm run test\n```\n\n```text\nnpm i @nestjs/testing@latest\n```\n\n```text\nnpm i @nestjs/testing@8.0.6 // <--- Change the NestJS version here\n```\n\n```text\n@nestjs/testing\n```\n\n```text\nclass Logger implements LoggerService { ... }\n\nawait Test.createTestingModule({\n  imports: [ApiModule],\n})\n  .setLogger(new Logger())\n  .compile();\n```\n\n```text\n\"@nestjs/testing\": \"^8.0.7\"\n```\n\n========================================\n\nComments:\n- did you upgrade `@nestjs&#47;testing` as well?","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":233,"estimatedTokens":1221}}233{"id":"stack-61306329","source":"stackoverflow","questionId":61306329,"title":"Nestjs Error: Cannot find module './app.controller'","tags":["node.js","angular","typescript","controller","nestjs"],"text":"Title: Nestjs Error: Cannot find module './app.controller'\nTags: node.js, angular, typescript, controller, nestjs\nSource: Stack Overflow\n\nQuestion:\nI cant seem to locate where the error is coming from as the app compiled with `Found 0 errors. Watching for file changes.` I have seen similar resolve on StackOverflow but none seem to address the issue\n\nHere is the stack trace\n\n```\ninternal/modules/cjs/loader.js:797\n throw err;\n ^\n\nError: Cannot find module './app.controller'\nRequire stack:\n- C:\\Users\\DELL\\Documents\\DokunFiles\\Nestjs\\app\\api\\dist\\src\\app.module.js\n- C:\\Users\\DELL\\Documents\\DokunFiles\\Nestjs\\app\\api\\dist\\src\\main.js\n```\n\nWith the appModule below, the app controller is properly imported into the app module\n\napp.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\n\n@Module({\n imports: [MongooseModule.forRoot(process.env.MONGO_URI,\n {\n useNewUrlParser: true,\n useUnifiedTopology: true\n })\n , UserModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\napp.controller.ts\n\n```\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get()\n getHello(): string {\n return this.appService.getHello();\n }\n}\n```\n\n========================================\n\nTop Answer:\nLook for `\"incremental\": true` in your `tsconfig.json` file. The true makes incremental updates. Setting it to false hopefully will save you having to clean `dist` every time\n\n========================================\n\nCode:\n```text\ninternal/modules/cjs/loader.js:797\n    throw err;\n    ^\n\nError: Cannot find module './app.controller'\nRequire stack:\n- C:\\Users\\DELL\\Documents\\DokunFiles\\Nestjs\\app\\api\\dist\\src\\app.module.js\n- C:\\Users\\DELL\\Documents\\DokunFiles\\Nestjs\\app\\api\\dist\\src\\main.js\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\n\n\n@Module({\n  imports: [MongooseModule.forRoot(process.env.MONGO_URI,\n    {\n      useNewUrlParser: true,\n      useUnifiedTopology: true\n    })\n    , UserModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getHello(): string {\n    return this.appService.getHello();\n  }\n}\n```\n\n```text\nFound 0 errors. Watching for file changes.\n```\n\n```text\nnpm run prebuild\n```\n\n```text\nrimraf dist\n```\n\n```text\nrm -rf dist/\n```\n\n```text\nstanislas@yeji > nest start                                                                                                    api -> master ! ? RC=130\ninternal/modules/cjs/loader.js:983\n  throw err;\n  ^\n\nError: Cannot find module './app.controller'\nRequire stack:\n- /Users/stanislas/git/soundbase/api/dist/src/app.module.js\n- /Users/stanislas/git/soundbase/api/dist/src/main.js\n    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)\n    at Function.Module._load (internal/modules/cjs/loader.js:862:27)\n    at Module.require (internal/modules/cjs/loader.js:1042:19)\n    at require (internal/modules/cjs/helpers.js:77:18)\n    at Object.<anonymous> (/Users/stanislas/git/soundbase/api/dist/src/app.module.js:13:26)\n    at Module._compile (internal/modules/cjs/loader.js:1156:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)\n    at Module.load (internal/modules/cjs/loader.js:1000:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:899:14)\n    at Module.require (internal/modules/cjs/loader.js:1042:19) {\n  code: 'MODULE_NOT_FOUND',\n  requireStack: [\n    '/Users/stanislas/git/soundbase/api/dist/src/app.module.js',\n    '/Users/stanislas/git/soundbase/api/dist/src/main.js'\n  ]\n}\n```\n\n```text\nstanislas@yeji > ll dist/src/                                                                      api -> master ! ?\ntotal 48\n-rw-r--r--  1 stanislas  staff   138B Apr 19 17:45 app.module.d.ts\n-rw-r--r--  1 stanislas  staff   2.1K Apr 19 17:45 app.module.js\n-rw-r--r--  1 stanislas  staff   753B Apr 19 17:45 app.module.js.map\n-rw-r--r--  1 stanislas  staff    11B Apr 19 17:45 main.d.ts\n-rw-r--r--  1 stanislas  staff   340B Apr 19 17:45 main.js\n-rw-r--r--  1 stanislas  staff   290B Apr 19 17:45 main.js.map\ndrwxr-xr-x  5 stanislas  staff   160B Apr 19 17:52 migration\n```\n\n```text\nstanislas@yeji > npm run build && npm run start:prod                                                                             api -> master ! ? RC=1\n\n> soundbase-api@0.0.1 prebuild /Users/stanislas/git/soundbase/api\n> rimraf dist\n\n\n> soundbase-api@0.0.1 build /Users/stanislas/git/soundbase/api\n> nest build\n\n\n> soundbase-api@0.0.1 start:prod /Users/stanislas/git/soundbase/api\n> node dist/main\n\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [NestFactory] Starting Nest application...\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] PassportModule dependencies initialized +34ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] JwtModule dependencies initialized +1ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] AuthModule dependencies initialized +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] AppModule dependencies initialized +1ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] TypeOrmCoreModule dependencies initialized +56ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [InstanceLoader] UsersModule dependencies initialized +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RoutesResolver] AppController {}: +3ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/auth/login, POST} route +3ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/profile, GET} route +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RoutesResolver] UserController {/users}: +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/users, POST} route +1ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/users, GET} route +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/users/:id, GET} route +1ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/users/:id, PUT} route +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [RouterExplorer] Mapped {/users/:id, DELETE} route +0ms\n[Nest] 95175   - 04/19/2020, 6:40:45 PM   [NestApplication] Nest application successfully started +2ms\n```\n\n```text\nstanislas@yeji > npm start                                                                                                     api -> master ! ? RC=130\n\n> soundbase-api@0.0.1 start /Users/stanislas/git/soundbase/api\n> nest start\n\n[Nest] 95255   - 04/19/2020, 6:41:00 PM   [NestFactory] Starting Nest application...\n[Nest] 95255   - 04/19/2020, 6:41:00 PM   [InstanceLoader] PassportModule dependencies initialized +35ms\n[Nest] 95255   - 04/19/2020, 6:41:00 PM   [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 95255   - 04/19/2020, 6:41:00 PM   [InstanceLoader] JwtModule dependencies initialized +0ms\n[Nest] 95255   - 04/19/2020, 6:41:00 PM   [InstanceLoader] AuthModule dependencies initialized +1ms\n[Nest] 95255   - 04/19/2020, 6:41:00 PM   [InstanceLoader] AppModule dependencies initialized +0ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [InstanceLoader] TypeOrmCoreModule dependencies initialized +56ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [InstanceLoader] UsersModule dependencies initialized +1ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RoutesResolver] AppController {}: +3ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/auth/login, POST} route +2ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/profile, GET} route +1ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RoutesResolver] UserController {/users}: +0ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/users, POST} route +1ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/users, GET} route +0ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/users/:id, GET} route +0ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/users/:id, PUT} route +1ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [RouterExplorer] Mapped {/users/:id, DELETE} route +0ms\n[Nest] 95255   - 04/19/2020, 6:41:01 PM   [NestApplication] Nest application successfully started +2ms\n```\n\n```text\nprod\n```\n\n```text\nnest build && node dist/main.js\n```\n\n```text\nnpm run prebuild\n```\n\n```text\nrimraf dist\n```\n\n```text\nrm -rf dist/\n```\n\n```text\ndist\n```\n\n```text\n\"incremental\": true\n```\n\n```text\ntsconfig.json\n```\n\n```text\ndist\n```\n\n```text\nnest g library my-library\n```\n\n```text\nnpm run prebuild\n```\n\n========================================\n\nComments:\n- That's weird, I'm encountering the same error. Glad i'm not the only one. I noticed the controller is not compiled in the dist/src folder.\n- I had the same issue. running `prebuild` solved it for me as well. Maybe a bug?\n- I did what you suggested so I got `Nest can't resolve dependencies of the UserService (?). Please make sure that the argument UserModel at index [0] is available in the UserModule context. Potential solutions: - If UserModel is a provider, is it part of the current UserModule? - If UserModel is exported from a separate @Module, is that module imported within UserModule? @Module({ imports: [ &#47;* the Module containing UserModel *&#47; ] })`\n- It's working now. After running the command, I got the above error the I reference this link on StackOverflow stackoverflow.com/questions/56870498/&hellip;. Thanks man\n- So incremental would save just time locally developing the app since it would compile faster? Btw. this worked for a similar bug in my nestjs application :D","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":290,"estimatedTokens":2633}}234{"id":"stack-64864783","source":"stackoverflow","questionId":64864783,"title":"How to add a route prefix to specific modules using NestJS?","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: How to add a route prefix to specific modules using NestJS?\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to add routing prefixes at the module level and/or have complex global routing prefix logic in general.\n\nI know I can use the undocumented function `NestApplication.setGlobalPrefix` to set a single global prefix:\n\n```\n// main.ts\napp.setGlobalPrefix(version);\n```\n\nHowever, I want to set prefixes at the module level in this case.\n\nIt appears I could achieve this by setting my desired prefix into the decorators at the controller level:\n\n```\n//controler.ts\n@Get('/PREFIX/health')\nasync getHealth() {\n\n // TODO: implement\n return {};\n}\n```\n\nBut this seems fairly hacky and error-prone. Surely there is a better way?\n\n========================================\n\nTop Answer:\nFor me, adding a third party package just to achieve this would be a bit unnecessary, let alone the risk of it being outdated/unmaintained. You can add your custom route prefix in the `Controller` class instead.\n\n```\n@Controller('custom/prefix')\n export const MyController {\n\n @Get('health')\n getHealth() {\n //this route would be: custom/prefix/health\n return {};\n }\n\n @Get('other')\n getOther() {\n //this route would be: custom/prefix/other\n return {};\n }\n }\n```\n\nThen just simply add this controller inside your `Module`\n\n========================================\n\nCode:\n```text\n// main.ts\napp.setGlobalPrefix(version);\n```\n\n```text\n//controler.ts\n@Get('/PREFIX/health')\nasync getHealth() {\n\n  // TODO: implement\n  return {};\n}\n```\n\n```text\nNestApplication.setGlobalPrefix\n```\n\n```js\n@Controller({\n  path: 'cats',\n  version: '1', // ๐Ÿ‘ˆ\n})\nexport class CatsController {\n...\n```\n\n```sh\nyarn add nest-router\n# or npm i nest-router\n```\n\n```text\nimport { Routes } from 'nest-router';\nimport { YourModule } from './your/your.module';\n\nexport const routes: Routes = [\n  {\n    path: '/v1',\n    module: YourModule,\n  },\n];\n```\n\n```text\n@Module({\n  imports: [\n    RouterModule.forRoutes(routes),\n    YourModule,\n    DebugModule\n  ],\n\n})\n```\n\n```sh\ncurl http://localhost:3000/v1/your/operation\n```\n\n```text\nmain.ts\n```\n\n```text\nroutes.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nYourModule\n```\n\n```text\nv1\n```\n\n```text\n@Controller('custom/prefix')\n  export const MyController {\n\n     @Get('health')\n     getHealth() {\n       //this route would be: custom/prefix/health\n       return {};\n     }\n\n     @Get('other')\n     getOther() {\n       //this route would be: custom/prefix/other\n       return {};\n     }\n  }\n```\n\n```text\nController\n```\n\n```text\nModule\n```\n\n```text\nimport { applyDecorators, Controller } from '@nestjs/common'\n\nexport function SystemController(path: string) {\n  return applyDecorators(Controller(`system/${path}`))\n}\n```\n\n```text\n// system/action module example\nimport { BaseController } from 'src/shared/providers/base.controller'\nimport { ActionsService } from './actions.service'\nimport { Action } from './entities/action.entity'\nimport { SystemController } from 'src/shared/decorators'\n\n@SystemController('actions')\nexport class ActionsController extends BaseController<Action> {\n  constructor(private readonly actionsService: ActionsService) {\n    super(actionsService)\n  }\n}\n```\n\n========================================\n\nComments:\n- It seems package is outdated.","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":191,"estimatedTokens":828}}235{"id":"stack-66169705","source":"stackoverflow","questionId":66169705,"title":"Bundle a NestJS + TypeORM application (with webpack)","tags":["nestjs","typeorm","bundling-and-minification"],"text":"Title: Bundle a NestJS + TypeORM application (with webpack)\nTags: nestjs, typeorm, bundling-and-minification\nSource: Stack Overflow\n\nQuestion:\nI recently have to think about a deployment method for a new piece of software that is written with:\n\n- NestJS 6 / Express\n\n- TypeORM 0.2\n\n- TypeScript is used\n\nThe software will be deployed on more than 160 servers, distributed all across Europe, and some of them have very bad Internet connections.\n\nI did some research and a lot of people explicitly advices **against** bundling. The main argument is that native extension will fails with bundlers like `webpack` or `rollup` (Spoiler: it's true, but there is a solution). In my opinion, it's largely due to the fact that people don't care for this: the author of `node-pre-gyp` used nearly the same words for this use case. So usually, I was told to either use `yarn install` or sync the `node_modules/` folder.\n\nThe project is new, but the `node_modules/` folder is already more than 480 MB. Using XZ with maximum compression gave me an archive of 20 MB. This is still way too large for me, and seems like a huge waste of resources.\n\nI also had a look at the following Q&A:\n\n- How to correctly build NestJS app for production with node_modules dependencies in bundle? Explains that NestJS support webpack **without** `node_modules/` out of the box.\n\n- Single file bundle with NestJS + Typescript + Webpack + node_modules Working answer, without further explanations. Also `IgnorePlugins` seems to be overkill.\n\n- How to bundle nestjs application with webpack Seems to copy/paste a working solution from ZenSoftware without quoting. Links to another answer.\n\n- NestJS optimization minimize not work with webpack Give an advice to disable minimization with NestJS application\n\nThere are also some separate Q&A for TypeORM, but all of them seems to require the installation of `ts-node` or `typescript`:\n\n- TypeORM + Webpack causes SyntaxError: Unexpected token for entity file\n\n- Isomoprhic application, problem with TypeORM && TypeScript && Express && Webpack setup\n\n- SyntaxError: Unexpected token import typeORM entity\n\n========================================\n\nCode:\n```text\nwebpack\n```\n\n```text\nrollup\n```\n\n```text\nnode-pre-gyp\n```\n\n```text\nyarn install\n```\n\n```text\nnode_modules/\n```\n\n```text\nnode_modules/\n```\n\n```text\nnode_modules/\n```\n\n```text\nIgnorePlugins\n```\n\n```text\nts-node\n```\n\n```text\ntypescript\n```\n\n```js\nentry: {\n    main: './src/main.ts',\n    console: \"./src/console.ts\",\n    'data-source': {\n      import: './src/data-source.ts',\n      library: {\n        type: 'commonjs2'\n      }\n    },\n    typeorm:  './node_modules/typeorm/cli.js',\n  },\n```\n\n```text\nwebpack.config.js\nwebpack\nโ”œโ”€โ”€ migrations.config.js\nโ””โ”€โ”€ typeorm-cli.config.js\n```\n\n```js\n// webpack.config.js\nconst { NODE_ENV = 'production' } = process.env;\n\nconsole.log(`-- Webpack <${NODE_ENV}> build --`);\n\nmodule.exports = {\n  target: 'node',\n  mode: NODE_ENV,\n  externals: [\n    // Here are listed all optional dependencies of NestJS,\n    // that are not installed and not required by my project\n    {\n      'fastify-swagger': 'commonjs2 fastify-swagger',\n      'aws-sdk': 'commonjs2 aws-sdk',\n      '@nestjs/websockets/socket-module': 'commonjs2 @nestjs/websockets/socket-module',\n      '@nestjs/microservices/microservices-module': 'commonjs2 @nestjs/microservices/microservices-module',\n      \n      // I'll skip pg-native in the production deployement, and use the pure JS implementation\n      'pg-native': 'commonjs2 pg-native'\n    }\n  ],\n  optimization: {\n    // Minimization doesn't work with @Module annotation\n    minimize: false,\n  }\n};\n```\n\n```js\n// webpack/typeorm-cli.config.js\n\nconst path = require('path');\n// TypeScript compilation option\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');\n// Don't try to replace require calls to dynamic files\nconst IgnoreDynamicRequire = require('webpack-ignore-dynamic-require');\n\nconst { NODE_ENV = 'production' } = process.env;\n\nconsole.log(`-- Webpack <${NODE_ENV}> build for TypeORM CLI --`);\n\nmodule.exports = {\n  target: 'node',\n  mode: NODE_ENV,\n  entry: './node_modules/typeorm/cli.js',\n  output: {\n    // Remember that this file is in a subdirectory, so the output should be in the dist/\n    // directory of the project root\n    path: path.resolve(__dirname, '../dist'),\n    filename: 'migration.js',\n  },\n  resolve: {\n    extensions: ['.ts', '.js'],\n    // Use the same configuration as NestJS\n    plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.build.json' })],\n  },\n  module: {\n    rules: [\n      { test: /\\.ts$/, loader: 'ts-loader' },\n      // Skip the shebang of typeorm/cli.js\n      { test: /\\.[tj]s$/i, loader: 'shebang-loader' }\n    ],\n  },\n  externals: [\n    {\n      // I'll skip pg-native in the production deployement, and use the pure JS implementation\n      'pg-native': 'commonjs2 pg-native'\n    }\n  ],\n  plugins: [\n    // Let NodeJS handle are requires that can't be resolved at build time\n    new IgnoreDynamicRequire()\n  ]\n};\n```\n\n```js\n// webpack/migrations.config.js\n\nconst glob = require('glob');\nconst path = require('path');\n// TypeScript compilation option\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');\n// Minimization option\nconst TerserPlugin = require('terser-webpack-plugin');\n\nconst { NODE_ENV = 'production' } = process.env;\n\nconsole.log(`-- Webpack <${NODE_ENV}> build for migrations scripts --`);\n\nmodule.exports = {\n  target: 'node',\n  mode: NODE_ENV,\n  // Dynamically generate a `{ [name]: sourceFileName }` map for the `entry` option\n  // change `src/db/migrations` to the relative path to your migration folder\n  entry: glob.sync(path.resolve('src/migration/*.ts')).reduce((entries, filename) => {\n    const migrationName = path.basename(filename, '.ts');\n    return Object.assign({}, entries, {\n      [migrationName]: filename,\n    });\n  }, {}),\n  resolve: {\n    // assuming all your migration files are written in TypeScript\n    extensions: ['.ts'],\n    // Use the same configuration as NestJS\n    plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.build.json' })],\n  },\n  module: {\n    rules: [\n      { test: /\\.ts$/, loader: 'ts-loader' }\n    ]\n  },\n  output: {\n    // Remember that this file is in a subdirectory, so the output should be in the dist/\n    // directory of the project root\n    path: __dirname + '/../dist/migration',\n    // this is important - we want UMD (Universal Module Definition) for migration files.\n    libraryTarget: 'umd',\n    filename: '[name].js',\n  },\n  optimization: {\n    minimizer: [\n      // Migrations rely on class and function names, so keep them.\n      new TerserPlugin({\n        terserOptions: {\n          mangle: true, // Note `mangle.properties` is `false` by default.\n          keep_classnames: true,\n          keep_fnames: true,\n        }\n      })\n    ],\n  },\n};\n```\n\n```js\n// webpack.config.js\nconst { merge } = require(\"webpack-merge\")\nconst path = require('path')\nconst glob = require('glob')\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')\nconst TerserPlugin = require('terser-webpack-plugin')\nconst MomentLocalesPlugin = require('moment-locales-webpack-plugin')\nconst IgnoreDynamicRequire = require('webpack-ignore-dynamic-require')\n\nconst { NODE_ENV = 'production', ENTRY, npm_lifecycle_event: lifecycle } = process.env\n\n// Build platform don't support ?? and ?. operators\nconst entry = ENTRY || (lifecycle && lifecycle.match(/bundle:(?<entry>\\w+)/).groups[\"entry\"])\n\nif (entry === undefined) {\n  throw new Error(\"ENTRY must be defined\")\n}\n\nconsole.log(`-- Webpack <${NODE_ENV}> build  for <${entry}> --`);\n\nconst BASE_CONFIG = {\n  target: 'node',\n  mode: NODE_ENV,\n  resolve: {\n    extensions: ['.ts', '.js'],\n    plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.build.json' })],\n  },\n  module: {\n    rules: [\n      { test: /\\.ts$/, loader: 'ts-loader' }\n    ]\n  },\n  output: {\n    path: path.resolve(__dirname, 'dist/'),\n    filename: '[name].js',\n  },\n}\n\nconst MIGRATION_CONFIG = {\n  // Dynamically generate a `{ [name]: sourceFileName }` map for the `entry` option\n  // change `src/db/migrations` to the relative path to your migration folder\n  entry: glob.sync(path.resolve('src/migration/*.ts')).reduce((entries, filename) => {\n    const migrationName = path.basename(filename, '.ts')\n    return Object.assign({}, entries, {\n      [migrationName]: filename,\n    })\n  }, {}),\n  output: {\n    path: path.resolve(__dirname, 'dist/migration'),\n    // this is important - we want UMD (Universal Module Definition) for migration files.\n    libraryTarget: 'umd',\n    filename: '[name].js',\n  },\n  optimization: {\n    minimizer: [\n      new TerserPlugin({\n        terserOptions: {\n          mangle: true, // Note `mangle.properties` is `false` by default.\n          keep_classnames: true,\n          keep_fnames: true,\n        }\n      })\n    ],\n  }\n}\n\nconst TYPEORM_CONFIG = {\n  entry: {\n    typeorm: './node_modules/typeorm/cli.js'\n  },\n  externals: [\n    {\n      'pg-native': 'commonjs2 pg-native',\n    }\n  ],\n  plugins: [\n    new IgnoreDynamicRequire(),\n  ],\n  module: {\n    rules: [\n      { test: /\\.[tj]s$/i, loader: 'shebang-loader' }\n    ],\n  },\n}\n\nconst MAIN_AND_CONSOLE_CONFIG = {\n  entry: {\n    main: './src/main.ts',\n    console: \"./src/console.ts\"\n  },\n  externals: [\n    {\n      'pg-native': 'commonjs2 pg-native',\n      'fastify-swagger': 'commonjs2 fastify-swagger',\n      '@nestjs/microservices/microservices-module': 'commonjs2 @nestjs/microservices/microservices-module',\n      '@nestjs/websockets/socket-module': 'commonjs2 @nestjs/websockets/socket-module',\n      // This one is a must have to generate the swagger document, but we remove it in production\n      'swagger-ui-express': 'commonjs2 swagger-ui-express',\n      'aws-sdk': 'commonjs2 aws-sdk',\n    }\n  ],\n  plugins: [\n    // We don't need moment locale\n    new MomentLocalesPlugin()\n  ],\n  optimization: {\n    // Full minization doesn't work with @Module annotation\n    minimizer: [\n      new TerserPlugin({\n        terserOptions: {\n          mangle: true, // Note `mangle.properties` is `false` by default.\n          keep_classnames: true,\n          keep_fnames: true,\n        }\n      })\n    ],\n    splitChunks: {\n      cacheGroups: {\n        commons: {\n          test: /[\\\\/]node_modules[\\\\/]/,\n          name: 'vendors',\n          chunks: 'all'\n        }\n      }\n    }\n  }\n}\n\nconst withPlugins = (config) => (runtimeConfig) => ({\n  ...config,\n  plugins: [\n    ...runtimeConfig.plugins,\n    ...(config.plugins || [])\n  ]\n})\n\nconst config = entry === \"migrations\" ? merge(BASE_CONFIG, MIGRATION_CONFIG)\n  : entry === \"typeorm\" ? merge(BASE_CONFIG, TYPEORM_CONFIG)\n  : entry === \"main\" ? merge(BASE_CONFIG, MAIN_AND_CONSOLE_CONFIG)\n    : undefined\n\n\nmodule.exports = withPlugins(config)\n```\n\n```text\nconst TYPEORM_CONFIG = {\n  entry: {\n    'data-source': {\n      // Are you ready? You must provide a data source as TypeORM cli >= 0.3\n      // But this will be a dynamic require(), so Webpack can't know how to handle it\n      // in TypeORM code. Instead, export this data source as a library.\n      // BUT, TypeORM expect it to be at the top level instead of a module variable, so\n      // we MUST remove the library name to make webpack export each variable from data source into the module\n      import: './src/data-source.ts',\n      library: {\n        type: 'commonjs2'\n      }\n    },\n    typeorm: './node_modules/typeorm/cli.js'\n  },\n  externals: [\n    {\n      'pg-native': 'commonjs2 pg-native',\n    }\n  ],\n  plugins: [\n    new IgnoreDynamicRequire(),\n  ],\n  module: {\n    rules: [\n      { test: /\\.[tj]s$/i, loader: 'shebang-loader' }\n    ],\n  },\n}\n```\n\n```json\n{\n  \"scripts\": {\n    \"bundle:application\": \"nest build --webpack\",\n    \"bundle:migrations\": \"nest build --webpack --webpackPath webpack/typeorm-cli.config.js && nest build --webpack --webpackPath webpack/migrations.config.js\",\n    \"bundle\": \"yarn bundle:application && yarn bundle:migrations\"\n  },\n}\n```\n\n```text\n%build\nmkdir yarncache\nexport YARN_CACHE_FOLDER=yarncache\n\n# Setting to avoid node-gype trying to download headers\nexport npm_config_nodedir=/opt/rh/rh-nodejs10/root/usr/\n\n%{_yarnbin} install --offline --non-interactive --frozen-lockfile\n%{_yarnbin} bundle\n\nrm -r yarncache/\n\n%install\ninstall -D -m644 dist/main.js $RPM_BUILD_ROOT%{app_path}/main.js\n\ninstall -D -m644 dist/migration.js $RPM_BUILD_ROOT%{app_path}/migration.js\n# Migration path have to be changed, let's hack it.\nsed -ie 's/src\\/migration\\/\\*\\.ts/migration\\/*.js/' ormconfig.json\ninstall -D -m644 ormconfig.json $RPM_BUILD_ROOT%{app_path}/ormconfig.json\nfind dist/migration -name '*.js' -execdir install -D -m644 \"{}\" \"$RPM_BUILD_ROOT%{app_path}/migration/{}\" \\;\n```\n\n```ini\n[Unit]\nDescription=NestJS Server\nAfter=network.target\n\n[Service]\nType=simple\nUser=nestjs\nEnvironment=SCLNAME=rh-nodejs10\nExecStartPre=/usr/bin/scl enable $SCLNAME -- /usr/bin/env node migration migration:run\nExecStart=/usr/bin/scl enable $SCLNAME -- /usr/bin/env node main\nWorkingDirectory=/export/myapplication\nRestart=on-failure\n\n# Hardening\nPrivateTmp=true\nNoNewPrivileges=true\nProtectSystem=full\nProtectHome=read-only\n\n[Install]\nWantedBy=multi-user.target\n```\n\n```text\normconfig.json\n```\n\n```text\nlibrary\n```\n\n```text\nwebpack\n```\n\n```text\nwebpack\n```\n\n```text\nbcrypt\n```\n\n```text\nbcrypt\n```\n\n```text\nnode-pre-gyp\n```\n\n```text\nwebpack\n```\n\n```text\nbuild\n```\n\n```text\nwebpack\n```\n\n```text\nwebpack\n```\n\n```text\nwebpack\n```\n\n```text\nIgnorePlugin\n```\n\n```text\nexternals\n```\n\n```text\nshebang-loader\n```\n\n```text\nwebpack\n```\n\n```text\nrequire\n```\n\n```text\nenv\n```\n\n```text\nyarn add -D webpack-merge\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nbundle:main\n```\n\n```text\nmain\n```\n\n```text\nconsole\n```\n\n```text\nsplitChunks\n```\n\n```text\nnode\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nyarn bundle\n```\n\n```text\ndist/\n```\n\n```text\normconfig.json\n```\n\n```text\n-f data-source.js\n```\n\n```text\nExecStartPre\n```\n\n```text\n.production.env\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- can you provide a sample project with all these configuration ?\n- Good research, indeed. How do you set up the ormconfig.json file?\n- Nothing special in `ormconfig.json`. It is just written as in any TypeORM project, depending on your needs.\n- Had it working with no ormconfig.json, in the end. I've used the programatic way of configuring TypeORM stated here Thanks for the hint of `minimize: false`, it made the trick!","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":54,"totalLines":615,"estimatedTokens":3617}}236{"id":"stack-54965381","source":"stackoverflow","questionId":54965381,"title":"How to insert an entity with OneToMany relation in NestJS?","tags":["nestjs","typeorm"],"text":"Title: How to insert an entity with OneToMany relation in NestJS?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThere is the description how to do this in typeorm official docs https://typeorm.io/#/many-to-one-one-to-many-relations. But I can't do the same in NestJS with `Repository` and `insert` method.\n\nI have written these entities (other columns were omitted)\n\n```\n@Entity()\n export class News {\n @OneToMany(type => NewsImage, image => image.news)\n public images: NewsImage[];\n }\n \n @Entity()\n export class NewsImage {\n @ManyToOne(type => News, news => news.images)\n public news: News;\n }\n```\n\nI have tried something like this\n\n```\nfunction first() {\n const news = new News();\n const image = new NewsImage();\n news.images = [ image ];\n return from(this.newsRepo.insert(news))\n .pipe(\n switchMap(() => this.imageRepo.insert(image)),\n );\n }\n \n function second() {\n const news = new News();\n const image = new NewsImage();\n image.news = news;\n return from(this.imageRepo.insert(image))\n .pipe(\n switchMap(() => this.newsRepo.insert(news)),\n )\n }\n```\n\nIt inserts news and image, but image's `newsId` is `null`.\n\n========================================\n\nTop Answer:\nDeclaring `new News()` creates a new entity but does not save it to the database. You first need to `insert` or `.save()` the `news` object and then add it to `image`.\n\n```\nasync function first() {\n // you can .save() it however you want, the point is it must be saved to the db\n const news = await News.create({ title: 'Async rules the world' }).save()\n const image = new NewsImage()\n image.news = news // now news has an id from the database\n // ...\n}\n```\n\n========================================\n\nCode:\n```js\n@Entity()\n    export class News {\n      @OneToMany(type => NewsImage, image => image.news)\n      public images: NewsImage[];\n    }\n    \n    @Entity()\n    export class NewsImage {\n      @ManyToOne(type => News, news => news.images)\n      public news: News;\n    }\n```\n\n```js\nfunction first() {\n      const news = new News();\n      const image = new NewsImage();\n      news.images = [ image ];\n      return from(this.newsRepo.insert(news))\n        .pipe(\n          switchMap(() => this.imageRepo.insert(image)),\n        );\n    }\n    \n    function second() {\n      const news = new News();\n      const image = new NewsImage();\n      image.news = news;\n      return from(this.imageRepo.insert(image))\n        .pipe(\n          switchMap(() => this.newsRepo.insert(news)),\n        )\n    }\n```\n\n```text\nRepository\n```\n\n```text\ninsert\n```\n\n```text\nnewsId\n```\n\n```text\nnull\n```\n\n```js\n@Entity()\nexport class News {\n  @OneToMany(type => NewsImage, image => image.news, { cascade: ['insert', 'update'] })\n  public images: NewsImage[];\n}\n```\n\n```js\nlet news = {\n        images: [{\n            date: \"\",\n            etc: \"\"\n        }],\n        title: \"\"\n    }\n```\n\n```text\nthis.repository.save(news)\n```\n\n```text\nasync function first() {\n  // you can .save() it however you want, the point is it must be saved to the db\n  const news = await News.create({ title: 'Async rules the world' }).save()\n  const image = new NewsImage()\n  image.news = news // now news has an id from the database\n  // ...\n}\n```\n\n```text\nnew News()\n```\n\n```text\ninsert\n```\n\n```text\n.save()\n```\n\n```text\nnews\n```\n\n```text\nimage\n```\n\n========================================\n\nComments:\n- Thanks, I tried this way, but `.insert` returns `InsertResult` object, not `news` entity. I retrieved `id` from `insertResults` and set `id` to `news`, created image entity with that news and it works!\n- How would you handle removing entities that are not in the images[] array, say for an update where an user removes one image from the array, it still exists in the database but instead of deleting the item typeorm/nestjs tries to set the newsId to null on the image @andressh11\n- here is a github issue regarding this : github.com/typeorm/typeorm/issues/1460 .","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":177,"estimatedTokens":976}}237{"id":"stack-71966734","source":"stackoverflow","questionId":71966734,"title":"How to avoid to write `@ApiProperty()` in each dto for NestJs-swagger","tags":["javascript","typescript","swagger","nestjs","nestjs-swagger"],"text":"Title: How to avoid to write `@ApiProperty()` in each dto for NestJs-swagger\nTags: javascript, typescript, swagger, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI'm researching the way on how to avoid to specify @ApiProperty() in each dto.\n\nI know there is exist a way to create file `nest-cli.json`, and if you specify `Promise` in your controller in nest-swagger it will produce the output dto from the route.\n\nThe structure looks like this:\n\n`nest-cli.json`\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"plugins\": [\n {\n \"name\": \"@nestjs/swagger\",\n \"options\": {\n \"introspectComments\": true\n }\n }\n ]\n }\n}\n```\n\n`controller.ts`\n\n```\n@Get()\n async getMonitors (): Promise { // And in swagger it shows something like this:\nhttps://i.sstatic.net/LEUez.png\n\nHowever, is there any way to setup NestJs to have the same things with inputDTO and not to write in each dto `@ApiProperty`?\n\nAs in example below:\n\n`ExampleDto.ts`\n\n```\nexport class GetListUsersDto {\n @ApiProperty()\n @IsString()\n name: string\n @ApiProperty()\n @IsString()\n email: string\n @ApiProperty()\n @IsString()\n publicApiKey: string\n @ApiProperty()\n @IsBoolean()\n isAdmin: boolean\n @ApiProperty()\n @IsBoolean()\n isDesigner: boolean\n @ApiProperty()\n @IsBoolean()\n isEditor: boolean\n @ApiProperty()\n @IsBoolean()\n isEnabled: boolean\n @ApiProperty()\n @IsString()\n boughtProduct: string\n}\n```\n\nAnd only after @ApiProperty it will show the structure as shown above for input in swagger.\n\n========================================\n\nTop Answer:\nUsing the plugin resolved this issue for me, see https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin.\n\nTo enable the plugin, open `nest-cli.json` (if you use Nest CLI) and add the following plugins configuration:\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"plugins\": [\"@nestjs/swagger\"]\n }\n}\n```\n\nThen this will automatically apply the @ApiProperty() without having to add it\n\n```\nexport class CreateUserDto {\n email: string;\n password: string;\n roles: RoleEnum[] = [];\n @IsOptional()\n isEnabled?: boolean = true;\n}\n```\n\n========================================\n\nCode:\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\n      {\n        \"name\": \"@nestjs/swagger\",\n        \"options\": {\n          \"introspectComments\": true\n        }\n      }\n    ]\n  }\n}\n```\n\n```text\n@Get()\n  async getMonitors (): Promise<OutputMonitorsDto> { // <-- Here is my outputDto\n    return this.monitorsService.getMonitors()\n  }\n```\n\n```text\nexport class GetListUsersDto {\n  @ApiProperty()\n  @IsString()\n  name: string\n  @ApiProperty()\n  @IsString()\n  email: string\n  @ApiProperty()\n  @IsString()\n  publicApiKey: string\n  @ApiProperty()\n  @IsBoolean()\n  isAdmin: boolean\n  @ApiProperty()\n  @IsBoolean()\n  isDesigner: boolean\n  @ApiProperty()\n  @IsBoolean()\n  isEditor: boolean\n  @ApiProperty()\n  @IsBoolean()\n  isEnabled: boolean\n  @ApiProperty()\n  @IsString()\n  boughtProduct: string\n}\n```\n\n```text\nnest-cli.json\n```\n\n```text\nPromise<DTO>\n```\n\n```text\nnest-cli.json\n```\n\n```text\ncontroller.ts\n```\n\n```text\n@ApiProperty\n```\n\n```text\nExampleDto.ts\n```\n\n```text\nexport class CreateUserDto {\n  email: string;\n  password: string;\n  roles: RoleEnum[] = [];\n  @IsOptional()\n  isEnabled?: boolean = true;\n}\n```\n\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger\"]\n  }\n}\n```\n\n```text\nexport class CreateUserDto {\n  email: string;\n  password: string;\n  roles: RoleEnum[] = [];\n  @IsOptional()\n  isEnabled?: boolean = true;\n}\n```\n\n```text\nnest-cli.json\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\n```\n\n========================================\n\nComments:\n- Why do you want to avoid using @ApiProperty()? It's something useful for the devs indicates if the value is optional or not and you have more readability and legibility.\n- I'd like to note that, as per @Deivy Gutierrez's answer, for those using the Nest CLI, there is a plugin that will decorate your DTOs for you. For those not using Nest CLI, you'll have to decorate your properties or come up with a custom solution.\n- Using this plugin is the correct answer. docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin\n- Can you please add explanation why?\n- Because the documentation of the CLI Plugin in the Options section says that it's the default convention @daniilsinelnik\n- above works for me","metadata":{"transformedAt":"2026-08-18T18:33:02.425Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":230,"estimatedTokens":1121}}238{"id":"stack-65570680","source":"stackoverflow","questionId":65570680,"title":"what is getRepositoryToken in nestjs typeorm and when to use it?","tags":["jestjs","nestjs","typeorm"],"text":"Title: what is getRepositoryToken in nestjs typeorm and when to use it?\nTags: jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe docs here are as below:\n\nWhen it comes to unit testing an application, we usually want to avoid\nmaking a database connection, keeping our test suites independent and\ntheir execution process as fast as possible. But our classes might\ndepend on repositories that are pulled from the connection instance.\nHow do we handle that? The solution is to create mock repositories. In\norder to achieve that, we set up custom providers. Each registered\nrepository is automatically represented by a Repository\ntoken, where EntityName is the name of your entity class.\n\nThe @nestjs/typeorm package exposes the getRepositoryToken() function\nwhich returns a prepared token based on a given entity.\n\nWhat does that even mean? Autocomplete docs just give the signature with no explanation.\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class FooService {\n  constructor(@InjectRepository(Foo) private readonly fooRepo: Repository<Foo>) {}\n\n}\n```\n\n```js\n{\n  provide: getRepositoryToken(Foo),\n  useValue: {\n    find: jest.fn(),\n    insert: jest.fn(),\n  },\n}\n```\n\n```text\ngetRepositoryToken()\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\n@InjectRepsitory()\n```\n\n========================================\n\nComments:\n- So let me see if I understand your answer correctly. This is specifically used when mocking and testing the service or thing that calls the injected repository? So in some cases I've seen where getRepository is not used, but I think in those cases it is only testing the repository directly and not the service calling the repository method?\n- Sounds about right. You could also use the `getRepositoryToken()` to properly inject the repository into a `useFactory` method for asynchronous registration of modules\n- Love your DND app btw. :) I'm still a bit curious about the difference in the end result. In practice, I see it still works without the getRespositoryToken method even when testing the above scenario, and I don't see any issues.\n- I'd probably have to see how you're testing things. This repo has a lot of different tests, and includes tests for typeorm, mongoose, and sequelize. None of them connect to a database during unit tests, so a database connection is not needed during them.\n- but if i need to reset the mock of `find` and insert between each test it can be done in this approach?\n- @MatanTubul you should be able to get the repository in the initial `beforeAll` using the `getRepositoryToken()` and then in an `afterEach` you can reset each method as necessary. Or just use `jest.resetAllMocks()`","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":79,"estimatedTokens":696}}239{"id":"stack-70137558","source":"stackoverflow","questionId":70137558,"title":"Does TypeORM provide transactions for different repositories?","tags":["nestjs","typeorm"],"text":"Title: Does TypeORM provide transactions for different repositories?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nCurrently, three different repositories have something to deal with as a single transaction.\n\nMy service code is written as follows. But unlike what I thought, each repository is generating its own transaction. How can I solve this problem?\n\n```\n// TrimService\n\n@Injectable()\nexport class TrimService {\n constructor(\n private readonly trimRepository: TrimRepository,\n private readonly tireRepository: TireRepository,\n private readonly userRepository: UserRepository\n ) {}\n\n async saveUserTrim(saveUserTrimDto: SaveUserTrimDto, res) {\n const queryRunner = await getConnection().createQueryRunner();\n await queryRunner.startTransaction();\n\n try {\n const findUser: User = await this.userRepository.findUser(\n saveUserTrimDto.id,\n queryRunner.manager\n );\n\n const createTrim: Trim = await this.trimRepository.saveUserTrim(\n findUser,\n saveUserTrimDto.trimId,\n queryRunner.manager\n );\n\n await this.tireRepository.saveTrimTire(\n createTrim,\n res,\n queryRunner.manager\n );\n\n await queryRunner.commitTransaction();\n return createTrim;\n } catch (err) {\n console.log(err);\n await queryRunner.rollbackTransaction();\n } finally {\n await queryRunner.release();\n }\n }\n}\n```\n\n```\n// userRepository\n\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n async findUser(\n id: string,\n @TransactionManager() transactionManager?: EntityManager\n ) {\n const findUser = await this.findOne({ id: id });\n\n if (!findUser) {\n throw new NotFoundUserException();\n }\n\n return findUser;\n }\n}\n```\n\n========================================\n\nTop Answer:\nRemove queryRunner.manager from saveUserTrim method and try below code.\nIt works for me.\n\n```\nconst createTrim: Trim = await queryRunner.manager.getRepository(Trim).saveUserTrim(\n findUser,\n saveUserTrimDto.trimId\n );\n```\n\n========================================\n\nCode:\n```js\n// TrimService\n\n@Injectable()\nexport class TrimService {\n    constructor(\n        private readonly trimRepository: TrimRepository,\n        private readonly tireRepository: TireRepository,\n        private readonly userRepository: UserRepository\n    ) {}\n\n    async saveUserTrim(saveUserTrimDto: SaveUserTrimDto, res) {\n        const queryRunner = await getConnection().createQueryRunner();\n        await queryRunner.startTransaction();\n\n        try {\n            const findUser: User = await this.userRepository.findUser(\n                saveUserTrimDto.id,\n                queryRunner.manager\n            );\n\n            const createTrim: Trim = await this.trimRepository.saveUserTrim(\n                findUser,\n                saveUserTrimDto.trimId,\n                queryRunner.manager\n            );\n\n            await this.tireRepository.saveTrimTire(\n                createTrim,\n                res,\n                queryRunner.manager\n            );\n\n            await queryRunner.commitTransaction();\n            return createTrim;\n        } catch (err) {\n            console.log(err);\n            await queryRunner.rollbackTransaction();\n        } finally {\n            await queryRunner.release();\n        }\n    }\n}\n```\n\n```js\n// userRepository\n\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n    async findUser(\n        id: string,\n        @TransactionManager() transactionManager?: EntityManager\n    ) {\n        const findUser = await this.findOne({ id: id });\n\n        if (!findUser) {\n            throw new NotFoundUserException();\n        }\n\n        return findUser;\n    }\n}\n```\n\n```js\n// TrimService\n\n@Injectable()\nexport class TrimService {\n    constructor(\n        private readonly trimRepository: TrimRepository,\n        private readonly tireRepository: TireRepository,\n        private readonly userRepository: UserRepository\n    ) {}\n\n    async saveUserTrim(saveUserTrimDto: SaveUserTrimDto, res) {\n        const queryRunner = await getConnection().createQueryRunner();\n        await queryRunner.startTransaction();\n\n        const findUser: User = await this.userRepository.findUser(\n            saveUserTrimDto.id\n        );\n\n        try {\n            const createTrim: Trim = await this.trimRepository.saveUserTrim(\n                queryRunner.manager,\n                findUser,\n                saveUserTrimDto.trimId\n            );\n\n            await this.tireRepository.saveTrimTire(\n                queryRunner.manager,\n                createTrim,\n                res\n            );\n\n            await queryRunner.commitTransaction();\n            return createTrim;\n        } catch (err) {\n            console.log(err);\n            await queryRunner.rollbackTransaction();\n        } finally {\n            await queryRunner.release();\n        }\n    }\n}\n```\n\n```js\n// TrimRepository\n\n@EntityRepository(Trim)\nexport class TrimRepository extends Repository<Trim> {\n    async saveUserTrim(\n        @TransactionManager() transactionManager: EntityManager,\n        findUser: User,\n        trimId: number\n    ) {\n        const findTrim = await transactionManager.findOne(Trim, {\n            trimId: trimId,\n            user: findUser\n        });\n\n        if (findTrim) {\n            throw new TrimOverlapException();\n        }\n\n        const createTrim: Trim = await transactionManager.create(Trim, {\n            trimId: trimId,\n            user: findUser\n        });\n\n        return await transactionManager.save(Trim, createTrim);\n    }\n}\n```\n\n```text\nconst createTrim: Trim = await queryRunner.manager.getRepository(Trim).saveUserTrim(\n                findUser,\n                saveUserTrimDto.trimId\n            );\n```\n\n========================================\n\nComments:\n- Oh gosh, you saved my life man!","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":239,"estimatedTokens":1425}}240{"id":"stack-61445185","source":"stackoverflow","questionId":61445185,"title":"how to implement user guards in nestjs graphql","tags":["javascript","graphql","jwt","nestjs","graphql-js"],"text":"Title: how to implement user guards in nestjs graphql\nTags: javascript, graphql, jwt, nestjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get the current user but in the resolver I get undefined, in the jwt strategy I get the user object using the token but in the resolver the user is undefined\n\n*auth guard*\n\n```\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AuthenticationError } from 'apollo-server-core';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n\n canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n\n return super.canActivate(\n new ExecutionContextHost([req]),\n );\n }\n\n handleRequest(err: any, user: any) {\n if (err || !user) {\n throw err || new AuthenticationError('GqlAuthGuard');\n }\n return user;\n }\n\n}\n```\n\n*user decorator*\n\n```\nimport {createParamDecorator} from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n (data, req) => req.user )\n;\n```\n\n*app module*\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n signOptions: {\n expiresIn: 3600,\n },\n }),\n SharedModule,\n AuthModule,\n GraphQLModule.forRoot({\n autoSchemaFile: 'schema.gql',\n context: ({ req }) => ({ req })\n }),\n MongooseModule.forRoot(process.env.MONGO_URI,\n {\n useNewUrlParser: true ,\n useUnifiedTopology: true\n }),\n // RewardsModule,\n OrdersModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n*resolver*\n\n```\nimport {User} from \"src/types/user\";\nimport {GqlAuthGuard} from \"../guards/graphql.auth.guard\";\n\n@Resolver()\nexport class OrdersResolver {\n constructor(\n private orderService: OrdersService\n ) {\n }\n\n @Query(returns => [Order])\n @UseGuards(GqlAuthGuard)\n listOrders(@CurrentUser() user: User): Promise {\n console.log(user)\n return this.orderService.listOrdersByUser(user.id);\n }\n\n}\n```\n\nI also tried to implement the solution explained here NestJS Get current user in GraphQL resolver authenticated with JWT and still, I got the same error\n\n========================================\n\nTop Answer:\nThis is what I'm using for `GraphqlJwtAuthGuard` based on documentaion:\n\n```\n@Injectable()\nexport class GqlJwtAuthGuard extends AuthGuard('jwt') {\n constructor(private reflector: Reflector) {\n super();\n }\n\n canActivate(ctx: ExecutionContext) {\n const context = GqlExecutionContext.create(ctx);\n const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n if (isPublic) {\n return true;\n }\n const { req } = context.getContext();\n return super.canActivate(new ExecutionContextHost([req])); // NOTE\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AuthenticationError } from 'apollo-server-core';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n\n    canActivate(context: ExecutionContext) {\n        const ctx = GqlExecutionContext.create(context);\n        const { req } = ctx.getContext();\n\n        return super.canActivate(\n            new ExecutionContextHost([req]),\n        );\n    }\n\n    handleRequest(err: any, user: any) {\n        if (err || !user) {\n            throw err || new AuthenticationError('GqlAuthGuard');\n        }\n        return user;\n    }\n\n}\n```\n\n```text\nimport {createParamDecorator} from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n    (data, req) =>  req.user )\n;\n```\n\n```text\n@Module({\n  imports: [\n      PassportModule.register({ defaultStrategy: 'jwt' }),\n      JwtModule.register({\n          signOptions: {\n              expiresIn: 3600,\n          },\n      }),\n      SharedModule,\n      AuthModule,\n      GraphQLModule.forRoot({\n          autoSchemaFile: 'schema.gql',\n          context: ({ req }) => ({ req })\n      }),\n      MongooseModule.forRoot(process.env.MONGO_URI,\n        {\n          useNewUrlParser: true ,\n          useUnifiedTopology: true\n        }),\n    // RewardsModule,\n    OrdersModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport {User} from \"src/types/user\";\nimport {GqlAuthGuard} from \"../guards/graphql.auth.guard\";\n\n@Resolver()\nexport class OrdersResolver {\n    constructor(\n        private orderService: OrdersService\n    ) {\n    }\n\n    @Query(returns => [Order])\n    @UseGuards(GqlAuthGuard)\n    listOrders(@CurrentUser() user: User): Promise<Order> {\n        console.log(user)\n        return this.orderService.listOrdersByUser(user.id);\n    }\n\n}\n```\n\n```js\nexport const CurrentUser = createParamDecorator(\n    (data, req) =>  req.user )\n;\n```\n\n```js\nexport const User = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const gqlCtx = GqlExecutionContext.create(ctx);\n    const request = gqlCtx.getContext().req;\n    return request.user;\n  },\n);\n```\n\n```text\ncontext: ({req}) => ({req})\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nGraphqlModule\n```\n\n```text\n@Injectable()\nexport class RolesGuard_ implements CanActivate {\n  constructor(private reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const ctx = GqlExecutionContext.create(context);\n\n    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n\n    if (!requiredRoles) {\n      return true;\n    }\n\n    const { user } = ctx.getContext().req;\n    return requiredRoles.some((role) => user.role?.includes(role));\n  }\n}\n```\n\n```text\n@Injectable()\nexport class GqlJwtAuthGuard extends AuthGuard('jwt') {\n  constructor(private reflector: Reflector) {\n    super();\n  }\n\n  canActivate(ctx: ExecutionContext) {\n    const context = GqlExecutionContext.create(ctx);\n    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n    if (isPublic) {\n      return true;\n    }\n    const { req } = context.getContext();\n    return super.canActivate(new ExecutionContextHost([req])); // NOTE\n  }\n}\n```\n\n```text\nGraphqlJwtAuthGuard\n```\n\n========================================\n\nComments:\n- Quick question: what's your Nest version? There was a change to the `createParamDecorator` function between v6 and v7.\n- These are the nestjs versions \"@nestjs/common\": \"^7.0.0\", \"@nestjs/core\": \"^7.0.0\", \"@nestjs/graphql\": \"^7.3.4\", \"@nestjs/jwt\": \"^7.0.0\", \"@nestjs/mongoose\": \"^6.4.0\", \"@nestjs/passport\": \"^7.0.0\", \"@nestjs/platform-express\": \"^7.0.0\", \"@nestjs/swagger\": \"^4.5.1\",","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":303,"estimatedTokens":1740}}241{"id":"stack-63257409","source":"stackoverflow","questionId":63257409,"title":"Nest js - circular reference at the moment to inject a repository","tags":["nestjs"],"text":"Title: Nest js - circular reference at the moment to inject a repository\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nEvery time I try to run my project, I get the error:\n\nCircularDependencyException [Error]: A circular dependency has been\ndetected inside @InjectRepository(). Please, make sure that each side\nof a bidirectional relationships are decorated with \"forwardRef()\".\nAlso, try to eliminate barrel files because they can lead to an\nunexpected behavior too.\n\nThe only clue I have is one of my modules:\n\nIf I comment this line:\n\n```\nconstructor(\n @InjectRepository(Role) private roleRepo: Repository\n ){}\n```\n\nand the project runs, but I notice the log when I start the project, the Module with the error starts before everything\n\n```\n[Nest] 16872 - 08/04/2020, 7:56:24 PM [NestFactory] Starting Nest application...\n[Nest] 16872 - 08/04/2020, 7:56:24 PM [InstanceLoader] TypeOrmModule dependencies initialized +91ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] MyErrorModule dependencies initialized +500ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] TypeOrmCoreModule dependencies initialized +630ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] TypeOrmModule dependencies initialized +2ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] TypeOrmModule dependencies initialized +4ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] AuthorizationModule dependencies initialized +3ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] AppModule dependencies initialized +3ms\n[Nest] 16872 - 08/04/2020, 7:56:25 PM [InstanceLoader] FirstModule dependencies initialized +2ms\n```\n\nBut I have my `app.module.ts` file with\n\n```\n@Module({\n imports: [TypeOrmModule.forRootAsync({\n useClass: DatabaseConnectionService\n }), \n AuthorizationModule,\n TypeOrmModule.forFeature([User, Role]),\n FirstModule, \n SecondModule,\n MyErrorModule, //This is the first to be executed\n],\n```\n\nSomeone has an idea about how to solve this issue?\n\n========================================\n\nTop Answer:\nin my case it was because of wrong \"paths\". I used shorthands for paths using \"@\" and IDE told me that the path is ok but nest.js said that it was a circular dependecy.\n\n========================================\n\nCode:\n```text\nconstructor(\n        @InjectRepository(Role) private roleRepo: Repository<Role>\n    ){}\n```\n\n```text\n[Nest] 16872   - 08/04/2020, 7:56:24 PM   [NestFactory] Starting Nest application...\n[Nest] 16872   - 08/04/2020, 7:56:24 PM   [InstanceLoader] TypeOrmModule dependencies initialized +91ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] MyErrorModule dependencies initialized +500ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmCoreModule dependencies initialized +630ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmModule dependencies initialized +2ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmModule dependencies initialized +4ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] AuthorizationModule dependencies initialized +3ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] AppModule dependencies initialized +3ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] FirstModule dependencies initialized +2ms\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forRootAsync({\n    useClass: DatabaseConnectionService\n  }), \n  AuthorizationModule,\n  TypeOrmModule.forFeature([User, Role]),\n  FirstModule, \n  SecondModule,\n  MyErrorModule, //This is the first to be executed\n],\n```\n\n```text\napp.module.ts\n```\n\n```text\n[Nest] 16872   - 08/04/2020, 7:56:24 PM   [NestFactory] Starting Nest application...\n[Nest] 16872   - 08/04/2020, 7:56:24 PM   [InstanceLoader] TypeOrmModule dependencies initialized +91ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] MyErrorModule dependencies initialized +500ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmCoreModule dependencies initialized +630ms\n[Nest] 16872   - 08/04/2020, 7:56:25 PM   [InstanceLoader] TypeOrmModule dependencies initialized +2ms\n```\n\n```text\nimport\n```\n\n```text\n@Module({\n  // imports: [ApiAppModule],\n  controllers: [UserController],\n  // providers: [],\n})\nexport class UserModule {}\n```\n\n```text\nyarn add -D eslint-plugin-import\n```\n\n```text\nmodule.exports = {\nย ย \"parser\": \"@typescript-eslint/parser\",\nย ย \"plugins\": [\nย ย ย ย \"import\",\nย ย ย ย // ...\nย ย ],\nย ย \"extends\": [\nย ย ย ย \"plugin:import/typescript\",\nย ย ย ย // ...\nย ย ],\nย ย \"rules\": {\nย ย ย ย \"import/no-cycle\": 2,\nย ย ย ย // ...\nย ย },\nย ย // ...\n};\n```\n\n```text\nyarn add -D madge\n```\n\n```text\nyarn madge --ts-config ./tsconfig.json --circular --extensions js,ts src/\n```\n\n```text\nimports: [\n  forwardRef(() => UserModule),\n  PassportModule,\n],\n```\n\n```text\nimports: [\n  PassportModule,\n  forwardRef(() => UserModule),\n],\n```\n\n========================================\n\nComments:\n- Awesome, thank you. I was having trouble with building tests and got this same error. Turns out I had the wrong import type (`import User` instead of `import { User }`), and because of that quote mentioning passing `undefined` values, I could identify it\n- For anyone who might run into this too, the issue in my case was the extra comma here: `imports: [TypeOrmModule.forFeature([Auth, User, ,Location])]`\n- Same here. If you are in the same module, then realtive path (barrels are ok) have to be uses.\n- I was able to find the circular reference with *madge*. In my case I use an `index.ts` file which loads everything on the directory and I was like loading `UserService` inside `UserController` (both in the same directory) but instead reference the `UserService` file itself I included it from `index.ts` and I had both `UserController` and `UserService` referenced on the file thus my circular reference found with `madge`.\n- I hadn't noticed (but also didn't know it was necessary to use the TypeORM package) that my entities in various locations were imported backwards. Let's say B depended on A but B was being imported before A and when I corrected the orientation in all codes the problem went away. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":177,"estimatedTokens":1672}}242{"id":"stack-65486947","source":"stackoverflow","questionId":65486947,"title":"NestJS transform a property using ValidationPipe before validation execution during DTO creation","tags":["validation","nestjs","dto","class-validator","class-transformer"],"text":"Title: NestJS transform a property using ValidationPipe before validation execution during DTO creation\nTags: validation, nestjs, dto, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'm using the built in NestJS ValidationPipe along with class-validator and class-transformer to validate and sanitize inbound JSON body payloads. One scenario I'm facing is a mixture of upper and lower case property names in the inbound JSON objects. I'd like to rectify and map these properties to standard camel-cased models in our new TypeScript NestJS API so that I don't couple mismatched patterns in a legacy system to our new API and new standards, essentially using the @Transform in the DTOs as an isolation mechanism for the rest of the application. For example, properties on the inbound JSON object:\n\n```\n\"propertyone\",\n\"PROPERTYTWO\",\n\"PropertyThree\"\n```\n\nshould map to\n\n```\n\"propertyOne\",\n\"propertyTwo\",\n\"propertyThree\"\n```\n\nI'd like to use @Transform to accomplish this, but I don't think my approach is correct. I'm wondering if I need to write a custom ValidationPipe. Here is my current approach.\n\nController:\n\n```\nimport { Body, Controller, Post, UsePipes, ValidationPipe } from '@nestjs/common';\nimport { TestMeRequestDto } from './testmerequest.dto';\n\n@Controller('test')\nexport class TestController {\n constructor() {}\n\n @Post()\n @UsePipes(new ValidationPipe({ transform: true }))\n async get(@Body() testMeRequestDto: TestMeRequestDto): Promise {\n const response = do something useful here... ;\n return response;\n }\n}\n```\n\nTestMeModel:\n\n```\nimport { IsNotEmpty } from 'class-validator';\n\nexport class TestMeModel {\n @IsNotEmpty()\n someTestProperty!: string;\n}\n```\n\nTestMeRequestDto:\n\n```\nimport { IsNotEmpty, ValidateNested } from 'class-validator';\nimport { Transform, Type } from 'class-transformer';\nimport { TestMeModel } from './testme.model';\n\nexport class TestMeRequestDto {\n @IsNotEmpty()\n @Transform((propertyone) => propertyone.valueOf())\n propertyOne!: string;\n\n @IsNotEmpty()\n @Transform((PROPERTYTWO) => PROPERTYTWO.valueOf())\n propertyTwo!: string;\n\n @IsNotEmpty()\n @Transform((PropertyThree) => PropertyThree.valueOf())\n propertyThree!: string;\n\n @ValidateNested({ each: true })\n @Type(() => TestMeModel)\n simpleModel!: TestMeModel\n\n}\n```\n\nSample payload used to POST to the controller:\n\n```\n{\n \"propertyone\": \"test1\",\n \"PROPERTYTWO\": \"test2\",\n \"PropertyThree\": \"test3\",\n \"simpleModel\": { \"sometestproperty\": \"test4\" }\n}\n```\n\nThe issues I'm having:\n\n- The transforms seem to have no effect. Class validator tells me that each of those properties cannot be empty. If for example I change \"propertyone\" to \"propertyOne\" then the class validator validation is fine for that property, e.g. it sees the value. The same for the other two properties. If I camelcase them, then class validator is happy. Is this a symptom of the transform not running before the validation occurs?\n\n- This one is very weird. When I debug and evaluate the TestMeRequestDto object, I can see that the simpleModel property contains an object containing a property name \"sometestproperty\", even though the Class definition for TestMeModel has a camelcase \"someTestProperty\". Why doesn't the @Type(() => TestMeModel) respect the proper casing of that property name? The value of \"test4\" is present in this property, so it knows how to understand that value and assign it.\n\n- Very weird still, the @IsNotEmpty() validation for the \"someTestProperty\" property on the TestMeModel is not failing, e.g. it sees the \"test4\" value and is satisfied, even though the inbound property name in the sample JSON payload is \"sometestproperty\", which is all lower case.\n\nAny insight and direction from the community would be greatly appreciated. Thanks!\n\n========================================\n\nTop Answer:\nYou'll probably need to make use of the Advanced Usage section of the class-transformer docs. Essentially, your `@Transform()` would need to look *something* like this:\n\n```\nimport { IsNotEmpty, ValidateNested } from 'class-validator';\nimport { Transform, Type } from 'class-transformer';\nimport { TestMeModel } from './testme.model';\n\nexport class TestMeRequestDto {\n @IsNotEmpty()\n @Transform((value, obj) => obj.propertyone.valueOf())\n propertyOne!: string;\n\n @IsNotEmpty()\n @Transform((value, obj) => obj.PROPERTYTWO.valueOf())\n propertyTwo!: string;\n\n @IsNotEmpty()\n @Transform((value, obj) => obj.PropertyThree.valueOf())\n propertyThree!: string;\n\n @ValidateNested({ each: true })\n @Type(() => TestMeModel)\n simpleModel!: TestMeModel\n\n}\n```\n\nThis should take an incoming payload of\n\n```\n{\n \"propertyone\": \"value1\",\n \"PROPERTYTWO\": \"value2\",\n \"PropertyThree\": \"value3\",\n}\n```\n\nand turn it into the DTO you envision.\n\n### Edit 12/30/2020\n\nSo the original idea I had of using `@Transform()` doesn't quite work as envisioned, which is a real bummer cause it looks so nice. So what you can do instead isn't quite as DRY, but it still works with class-transformer, which is a win. By making use of `@Exclude()` and `@Expose()` you're able to use property accessors as an alias for the weird named property, looking something like this:\n\n```\nclass CorrectedDTO {\n @Expose()\n get propertyOne() {\n return this.propertyONE;\n }\n @Expose()\n get propertyTwo(): string {\n return this.PROPERTYTWO;\n }\n @Expose()\n get propertyThree(): string {\n return this.PrOpErTyThReE;\n }\n @Exclude({ toPlainOnly: true })\n propertyONE: string;\n @Exclude({ toPlainOnly: true })\n PROPERTYTWO: string;\n @Exclude({ toPlainOnly: true })\n PrOpErTyThReE: string;\n}\n```\n\nNow you're able to access `dto.propertyOne` and get the expected property, and when you do `classToPlain` it will strip out the `propertyONE` and other properties (if you're using Nest's serialization interceptor. Otherwise in a secondary pipe you could `plainToClass(NewDTO, classToPlain(value))` where `NewDTO` has only the corrected fields).\n\nThe other thing you may want to look into is an automapper and see if it has better capabilities for something like this.\n\nIf you're interested, here's the StackBlitz I was using to test this out\n\n========================================\n\nCode:\n```text\n\"propertyone\",\n\"PROPERTYTWO\",\n\"PropertyThree\"\n```\n\n```text\n\"propertyOne\",\n\"propertyTwo\",\n\"propertyThree\"\n```\n\n```js\nimport { Body, Controller, Post, UsePipes, ValidationPipe } from '@nestjs/common';\nimport { TestMeRequestDto } from './testmerequest.dto';\n\n@Controller('test')\nexport class TestController {\n  constructor() {}\n\n  @Post()\n  @UsePipes(new ValidationPipe({ transform: true }))\n  async get(@Body() testMeRequestDto: TestMeRequestDto): Promise<TestMeResponseDto> {\n    const response = do something useful here... ;\n    return response;\n  }\n}\n```\n\n```js\nimport { IsNotEmpty } from 'class-validator';\n\nexport class TestMeModel {\n  @IsNotEmpty()\n  someTestProperty!: string;\n}\n```\n\n```js\nimport { IsNotEmpty, ValidateNested } from 'class-validator';\nimport { Transform, Type } from 'class-transformer';\nimport { TestMeModel } from './testme.model';\n\nexport class TestMeRequestDto {\n  @IsNotEmpty()\n  @Transform((propertyone) => propertyone.valueOf())\n  propertyOne!: string;\n\n  @IsNotEmpty()\n  @Transform((PROPERTYTWO) => PROPERTYTWO.valueOf())\n  propertyTwo!: string;\n\n  @IsNotEmpty()\n  @Transform((PropertyThree) => PropertyThree.valueOf())\n  propertyThree!: string;\n\n  @ValidateNested({ each: true })\n  @Type(() => TestMeModel)\n  simpleModel!: TestMeModel\n\n}\n```\n\n```json\n{\n  \"propertyone\": \"test1\",\n  \"PROPERTYTWO\": \"test2\",\n  \"PropertyThree\": \"test3\",\n  \"simpleModel\": { \"sometestproperty\": \"test4\" }\n}\n```\n\n```js\nexport class RequestConverterPipe implements PipeTransform{\n  transform(body: any, metadata: ArgumentMetadata): TestMeRequestDto {\n    const result = new TestMeRequestDto();\n    // can of course contain more sophisticated mapping logic\n    result.propertyOne = body.propertyone;\n    result.propertyTwo = body.PROPERTYTWO;\n    result.propertyThree = body.PropertyThree;\n    return result;\n  }\n\nexport class TestMeRequestDto {\n  @IsNotEmpty()\n  propertyOne: string;\n  @IsNotEmpty()\n  propertyTwo: string;\n  @IsNotEmpty()\n  propertyThree: string;\n}\n```\n\n```js\n@UsePipes(new RequestConverterPipe(), new ValidationPipe())\nasync post(@Body() requestDto: TestMeRequestDto): Promise<TestMeResponseDto> {\n  // ...\n}\n```\n\n```text\nRequestConverterPipe\n```\n\n```text\nValidationPipe\n```\n\n```text\nValidationPipe\n```\n\n```js\nimport { IsNotEmpty, ValidateNested } from 'class-validator';\nimport { Transform, Type } from 'class-transformer';\nimport { TestMeModel } from './testme.model';\n\nexport class TestMeRequestDto {\n  @IsNotEmpty()\n  @Transform((value, obj) => obj.propertyone.valueOf())\n  propertyOne!: string;\n\n  @IsNotEmpty()\n  @Transform((value, obj) => obj.PROPERTYTWO.valueOf())\n  propertyTwo!: string;\n\n  @IsNotEmpty()\n  @Transform((value, obj) => obj.PropertyThree.valueOf())\n  propertyThree!: string;\n\n  @ValidateNested({ each: true })\n  @Type(() => TestMeModel)\n  simpleModel!: TestMeModel\n\n}\n```\n\n```json\n{\n  \"propertyone\": \"value1\",\n  \"PROPERTYTWO\": \"value2\",\n  \"PropertyThree\": \"value3\",\n}\n```\n\n```js\nclass CorrectedDTO {\n  @Expose()\n  get propertyOne() {\n    return this.propertyONE;\n  }\n  @Expose()\n  get propertyTwo(): string {\n    return this.PROPERTYTWO;\n  }\n  @Expose()\n  get propertyThree(): string {\n    return this.PrOpErTyThReE;\n  }\n  @Exclude({ toPlainOnly: true })\n  propertyONE: string;\n  @Exclude({ toPlainOnly: true })\n  PROPERTYTWO: string;\n  @Exclude({ toPlainOnly: true })\n  PrOpErTyThReE: string;\n}\n```\n\n```text\n@Transform()\n```\n\n```text\n@Transform()\n```\n\n```text\n@Exclude()\n```\n\n```text\n@Expose()\n```\n\n```text\ndto.propertyOne\n```\n\n```text\nclassToPlain\n```\n\n```text\npropertyONE\n```\n\n```text\nplainToClass(NewDTO, classToPlain(value))\n```\n\n```text\nNewDTO\n```\n\n```js\nexport class TransformPipe<T> implements PipeTransform {\n    constructor(private rules: Record<any, (value: any) => any> = null) {}\n\n    transform(body: T): T {\n        const result: T | null = null;\n        for (const key in body) {\n            if (this.rules[key])\n                result[key] = this.rules[key] ? this.rules[key](body[key]) : body[key];\n        }\n        return result;\n    }\n}\n```\n\n```js\nclass CoolDto {\n    phone: string;\n    text: string;\n}\n\n@UsePipes(\n    new TransformPipe<CoolDto>({\n        phone: (v) => v?.trim() || '',\n        text: (v) => v?.trim() || '',\n    }),\n    new ValidationPipe())\n    @Post('send')\n    async send(@Body() body: CoolDto) {\n        //...\n}\n```\n\n========================================\n\nComments:\n- why not stick with defined names in dto?\n- Hello AZ_, I don't fully understand your comment. Could you elaborate?\n- I mean let the prop names be as they are in legacy consumer and use the same or add other getter methods `get lowercase() {return this.camelCase}`. Or maybe add a serializer to exclude the CamelCased values if required. or a `classToClass` serializer with `@Expose({name: lowercase})`\n- Hey Jay thanks for the response! What's odd is the objects for the Transform are not available (the value or obj arguments) if the property on the inbound JSON payload is different from that of the DTO. The DTO property is \"propertyOne\" and inbound JSON payload property is \"propertyone\". If I change the inbound JSON payload property to \"propertyOne\" then the Transform has proper value and obj arguments, but that defeats the purpose\n- @BSmith you're right, I was under the assumption that in `@Transform()` class-transformer would give you access to the full object, regardless of the property. I've updated my answer to provide something that *does* work, but it's not necessarily pretty.\n- No need of getters to rename when using `classToPlain`, `plaintoClass`. rather `@Exclude({ toPlainOnly: true })` use `Expose({name: 'lowercase'})` on any other prop names.\n- Thanks. @Expose on the getter method work for me.\n- This is another good approach. The thing to be aware of with this is that you *must* run the `RequestConverterPipe` before the `ValidationPipe` which means that the `ValidationPipe` cannot be globally set.\n- Hey Eol thanks for the response! I may have to create a custom PipeTransform class like you illustrated. Even though I'm very attracted to the elegance of a single-line Transform in a DTO like in Jay's example below, the issue I have is when the case of the inbound property doesn't match the case of the DTO's property, I'm not able to get the object and value arguments into the Transform. I just cannot figure out what layer is causing this problem.\n- I marked your response as the answer because it seemed like the most simple path forward. While the Exclude and Expose decorators on the DTO would work, I felt I was adding additional weight to the DTO and wanted to keep as much logic out of the DTO as possible. I wanted to maintain clearly separated lines in the architecture, leaving DTOs as lean as possible to fulfill their role as transfer entities, not performing transforms, and leaving transform operations in a class which implements PipeTransform.\n- Happy it helped! :)\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":431,"estimatedTokens":3316}}243{"id":"stack-55826790","source":"stackoverflow","questionId":55826790,"title":"NestJs using same instance of service in multiple modules","tags":["nestjs"],"text":"Title: NestJs using same instance of service in multiple modules\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have got a NestJs app, that uses two services. The DbService that connects to the Db and the SlowService that does stuff rather slow and uses the injected DbService.\n\nNow the app shall provide health routes outside of the api base path, so i need a different module that provides the controllers for the health routes.\n\nI created a base module.\n\n```\nimport { Module } from '@nestjs/common'\nimport { SlowService } from './slow.service'\nimport { DbService } from './db.service'\n\n@Module({\n imports: [],\n controllers: [],\n providers: [DbService, SlowService],\n exports: [DbService, SlowService]\n})\nexport class BaseModule {\n}\n```\n\nThe ApiModule and the HealthModule now both import the base module to be able to use the services. \n\n```\nimports: [BaseModule],\n```\n\nThere is only a small problem. Both modules seem to construct their own instance of the service but I need it to be the same instance. I assume this, because the console.log from the constructor appear twice when starting the app. Am I missing a setting or something?\n\nUPDATE\n\nHere is my bootstrap method, so you can see how I initialize the modules. \n\n```\nasync function bootstrap (): Promise {\n const server = express()\n const api = await NestFactory.create(AppModule, server.application, { cors: true })\n api.setGlobalPrefix('api/v1')\n await api.init()\n const options = new DocumentBuilder()\n .setTitle('...')\n .setLicense('MIT', 'https://opensource.org/licenses/MIT')\n .build()\n const document = SwaggerModule.createDocument(api, options)\n server.use('/swaggerui', SwaggerUI.serve, SwaggerUI.setup(document))\n server.use('/swagger', (req: express.Request, res: express.Response, next?: express.NextFunction) => res.send(document))\n const health = await NestFactory.create(HealthModule, server.application, { cors: true })\n health.setGlobalPrefix('health')\n await health.init()\n http.createServer(server).listen(Number.parseInt(process.env.PORT || '8080', 10))\n}\nconst p = bootstrap()\n```\n\n========================================\n\nTop Answer:\nThere are two logs generated because you are initialising two NestJS applications.\n\nEach application will have its own instances.\n\nHere is where you initialise the first app:\n\n```\nconst api = await NestFactory.create(AppModule, server.application, { cors: true })\n api.setGlobalPrefix('api/v1')\n await api.init()\n```\n\nAnd here is the second app:\n\n```\nconst health = await NestFactory.create(HealthModule, server.application, { cors: true })\n health.setGlobalPrefix('health')\n await health.init()\n```\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common'\nimport { SlowService } from './slow.service'\nimport { DbService } from './db.service'\n\n@Module({\n  imports: [],\n  controllers: [],\n  providers: [DbService, SlowService],\n  exports: [DbService, SlowService]\n})\nexport class BaseModule {\n}\n```\n\n```text\nimports: [BaseModule],\n```\n\n```text\nasync function bootstrap (): Promise<void> {\n  const server = express()\n  const api = await NestFactory.create(AppModule, server.application, { cors: true })\n  api.setGlobalPrefix('api/v1')\n  await api.init()\n  const options = new DocumentBuilder()\n    .setTitle('...')\n    .setLicense('MIT', 'https://opensource.org/licenses/MIT')\n    .build()\n  const document = SwaggerModule.createDocument(api, options)\n  server.use('/swaggerui', SwaggerUI.serve, SwaggerUI.setup(document))\n  server.use('/swagger', (req: express.Request, res: express.Response, next?: express.NextFunction) => res.send(document))\n  const health = await NestFactory.create(HealthModule, server.application, { cors: true })\n  health.setGlobalPrefix('health')\n  await health.init()\n  http.createServer(server).listen(Number.parseInt(process.env.PORT || '8080', 10))\n}\nconst p = bootstrap()\n```\n\n```js\nimport {Injectable, Module} from '@nestjs/common';\nimport {NestFactory} from '@nestjs/core';\n\n@Injectable()\nexport class SlowService {\n  constructor() {\n    console.log(`Created SlowService`);\n  }\n}\n\n@Injectable()\nexport class DbService {\n  constructor() {\n    console.log(`Created DbService`);\n  }\n}\n\n@Module({\n  imports: [],\n  providers: [SlowService, DbService],\n  exports: [SlowService, DbService]\n})\nexport class BaseModule {}\n\n@Injectable()\nexport class OtherService {\n  constructor(private service: DbService) {\n    console.log(`Created OtherService with dependency DbService`);\n  }\n}\n\n@Module({\n  imports: [BaseModule],\n  providers: [OtherService],\n})\nexport class OtherModule {}\n\n@Module({\n  imports: [\n    BaseModule,\n    OtherModule\n  ],\n})\nexport class AppModule {}\n\nNestFactory.createApplicationContext(AppModule).then((app) => console.log('๐Ÿฅ‘ context created'));\n```\n\n```text\nBaseModule\n```\n\n```text\nOtherService\n```\n\n```text\nOtherModule\n```\n\n```text\nDbService\n```\n\n```text\nBaseModule\n```\n\n```text\nDbService\n```\n\n```text\nDbService\n```\n\n```text\nnest g s shared-services/db\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\n\n/* Define global variable as \"any\" so we don't get nasty error. */\ndeclare var global: any;\n\n@Injectable()\nexport class DbService {\n  constructor() {\n    console.log(`Created DbService`);\n\n    /* Put the class inside global variable. */\n    global.dbService = this;\n  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { DbService} from './../shared-services/db.service';\n\n/* Define global variable as \"any\" so we don't get nasty error. */\ndeclare var global: any;\n\n@Injectable()\nexport class OtherService {\n\n  /* Call the service. */\n  protected readonly dbService: DbService = global.dbService;\n  constructor() {\n  }\n}\n```\n\n```text\napp.module\n```\n\n```text\nconst api = await NestFactory.create(AppModule, server.application, { cors: true })\n  api.setGlobalPrefix('api/v1')\n  await api.init()\n```\n\n```text\nconst health = await NestFactory.create(HealthModule, server.application, { cors: true })\n  health.setGlobalPrefix('health')\n  await health.init()\n```\n\n========================================\n\nComments:\n- This is surprising to me. Both controllers use the default injection scope when injecting the `SlowService`?\n- Yes they do. I tried to debug into it and it seems they even use the same context. Still the console.log from the constructor appears twice. And believe me, I was very surprised aswell as the new lightwight health controller ruined the performance of my test system.\n- Thank you very much for your detailed answer. This is exactly what I thought I did, but I will investigate it again.\n- @Woozar, I've got the same issue and this answer have helped me too. I suggest selecting it as accepted.\n- This is valuable information that is not easily extracted from the documentation. Thank you very much for this level of detail; for some like me, the subtlety is very difficult to understand.\n- If you import `BaseService` on multiple modules, then the services inside of it will be instatiated multiple times. Indeed every module have the same services, but it is not quite true for the module have the same instance of services with the other modules.\n- I have a similiar problem. But I didnt import the module twice, I listed it in app.modules in imports and used it in the main.ts. I am using the app.get to instantiate the needed service. I thought nestjs will take the same service. But it gets a new one.\n- Why to add the service class in both `providers` & `exports`? I'm really confused when to add in providers and when to add in exports and when at both places?\n- @Khatri, if a provider is not exported, it will only be available to members (and children) of the module. Think of it like a \"private\" service, while exporting it will then make it available to other modules importing this one. Hope that makes sense\n- Isn't this anti-pattern? Why take this approach vs importing/providing this in the root module and/or a @Global module? Wouldn't this also mean that it isn't injected anywhere, defeating the purpose of @Injectable? If this is the approach you need, seems sensible to just stick it in an export file that is imported where you need it.\n- This is not a very good approach\n- Why then use Nest at all if you wanna store it outside...","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":271,"estimatedTokens":2053}}244{"id":"stack-63838204","source":"stackoverflow","questionId":63838204,"title":"Error when creating a new migration using TypeORM and NestJs with Typescript","tags":["node.js","typescript","npm","nestjs","typeorm"],"text":"Title: Error when creating a new migration using TypeORM and NestJs with Typescript\nTags: node.js, typescript, npm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a node application using typescript and I'm trying to create a new migration, following the documentation of the TypeORM.\n\nFirst I installed the CLI, set up my connection options like this and when I try to run this command:\n\n`npm run typeorm migration:create -- -n migrationNameHere`\nI get the following error:\n\nError during migration creation: TypeError: Cannot read property 'startsWith' of undefined\nat Object. (...\\src\\commands\\MigrationCreateCommand.ts:62:37)\nat step (...\\node_modules\\typeorm\\node_modules\\tslib\\tslib.js:141:27)\nat Object.throw (...\\node_modules\\typeorm\\node_modules\\tslib\\tslib.js:122:57)\nat rejected (...\\node_modules\\typeorm\\node_modules\\tslib\\tslib.js:113:69) npm ERR!\ncode ELIFECYCLE npm ERR! errno 1 npm ERR! backend@0.0.1 typeorm: node\n--require ts-node/register ./node_modules/typeorm/cli.js \"migration:create\" \"-n\" \"migrationNameHere\"` npm ERR! Exit status 1\n\nThese are my nest dependencies in package.json:\n\nMy node version is **v12.14.1**, nestjs is **7.0.0** and nestjs/typeorm is **7.1.3**\n\nMy app.module.ts is like this:\n\n```\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption],\n migrations: ['migration/*.js'],\n cli: {\n migrationsDir: 'migration'\n },\n synchronize: true,\n })\n```\n\nDoes anybody has ever faced this sort of problem?\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRoot({\n      type: 'mysql',\n      host: database().host,\n      port: parseInt(database().port),\n      username: database().username,\n      password: database().password,\n      database: database().schema,\n      entities: [Question, QuestionOption],\n      migrations: ['migration/*.js'],\n      cli: {\n        migrationsDir: 'migration'\n      },\n      synchronize: true,\n    })\n```\n\n```text\nnpm run typeorm migration:create -- -n migrationNameHere\n```\n\n```text\nnpx typeorm migration:create -n YourName -d src/migrations\n```\n\n========================================\n\nComments:\n- Thanks, the secret was the -d src/migrations, with that, the migration file was created. One strange thing is that I configured that in the app.module.ts (see migrationDir), where I tried to add src/migration too but the same error happened, but your solution worked pretty well","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":77,"estimatedTokens":638}}245{"id":"stack-59822046","source":"stackoverflow","questionId":59822046,"title":"Nestjs mocking service constructor with Jest","tags":["javascript","typescript","jestjs","twilio","nestjs"],"text":"Title: Nestjs mocking service constructor with Jest\nTags: javascript, typescript, jestjs, twilio, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have created following service to use twilio send login code sms to users:\n\nsms.service.ts\n\n```\nimport { Injectable, Logger } from '@nestjs/common';\nimport * as twilio from 'twilio';\n\nInjectable()\nexport class SmsService {\n private twilio: twilio.Twilio;\n constructor() {\n this.twilio = this.getTwilio();\n }\n\n async sendLoginCode(phoneNumber: string, code: string): Promise {\n const smsClient = this.twilio;\n const params = {\n body: 'Login code: ' + code,\n from: process.env.TWILIO_SENDER_NUMBER,\n to: phoneNumber\n };\n smsClient.messages.create(params).then(message => {\n return message;\n });\n }\n getTwilio() {\n return twilio(process.env.TWILIO_SID, process.env.TWILIO_SECRET);\n }\n}\n```\n\nsms.service.spec.js that contains my test\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { SmsService } from './sms.service';\nimport { Logger } from '@nestjs/common';\n\ndescribe('SmsService', () => {\n let service: SmsService;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [SmsService]\n }).compile();\n service = module.get(SmsService);\n});\n\ndescribe('sendLoginCode', () => {\n it('sends login code', async () => {\n const mockMessage = {\n test: \"test\"\n }\n jest.mock('twilio')\n const twilio = require('twilio');\n twilio.messages = {\n create: jest.fn().mockImplementation(() => Promise.resolve(mockMessage))\n }\n expect(await service.sendLoginCode(\"4389253\", \"123456\")).toBe(mockMessage);\n });\n });\n});\n```\n\nHow can I use jest create mock of the `SmsService` constructor so that it's `twilio` variable gets set to mocked version of it I create in `service.spec.js`?\n\n========================================\n\nCode:\n```text\nimport { Injectable, Logger } from '@nestjs/common';\nimport * as twilio from 'twilio';\n\nInjectable()\nexport class SmsService {\n    private twilio: twilio.Twilio;\n    constructor() {\n        this.twilio = this.getTwilio();\n    }\n\n    async sendLoginCode(phoneNumber: string, code: string): Promise<any> {\n        const smsClient = this.twilio;\n        const params = {\n            body: 'Login code: ' + code,\n            from: process.env.TWILIO_SENDER_NUMBER,\n            to: phoneNumber\n        };\n        smsClient.messages.create(params).then(message => {\n            return message;\n        });\n    }\n    getTwilio() {\n        return twilio(process.env.TWILIO_SID, process.env.TWILIO_SECRET);\n    }\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { SmsService } from './sms.service';\nimport { Logger } from '@nestjs/common';\n\ndescribe('SmsService', () => {\n  let service: SmsService;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n        providers: [SmsService]\n    }).compile();\n    service = module.get<SmsService>(SmsService);\n});\n\ndescribe('sendLoginCode', () => {\n    it('sends login code', async () => {\n      const mockMessage = {\n        test: \"test\"\n      }\n      jest.mock('twilio')\n      const twilio = require('twilio');\n      twilio.messages = {\n          create: jest.fn().mockImplementation(() => Promise.resolve(mockMessage))\n      }\n      expect(await service.sendLoginCode(\"4389253\", \"123456\")).toBe(mockMessage);\n    });\n  });\n});\n```\n\n```text\nSmsService\n```\n\n```text\ntwilio\n```\n\n```text\nservice.spec.js\n```\n\n```text\n@Module({\n  providers: [\n    {\n      provide: 'Twillio',\n      useFactory: async (configService: ConfigService) =>\n                    twilio(configService.TWILIO_SID, configService.TWILIO_SECRET),\n      inject: [ConfigService],\n    },\n  ]\n```\n\n```text\nconstructor(@Inject('Twillio') twillio: twilio.Twilio) {}\n```\n\n```text\nconst module: TestingModule = await Test.createTestingModule({\n  providers: [\n    SmsService,\n    { provide: 'Twillio', useFactory: twillioMockFactory },\n  ],\n}).compile();\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":170,"estimatedTokens":986}}246{"id":"stack-57266622","source":"stackoverflow","questionId":57266622,"title":"Unable to create a new project with the Nest CLI","tags":["javascript","node.js","typescript","npm","nestjs"],"text":"Title: Unable to create a new project with the Nest CLI\nTags: javascript, node.js, typescript, npm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am following this tutorial to create a nest project. I have installed **Nest CLI** using this command:\n\n```\nnpm i -g @nestjs/cli\n```\n\nhttps://i.sstatic.net/3aVd1.png\n\nI have checked the list of packages installed locally using the following command and found that it was successfully installed:\n\n```\nnpm list -g --depth 0\n```\n\nhttps://i.sstatic.net/8qXAV.png\n\nbut when I tried to create a new project using following command it gave me an error:\n\n```\nnest new project-name\n```\n\n**Error:**\n\n nest : The term 'nest' is not recognized as the name of a cmdlet, function, script file, or\n operable program. Check the spelling of the name, or if a path was included, verify that the\n path is correct and try again.\n\n \n At line:1 char:1\n\n \n \n nest new project-name\n\n \n\n```\n+ CategoryInfo : ObjectNotFound: (nest:String) [], CommandNotFoundException\n\n+ FullyQualifiedErrorId : CommandNotFoundException\n```\n\n \n\n**Screenshot:**\n\nhttps://i.sstatic.net/8TtV1.png\n\n \n\n### Why it is so? What's wrong with it? Can someone assist me in identifying the issue?\n\nThanks in advance\n\n========================================\n\nTop Answer:\nTry installing latest npm using command:\n\n`npm install npm@latest -g`\n\nIt worked for me. Also found a related answer here:\n\nhttps://github.com/nestjs/nest-cli/issues/223\n\n========================================\n\nCode:\n```text\nnpm i -g @nestjs/cli\n```\n\n```text\nnpm list -g --depth 0\n```\n\n```text\nnest new project-name\n```\n\n```text\n+ CategoryInfo          : ObjectNotFound: (nest:String) [], CommandNotFoundException\n\n+ FullyQualifiedErrorId : CommandNotFoundException\n```\n\n```text\nnpx @nestjs/cli new project-name\n```\n\n```text\nnpx\n```\n\n```text\nnest\n```\n\n```text\nnpx @nestjs/cli\n```\n\n```text\nC:\\Users\\<user.name>\\AppData\\Roaming\\npm\n```\n\n```text\nPATH\n```\n\n```text\nnpm install npm@latest -g\n```\n\n```text\n%AppData%\\Roaming\\npm\n```\n\n```text\nnest -v\n```\n\n```text\nnest new project-name\n```\n\n```text\nnpx @nestjs/cli new project-name\n```\n\n```text\nnotepad $PROFILE\n\n# add the function below\n\nfunction nest {\n    & npx @nestjs/cli @args\n}\n\n# restart PowerShell\n```\n\n========================================\n\nComments:\n- Try to clean npm cache and then install nest again.\n- Try to get the latest of node and npm versions as well.\n- Try adding alias to your .bash_profile alias nest=\"/usr/local/Cellar/node/11.9.0/bin/nest\"\n- Great! It worked!, can you explain what is the difference b/w use of npx and global packages and why `nest new project-name` did not worked?\n- If I had to guess, you may have needed to close and restart your command prompt. I haven't working with Powershell in a long time though, so take tat with a grain of salt :)\n- Yup, would have suspected the same. Needs to read in the path again. Npx looks for a locally installed version in your current folder or otherwise installs it but not permanently.\n- Yeah, it works. After installation on npm I see: `npm notice New minor version of npm available! 9.5.0 -> 9.6.2` so after command `npm install npm@latest -g` nest working without problems!","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":158,"estimatedTokens":791}}247{"id":"stack-58602306","source":"stackoverflow","questionId":58602306,"title":"nestjs returns 404 not found for 1 routes working fine for others","tags":["nestjs"],"text":"Title: nestjs returns 404 not found for 1 routes working fine for others\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using nestjs to create an API, quite new to it. I created 4 modules and all 4 seem to be working fine.\nI created another module name steps but all routes I access in it returns 404 not found.\n\n========================================\n\nTop Answer:\nwhen after add new routes and controllers, we should clean up `dist` folder and restart `yarn start:dev` to make sure the added fils work...\n\n========================================\n\nCode:\n```text\nyarn run build\nyarn start\n```\n\n```text\ndist\n```\n\n```text\nyarn start:dev\n```\n\n```text\napp.setGlobalPrefix\n```\n\n```js\n@Controller('foo/:foo-id')\nexport class FooController {\n\n  @Get('/')\n  async foo() {}\n}\n```\n\n```js\n@Controller('foo/:fooId')\nexport class FooController {\n\n  @Get('/')\n  async foo() {}\n}\n```\n\n```text\nGET /foo/1\n```\n\n```text\n:foo-id\n```\n\n```text\n:fooId\n```\n\n```text\n@Module({\n    imports: [TypeOrmModule.forFeature([Picture]), ProductsModule],\n    controllers: [PicturesController],\n    providers: [\n      PicturesService,\n    ],\n  })\nexport class PicturesModule {}\n```\n\n```text\nimport { AgencyModule } from './modules/agency/agency.module';//NEW\n\n@Module({\n    imports: [\n        ConfigModule.forRoot({\n            load: [configuration],\n            isGlobal: true,\n        }),\n        SharedModule,\n        DatabaseModule,\n        AgencyModule, //ADD HERE\n       \n    ],\n    controllers: [AppController],\n    providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\napp.module.ts\n```\n\n========================================\n\nComments:\n- Thanks for the reply Bruno , my issue was similar , actually i didn't import my file_module in the app.module.ts\n- Thanks, I had it imported on 'providers' array because of a copy paste of that module from another personal API built using GraphQL (it was a resolver and those are imported on the 'providers' array)","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":103,"estimatedTokens":488}}248{"id":"stack-60582058","source":"stackoverflow","questionId":60582058,"title":"Typeorm relationships - save by id","tags":["nestjs","typeorm"],"text":"Title: Typeorm relationships - save by id\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI've been kinda confused by the relationships as I'm used to save relationship by id, while docs and examples I found suggest to get the entire object and use that instead (Isn't this strange???)\n\nI found this on github addressing this issue ( https://github.com/typeorm/typeorm/issues/447 ) , where they suggest to use an object with just the id property, but it's from 2017. Is that a good way to do it ? And is it still the only way to do it ? (I find it pretty lame tbh)\n\n```\nasync create( @Body() product: Product) {\n product.category = { id: product.category };\n return { payload: await this.repository.persist(product) };\n}\n```\n\nAnother one suggested to name the column as categoryId and it would work as expected (with id instead of object) but WHY? What does the name have to do with that ??\n\n```\n@Entity()\nclass Product {\n\n @Column({ type: \"int\", nullable: true })\n categoryId: number;\n\n @ManyToOne(type => Category)\n @JoinColumn({ name: \"categoryId\" })\n category: Category;\n\n}\n```\n\nI'm just confused, help ^_^\n\n========================================\n\nTop Answer:\nAccording to this GitHub thread, it seems you can also do something like this:\n\n```\nproduct.category = { id: 1 }\nproduct.save()\n\n// Or\nproduct.category = new Category().id = 1\nproduct.save()\n```\n\n========================================\n\nCode:\n```js\nasync create( @Body() product: Product) {\n    product.category = <any>{ id: product.category };\n    return { payload: await this.repository.persist(product) };\n}\n```\n\n```js\n@Entity()\nclass Product {\n\n     @Column({ type: \"int\", nullable: true })\n     categoryId: number;\n\n     @ManyToOne(type => Category)\n     @JoinColumn({ name: \"categoryId\" })\n     category: Category;\n\n}\n```\n\n```text\nproduct.category = <any>3;\n// or\nproduct['category' as any] = 3;\nrepository.save(product) // I don't know how you have the persist() method.\n```\n\n```text\nproduct.category\n```\n\n```text\nCategory\n```\n\n```text\ncategory\n```\n\n```text\nCategory | number\n```\n\n```text\ncategory\n```\n\n```text\ncategoryId\n```\n\n```text\ncategoryId\n```\n\n```text\nname: 'actual_name'\n```\n\n```text\n@Column\n```\n\n```text\ncolumnId\n```\n\n```text\ncolumn\n```\n\n```js\nproduct.category = { id: 1 }\nproduct.save()\n\n// Or\nproduct.category = new Category().id = 1\nproduct.save()\n```\n\n```text\nproduct.category = Object.assign( new Category(), {\n    id: id,\n});\n```\n\n```text\nroduct.category = { id: 1 }\n```\n\n```text\nproduct.category = new Category().id = 1\n```\n\n```text\nproduct.category = { id: 3 } as Category;\n```\n\n========================================\n\nComments:\n- What do you mean by \"you can just do product.category = 3\" ? I get a type error on that, do you mean that it works even if it gives a type error?\n- You are right. I was testing my code in node REPL and it worked because it's just js. I will edit my answer.\n- It's absurd that this still seems the only way to update related entities without setting the whole object. Did you ever manage to find a cleaner method?","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":156,"estimatedTokens":761}}249{"id":"stack-72238595","source":"stackoverflow","questionId":72238595,"title":"How to secure a REST API with an API key","tags":["nestjs"],"text":"Title: How to secure a REST API with an API key\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm currently creating a Rest API with NestJS (it's really cool by the way).\n\nIn this API, I'm using JWT (JSON Web Token) to allow users to log in and view different resources based on their role.\n\nHowever, I want to implement an API Key system to protect the API itself. I don't want any developer to be able to use my API. I want him to go through this API Key to use my API.\n\nEither by a query in the URL: `https://domaine.com?api_key=${API_KEY}` or via the header:\n\n```\nGET /v1/some-resource\nHost: docmaine.com\nAccept: application/json\nX-API-KEY: MyAwes0m3API_KeY\n```\n\nDo you have a tutorial, course or a track to advise me?\n\n========================================\n\nTop Answer:\nThe simplest guard you can made is:\n\n```\nimport {\n Injectable,\n CanActivate,\n ExecutionContext,\n UnauthorizedException,\n} from '@nestjs/common';\n\n@Injectable()\nexport class ApiKeyGuard implements CanActivate {\n async canActivate(context: ExecutionContext): Promise {\n const request = context.switchToHttp().getRequest();\n\n const apiKey = request.headers['api-key']; // give the name you want\n\n if (!apiKey) {\n throw new UnauthorizedException('API key is missing.');\n }\n\n // call your env. var the name you want\n if (apiKey !== process.env.API_KEY) {\n throw new UnauthorizedException('Invalid API key.');\n }\n\n return true;\n }\n}\n```\n\nAnd use it globally for every routes of your controller.\n\n```\n@Controller()\n@UseGuards(ApiKeyGuard)\nexport class YourController {\n // constructor () {}\n\n // your routes POST,GET,PATCH, ....\n}\n```\n\nAnd give the env. var `API_KEY` to your client-side (he needs to protect it).\n\n========================================\n\nCode:\n```bash\nGET /v1/some-resource\nHost: docmaine.com\nAccept: application/json\nX-API-KEY: MyAwes0m3API_KeY\n```\n\n```text\nhttps://domaine.com?api_key=${API_KEY}\n```\n\n```js\n@Injectable()\nexport class ApiKeyGuard implements CanActivate {\n  constructor(private readonly apiKeyService: ApiKeyService) {} // made up service for the point of the exmaple\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const req = context.switchToHttp().getRequest();\n    const key = req.headers['X-API-KEY'] ?? req.query.api_key; // checks the header, moves to query if null\n    return this.apiKeyService.isKeyValid(key);\n  }\n}\n```\n\n```text\n@UseGuards(ApiKeyGuard)\n```\n\n```js\nimport {\n  Injectable,\n  CanActivate,\n  ExecutionContext,\n  UnauthorizedException,\n} from '@nestjs/common';\n\n@Injectable()\nexport class ApiKeyGuard implements CanActivate {\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n\n    const apiKey = request.headers['api-key']; // give the name you want\n\n    if (!apiKey) {\n      throw new UnauthorizedException('API key is missing.');\n    }\n\n    // call your env. var the name you want\n    if (apiKey !== process.env.API_KEY) {\n      throw new UnauthorizedException('Invalid API key.');\n    }\n\n    return true;\n  }\n}\n```\n\n```js\n@Controller()\n@UseGuards(ApiKeyGuard)\nexport class YourController {\n  // constructor () {}\n\n  // your routes POST,GET,PATCH, ....\n}\n```\n\n```text\nAPI_KEY\n```\n\n========================================\n\nComments:\n- how about a feedback?\n- Thanks, most of the answers on the web mentions using extra packages like passport. Your answer is simple and neat.\n- I think it's better not to allow api-keys to be passed into query string. It will appear in all intermediary logs of network infra devices (router, proxies ...Etc).\n- Agree, Cabrinha, which is why my solution goes for the headers first. However, I was also just answering OPs question of \"how\" not necessarily if it was a great idea","metadata":{"transformedAt":"2026-08-18T18:33:02.426Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":151,"estimatedTokens":935}}250{"id":"stack-60253136","source":"stackoverflow","questionId":60253136,"title":"Import a Nest.js app as a simple Express middleware","tags":["javascript","typescript","express","middleware","nestjs"],"text":"Title: Import a Nest.js app as a simple Express middleware\nTags: javascript, typescript, express, middleware, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've a Nestjs app (a Rest API) that I would like to import in another node module, as a simple Express middleware (not a Nest middleware). Actually I'm still not able to make it working.\n\n```\n// main.ts \n// => The main file of my Nest app, this one is working properly.\n\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n}\nbootstrap();\n```\n\n```\n// app.middleware.ts\n\nimport {Injectable, NestMiddleware} from '@nestjs/common';\nimport {NestFactory} from '@nestjs/core';\nimport {AppModule} from './app.module';\nimport {ExpressAdapter} from '@nestjs/platform-express';\nimport express, {Request, Response} from 'express';\n\nconst bootstrap = async () => {\n const expressApp = express();\n const adapter = new ExpressAdapter(expressApp);\n const app = await NestFactory.create(AppModule, adapter);\n await app.init();\n return app;\n};\n\n@Injectable()\nexport class AppMiddleware implements NestMiddleware {\n use(req: Request, res: Response, next: Function) {\n return bootstrap();\n }\n}\n```\n\n```\n// express-app.ts \n// => Here I'm trying to load my app through a simple Express middleware, but it doesn't works.\n\nimport express from 'express';\nimport { AppMiddleware } from './app.middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\napp.use((req, res, next) => {\n const app = new AppMiddleware().use(req, res, next);\n app.then(next);\n});\n\napp.listen(PORT, () => {\n console.log(`app running on port ${PORT}`);\n});\n```\n\nWhen running my app from `main.ts` it's working properly (all the routes are working and I'm getting the correct data). However when I try to run the app through `express-app.ts`, all the routes seems working (they are displayed in the terminal), but instead of returning a JSON object, in any case I'm getting this error:\n\n```\n\n \n Error\n\n [object Object]\n\n```\n\nNest component versions:\n\n```\n- @nestjs/common: \"^6.10.14\"\n- @nestjs/core: \"^6.10.14\"\n- @nestjs/platform-express: \"^6.10.14\"\n- express: \"^4.16.4\"\n```\n\n========================================\n\nTop Answer:\n**@Etienne** your `bootstrap` function is actually fine as it is and you can use it directly in `express-app.ts`. Advantages:\n\n- No new Nest instance per request\n\n- Independent configuration for each express app\n\n**app.middleware.ts**\n\n```\nimport {NestFactory} from '@nestjs/core';\nimport {AppModule} from './app.module';\nimport {ExpressAdapter} from '@nestjs/platform-express';\nimport express from 'express';\n\nexport const bootstrap = async () => {\n const expressApp = express();\n const adapter = new ExpressAdapter(expressApp);\n const app = await NestFactory.create(AppModule, adapter);\n await app.init();\n return app;\n};\n```\n\n**express-app.ts**\n\n```\nimport express from 'express';\nimport { bootstrap } from './app.middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\nbootstrap().then(expressApp => {\n app.use(expressApp);\n\n app.listen(PORT, () => {\n console.log(`app running on port ${PORT}`);\n });\n});\n```\n\n========================================\n\nCode:\n```js\n// main.ts  \n// => The main file of my Nest app, this one is working properly.\n\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```js\n// app.middleware.ts\n\nimport {Injectable, NestMiddleware} from '@nestjs/common';\nimport {NestFactory} from '@nestjs/core';\nimport {AppModule} from './app.module';\nimport {ExpressAdapter} from '@nestjs/platform-express';\nimport express, {Request, Response} from 'express';\n\nconst bootstrap = async () => {\n  const expressApp = express();\n  const adapter = new ExpressAdapter(expressApp);\n  const app = await NestFactory.create(AppModule, adapter);\n  await app.init();\n  return app;\n};\n\n@Injectable()\nexport class AppMiddleware implements NestMiddleware {\n  use(req: Request, res: Response, next: Function) {\n    return bootstrap();\n  }\n}\n```\n\n```js\n// express-app.ts  \n// => Here I'm trying to load my app through a simple Express middleware, but it doesn't works.\n\nimport express from 'express';\nimport { AppMiddleware } from './app.middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\napp.use((req, res, next) => {\n  const app = new AppMiddleware().use(req, res, next);\n  app.then(next);\n});\n\napp.listen(PORT, () => {\n  console.log(`app running on port ${PORT}`);\n});\n```\n\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <meta charset=\"utf-8\">\n    <title>Error</title>\n</head>\n\n<body>\n    <pre>[object Object]</pre>\n</body>\n\n</html>\n```\n\n```text\n- @nestjs/common: \"^6.10.14\"\n- @nestjs/core: \"^6.10.14\"\n- @nestjs/platform-express: \"^6.10.14\"\n- express: \"^4.16.4\"\n```\n\n```text\nmain.ts\n```\n\n```text\nexpress-app.ts\n```\n\n```js\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { ExpressAdapter } from '@nestjs/platform-express';\nimport { AppModule } from './app.module';\n\nconst bootstrap = async (express: Express.Application) => {\n  const app = await NestFactory.create(AppModule, new ExpressAdapter(express));\n  await app.init();\n  return app;\n}\n\n@Injectable()\nexport class AppMiddleware implements NestMiddleware {\n\n  constructor(private expressInstance: Express.Application) {}\n\n  use(req: any, res: any, next: () => void) {\n    console.log('In Nest middleware');\n    return bootstrap(this.expressInstance);\n  }\n}\n```\n\n```js\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getHello(): string {\n    return this.appService.getHello();\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n  getHello(): string {\n    return 'Hello World!';\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```js\nimport * as express from 'express';\n\nimport { AppMiddleware } from './app.middleware';\n\nconst app = express();\n\napp.use((req, res, next) => {\n  const nest = new AppMiddleware(app).use(req, res, next);\n  nest.then(() => {\n    next();\n  }).catch(err => {\n    console.log(JSON.stringify(err));\n    next();\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Listening on port 3000');\n});\n```\n\n```sh\nnpm run build\n# mapped to nest build\n```\n\n```sh\nnode dist/server.js\n```\n\n```sh\nโ–ถ curl http://localhost:3000\nHello World!\n```\n\n```sh\nListening on port 3000\nIn Nest middleware\n[Nest] 24235   - 02/18/2020, 8:05:44 PM   [NestFactory] Starting Nest application...\n[Nest] 24235   - 02/18/2020, 8:05:44 PM   [InstanceLoader] AppModule dependencies initialized +15ms\n[Nest] 24235   - 02/18/2020, 8:05:44 PM   [RoutesResolver] AppController {/}: +3ms\n[Nest] 24235   - 02/18/2020, 8:05:44 PM   [RouterExplorer] Mapped {/, GET} route +2ms\n[Nest] 24235   - 02/18/2020, 8:05:44 PM   [NestApplication] Nest application successfully started +2ms\n```\n\n```text\nnest new express-server -p npm\n```\n\n```text\nsrc/server.ts\n```\n\n```text\nExpressAdapter\n```\n\n```text\napp.listen()\n```\n\n```text\napp.middleware\n```\n\n```text\n[Object object]\n```\n\n```text\nCannot GET /\n```\n\n```text\nJSON.stringify()\n```\n\n```js\nimport dotenv from 'dotenv'\nimport bodyParser from 'body-parser'\nimport { useExpress } from './workspaces/poc/server'\nimport { TodoModule } from './workspaces/todo/todo.module'\nimport { NestFactory } from '@nestjs/core';\n\n// was in src/workspaces/my-legacy-app/server.ts\ndotenv.config()\n\nasync function bootstrap() {\n  const app = await NestFactory.create(TodoModule);\n  app.use(bodyParser.json());\n\n  // was in src/workspaces/my-legacy-app/server.ts\n  // also did not know how to resolve the issue of types, so use \"any\"\n  useExpress(app.getHttpAdapter() as any)\n\n  await app.listen(3000,() => {\n    console.info(`App runnning on port: ${3000}`)\n  });\n}\nbootstrap();\n```\n\n```js\nimport { validatorMiddleware } from './middlewares/validator.middleware'\nimport { logMiddleware } from './middlewares/log.middleware'\nimport { userRouter } from './routes/user.route'\nimport { Express } from 'express'\n\nexport function useExpress(server: Express){\n\n  server.use(validatorMiddleware)\n  server.use(logMiddleware)\n  server.use('/user', userRouter)\n  \n  // commented because the server will go up here more, but just to show that it was the same way as in express\n  // server.listen(\n  //   process.env.PORT,\n  //   () => console.log(`Server is running on port ${process.env.PORT ?? 3000}`)\n  // )\n}\n```\n\n```js\nimport {NestFactory} from '@nestjs/core';\nimport {AppModule} from './app.module';\nimport {ExpressAdapter} from '@nestjs/platform-express';\nimport express from 'express';\n\nexport const bootstrap = async () => {\n  const expressApp = express();\n  const adapter = new ExpressAdapter(expressApp);\n  const app = await NestFactory.create(AppModule, adapter);\n  await app.init();\n  return app;\n};\n```\n\n```js\nimport express from 'express';\nimport { bootstrap } from './app.middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\nbootstrap().then(expressApp => {\n  app.use(expressApp);\n\n  app.listen(PORT, () => {\n    console.log(`app running on port ${PORT}`);\n  });\n});\n```\n\n```text\nbootstrap\n```\n\n```text\nexpress-app.ts\n```\n\n========================================\n\nComments:\n- Why do you want to make your Nest server a middleware instead of having the Nest application run the express application by default?\n- @JayMcDoniel I just upgraded an Express node module to Nest, and I want this module to remain compatible as an express middleware for some time.\n- Well, my proposed solution does work, however, I still don't see why you don't take the existing Express app and pass it as the parameter to the `ExpressAdapter` and let Nest be the top layer. It would make porting code easier and more understandable, but to each their own\n- Yes, you are right, this is something that I am now considering in light of your post, and with the performance issues we can notice. Thank you for your help, this allows me to move forward on a better architecture addressing my concerns.\n- Thank you very much for your answer, well detailed, explained and instructive. I just upgraded an Express node module to Nest, and this adapter allows remaining compatible as an express middleware for some time (hopefully short). Indeed, start a new Nest instance on every request isn't an ideal scenario. Thank you for the points you mention at the end of this post! I'm also considering making the main Nest app running through an aws lambda instead, so the performance is definitely something I'll look closer.","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":456,"estimatedTokens":2768}}251{"id":"stack-69778679","source":"stackoverflow","questionId":69778679,"title":"NestJS - Expected undefined to be a GraphQL schema","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: NestJS - Expected undefined to be a GraphQL schema\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup a very small GraphQL API using NestJS 8. I installed all required redepndencies from the documentation, but when I start the server, I get this error:\n\n```\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [NestFactory] Starting Nest application...\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] AppModule dependencies initialized +43ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigHostModule dependencies initialized +7ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +21ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] GraphQLModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +93ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] PostModule dependencies initialized +0ms\n\n/workspace/node_modules/graphql/type/schema.js:35\n throw new Error(\n ^\nError: Expected undefined to be a GraphQL schema.\n at assertSchema (/workspace/node_modules/graphql/type/schema.js:35:11)\n at validateSchema (/workspace/node_modules/graphql/type/validate.js:34:28)\n at graphqlImpl (/workspace/node_modules/graphql/graphql.js:52:64)\n at /workspace/node_modules/graphql/graphql.js:21:43\n at new Promise ()\n at graphql (/workspace/node_modules/graphql/graphql.js:21:10)\n at GraphQLSchemaFactory.create (/workspace/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:48:60)\n at GraphQLSchemaBuilder.buildSchema (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:62:52)\n at GraphQLSchemaBuilder.build (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:24:31)\n at GraphQLFactory.mergeOptions (/workspace/node_modules/@nestjs/graphql/dist/graphql.factory.js:33:69)\n```\n\nI don't understand this error, as I am just following the documentation...\n\n```\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphqlOptions } from './config/graphql.config';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { PostModule } from './post/post.module';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n GraphQLModule.forRootAsync({\n useClass: GraphqlOptions,\n }),\n PostModule,\n ],\n})\nexport class AppModule {}\n```\n\n```\n// graphql.config.ts\nimport { Injectable } from '@nestjs/common';\nimport { GqlModuleOptions, GqlOptionsFactory } from '@nestjs/graphql';\n\n@Injectable()\nexport class GraphqlOptions implements GqlOptionsFactory {\n createGqlOptions(): Promise | GqlModuleOptions {\n return {\n autoSchemaFile: 'schema.gql',\n sortSchema: true,\n debug: true,\n installSubscriptionHandlers: true,\n context: ({ req }) => ({ req }),\n };\n }\n}\n```\n\n```\n// post.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Post } from './post.entity';\nimport { PostResolver } from './post.resolver';\nimport { PostService } from './post.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Post])],\n providers: [PostService, PostResolver],\n exports: [PostService],\n})\nexport class PostModule {}\n```\n\n```\n// post.entity.ts\nimport { Field, ID, ObjectType } from '@nestjs/graphql';\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity('post')\n@ObjectType()\nexport class Post {\n @Field(() => ID)\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Field()\n @Column({ nullable: false })\n title: string;\n\n @Field()\n @Column({ nullable: false, unique: true })\n slug: string;\n\n @Field()\n @Column({ nullable: false })\n content: string;\n\n @Field()\n @Column({ type: 'timestamp' })\n createdAt: Date;\n\n @Field()\n @Column({ type: 'timestamp', nullable: true })\n updatedAt: Date;\n}\n```\n\nDoes anyone can highlight what's wrong with my project?\n\n========================================\n\nTop Answer:\nAs I got to know from the official documentation of nestjs. It's a version issue.\n\nTo avoid this issue just install\n\n```\nnpm i @nestjs/graphql graphql@^15 apollo-server-express\n```\n\nfor better understanding - refer to documentation of nestjs\n\nGraphql with nestjs\n\n========================================\n\nCode:\n```sh\n[Nest] 22727  - 10/30/2021, 10:11:10 AM     LOG [NestFactory] Starting Nest application...\n[Nest] 22727  - 10/30/2021, 10:11:10 AM     LOG [InstanceLoader] AppModule dependencies initialized +43ms\n[Nest] 22727  - 10/30/2021, 10:11:10 AM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727  - 10/30/2021, 10:11:10 AM     LOG [InstanceLoader] ConfigHostModule dependencies initialized +7ms\n[Nest] 22727  - 10/30/2021, 10:11:10 AM     LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727  - 10/30/2021, 10:11:10 AM     LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727  - 10/30/2021, 10:11:11 AM     LOG [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +21ms\n[Nest] 22727  - 10/30/2021, 10:11:11 AM     LOG [InstanceLoader] GraphQLModule dependencies initialized +1ms\n[Nest] 22727  - 10/30/2021, 10:11:11 AM     LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +93ms\n[Nest] 22727  - 10/30/2021, 10:11:11 AM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727  - 10/30/2021, 10:11:11 AM     LOG [InstanceLoader] PostModule dependencies initialized +0ms\n\n/workspace/node_modules/graphql/type/schema.js:35\n    throw new Error(\n          ^\nError: Expected undefined to be a GraphQL schema.\n    at assertSchema (/workspace/node_modules/graphql/type/schema.js:35:11)\n    at validateSchema (/workspace/node_modules/graphql/type/validate.js:34:28)\n    at graphqlImpl (/workspace/node_modules/graphql/graphql.js:52:64)\n    at /workspace/node_modules/graphql/graphql.js:21:43\n    at new Promise (<anonymous>)\n    at graphql (/workspace/node_modules/graphql/graphql.js:21:10)\n    at GraphQLSchemaFactory.create (/workspace/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:48:60)\n    at GraphQLSchemaBuilder.buildSchema (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:62:52)\n    at GraphQLSchemaBuilder.build (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:24:31)\n    at GraphQLFactory.mergeOptions (/workspace/node_modules/@nestjs/graphql/dist/graphql.factory.js:33:69)\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphqlOptions } from './config/graphql.config';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { PostModule } from './post/post.module';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n    GraphQLModule.forRootAsync({\n      useClass: GraphqlOptions,\n    }),\n    PostModule,\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n// graphql.config.ts\nimport { Injectable } from '@nestjs/common';\nimport { GqlModuleOptions, GqlOptionsFactory } from '@nestjs/graphql';\n\n@Injectable()\nexport class GraphqlOptions implements GqlOptionsFactory {\n  createGqlOptions(): Promise<GqlModuleOptions> | GqlModuleOptions {\n    return {\n      autoSchemaFile: 'schema.gql',\n      sortSchema: true,\n      debug: true,\n      installSubscriptionHandlers: true,\n      context: ({ req }) => ({ req }),\n    };\n  }\n}\n```\n\n```text\n// post.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Post } from './post.entity';\nimport { PostResolver } from './post.resolver';\nimport { PostService } from './post.service';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Post])],\n  providers: [PostService, PostResolver],\n  exports: [PostService],\n})\nexport class PostModule {}\n```\n\n```text\n// post.entity.ts\nimport { Field, ID, ObjectType } from '@nestjs/graphql';\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity('post')\n@ObjectType()\nexport class Post {\n  @Field(() => ID)\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Field()\n  @Column({ nullable: false })\n  title: string;\n\n  @Field()\n  @Column({ nullable: false, unique: true })\n  slug: string;\n\n  @Field()\n  @Column({ nullable: false })\n  content: string;\n\n  @Field()\n  @Column({ type: 'timestamp' })\n  createdAt: Date;\n\n  @Field()\n  @Column({ type: 'timestamp', nullable: true })\n  updatedAt: Date;\n}\n```\n\n```text\nfunction graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {\n  var _arguments = arguments;\n\n  /* eslint-enable no-redeclare */\n  // Always return a Promise for a consistent API.\n  return new Promise(function (resolve) {\n    return resolve( // Extract arguments from object args if provided.\n    _arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({\n      schema: argsOrSchema,\n      source: source,\n      rootValue: rootValue,\n      contextValue: contextValue,\n      variableValues: variableValues,\n      operationName: operationName,\n      fieldResolver: fieldResolver,\n      typeResolver: typeResolver\n    }));\n  });\n}\n```\n\n```text\n@nestjs/graphql@9.1.1\n```\n\n```text\nGraphQL@16\n```\n\n```text\nGraphQL@16\n```\n\n```text\ngqaphql\n```\n\n```text\ngraphqlImpl\n```\n\n```text\ngraphql\n```\n\n```text\nnpm i @nestjs/graphql graphql@^15 apollo-server-express\n```\n\n========================================\n\nComments:\n- After downgrade to version 15.7.2, everything started working. You saved my day!!!\n- Also tested with 15.8.0, thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":326,"estimatedTokens":2584}}252{"id":"stack-51466859","source":"stackoverflow","questionId":51466859,"title":"Publish nestjs application in GAE","tags":["google-app-engine","nestjs"],"text":"Title: Publish nestjs application in GAE\nTags: google-app-engine, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm learning nestjs and I followed this step by step.\n\nThe application works correctly. But I want to post it as a microservice in my GAE. I'm also able to do this part well, but when I call the address in the GPC, I'm getting the error 502 - Bad Gateway.\n\nI believe it's something in my package.json file. But I have not figured it out yet. The following is the dependencies configuration:\n\n```\n\"dependencies\": {\nย ย  \"@ nestjs / common\": \"^ 5.0.0\",\nย ย  \"@ nestjs / core\": \"^ 5.0.0\",\nย ย  \"@ nestjs / microservices\": \"^ 5.0.0\",\nย ย  \"@ nestjs / testing\": \"^ 5.0.0\",\nย ย  \"@ nestjs / websockets\": \"^ 5.0.0\",\nย ย  \"reflect-metadata\": \"^ 0.1.12\",\nย ย  \"rxjs\": \"^ 6.0.0\",\nย ย  \"typescript\": \"^ 2.8.0\",\nย ย  \"ts-node\": \"^ 6.0.0\",\nย ย  \"tsconfig-paths\": \"^ 3.3.1\"\nย ย  },\n```\n\nThis is my start instruction:\n\n```\n\"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n```\n\nFinally, my app.yaml:\n\n```\nenv: flex \nruntime: nodejs \nservice: nestapp\n```\n\n========================================\n\nTop Answer:\nThe changes required to a\n\n```\nnest new \n```\n\nare:\n\npackage.json\n(main property and some scripts)\n\n```\n{\n ...\n+ \"main\": \"dist/main.js\",\n \"scripts\": {\n...\n- \"build\": \"nest build\",\n+ \"build\": \"tsc -p tsconfig.build.json\",\n+ \"gcp-build\": \"npm run build\",\n...\n- \"start\": \"nest start\",\n+ \"start\": \"node ./dist/main.js\", \n }\n...\n}\n```\n\nsrc/main.ts\n(add port environment variable to be listened to)\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n- await app.listen(3000);\n+ const PORT = Number(process.env.PORT) || 8080;\n+ await app.listen(PORT);\n }\n bootstrap();\n```\n\nAdditionally its suggested to add a deploy script on the package.json script\n\nwith the devDependency @google-cloud/nodejs-repo-tools\n\n```\n+ \"deploy\": \"gcloud app deploy\"\n```\n\nNote: The solution is @Kim T, I just added it formatted in this way because I had troubling reading and executing it fast\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\nย ย  \"@ nestjs / common\": \"^ 5.0.0\",\nย ย  \"@ nestjs / core\": \"^ 5.0.0\",\nย ย  \"@ nestjs / microservices\": \"^ 5.0.0\",\nย ย  \"@ nestjs / testing\": \"^ 5.0.0\",\nย ย  \"@ nestjs / websockets\": \"^ 5.0.0\",\nย ย  \"reflect-metadata\": \"^ 0.1.12\",\nย ย  \"rxjs\": \"^ 6.0.0\",\nย ย  \"typescript\": \"^ 2.8.0\",\nย ย  \"ts-node\": \"^ 6.0.0\",\nย ย  \"tsconfig-paths\": \"^ 3.3.1\"\nย ย  },\n```\n\n```text\n\"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n```\n\n```text\nenv: flex \nruntime: nodejs \nservice: nestapp\n```\n\n```text\n\"build\": \"tsc -p tsconfig.build.json\",\n\"gcp-build\": \"npm run build\"\n```\n\n```text\n\"main\": \"dist/main.js\",\n```\n\n```text\nconst PORT = Number(process.env.PORT) || 8080;\nawait app.listen(PORT);\n```\n\n```text\nruntime: nodejs10\n```\n\n```text\n{\n  \"name\": \"appengine-nest\",\n  \"description\": \"An example TypeScript app running on Google App Engine.\",\n  \"version\": \"0.0.1\",\n  \"author\": \"kmturley\",\n  \"license\": \"MIT\",\n  \"engines\": {\n    \"node\": \">=8.0.0\"\n  },\n  \"main\": \"dist/main.js\",\n  \"scripts\": {\n    \"prepare\": \"npm run build\",\n    \"pretest\": \"npm run build\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"deploy\": \"gcloud app deploy\",\n    \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n    \"start\": \"node ./dist/main.js\",\n    \"start:dev\": \"nodemon\",\n    \"start:debug\": \"nodemon --config nodemon-debug.json\",\n    \"test\": \"repo-tools test app -- dist/main.js\",\n    \"gcp-build\": \"npm run build\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^5.6.2\",\n    \"@nestjs/core\": \"^5.6.2\",\n    \"express\": \"^4.16.3\",\n    \"nodemon\": \"^1.18.9\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rxjs\": \"^6.3.3\",\n    \"ts-node\": \"^8.0.2\",\n    \"tsconfig-paths\": \"^3.7.0\",\n    \"typescript\": \"^3.0.1\"\n  },\n  \"devDependencies\": {\n    \"@google-cloud/nodejs-repo-tools\": \"^3.0.0\",\n    \"@types/express\": \"^4.16.0\",\n    \"tslint\": \"^5.11.0\"\n  }\n}\n```\n\n```text\n\"gcp-build\"\n```\n\n```text\nenv: flex\n```\n\n```text\nnest new <project>\n```\n\n```text\n{\n    ...\n+  \"main\": \"dist/main.js\",\n   \"scripts\": {\n...\n-    \"build\": \"nest build\",\n+    \"build\": \"tsc -p tsconfig.build.json\",\n+    \"gcp-build\": \"npm run build\",\n...\n-    \"start\": \"nest start\",\n+    \"start\": \"node ./dist/main.js\",    \n   }\n...\n}\n```\n\n```text\nasync function bootstrap() {\n   const app = await NestFactory.create(AppModule);\n-  await app.listen(3000);\n+  const PORT = Number(process.env.PORT) || 8080;\n+  await app.listen(PORT);\n }\n bootstrap();\n```\n\n```text\n+    \"deploy\": \"gcloud app deploy\"\n```\n\n```text\n**cloudbuild.yaml**\n\nsubstitutions:\n  _BRANCH_NAME: ${BRANCH_NAME}\n\nsteps:\n  - name: 'gcr.io/cloud-builders/gcloud'\n    args: ['app', 'deploy']\n\noptions:\n  logging: CLOUD_LOGGING_ONLY\n```\n\n========================================\n\nComments:\n- I've updated my answer to to show exactly how I got it to work, with an example repo :)\n- It is iimportant to state that the changes required are, the start, build and gcp-build comands, the main property on the package.json and the modification to the src/main.ts to add the port environment variable.\n- Be aware that if you don't build your project using the `nest` command your nest-cli plugins (i.e.: Swagger) won't work at build time.","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":245,"estimatedTokens":1286}}253{"id":"stack-52030009","source":"stackoverflow","questionId":52030009,"title":"NestJS with TypeORM: When using custom repository, is a service needed anymore?","tags":["nestjs","typeorm"],"text":"Title: NestJS with TypeORM: When using custom repository, is a service needed anymore?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nNewbie question:\nWhen working with NestJS and TypeORM, and one has created a custom repository (which extends the standard repository), **is a seperate service class needed anymore?**\n\nAt the moment, I'm working only with the custom Repository class and it works fine, but I'm not sure if this is correct and perhaps has some side effects.\n\nBtw, in another project i have no custom repo, only a service which get's two standard repo's injected, and this works also fine.\n\nRegards,\n\nsagerobert\n\n========================================\n\nCode:\n```js\nimport {Controller, Get} from '@nestjs/common';\nimport {InjectRepository} from '@nestjs/typeorm';\nimport {Repository} from 'typeorm';\nimport {User} from './entities/User.entity';\n\n@Controller()\nexport class AppController {\n    constructor(\n        @InjectRepository(User)\n        private readonly userRepository: Repository<User>,\n    ) {\n    }\n\n    @Get()\n    async root(): Promise<User> {\n        return await this.userRepository.find(1);\n    }\n}\n```\n\n========================================\n\nComments:\n- A separate repository layer does become useful if you want to use complex queries where you have lengthy sqls or complex query builders. This layer would abstract out all the db specific logic from the service layer.\n- Thanks for the great explantion, now I'm on it. The last sentence says it all: \"A service class is not needed. But it will help you keep your code clean\".\n- You are right, i should probably put it at the top and add a tldr mention\n- Do you know if it's possible to inject a Custom Repository into a Service when not using NestJS? Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":47,"estimatedTokens":439}}254{"id":"stack-53473153","source":"stackoverflow","questionId":53473153,"title":"How to construct DTO in Nest.js for @Body","tags":["javascript","nestjs","typeorm"],"text":"Title: How to construct DTO in Nest.js for @Body\nTags: javascript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in Nest.js and I found it extremely good. I read the official docs and learned about DTOs. When My Body is like this:\n\n\r\n\r\n\n```\n{\r\n \"username\" : \"username\",\r\n \"password\" : \"password\"\r\n}\n```\n\n\r\n\r\n\r\n\nthen I can simply create `user.dto.ts` like this:\n\n\r\n\r\n\n```\nimport { IsNotEmpty } from 'class-validator';\r\n\r\nexport class UserDTO {\r\n @IsNotEmpty()\r\n username: string;\r\n @IsNotEmpty()\r\n password: string;\r\n}\n```\n\n\r\n\r\n\r\n\nThen I use this in my controller like this.\n\n\r\n\r\n\n```\n@Post('login')\r\n @UsePipes(new ValidationPipe())\r\n login(@Body() data: UserDTO) {\r\n return this.userService.login(data);\r\n }\n```\n\n\r\n\r\n\r\n\nBut my question is what if my Body is something like this.\n\n\r\n\r\n\n```\n{\r\n \"data\": {\r\n \"username\": \"username\",\r\n \"password\": \"password\",\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nthen what modifications I need to make in my ```user.dto.ts`` file to make it work? Thanks\n\n========================================\n\nTop Answer:\nYou may create a wrapper class that would carry your dto such as\n\n```\nexport class Data {\n\n @ApiModelProperty()\n readonly data: T;\n\n constructor(data: any = {}) {\n this.data = data;\n }\n}\n```\n\nand in your controller you will have\n\n```\n@Post('login')\n@UsePipes(new ValidationPipe())\nlogin(@Body() data: Data) {\n return this.userService.login(data);\n}\n```\n\nin your service you will do something like\n\n```\nreturn new Data(this.userDto);\n```\n\n========================================\n\nCode:\n```js\n{\n  \"username\" : \"username\",\n  \"password\" : \"password\"\n}\n```\n\n```js\nimport { IsNotEmpty } from 'class-validator';\n\nexport class UserDTO {\n  @IsNotEmpty()\n  username: string;\n  @IsNotEmpty()\n  password: string;\n}\n```\n\n```js\n@Post('login')\n  @UsePipes(new ValidationPipe())\n  login(@Body() data: UserDTO) {\n    return this.userService.login(data);\n  }\n```\n\n```js\n{\n  \"data\": {\n    \"username\": \"username\",\n    \"password\": \"password\",\n  }\n}\n```\n\n```text\nuser.dto.ts\n```\n\n```text\n@Post('login')\n@UsePipes(new ValidationPipe())\nlogin(@Body('data') data: UserDTO) {\n   // data will be your req.body.data which is your UserDTO\n   return this.userService.login(data);\n}\n```\n\n```text\nDTO\n```\n\n```text\n@Body()\n```\n\n```text\n@Body(path?: string)\n```\n\n```text\n@Body()\n```\n\n```text\n@Body()\n```\n\n```text\nreq.body\n```\n\n```text\n@Body('path')\n```\n\n```text\nreq.body.path\n```\n\n```text\nreq.body['path']\n```\n\n```text\n'data'\n```\n\n```text\n@Body('data')\n```\n\n```text\nreq.body.data\n```\n\n```text\nDTO\n```\n\n```text\nexport class Data<T> {\n\n  @ApiModelProperty()\n  readonly data: T;\n\n  constructor(data: any = {}) {\n    this.data = data;\n  }\n}\n```\n\n```text\n@Post('login')\n@UsePipes(new ValidationPipe())\nlogin(@Body() data: Data<UserDTO>) {\n return this.userService.login(data);\n}\n```\n\n```text\nreturn new Data(this.userDto);\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":237,"estimatedTokens":708}}255{"id":"stack-65981642","source":"stackoverflow","questionId":65981642,"title":"Two endpoints for same controller (route aliases) in NestJS","tags":["node.js","typescript","nestjs"],"text":"Title: Two endpoints for same controller (route aliases) in NestJS\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to change an entity name from **Person** to **Individual**. I want to keep the old `/person` endpoint (for temporary backward compatibility) and add a new `/individual` endpoint.\n\nWhat would be the easiest way to do it in Node.js using Nest?\n\nI can copy the code but I'm hoping for a better solution that won't require duplication\n\n========================================\n\nTop Answer:\nIn NestJS, We can have multiple routes for the whole controller or for a single route. This is supported for all HTTP methods (POST, GET, PATCH etc., )\n\n```\n@Controller(['route-1', 'route-2'])\nexport class IndividualController {\n\n @Get(['/sub-route-1','/sub-route-2'])\n public async getSomething(...){...}\n```\n\nAll HTTP methods support either a single string route or an array of string routes. We could use this technique to deprecate a bad route and start introducing a better route without breaking the consumers immediately.\n\n========================================\n\nCode:\n```text\n/person\n```\n\n```text\n/individual\n```\n\n```js\nimport { Controller, Get } from '@nestjs/common';\n\n@Controller(['person', 'individual'])\nexport class IndividualController {\n  @Get()\n  findAll(): { /* ... */ }\n}\n```\n\n```text\n@Controller()\n```\n\n```js\n// your controller code\nconst doSomethingWithPersonEntity = (req, res, next) => {\n   res.status(200).json(persons);\n}\n\nrouter.get(\"/person\", doSomethingWithPersonEntity);\nrouter.get(\"/individual\", doSomethingWithPersonEntity);\n```\n\n```text\nexpressjs\n```\n\n```text\njestjs\n```\n\n```text\n@Controller(['route-1', 'route-2'])\nexport class IndividualController {\n\n  @Get(['/sub-route-1','/sub-route-2'])\n  public async getSomething(...){...}\n```\n\n========================================\n\nComments:\n- This is exactly what I need but seems that maybe I'm using an older version of Nest. What version are you using?\n- this feature was added on Nestjs v6\n- It does not work with @Post(['v1/:id', 'v1'])","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":83,"estimatedTokens":513}}256{"id":"stack-67879357","source":"stackoverflow","questionId":67879357,"title":"Nestjs: How to use mongoose to start a session for transaction?","tags":["mongoose","nestjs"],"text":"Title: Nestjs: How to use mongoose to start a session for transaction?\nTags: mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nThe mongoose documentation to use a transaction is straightforward but when it is followed in nestjs, it returns an error:\n\n```\nConnection 0 was disconnected when calling `startSession`\nMongooseError: Connection 0 was disconnected when calling `startSession`\n at NativeConnection.startSession\n```\n\nMy code:\n\n```\nconst transactionSession = await mongoose.startSession();\n transactionSession.startTransaction();\n\n try\n {\n const newSignupBody: CreateUserDto = {password: hashedPassword, email, username};\n \n const user: User = await this.userService.create(newSignupBody);\n\n //save the profile.\n const profile: Profile = await this.profileService.create(user['Id'], signupDto);\n\n const result:AuthResponseDto = this.getAuthUserResponse(user, profile);\n\n transactionSession.commitTransaction();\n return result;\n }\n catch(err)\n {\n transactionSession.abortTransaction();\n }\n finally\n {\n transactionSession.endSession();\n }\n```\n\n========================================\n\nTop Answer:\nIn addition to the answer provided by Noobish I would like to demonstrate a reusable function that I use in my projects:\n\n```\nimport { ClientSession, Connection } from 'mongoose';\n\nexport const transaction = async (connection: Connection, cb: (session: ClientSession) => Promise): Promise => {\n const session = await connection.startSession();\n\n try {\n session.startTransaction();\n const result = await cb(session);\n await session.commitTransaction();\n return result;\n } catch (err) {\n await session.abortTransaction();\n throw err;\n } finally {\n await session.endSession();\n }\n}\n```\n\nIt can then be used i.e. like this:\n\n```\n@Injectable()\nexport class MyService {\n constructor(\n @InjectModel(MyModel.name) private myModel: Model,\n @InjectConnection() private connection: Connection,\n ) {}\n\n async find(id: string): Promise {\n return transaction(this.connection, async session => {\n return this.myModel\n .findOne(id)\n .session(session);\n });\n }\n\n async create(myDto: MyDto): Promise {\n return transaction(this.connection, async session => {\n const newDoc = new this.myModel(myDto);\n return newDoc.save({ session });\n });\n }\n```\n\nObviously, the above example is just for demonstration purposes in which a transaction is not necessary, since the operations are already atomic. However, one could extend the inner callback with a more complex example in which the operations would not be atomic, such as:\n\n- Creating a document that has a reference to a document of another schema\n\n- Lookup if that referenced document exists and if so, add it to an array (One-to-many relation)\n\n- If the referenced document doesn't exist, throw an error. This would abort the transaction and rollback all changes, such as deleting the document created in step 1. One needs to carefully specify the `session` though in all these steps\n\n========================================\n\nCode:\n```text\nConnection 0 was disconnected when calling `startSession`\nMongooseError: Connection 0 was disconnected when calling `startSession`\n    at NativeConnection.startSession\n```\n\n```text\nconst transactionSession = await mongoose.startSession();\n    transactionSession.startTransaction();\n\n    try\n    {\n      const newSignupBody: CreateUserDto = {password: hashedPassword, email, username};\n  \n      const user: User = await this.userService.create(newSignupBody);\n\n      //save the profile.\n      const profile: Profile = await this.profileService.create(user['Id'], signupDto);\n\n      const result:AuthResponseDto = this.getAuthUserResponse(user, profile);\n\n      transactionSession.commitTransaction();\n      return result;\n    }\n    catch(err)\n    {\n      transactionSession.abortTransaction();\n    }\n    finally\n    {\n      transactionSession.endSession();\n    }\n```\n\n```js\nimport {InjectConnection} from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\n```\n\n```js\nexport class AuthService {\nconstructor(\n  // other dependencies...\n  @InjectConnection() private readonly connection: mongoose.Connection){}\n```\n\n```js\nconst transactionSession = await mongoose.startSession();\ntransactionSession.startTransaction();\n```\n\n```js\nconst transactionSession = await this.connection.startSession();\ntransactionSession.startTransaction();\n```\n\n```ts\nimport { ClientSession, Connection } from 'mongoose';\n\nexport const transaction = async <T>(connection: Connection, cb: (session: ClientSession) => Promise<T>): Promise<T> => {\n  const session = await connection.startSession();\n\n  try {\n    session.startTransaction();\n    const result = await cb(session);\n    await session.commitTransaction();\n    return result;\n  } catch (err) {\n    await session.abortTransaction();\n    throw err;\n  } finally {\n    await session.endSession();\n  }\n}\n```\n\n```ts\n@Injectable()\nexport class MyService {\n  constructor(\n    @InjectModel(MyModel.name) private myModel: Model<MyModelDocument>,\n    @InjectConnection() private connection: Connection,\n  ) {}\n\n  async find(id: string): Promise<MyModelDocument> {\n    return transaction(this.connection, async session => {\n      return this.myModel\n        .findOne(id)\n        .session(session);\n    });\n  }\n\n  async create(myDto: MyDto): Promise<MyModelDocument> {\n    return transaction(this.connection, async session => {\n      const newDoc = new this.myModel(myDto);\n      return newDoc.save({ session });\n    });\n  }\n```\n\n```text\nsession\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport abstract class DbSession<T> {\n  public abstract start(): Promise<void>;\n  public abstract commit(): Promise<void>;\n  public abstract end(): Promise<void>;\n  public abstract abort(): Promise<void>;\n  public abstract get(): T | null;\n}\n```\n\n```js\nimport { InjectConnection } from '@nestjs/mongoose';\nimport { Injectable } from '@nestjs/common';\nimport * as mongoose from 'mongoose';\nimport { RequestScope } from 'nj-request-scope';\n\nimport { DbSession } from '../../abstracts';\n\n@Injectable()\n@RequestScope()\nexport class MongoDbSession implements DbSession<mongoose.ClientSession> {\n  constructor(\n    @InjectConnection()\n    private readonly connection: mongoose.Connection\n  ) {}\n\n  private session: mongoose.ClientSession | null = null;\n\n  public async start() {\n    if (this.session) {\n      if (this.session.inTransaction()) {\n        await this.session.abortTransaction();\n        await this.session.endSession();\n        throw new Error('Session already in transaction');\n      }\n      await this.session.endSession();\n    }\n    this.session = await this.connection.startSession();\n    this.session.startTransaction({\n      readConcern: { level: 'majority' },\n      writeConcern: { w: 'majority' },\n      readPreference: 'primary',\n      retryWrites: true,\n    });\n  }\n\n  public async commit() {\n    if (!this.session) {\n      throw new Error('Session not started');\n    }\n    await this.session.commitTransaction();\n  }\n\n  public async end() {\n    if (!this.session) {\n      throw new Error('Session not started');\n    }\n    await this.session.endSession();\n  }\n\n  public async abort() {\n    if (!this.session) {\n      throw new Error('Session not started');\n    }\n    await this.session.abortTransaction();\n  }\n\n  public get() {\n    return this.session;\n  }\n}\n```\n\n```js\nimport {\n  CallHandler,\n  ExecutionContext,\n  Injectable,\n  Logger,\n  NestInterceptor,\n} from '@nestjs/common';\nimport { Observable, tap } from 'rxjs';\n\nimport { DbSession } from '../abstracts/services';\n\n@Injectable()\nexport class DbSessionInterceptor implements NestInterceptor {\n  constructor(private readonly dbSession: DbSession<unknown>) {}\n\n  private readonly logger = new Logger(DbSessionInterceptor.name);\n\n  async intercept(\n    _: ExecutionContext,\n    next: CallHandler\n  ): Promise<Observable<any>> {\n    await this.dbSession.start();\n\n    return next.handle().pipe(\n      tap({\n        finalize: async () => {\n          await this.dbSession.commit();\n          await this.dbSession.end();\n        },\n        error: async (err: Error) => {\n          await this.dbSession.abort();\n          await this.dbSession.end();\n          this.logger.error(err);\n          throw err;\n        },\n      })\n    );\n  }\n}\n```\n\n```js\nimport { UseInterceptors, applyDecorators } from '@nestjs/common';\nimport { Resolver } from '@nestjs/graphql';\n\nimport { DbSessionInterceptor } from '../abstracts';\n\nexport function ResolverWithDbSession(resolverParams?: any) {\n  return applyDecorators(\n    Resolver(resolverParams),\n    UseInterceptors(DbSessionInterceptor)\n  );\n}\n```\n\n```js\nimport { Inject, Logger } from '@nestjs/common';\n\nimport { DbSession } from '../abstracts';\n\nexport function WithSessionDb() {\n  const dbSessionInjector = Inject(DbSession);\n\n  return function decorator(\n    target: any,\n    _propertyKey: string,\n    descriptor: any // PropertyDescriptor\n  ): void {\n    dbSessionInjector(target, 'dbSession');\n    const method = descriptor.value;\n    const logger = new Logger(`${WithSessionDb.name}#${method.name}`);\n\n    descriptor.value = async function wrapper(...args: any[]) {\n      try {\n        await this.dbSession.start();\n        const result = await method.apply(this, args);\n        await this.dbSession.commit();\n        return result;\n      } catch (error) {\n        await this.dbSession.abort();\n        logger.error(error);\n        throw error;\n      } finally {\n        await this.dbSession.end();\n      }\n    };\n  };\n}\n```\n\n```js\nimport { Global, Module } from '@nestjs/common';\nimport { RequestScopeModule } from 'nj-request-scope';\n\nimport { MongoDbSession } from './mongo';\nimport { DbSession } from './abstracts';\n\n@Global()\n@Module({\n  imports: [RequestScopeModule],\n  providers: [\n    {\n      provide: DbSession,\n      useClass: MongoDbSession,\n    },\n  ],\n  exports: [DbSession],\n})\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport class DataServicesModule {}\n```\n\n```js\n// ...\nimport { DbSession } from '../../frameworks/data-services';\n// ...\n\n@Injectable()\nexport class SomeRandomService {\n  constructor(\n    @InjectModel(SomeRandomModel.name)\n    private readonly someRandomModel: Model<SomeRandomDocument>,\n    // ...\n    private readonly dbSession: DbSession<mongoose.ClientSession>\n  ) {}\n\n  \n  async countRandom() {\n    return this.someRandomModel.countDocuments().session(this.dbSession.get()).exec();\n  }\n\n  // ...\n}\n```\n\n```text\nonModuleInit()\n```\n\n```text\ndata-services.module.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":428,"estimatedTokens":2615}}257{"id":"stack-66786969","source":"stackoverflow","questionId":66786969,"title":"NestJS/Mongoose - Create an Array of Object with reference to another Schema","tags":["node.js","typescript","mongoose","nestjs"],"text":"Title: NestJS/Mongoose - Create an Array of Object with reference to another Schema\nTags: node.js, typescript, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm building the back-end side of a personal application, and I have two particular models/schemas. One if for Products an another for Orders. I want to do the following:\n\nThe Orders need to have the following array with this structure:\n\n```\nproducts: [\n {\n product: string;\n quantity: number;\n }\n]\n```\n\nThe product should be an `ObjectId` of mongo, and this needs a reference for a 'Product' model.\n\nHow I can reach this? I don't really know how to \"type\" this with the `@Prop()` decorator.\n\n```\n@Prop({\n // HOW I DO THIS?\n})\nproducts: [{ quantity: number; product: mongoose.Types.ObjectId }];\n```\n\nThis is my Order Schema:\n\n```\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Document } from 'mongoose';\n\nexport type OrderDocument = Order & Document;\n\n@Schema()\nexport class Order {\n @Prop({ type: String, required: true })\n name: string;\n\n @Prop({ type: Number, min: 0, required: true })\n total: number;\n\n @Prop({\n type: String,\n default: 'PENDING',\n enum: ['PENDING', 'IN PROGRESS', 'COMPLETED'],\n })\n status: string;\n\n @Prop({\n // HOW I DO THIS?\n })\n products: [{ quantity: number; product: mongoose.Types.ObjectId }];\n\n @Prop({\n type: mongoose.Schema.Types.ObjectId,\n ref: 'Customer',\n required: true,\n })\n customer: mongoose.Types.ObjectId;\n\n @Prop({\n type: mongoose.Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n })\n owner: mongoose.Types.ObjectId;\n\n @Prop({ type: Date, default: Date.now() })\n createdAt: Date;\n}\n\nexport const OrderSchema = SchemaFactory.createForClass(Order);\n```\n\n========================================\n\nTop Answer:\nThe best way to achieve both reference population and mongoose schema validation is to create a subschema for the nested entity.\n\n```\nimport { Document, SchemaTypes, Types } from 'mongoose';\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\n@Schema({ _id: false, versionKey: false })\nclass OrderProduct {\n @Prop({ required: true })\n quantity: number;\n\n @Prop({ type: [SchemaTypes.ObjectId], ref: 'Product', required: true })\n product: Product[];\n}\n\nconst OrderProductSchema = SchemaFactory.createForClass(OrderProduct);\n\n@Schema()\nexport class Order {\n // other order schema props ...\n\n @Prop([{ type: OrderProductSchema }])\n products: OrderProduct[];\n}\n```\n\n========================================\n\nCode:\n```js\nproducts: [\n  {\n    product: string;\n    quantity: number;\n  }\n]\n```\n\n```js\n@Prop({\n    // HOW I DO THIS?\n})\nproducts: [{ quantity: number; product: mongoose.Types.ObjectId }];\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Document } from 'mongoose';\n\nexport type OrderDocument = Order & Document;\n\n@Schema()\nexport class Order {\n  @Prop({ type: String, required: true })\n  name: string;\n\n  @Prop({ type: Number, min: 0, required: true })\n  total: number;\n\n  @Prop({\n    type: String,\n    default: 'PENDING',\n    enum: ['PENDING', 'IN PROGRESS', 'COMPLETED'],\n  })\n  status: string;\n\n  @Prop({\n    // HOW I DO THIS?\n  })\n  products: [{ quantity: number; product: mongoose.Types.ObjectId }];\n\n  @Prop({\n    type: mongoose.Schema.Types.ObjectId,\n    ref: 'Customer',\n    required: true,\n  })\n  customer: mongoose.Types.ObjectId;\n\n  @Prop({\n    type: mongoose.Schema.Types.ObjectId,\n    ref: 'User',\n    required: true,\n  })\n  owner: mongoose.Types.ObjectId;\n\n  @Prop({ type: Date, default: Date.now() })\n  createdAt: Date;\n}\n\nexport const OrderSchema = SchemaFactory.createForClass(Order);\n```\n\n```text\nObjectId\n```\n\n```text\n@Prop()\n```\n\n```text\n@Prop({\n    type:[{quantity:{type:Number}, product:{type:Schema.Types.ObjectId}}]\n  })\n  products: { quantity: number; product: Product }[];\n```\n\n```js\nimport { Document, SchemaTypes, Types } from 'mongoose';\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\n@Schema({ _id: false, versionKey: false })\nclass OrderProduct {\n  @Prop({ required: true })\n  quantity: number;\n\n  @Prop({ type: [SchemaTypes.ObjectId], ref: 'Product', required: true })\n  product: Product[];\n}\n\nconst OrderProductSchema = SchemaFactory.createForClass(OrderProduct);\n\n@Schema()\nexport class Order {\n   // other order schema props ...\n\n  @Prop([{ type: OrderProductSchema }])\n  products: OrderProduct[];\n}\n```\n\n========================================\n\nComments:\n- Maybe you should use mysql or other relational database, because it will be easier for you to organize relationships between tables if there are many of them\n- but when get data by findByIdAndUpdate query i have not receive products key. but in database its available.\n- don't you mean @Prop({ type: [OrderProductSchema] }) ?","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":220,"estimatedTokens":1202}}258{"id":"stack-51692886","source":"stackoverflow","questionId":51692886,"title":"Nest can't resolve dependencies of the UserService (?, +). Please make sure that the argument at index [0] is available in the current context","tags":["dependency-injection","inversion-of-control","circular-dependency","nestjs"],"text":"Title: Nest can't resolve dependencies of the UserService (?, +). Please make sure that the argument at index [0] is available in the current context\nTags: dependency-injection, inversion-of-control, circular-dependency, nestjs\nSource: Stack Overflow\n\nQuestion:\nhaving some problems, di/circular-references I'm sure I'm doing wrong, I just can't see it.\n\nAny help would be much appreciated\n\nuser.module.ts\n\n```\n@Module({\n imports: [\n TypeOrmModule.forFeature([User]),\n forwardRef(() => AuthModule)\n ],\n providers: [ UserService, TokenService ],\n exports: [ UserService ]\n})\nexport class UserModule {}\n```\n\nauth.module.ts\n\n```\n@Module({\n imports: [ forwardRef(() => UserModule) ],\n controllers: [ AuthController ],\n providers: [\n AuthService,\n UserService,\n TokenService\n ],\n exports: [ AuthService, TokenService ]\n})\nexport class AuthModule {}\n```\n\napp.module.ts\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n forwardRef(() => UserModule),\n forwardRef(() => AuthModule),\n ],\n})\nexport class AppModule {}\n```\n\nI get [ExceptionHandler] Cannot read property 'module' of undefined.\n\nWas originally having \"Nest can't resolve dependencies of the UserService. I then deleted the UserModule entirely and just used the AuthModule, everything worked, then decided to add the UserModule back in today and move the code from AuthModule back into the UserModule, then discovered the forwardRef(() => ) and now I'm getting the cannot read property 'model'.\n\nThanks in advance\n\n========================================\n\nTop Answer:\nIn case, you got above error when adding the repository to the service with `TypeORM`, then add below code in the module file\n\n```\nimports: [\n TypeOrmModule.forFeature([])\n],\n```\n\n========================================\n\nCode:\n```text\n@Module({\n    imports: [\n        TypeOrmModule.forFeature([User]),\n        forwardRef(() => AuthModule)\n    ],\n    providers: [ UserService, TokenService ],\n    exports: [ UserService ]\n})\nexport class UserModule {}\n```\n\n```text\n@Module({\n    imports: [ forwardRef(() => UserModule) ],\n    controllers: [ AuthController ],\n    providers: [\n        AuthService,\n        UserService,\n        TokenService\n    ],\n    exports: [ AuthService, TokenService ]\n})\nexport class AuthModule {}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    forwardRef(() => UserModule),\n    forwardRef(() => AuthModule),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nconstructor(@Inject(forwardRef(() => TokenService)) private readonly tokenService: TokenService) {}\n```\n\n```text\nUserService\n```\n\n```text\nforwardRef\n```\n\n```text\nUserModule\n```\n\n```text\nAuthModule\n```\n\n```text\nAuthService\n```\n\n```text\nUserModule\n```\n\n```text\nUserService\n```\n\n```text\nAuthModule\n```\n\n```text\nTokenService\n```\n\n```text\nUserModule\n```\n\n```text\nimports: [\n  TypeOrmModule.forFeature([<your-entity>])\n],\n```\n\n```text\nTypeORM\n```\n\n```text\nproviders: [\n    AService,\n    BService,, // <- NOT ALLOWED CIRCULAR PROBLEM \n  ],\n```\n\n========================================\n\nComments:\n- Could you include the `import`s part of your code?\n- Why `UserService` is defined in the `AuthModule`?\n- I've tried different things, that's the state that I ended up with a different error.\n- In the docs they pointed to use one and not them combined\n- I also had to use both, which is weird\n- You can use tools like prettier, eslint/tslint to avoid this","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":179,"estimatedTokens":843}}259{"id":"stack-64974561","source":"stackoverflow","questionId":64974561,"title":"NestJS Alphabetize Endpoints in SwaggerUI","tags":["swagger","nestjs","swagger-ui","nestjs-swagger"],"text":"Title: NestJS Alphabetize Endpoints in SwaggerUI\nTags: swagger, nestjs, swagger-ui, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nThis SO answer shows that SwaggerUi will sort endpoints alphabetically if it is passed `apisSorter : \"alpha\"` when instantiated. In NestJS the config options are passed in the `SwaggerModule.createDocument`. I cannot see where in the config eg here I can pass this.\n\n========================================\n\nTop Answer:\nTo anyone trying @midopa's solution for FastifySwagger, pass the `tagsSorter` and `operationsSorter` values to `uiConfig` instead of `swaggerOptions`.\n\n```\nconst doc = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup('docs', app, doc, {\n uiConfig: {\n tagsSorter: 'alpha',\n operationsSorter: 'alpha',\n },\n });\n```\n\n**NOTE**: This is for @nestjs/swagger version 6 or less. For v7 or above, `swaggerOptions` will work just fine.\n\n========================================\n\nCode:\n```text\napisSorter : \"alpha\"\n```\n\n```text\nSwaggerModule.createDocument\n```\n\n```js\nconst document = SwaggerModule.createDocument(app, options);\n  SwaggerModule.setup('docs', app, document, {\n    swaggerOptions: {\n      tagsSorter: 'alpha',\n      operationsSorter: 'alpha',\n    },\n  });\n```\n\n```text\nSwaggerModule.setup\n```\n\n```text\nswaggerOptions\n```\n\n```text\nuntyped\n```\n\n```ts\nconst doc = SwaggerModule.createDocument(app, config);\n    SwaggerModule.setup('docs', app, doc, {\n    uiConfig: {\n      tagsSorter: 'alpha',\n      operationsSorter: 'alpha',\n      },\n    });\n```\n\n```text\ntagsSorter\n```\n\n```text\noperationsSorter\n```\n\n```text\nuiConfig\n```\n\n```text\nswaggerOptions\n```\n\n```text\nswaggerOptions\n```\n\n========================================\n\nComments:\n- this works thanks I had seen github.com/nestjs/swagger/blob/&hellip;, but wasn't sure that was the right key...I had tried passing the hash directly, which of course didn't work\n- that atributte not found in nest js swagger version 7 above\n- The answer has been edited to add the version for which this solution was necessary. For @nestjs/swagger v7 or above, `swaggerOptions` will work. Thank you for directing my attention to this.","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":93,"estimatedTokens":535}}260{"id":"stack-62460079","source":"stackoverflow","questionId":62460079,"title":"TypeORM foreign key not showing on a find call","tags":["node.js","nestjs","typeorm"],"text":"Title: TypeORM foreign key not showing on a find call\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nexport class Contact extends BaseEntity {\n ...\n @ManyToOne(() => User, { nullable: false })\n @JoinColumn({ name: 'user_id' })\n user: User;\n ...\n}\n\nconst repo = new Repository ();\nconst response = await repo.findAll();\nconsole.log(response);\n\nconsole.log:\n[\n Contact {\n id: 1,\n ...\n },\n Contact {\n id: 2,\n ...\n }\n]\n```\n\nI am trying to fetch all the columns included on my `Contact`, but I only able to fetch the columns that does not have any relationship from the other entity.\nIt does not include user_id columns. Why can't to get foreign key for instance?\n\n========================================\n\nTop Answer:\nYou can set `eager: true` in order to load User with the find command\n\n```\n@ManyToOne(() => User, { nullable: false, eager: true })\n @JoinColumn({ name: 'user_id' })\n user: User;\n```\n\nLink: https://orkhan.gitbook.io/typeorm/docs/relations\n\n========================================\n\nCode:\n```text\nexport class Contact extends BaseEntity {\n  ...\n  @ManyToOne(() => User, { nullable: false })\n  @JoinColumn({ name: 'user_id' })\n  user: User;\n  ...\n}\n\nconst repo = new Repository<User> ();\nconst response = await repo.findAll();\nconsole.log(response);\n\nconsole.log:\n[\n Contact {\n  id: 1,\n  ...\n },\n Contact {\n  id: 2,\n  ...\n }\n]\n```\n\n```text\nContact\n```\n\n```text\nexport class Contact extends BaseEntity {\n  ...\n  // add column explicitly here\n  @Column({ name: 'user_id' })\n  userId: number;\n\n  @ManyToOne(() => User, { nullable: false })\n  @JoinColumn({ name: 'user_id' })\n  user: User;\n  ...\n}\n```\n\n```text\nuserId\n```\n\n```text\n@JoinColumn\n```\n\n```text\n@ManyToOne(() => User, { nullable: false, eager: true })\n  @JoinColumn({ name: 'user_id' })\n  user: User;\n```\n\n```text\neager: true\n```\n\n========================================\n\nComments:\n- Btw, should I add `{ nullable: false }` to `userId` column?\n- Sure I believe you could add whatever you want ;)\n- \"eager: true\" => now I can see foreign keys in response body. Thanks !","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":118,"estimatedTokens":515}}261{"id":"stack-54727103","source":"stackoverflow","questionId":54727103,"title":"NestJS: How to pass the error from one Error Filter to another?","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: NestJS: How to pass the error from one Error Filter to another?\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS for my application and catch all the errors in a Filter.\nI have some logic where I want every specific error to be formatted and then be sent to the final `ExceptionFilter`. I have the following code:\n\n```\n@Catch()\n export class GlobalErrorFilter implements ExceptionFilter {\n public catch(error: HttpException, host: ArgumentsHost) {\n// do something\n}\n }\n```\n\nAnd also this one:\n\n```\n@Catch(NotFoundException)\nexport class NotfoundFilter implements ExceptionFilter {\n public catch(error: NotFoundException, host: ArgumentsHost) {\n // do something here\n }\n}\n```\n\nIs there a way that the first Filter catches the error after the first one? Thanks!\n\n========================================\n\nTop Answer:\nI see 2 different exceptions here with a specific type. So it should be possible (i think) that after the first filter catches the exception you could have it do something and then throw a new exception of the other type which should then be caught there. Hope it helps\n\n========================================\n\nCode:\n```text\n@Catch()\n    export class GlobalErrorFilter implements ExceptionFilter {\n public catch(error: HttpException, host: ArgumentsHost) {\n// do something\n}\n    }\n```\n\n```text\n@Catch(NotFoundException)\nexport class NotfoundFilter implements ExceptionFilter<NotFoundException> {\n    public catch(error: NotFoundException, host: ArgumentsHost) {\n        // do something here\n    }\n}\n```\n\n```text\nExceptionFilter\n```\n\n```text\n// First NotfoundFilter is checked\n@UseFilters(NotfoundFilter)\n```\n\n```text\n// Then GlobalErrorFilter is checked\napp.useGlobalFilters(new GlobalErrorFilter());\n```\n\n```text\n@UseFilters(GlobalErrorFilter, NotfoundFilter)\n//          ^^^ 2nd            ^^^ 1st\n```\n\n```text\napp.useGlobalFilters(new GlobalErrorFilter(), new NotfoundFilter());\n//                       ^^^ 2nd                  ^^^ 1st\n```\n\n```text\nExceptionFilter\n```\n\n```text\nreturn Promise.reject(error)\n```\n\n========================================\n\nComments:\n- I tried to do that, i.e. throw a new exception from the second Filter. It doesn't work, only one of two filters is triggered.\n- That's a good idea but you must never throw an exception from an `ExceptionFilter`. You can try it, this will cause an `UnhandledPromiseRejectionWarning`. The `ExceptionFilter` is the last place where an error hits and always has to handle it by setting the response correspondingly. Also, only *one* `ExceptionFilter` handles an error. If you have multiple ones that match then the first match according to the priorities explained in my post will be used.\n- I couldn't find this in the official documentation, thanks. Do you know where is this behaviour defined?\n- @IanSebastian I am afraid I do not remember, sorry. It definitely is not in the docs, I either just tried it out or looked at the source code.\n- When a filter is loaded using the APP_FILTER provider, it will take precedence a filter declared in a submodule than in the main app module.","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":96,"estimatedTokens":781}}262{"id":"stack-69178586","source":"stackoverflow","questionId":69178586,"title":"NestJS GraphQL subscriptions not working with `graphql-ws`","tags":["graphql","nestjs","graphql-subscriptions"],"text":"Title: NestJS GraphQL subscriptions not working with `graphql-ws`\nTags: graphql, nestjs, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI'm trying to upgrade our NestJS GraphQL subscriptions server to utilize `graphql-ws` rather than the current `subscriptions-transport-ws` (as suggested by the NestJS documentation).\nI upgraded the NestJS version to\n\n```\n\"@nestjs/core\": \"^8.0.6\",\n \"@nestjs/graphql\": \"^9.0.4\",\n \"@nestjs/platform-express\": \"^8.0.6\",\n \"graphql\": \"^15.5.3\",\n \"graphql-tools\": \"^8.2.0\",\n \"apollo-server-express\": \"^3.3.0\",\n```\n\nAnd after, I added the `subscriptions` option to the `App.Module`:\n\n```\nGraphQLModule.forRoot({\n autoSchemaFile: true,\n sortSchema: true,\n playground: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'graphql-ws': true\n },\n }),\n```\n\nHowever when I subscribe (in playground) to a previously working subscription, I get:\n\n```\n{\n \"error\": \"Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct.\"\n}\n```\n\nAnd in the console I get:\n\n```\nWebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol \"graphql-ws\" requested by the client. graphql-ws implements exclusively the \"graphql-transport-ws\" subprotocol, please make sure that the client implements it too.\n```\n\nThings I have tried:\n\n- Adding the `graphql-ws` package\n\n- Upgrading the NestJS version again\n\n- Removing the `installSubscriptionHandlers` option from config\n\n- Setting `graphql-ws` configs instead of passing `true`\n\n- Using the `WebSocket Test Client` Google Chrome extension instead of Playground\n\nBut none have worked. Sorry for the long post. How can I fix this?\n\n========================================\n\nTop Answer:\nThis will do the job:\n\n```\nsubscriptions: {\n 'graphql-ws': true,\n 'subscriptions-transport-ws': true,\n },\n```\n\nAs mentionned in the doc:\n\nHINT\n\nYou can also use both packages (subscriptions-transport-ws and graphql-ws) at > the same time, for example, for backward compatibility.\n\n========================================\n\nCode:\n```text\n\"@nestjs/core\": \"^8.0.6\",\n    \"@nestjs/graphql\": \"^9.0.4\",\n    \"@nestjs/platform-express\": \"^8.0.6\",\n    \"graphql\": \"^15.5.3\",\n    \"graphql-tools\": \"^8.2.0\",\n    \"apollo-server-express\": \"^3.3.0\",\n```\n\n```text\nGraphQLModule.forRoot({\n      autoSchemaFile: true,\n      sortSchema: true,\n      playground: true,\n      installSubscriptionHandlers: true,\n      subscriptions: {\n        'graphql-ws': true\n      },\n    }),\n```\n\n```text\n{\n  \"error\": \"Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct.\"\n}\n```\n\n```text\nWebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol \"graphql-ws\" requested by the client. graphql-ws implements exclusively the \"graphql-transport-ws\" subprotocol, please make sure that the client implements it too.\n```\n\n```text\ngraphql-ws\n```\n\n```text\nsubscriptions-transport-ws\n```\n\n```text\nsubscriptions\n```\n\n```text\nApp.Module\n```\n\n```text\ngraphql-ws\n```\n\n```text\ninstallSubscriptionHandlers\n```\n\n```text\ngraphql-ws\n```\n\n```text\ntrue\n```\n\n```text\nWebSocket Test Client\n```\n\n```text\nsubscriptions: {\n    'graphql-ws': true,\n    'subscriptions-transport-ws': true,\n  },\n```\n\n========================================\n\nComments:\n- Oh well, that's disappointing. So the Google Chrome extension failed for the same reason as well?","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":158,"estimatedTokens":856}}263{"id":"stack-55431189","source":"stackoverflow","questionId":55431189,"title":"NestJS: Logging the request/response from HttpService calls?","tags":["javascript","node.js","typescript","axios","nestjs"],"text":"Title: NestJS: Logging the request/response from HttpService calls?\nTags: javascript, node.js, typescript, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI was wondering if its possible to log the requests, response and errors using the `HttpService` from the `HttpModule`.\n\nI used to use Interceptors from AXIOS, `HttpService` wraps axios but I can't seem to add any interceptors here, there doesn't seem to be a place in\n\n```\nHttpModule.register(...)\n```\n\nThen I thought that NestJS comes with its own interceptors and wondered if its possible to use NestJS interceptors.\n\nI wouldn't want to apply the interceptor over a controller, service but apply it to the `HttpService`?\n\nAny ideas, a little lost how to do this in the nestjs way.\n\nThanks in advance\n\n========================================\n\nCode:\n```text\nHttpModule.register(...)\n```\n\n```text\nHttpService\n```\n\n```text\nHttpModule\n```\n\n```text\nHttpService\n```\n\n```text\nHttpService\n```\n\n```text\nthis.httpService.axiosRef.interceptors.request.use(config => console.log(config));\n```\n\n```text\nHttpService\n```\n\n```text\naxios\n```\n\n```text\nget axiosRef()\n```\n\n```text\naxios interceptor\n```\n\n```text\nonModuleInit()\n```\n\n```text\nAppModule\n```\n\n========================================\n\nComments:\n- Thanks ! This allows me to continue using my original interceptors, out of interest, am I reinventing the wheel here :-) I mean, is it possible to use nestjs interceptor to do the same job - or its best to stick with AXIO interceptors.\n- It's not possible to use nest interceptors outside of the context of controllers, I wouldn't know how at least. ๐Ÿคท\n- So I think sticking with the axios interceptors is your best option here. Alternatively, you could also build a facade for the `HttpService` that does the logging. But in my opinion, using an Interceptor is cleaner\n- Thank you for your help.\n- @Kim Kern Is it possible to read the cookie from incoming request to controller and pass it on the interceptor for adding it in header for axios request?\n- don't forget to add `return config`, otherwise you might see error like mentioned here for `cancelToken`","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":81,"estimatedTokens":527}}264{"id":"stack-55174802","source":"stackoverflow","questionId":55174802,"title":"NestJS Global Modules in tests","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: NestJS Global Modules in tests\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there a way to automatically provide all `@Global`modules into a `TestModule` ? (i.e without having to import them, the same way the main application works)\n\nSo far, I had to make sure to insert any global modules into the `import` list of my call: \n\n```\nawait Test.createTestingModule({\n imports: [\n GlobalModule1,\n GlobalModule2\n```\n\n========================================\n\nCode:\n```text\nawait Test.createTestingModule({\n      imports: [\n        GlobalModule1,\n        GlobalModule2\n```\n\n```text\n@Global\n```\n\n```text\nTestModule\n```\n\n```text\nimport\n```\n\n```text\nCatsService\n```\n\n```text\nCatsModule\n```\n\n```text\nCommonsModule\n```\n\n```text\nCommonsModule\n```\n\n```text\nAppModule\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":57,"estimatedTokens":201}}265{"id":"stack-55200278","source":"stackoverflow","questionId":55200278,"title":"Nest JS - Issue writing Jest Test Case for a function returning Observable Axios Response","tags":["node.js","typescript","rxjs","jestjs","nestjs"],"text":"Title: Nest JS - Issue writing Jest Test Case for a function returning Observable Axios Response\nTags: node.js, typescript, rxjs, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am fairly new to NestJS + Typescript + RxJs tech stack. I am trying to write a unit test case using Jest for one of my functions but not sure if doing it correctly. \n\n**component.service.ts**\n\n```\npublic fetchComponents(queryParams) {\n const url = this.prepareUrl(queryParams);\n\n const data$ = this.httpService.get(url);\n\n return data$\n .pipe(map(({ data }) => data));\n}\n```\n\n**component.sevice.spec.ts** \n\n Test case works and passes\n\n```\ndescribe('fetchComponents', () => {\n const query = {\n limit: 10,\n offset: 0\n };\n\n const result: AxiosResponse = {\n data: 'Components',\n status: 200,\n statusText: 'OK',\n headers: {},\n config: {}\n };\n it('should return Dummy Data when called successfully', () => {\n componentService.prepareUrl = jest.fn();\n\n jest.spyOn(httpService, 'get').mockImplementation(() => of(result));\n\n componentService.fetchComponents(market, query)\n .subscribe(\n (res) => {\n expect(res).toEqual('Components');\n }\n );\n });\n});\n```\n\nCan you please provide suggestions and pointers on how exactly I should test this function. Also without using Library like `marbel-rx`\nI am not sure if I am testing it correctly. Is there something else also which I should test?\n\n========================================\n\nCode:\n```text\npublic fetchComponents(queryParams) {\n  const url = this.prepareUrl(queryParams);\n\n  const data$ = this.httpService.get(url);\n\n  return data$\n    .pipe(map(({ data }) => data));\n}\n```\n\n```text\ndescribe('fetchComponents', () => {\n  const query = {\n    limit: 10,\n    offset: 0\n  };\n\n  const result: AxiosResponse = {\n    data: 'Components',\n    status: 200,\n    statusText: 'OK',\n    headers: {},\n    config: {}\n  };\n  it('should return Dummy Data when called successfully', () => {\n    componentService.prepareUrl = jest.fn();\n\n    jest.spyOn(httpService, 'get').mockImplementation(() => of(result));\n\n   componentService.fetchComponents(market, query)\n    .subscribe(\n      (res) => {\n        expect(res).toEqual('Components');\n      }\n    );\n  });\n});\n```\n\n```text\nmarbel-rx\n```\n\n```text\nit('should return Dummy Data when called successfully', done => {\n// Add done parameter                                   ^^^^\n  componentService.prepareUrl = jest.fn();\n\n  jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(result));\n// Prefer mockImplementationOnce                   ^^^^\n\n  componentService.fetchComponents(market, query)\n    .subscribe(\n      (res) => {\n        expect(res).toEqual('Components');\n        done();\n//      ^^^^^^  Call done() when test is finished\n      }\n    );\n});\n```\n\n```text\nObservables\n```\n\n```text\ndone\n```\n\n```text\ndone()\n```\n\n```text\nexpect\n```\n\n```text\nsubscribe()\n```\n\n```text\nsubscribe\n```\n\n```text\n'Komponents'\n```\n\n```text\nmockImplementationOnce\n```\n\n```text\nmockImplementation\n```\n\n========================================\n\nComments:\n- Thanks for the code review. I actually wrote a catchError() block in my code and was testing it by calling incorrect URL. Still, Jest was complaining about that piece of code not reachable. The moment I added `done()` callback, that piece of code became reachable in my test and now it's 100%. Super thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.427Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":162,"estimatedTokens":828}}266{"id":"stack-71394797","source":"stackoverflow","questionId":71394797,"title":"NestJs reusable controller with validation","tags":["typescript","nestjs","class-validator"],"text":"Title: NestJs reusable controller with validation\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nMost of my NestJs controllers look the same. They have basic CRUD functionality and do the exact same things.\n\nThe only differences between the controllers are:\n\n- the path\n\n- the service that is injected (and the services are all extended from an abstract service)\n\n- the entity that is returned from the methods\n\n- the create, update, and query dtos\n\nHere is an example CRUD controller:\n\n```\n@UseGuards(JwtAuthGuard)\n@Controller(\"/api/warehouse/goods-receipts\")\nexport class GoodsReceiptsController\n implements ICrudController {\n constructor(private service: GoodsReceiptsService) {\n }\n\n @Post()\n create(@Body() body: CreateGoodsReceiptDto, @CurrentUser() user: Partial): Promise {\n return this.service.createItem(body, user);\n }\n\n @Delete(\":id\")\n delete(@Param() params: NumberIdDto): Promise> {\n return this.service.deleteItem(params.id);\n }\n\n @Get(\":id\")\n getOne(@Param() params: NumberIdDto): Promise {\n return this.service.getItem(params.id);\n }\n\n @Get()\n get(@Query() query: QueryGoodsReceiptDto): Promise {\n return this.service.getItems(query);\n }\n\n @Patch()\n update(@Body() body: UpdateGoodsReceiptDto, @CurrentUser() user: Partial): Promise {\n return this.service.updateItem(body,user);\n }\n}\n```\n\nThis is the interface I have created for my controllers:\n\n```\nexport interface ICrudController {\n\n getOne(id: NumberIdDto): Promise;\n\n get(query: QueryDto): Promise;\n\n create(body: CreateDto, user: Partial): Promise;\n\n update(body: UpdateDto, user: Partial): Promise;\n\n delete(id: NumberIdDto): Promise>;\n}\n```\n\nWriting all these repetitive controllers has got pretty tiresome (yes I know about `nest g resource` but that is not really the point of this question), so I decided to create an abstract controller that will do most of the heavy lifting and have the controllers extend this.\n\n```\nexport abstract class CrudController implements ICrudController {\n protected service: ICrudService;\n\n @Post()\n create(@Body() body: C, @CurrentUser() user: Partial): Promise {\n return this.service.createItem(body, user);\n }\n\n @Get(\":id\")\n getOne(@Param() params: NumberIdDto): Promise {\n return this.service.getItem(params.id);\n }\n\n @Get()\n get(@Query() query: Q): Promise {\n return this.service.getItems(query);\n }\n\n @Delete(\":id\")\n delete(@Param() params: NumberIdDto): Promise> {\n return this.service.deleteItem(params.id);\n }\n\n @Patch()\n update(@Body() body: U, @CurrentUser() user: Partial): Promise {\n return this.service.updateItem(body, user);\n }\n}\n```\n\nNow all I need to do to add a new controller is this:\n\n```\n@UseGuards(JwtAuthGuard)\n@Controller(\"/api/warehouse/goods-receipts\")\nexport class GoodsReceiptsController\n extends CrudController {\n constructor(protected service: GoodsReceiptsService) {\n super();\n }\n}\n```\n\nI was very proud of myself at that point. That is until I figured out that validation no longer works because class-validator doesn't work with generic types.\n\nThere has to be some way I could fix this with minimal intervention and maximal use of reusable code?\n\n========================================\n\nCode:\n```text\n@UseGuards(JwtAuthGuard)\n@Controller(\"/api/warehouse/goods-receipts\")\nexport class GoodsReceiptsController\n  implements ICrudController<GoodsReceipt, CreateGoodsReceiptDto, UpdateGoodsReceiptDto, QueryGoodsReceiptDto> {\n  constructor(private service: GoodsReceiptsService) {\n  }\n\n  @Post()\n  create(@Body() body: CreateGoodsReceiptDto, @CurrentUser() user: Partial<User>): Promise<GoodsReceipt> {\n    return this.service.createItem(body, user);\n  }\n\n  @Delete(\":id\")\n  delete(@Param() params: NumberIdDto): Promise<Partial<GoodsReceipt>> {\n    return this.service.deleteItem(params.id);\n  }\n\n  @Get(\":id\")\n  getOne(@Param() params: NumberIdDto): Promise<GoodsReceipt> {\n    return this.service.getItem(params.id);\n  }\n\n  @Get()\n  get(@Query() query: QueryGoodsReceiptDto): Promise<GoodsReceipt[]> {\n    return this.service.getItems(query);\n  }\n\n  @Patch()\n  update(@Body() body: UpdateGoodsReceiptDto, @CurrentUser() user: Partial<User>): Promise<GoodsReceipt> {\n    return this.service.updateItem(body,user);\n  }\n}\n```\n\n```text\nexport interface ICrudController<EntityType, CreateDto, UpdateDto, QueryDto> {\n\n  getOne(id: NumberIdDto): Promise<EntityType>;\n\n  get(query: QueryDto): Promise<EntityType[]>;\n\n  create(body: CreateDto, user: Partial<User>): Promise<EntityType>;\n\n  update(body: UpdateDto, user: Partial<User>): Promise<EntityType>;\n\n  delete(id: NumberIdDto): Promise<Partial<EntityType>>;\n}\n```\n\n```text\nexport abstract class CrudController<T, C, U, Q> implements ICrudController<T, C, U, Q> {\n  protected service: ICrudService<T, C, U, Q>;\n\n  @Post()\n  create(@Body() body: C, @CurrentUser() user: Partial<User>): Promise<T> {\n    return this.service.createItem(body, user);\n  }\n\n  @Get(\":id\")\n  getOne(@Param() params: NumberIdDto): Promise<T> {\n    return this.service.getItem(params.id);\n  }\n\n  @Get()\n  get(@Query() query: Q): Promise<T[]> {\n    return this.service.getItems(query);\n  }\n\n  @Delete(\":id\")\n  delete(@Param() params: NumberIdDto): Promise<Partial<T>> {\n    return this.service.deleteItem(params.id);\n  }\n\n  @Patch()\n  update(@Body() body: U, @CurrentUser() user: Partial<User>): Promise<T> {\n    return this.service.updateItem(body, user);\n  }\n}\n```\n\n```text\n@UseGuards(JwtAuthGuard)\n@Controller(\"/api/warehouse/goods-receipts\")\nexport class GoodsReceiptsController\n  extends CrudController<GoodsReceipt, CreateGoodsReceiptDto, UpdateGoodsReceiptDto, QueryGoodsReceiptDto> {\n  constructor(protected service: GoodsReceiptsService) {\n    super();\n  }\n}\n```\n\n```text\nnest g resource\n```\n\n```text\n@Injectable()\nexport class AbstractValidationPipe extends ValidationPipe {\n  constructor(\n    options: ValidationPipeOptions,\n    private readonly targetTypes: { body?: Type; query?: Type; param?: Type; }\n  ) {\n    super(options);\n  }\n\n  async transform(value: any, metadata: ArgumentMetadata) {\n    const targetType = this.targetTypes[metadata.type];\n    if (!targetType) {\n      return super.transform(value, metadata);\n    }\n    return super.transform(value, { ...metadata, metatype: targetType });\n  }\n}\n\nexport function ControllerFactory<T, C, U, Q>(\n  createDto: Type<C>,\n  updateDto: Type<U>,\n  queryDto: Type<Q>\n): ClassType<ICrudController<T, C, U, Q>> {\n  const createPipe = new AbstractValidationPipe({ whitelist: true, transform: true }, { body: createDto });\n  const updatePipe = new AbstractValidationPipe({ whitelist: true, transform: true }, { body: updateDto });\n  const queryPipe = new AbstractValidationPipe({ whitelist: true, transform: true }, { query: queryDto });\n\n  class CrudController<T, C, U, Q> implements ICrudController<T, C, U, Q> {\n    protected service: ICrudService<T, C, U, Q>;\n\n    @Post()\n    @UsePipes(createPipe)\n    async create(@Body() body: C, @CurrentUser() user: Partial<User>): Promise<T> {\n      return this.service.createItem(body, user);\n    }\n\n    @Get(\":id\")\n    getOne(@Param() params: NumberIdDto): Promise<T> {\n      return this.service.getItem(params.id);\n    }\n\n    @Get()\n    @UsePipes(queryPipe)\n    get(@Query() query: Q): Promise<T[]> {\n      return this.service.getItems(query);\n    }\n\n    @Delete(\":id\")\n    delete(@Param() params: NumberIdDto): Promise<Partial<T>> {\n      return this.service.deleteItem(params.id);\n    }\n\n    @Patch()\n    @UsePipes(updatePipe)\n    update(@Body() body: U, @CurrentUser() user: Partial<User>): Promise<T> {\n      return this.service.updateItem(body, user);\n    }\n  }\n\n  return CrudController;\n}\n```\n\n```text\n@UseGuards(JwtAuthGuard)\n@Controller(\"/api/warehouse/goods-receipts\")\nexport class GoodsReceiptsController\n  extends ControllerFactory<GoodsReceipt, CreateGoodsReceiptDto, UpdateGoodsReceiptDto, QueryGoodsReceiptDto>\n  (CreateGoodsReceiptDto,UpdateGoodsReceiptDto,QueryGoodsReceiptDto){\n  constructor(protected service: GoodsReceiptsService) {\n    super();\n  }\n}\n```\n\n========================================\n\nComments:\n- Can you clarify what is ClassType?\n- @MML1357 I think it came from swagger or graphql package. I have since replaced it with `Type` from `@nestjs&#47;common`\n- I'm using swagger. On the create, when I Try, the textarea to insert the body doesn't show.\n- You need to add the `@ApiBody` decorator to the factory create function. `@ApiBody({ type: createDto })` You also need to add another argument in the factory constructor where you pass the entity type, then add `@ApiResponse({ type: entityType })` so swagger knows what the endpoint returns. Other decorators you might find useful are `@ApiParam`, `@ApiQuery` etc.\n- that works, now the schema is displayed but... the controller it's no catching the body value. If I do a `console.log(body)` it shows only `CreateAreaDto {}`. CreateAreaDto is the Dto I'm passing as C.\n- Did you decorate the fields in your DTO with `@ApiProperty`? Or if you don't want to do that you can enable the swagger plugin in nest-cli.json.\n- Can I disable some route like disabling \"update\" function will make it not available to request PATCH request?","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":306,"estimatedTokens":2278}}267{"id":"stack-49879274","source":"stackoverflow","questionId":49879274,"title":"NestJS - Default (wildcard) route?","tags":["express","router","nestjs"],"text":"Title: NestJS - Default (wildcard) route?\nTags: express, router, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my Angular app, if I load the home page `/` and then navigate to, say, `/products`, it works fine (it's a lazy-loaded module). But if now I reload the page, the browser makes a `GET /products` call to the server, which results in a 404.\n\nThe solution is to send `index.html` and the Angular app is back on rails. So in Express I do `app.all(\"*\", (req,res) => { res.sendFile(\"index.html\") })` and it works.\n\nHow to do the same thing in Nest?\n\nThere is a `@All` decorator, but each controller in a given component handles a subroute, for instance `@Controller(\"cats\")` will match `/cats` routes, so if I add `@All` in this controller, it will match only `/cats/*`, not `*`.\n\nMust I really create a whole separate module with a controller, just for this? That's what I did\n\n```\n@Controller() // Matches \"/\"\nexport class GenericController {\n\n @All() // Matches \"*\" on all methods GET, POST...\n genericFunction(){\n console.log(\"Generic route reached\")\n }\n}\n```\n\nAnd in my main module :\n\n```\n@Module({\n imports: [\n ItemsModule, // Other routes like /items\n GenericModule, // Generic \"*\" route last\n ],\n})\n```\n\nIt works, but it seems overkill. Is this the way to go or is there a simpler trick?\n\n========================================\n\nTop Answer:\nYou don't need to create a separated `GenericModule`. However, `GenericController` is fully valid and you approach is definitely a good one. The question is rather what would you like to achieve using this generic route. If handling \"Route not found\" error is your requirement, a better choice is an exception filter.\n\n========================================\n\nCode:\n```text\n@Controller() // Matches \"/\"\nexport class GenericController {\n\n    @All() // Matches \"*\" on all methods GET, POST...\n    genericFunction(){\n        console.log(\"Generic route reached\")\n    }\n}\n```\n\n```text\n@Module({\n    imports: [\n        ItemsModule, // Other routes like /items\n        GenericModule, // Generic \"*\" route last\n    ],\n})\n```\n\n```text\n/\n```\n\n```text\n/products\n```\n\n```text\nGET /products\n```\n\n```text\nindex.html\n```\n\n```text\napp.all(\"*\", (req,res) => { res.sendFile(\"index.html\") })\n```\n\n```text\n@All\n```\n\n```text\n@Controller(\"cats\")\n```\n\n```text\n/cats\n```\n\n```text\n@All\n```\n\n```text\n/cats/*\n```\n\n```text\n*\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(ApplicationModule);\n  app.useGlobalFilters(new NotFoundExceptionFilter());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nimport { ExceptionFilter, Catch, NotFoundException } from '@nestjs/common';\nimport { HttpException } from '@nestjs/common';\n\n@Catch(NotFoundException)\nexport class NotFoundExceptionFilter implements ExceptionFilter {\n    catch(exception: HttpException, host: ArgumentsHost) {\n        const ctx = host.switchToHttp();\n        const response = ctx.getResponse();\n        // here return `index.html`\n    }\n}\n```\n\n```text\nglobal-scoped\n```\n\n```text\nGenericModule\n```\n\n```text\nGenericController\n```\n\n```text\nimport {RouterModule} from '@nestjs/core/router';\nimport {ContentBlockModule} from './content_block/content_block.module';\nimport {FallbackModule} from './fallback/fallback.module';\n\nconst APIRoutesWithFallbackRoute = RouterModule.register([\n  {\n    // This lets me avoid prepending my routes with /api prefixes \n    path: 'api',\n    \n    // Overload the /api/content_blocks route and foward it to the custom module\n    children: [\n      {\n        path: 'content_blocks',\n        module: ContentBlockModule,\n      },\n    ],\n  },\n  { //Fallback Route catches any post to /api/:resource\n    path: 'api',\n    module: FallbackModule,\n  },\n]);\n```\n\n```text\nimport {Module} from '@nestjs/common';\n\nimport {AppService} from './app.service';\nimport {APIRoutesWithFallbackRoute} from './APIRoutesWithFallbackRoute';\nimport {ContentBlockModule} from './content_block/content_block.module';\nimport {FallbackModule} from './fallback/fallback.module';\n\n// APIRoutes include first, Fallback Routes prepended.\n@Module({\n  imports: [APIRoutesWithFallbackRoute, ContentBlockModule, FallbackModule],\n  controllers: [],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport {Controller, Post, Req, Res} from '@nestjs/common';\nimport {defaultHandler} from 'ra-data-simple-prisma';\n\nimport {FallbackService} from './fallback.service';\n\n@Controller()\nexport class FallbackController {\n  constructor(private readonly prisma: FallbackService) {}\n\n  @Post(':resource')\n  fallback(@Req() req, @Res() res) {\n    // return this.appService.getData();\n    console.log('executing from the default fallback route');\n\n    return defaultHandler(req, res, this.prisma);\n  }\n}\n```\n\n```text\n@Controller()\nexport class ContentBlockController {\n  constructor(\n    private readonly contentBlockService: ContentBlockService,\n    private readonly prisma: PrismaService,\n  ) {}\n\n  @Post()\n  async create(\n    @Body() contentBlock: content_blocks,\n    @Req() req: Request,\n    @Res() res: Response,\n  ): Promise<void> {\n    console.log('executing from the resource specific route');\n \n    // lean on my service to do heavy business logic\n    const [model, values] = await this.contentBlockService.createContentBlock(\n      contentBlock,\n    );\n\n    // inject custom logic...\n    const alteredRequest: CreateRequest = {\n      ...req,\n      body: {\n        ...req.body,\n        params: {\n          data: values,\n        },\n      },\n    };\n   \n\n    return createHandler(alteredRequest, res, model);\n  } \n}\n```\n\n```text\n/api/:resource\n```\n\n```text\nFallbackModule\n```\n\n========================================\n\nComments:\n- Here good boilerplate: github.com/Innovic-io/angular-nestjs-rendering You can use `angular-cli` too. Since it used `angular-cli`, front app use separate `express` instance and it's already configured to handle not found requests...\n- Oh I have always been using Angular CLI. But what do you mean `front app use separate express instance`? Express is server-side\n- I mean `angular-cli` use separate express instance\n- But that's `ng serve`, isn't it? It's CLI's built-in server. I'm not using `ng serve`, I'm building my own server. Anyway, your answer worked. Thanks!\n- Yes you are right. It's CLI's built-in server used when debugging app locally. In production of course you need own server, where in your case `NestJS` is usedโœŒ\n- For some reason I needed to explicitly use @All('*') (with the *) to pick it up. Hope this helps some googlers.\n- What an honor. The man himself :) What I want to do is `sendFile(\"index.html\")`. Let me explain. In my Angular app, if I load the home page `&#47;` and then navigate to, say, `&#47;products`, it works fine (it's a lazy-loaded module). But if now I reload the page, the browser makes a `GET &#47;products` call to the server, which results in a 404. The solution is to send `index.html` and the Angular app is back on rails. So in Express I do `app.all(\"*\", (req,res) => { res.sendFile(\"index.html\") })` and it works. How to implement `GenericController` without a module? Still haven't figured that out\n- @JeremyThille means something like angular.io/guide/&hellip;\n- @JeremyThille, I think, your question can be replaced with your comment above ๐Ÿ™‚\n- That's actually true, did so, thanks for the advice :)\n- This works for the most part, however - the problem is that valid routes that return 404 (like GET /items/ will return index.html and not the 404. The question was how to handle non-matching routes only.","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":268,"estimatedTokens":1880}}268{"id":"stack-67435944","source":"stackoverflow","questionId":67435944,"title":"Is there a way to declare a default value when using @ApiQuery with nestJS and swagger?","tags":["nestjs","nestjs-swagger"],"text":"Title: Is there a way to declare a default value when using @ApiQuery with nestJS and swagger?\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nEDIT: found a solution thanks to the comment suggesting to use a DTO. Answer detailed at the bottom.\n\nThe NestJS website has documentation to [declare default values][1] when using @ApiBody(), is there a way to do so with @ApiQuery()? (i.e. show in the documentation that the queries have default values)\n\nfor example, if I have pagination queries and want the default to be page 1 with 5 entries per page:\n\n```\n@Get()\n @ApiQuery({name: 'page', default: 1, type: Number})\n @ApiQuery({name: 'limit', default: 5, type: Number})\n async getDocuments(\n @Query('page') page: Number = 1, \n @Query('limit') limit: Number = 5\n ){\n return this.documentsService.getDocuments(page, limit);\n }\n```\n\n========================================\n\nTop Answer:\n```\n@Get()\n @ApiQuery({name: 'page', type: Number})\n @ApiQuery({name: 'limit', type: Number})\n async getDocuments(\n @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: Number = 1, \n @Query('limit', new DefaultValuePipe(5), ParseIntPipe) limit: Number = 5\n ){\n return this.documentsService.getDocuments(page, limit);\n }\n```\n\n========================================\n\nCode:\n```typescript\n@Get()\n  @ApiQuery({name: 'page', default: 1, type: Number})\n  @ApiQuery({name: 'limit', default: 5, type: Number})\n  async getDocuments(\n    @Query('page') page: Number = 1, \n    @Query('limit') limit: Number = 5\n  ){\n    return this.documentsService.getDocuments(page, limit);\n  }\n```\n\n```typescript\n//dto.ts\nexport class PageDTO {\n  @ApiProperty({default: 1, required: false})\n  page: Number\n}\nexport class LimitDTO {\n  @ApiProperty({default: 5, required: false})\n  limit: Number\n}\n//documents.controller.ts\n...\n  @Get()\n  @ApiQuery({name: 'page', default: 1, type: PageDTO})\n  @ApiQuery({name: 'limit', default: 5, type: LimitDTO})\n  async getDocuments(\n    @Query('page') page = 1, \n    @Query('limit') limit = 5\n  ){\n    return this.documentsService.getDocuments(page, limit);\n  }\n```\n\n```typescript\n//dto.ts\nexport class PaginationDTO {\n  @ApiProperty({default: 1, required: false})\n  page: Number\n  @ApiProperty({default: 5, required: false})\n  limit: Number\n}\n\n//documents.controller.ts\n...\n  @Get()\n  @ApiQuery({type: PaginationDTO})\n  async getDocuments(\n    @Query('page') page = 1, \n    @Query('limit') limit = 5 \n  ){\n    return this.documentsService.getDocuments(page, limit);\n  }\n```\n\n```js\n@Get()\n  @ApiQuery({name: 'page', type: Number})\n  @ApiQuery({name: 'limit', type: Number})\n  async getDocuments(\n    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: Number = 1, \n    @Query('limit', new DefaultValuePipe(5), ParseIntPipe) limit: Number = 5\n  ){\n    return this.documentsService.getDocuments(page, limit);\n  }\n```\n\n========================================\n\nComments:\n- What's wrong with the above?\n- The above is what I would like to achieve. In reality, adding โ€œdefaultโ€ key to ApiQuery throws an error.\n- What about using a DTO to show this information?\n- Just tried it out and it works (edited the original post to show my implementation), does it look correct? Thank you so much!\n- FYI: you can (and usually should) post an answer to your own question rather than editing the answer into the question\n- Will do, thanks for letting me know","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":118,"estimatedTokens":842}}269{"id":"stack-59902490","source":"stackoverflow","questionId":59902490,"title":"Nestjs Swagger - Publishing different API docs on separate routes","tags":["swagger","nestjs","nestjs-swagger"],"text":"Title: Nestjs Swagger - Publishing different API docs on separate routes\nTags: swagger, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI am building an app that has public API and internal one. I would like to publish docs for these to different routes. I thought this would be accomplished by adding only certain tags to document (`addTag`) but after further reading and experiments it does not do the job.\n\nThe docs always contain everything, all documented endpoints from all modules.\n\nIs this even possible? If so, how?\n\nI don't believe code is necessary but FWIW:\n\n```\nconst pubOptions = new DocumentBuilder()\n .setTitle('Pub API Docs')\n .setDescription('Blah blah API documentation')\n .setVersion(p.version)\n .addBearerAuth()\n .addTag('public-app')\n .build();\nconst document = SwaggerModule.createDocument(app, pubOptions);\nSwaggerModule.setup('public-api', app, document);\n\nconst internalOptions = new DocumentBuilder()\n .setTitle('Internal API Docs')\n .setDescription('Blah blah API documentation')\n .setVersion(p.version)\n .addBearerAuth()\n .addTag('internal')\n .build();\nconst iDocument = SwaggerModule.createDocument(app, internalOptions);\nSwaggerModule.setup('internal-api', app, iDocument);\n```\n\n========================================\n\nCode:\n```js\nconst pubOptions = new DocumentBuilder()\n    .setTitle('Pub API Docs')\n    .setDescription('Blah blah API documentation')\n    .setVersion(p.version)\n    .addBearerAuth()\n    .addTag('public-app')\n    .build();\nconst document = SwaggerModule.createDocument(app, pubOptions);\nSwaggerModule.setup('public-api', app, document);\n\nconst internalOptions = new DocumentBuilder()\n    .setTitle('Internal API Docs')\n    .setDescription('Blah blah API documentation')\n    .setVersion(p.version)\n    .addBearerAuth()\n    .addTag('internal')\n    .build();\nconst iDocument = SwaggerModule.createDocument(app, internalOptions);\nSwaggerModule.setup('internal-api', app, iDocument);\n```\n\n```text\naddTag\n```\n\n```text\nSwaggerModule.createDocument\n```\n\n```text\ninclude\n```\n\n========================================\n\nComments:\n- According to this PR , the `exclude` option is going to be added as a complement\n- Would be great if the include options could take controllers as element of the array","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":562}}270{"id":"stack-53307541","source":"stackoverflow","questionId":53307541,"title":"Firebase - Handle cloud events within NestJS Framework","tags":["firebase","google-cloud-functions","nestjs"],"text":"Title: Firebase - Handle cloud events within NestJS Framework\nTags: firebase, google-cloud-functions, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS as my backend Framework and Firebase.\n\nTo integrate Nest with Firebase on HTTP requests is simple as attaching the express instance of nest to Firebase:\n\n```\nconst server: Express = express();\n\nconst bootstrap = async (expressInstance: Express) => {\n const app = await NestFactory.create(AppModule, expressInstance);\n await app.listen(3000);\n await app.init();\n};\n\nbootstrap(server);\n\nexports.api = functions.https.onRequest(server);\n```\n\nBut what about the other Google Functions (such as pubsub, firestore, auth, etc.)?\n\nI'm building a subscription application, and I depend on `functions.pubsub` to check at the end of every day which subscriptions should I charge. It requires writing business logic that I want to write withing NestJs.\n\nI'm trying to achieve something like this (in a nutshell):\n\n```\nfunctions.pubsub\n .topic('topic')\n .onPublish(app.getService(Service).method);\n```\n\n========================================\n\nTop Answer:\nFound a new solution for standalone applications:\nhttps://docs.nestjs.com/standalone-applications\n\nYou don't need to bootstrap NestJS with Express server to handle PubSub messages.\n\n```\nexport const subscriptions = functions\n .pubsub\n .topic('cron-topic')\n .onPublish((context, message) => {\n const app = await NestFactory.create(ApplicationModule);\n return app.get(SubscribeService).initDailyCharges(context, message);\n });\n```\n\n========================================\n\nCode:\n```text\nconst server: Express = express();\n\nconst bootstrap = async (expressInstance: Express) => {\n  const app = await NestFactory.create(AppModule, expressInstance);\n  await app.listen(3000);\n  await app.init();\n};\n\nbootstrap(server);\n\nexports.api = functions.https.onRequest(server);\n```\n\n```text\nfunctions.pubsub\n    .topic('topic')\n    .onPublish(app.getService(Service).method);\n```\n\n```text\nfunctions.pubsub\n```\n\n```text\nconst bootstrap = async (expressInstance: Express) => {\n  const app = await NestFactory.create(AppModule, expressInstance);\n  await app.init();\n\n  return app;\n};\n\nconst main = bootstrap(server);\n\nexport const subscriptions = functions\n  .pubsub\n  .topic('cron-topic')\n  .onPublish((context, message) => main.then(app => {\n    return app.get(SubscribeService).initDailyCharges(context, message));\n  });\n```\n\n```text\ngetService\n```\n\n```text\nget\n```\n\n```text\nexport const subscriptions = functions\n  .pubsub\n  .topic('cron-topic')\n  .onPublish((context, message) => {\n    const app = await NestFactory.create(ApplicationModule);\n    return app.get(SubscribeService).initDailyCharges(context, message);\n  });\n```\n\n========================================\n\nComments:\n- What minimal memory amount should be set to the Cloud Function execution environment to run Nest?\n- @ViacheslavDobromyslov I haven't had any issues with memory. Just used the default amount back then\n- Thanks. Found here github.com/nestjs/nest/issues/1519 it consumes about 32Mb.","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":122,"estimatedTokens":764}}271{"id":"stack-70681202","source":"stackoverflow","questionId":70681202,"title":"Is it good way to throw error from service in nestjs like it:","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Is it good way to throw error from service in nestjs like it:\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nconst movie = await this.movieService.getOne(movie_id);\nif(!movie){\n throw new Error(\n JSON.stringify({\n message:'some message',\n status:'http status'\n })\n );\n}\nconst rating = await this.ratingRepository.find({where:{movie});\nreturn rating;\n```\n\nAnd after it use try catch in controller and throw HttpExeption.\n\n```\nasync getAllByMovie(@Param('movie_id') movie_id:string):Promise{\n try{\n const ratings = await this.ratingService.getAllRatingsByMovie(Number(movie_id));\n return ratings;\n }catch(err){\n const {message,status} = JSON.parse(err.message);\n throw new HttpExeption(message,status);\n }\n}\n```\n\nIs it good or not?\n\n========================================\n\nTop Answer:\nIn general it's a good idea to throw business errors from your services and handle theses errors on controller layer.\nBut there is room for improvement looking at your code:\n\nTo me it looks a bit odd to stringify the `message` and `status` in order to pass it to `Error`. You could create a custom Error that contains these properties:\n\n```\nclass MyBusinessError extends Error {\n status: number;\n\n constructor(message: string, status: number) {\n super(message);\n this.status = status;\n }\n}\n```\n\nBut I suggest to decide on controller level which status should be returned from the API because this is http specific and should not be part of your business logic.\n\nAlso there are exception filters coming with NestJS that you can use to catch exceptions and transform them into http exceptions. With that you don't need to try-catch in every controller method.\nYou can check for specific Error type using `instanceof`:\n\n```\ntry {\n // ...\n}\ncatch(err) {\n if(err instanceof MyBusinessError) {\n // handle business error\n }\n \n throw err;\n}\n```\n\n========================================\n\nCode:\n```text\nconst movie = await this.movieService.getOne(movie_id);\nif(!movie){\n  throw new Error(\n    JSON.stringify({\n      message:'some message',\n      status:'http status'\n   })\n  );\n}\nconst rating = await this.ratingRepository.find({where:{movie});\nreturn rating;\n```\n\n```text\nasync getAllByMovie(@Param('movie_id') movie_id:string):Promise<Rating[]>{\n  try{\n    const ratings = await this.ratingService.getAllRatingsByMovie(Number(movie_id));\n    return ratings;\n  }catch(err){\n    const {message,status} = JSON.parse(err.message);\n    throw new HttpExeption(message,status);\n  }\n}\n```\n\n```js\nimport {\n  ExceptionFilter,\n  Catch,\n  ArgumentsHost,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\nimport { object } from 'underscore';\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n  \n  catch(exception: any, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse();\n    const request = ctx.getRequest<CustomRequest>();\n    let internalStatus;\n   \n    let status =\n      exception instanceof HttpException\n        ? exception.getStatus()\n        : HttpStatus.INTERNAL_SERVER_ERROR;\n    let message = exception.sqlMessage || exception.response || exception;\n    let error = exception.sqlState === 45000 ? 'Bad Request' : 'Bad Request';\n\n    \n    request.log.timeTookToServe = Date.now() - request.log.timestamp;\n    request.log.message = message;\n    request.log.status = `${status}`;\n    \n    if (exception instanceof TypeError) {\n      status = 400;\n      error = 'Bad Request';\n      message = exception.message\n        .substring(exception.message.indexOf('\\n\\n\\n') + 1)\n        .trim();\n    }\n\n    if (status === 500) {\n     \n      console.log(exception.sqlMessage, exception.sqlState, exception);\n     \n    } else {\n       console.log(exception.sqlMessage, exception.sqlState, exception);\n    }\n    const errMessage = errJson[request.log['module']];\n \n    response.status(status).json({\n      status: exception.status || status,\n     \n      error: error,\n      message: [\n        status === 403\n          ? \"Either you don't have the privilege or been logged out.\"\n          : message,\n      ],\n    });\n  }\n}\n```\n\n```js\nclass MyBusinessError extends Error {\n  status: number;\n\n  constructor(message: string, status: number) {\n    super(message);\n    this.status = status;\n  }\n}\n```\n\n```js\ntry {\n  // ...\n}\ncatch(err) {\n  if(err instanceof MyBusinessError) {\n    // handle business error\n  }\n  \n  throw err;\n}\n```\n\n```text\nmessage\n```\n\n```text\nstatus\n```\n\n```text\nError\n```\n\n```text\ninstanceof\n```\n\n========================================\n\nComments:\n- Business logic can be reused across many controllers, and the error codes and messages they throw might not be relevant to the context of all endpoints. You should still handle errors on the controller level.","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":206,"estimatedTokens":1189}}272{"id":"stack-51721930","source":"stackoverflow","questionId":51721930,"title":"nestjs configuration with dotenv","tags":["configuration","nestjs"],"text":"Title: nestjs configuration with dotenv\nTags: configuration, nestjs\nSource: Stack Overflow\n\nQuestion:\nReferring to official NestJS documentation, it is recommended to use `ConfigService` in order to use environment variables.\n\nSo in the code, we access all vars defined in an `.env` file with something like:\n\n```\nconfig.get('PORT')\n```\n\nBut it is not recommended to use `.env` in production environment. So how to deploy in that way?\n\nWhy not just use the standard method with `dotenv` and `process.env.PORT`?\n\n========================================\n\nTop Answer:\nBut this is not recommended to use .env in production environnement. So how to deploy that way ?\n\nActually, it is not recommended **to commit** your .env files. It's perfectly fine to use them in production :-).\n\n Why not use the standard method with dotenv and process.env.PORT?\n\nIt allows **decoupling** your core code from the code responsible for providing configuration data. Thus: \n\n- The core code is easier to test: doing some manual changes/mocking of `process.env` is **such** - **a** - **pain**, whereas mocking a \"`ConfigService`\" is pretty easy\n\n- You can imagine using anything else than environment variables in the future by just replacing a single method (or a few getters) in a dedicated class, instead of replacing all the occurrences of `process.env.*` in your code // *to be fair, this is unlikely to happen, as using env. variables is the most common way to load configuration data, but still.*\n\n========================================\n\nCode:\n```text\nconfig.get('PORT')\n```\n\n```text\nConfigService\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\ndotenv\n```\n\n```text\nprocess.env.PORT\n```\n\n```text\ndotenv.parse(fs.readFileSync(filePath))\n```\n\n```text\n[Nest] 63403 [ExceptionHandler] path must be a string or Buffer\nTypeError: path must be a string or Buffer\n    at Object.fs.openSync (fs.js:646:18)\n    at Object.fs.readFileSync (fs.js:551:33)\n    at new ConfigService (../config/config.service.ts:8:38)\n```\n\n```text\nthis.configService.get('API_KEY')\n```\n\n```text\nimports: [\n  MongooseModule.forRoot(process.env.MONGO_URI, { useNewUrlParser: true }),\n  ConfigModule,\n],\n```\n\n```text\nConfigService\n```\n\n```text\n.env\n```\n\n```text\nreadFileSync\n```\n\n```text\nprocess.env.API_KEY\n```\n\n```text\nConfigService\n```\n\n```text\nprod.env\n```\n\n```text\nprocess.env\n```\n\n```text\nConfigService\n```\n\n```text\nprocess.env.*\n```\n\n```text\n@nestjs/config\n```\n\n```text\nConfigModule\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- It's not recommended to *commit* the .env file, not to *use* It. Basically your env file will hold your secrets, so passwords for example will be not committed in your VCS.\n- i have just been coming to this realization, how does nest expect us to use config service in a real production environment? i.e. say env is injected via docker, bash etc ?\n- if anyone cares, i've just added `if (process.env[key]) { return process.env[key]; } return this.envConfig[key];` ...to my config.service.ts, which surprisingly, seems to work fine just like that\n- somehow the nestjs build, does not copy the .env files to the dist folder and as a result I keep getting file not found error","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":141,"estimatedTokens":803}}273{"id":"stack-51697680","source":"stackoverflow","questionId":51697680,"title":"How do you detect if an attribute like password has changed in typeorm","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: How do you detect if an attribute like password has changed in typeorm\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn typeorm, I am trying to use a subscriber decorator to hash users password before persisting to the database. Unfortunately, I can't find a reference in the docs.\n\nIn sequelizejs, I use the following code,\n\n```\nUser.hashPassword = (user, options) => {\n if (!user.changed('password')) {\n return null;\n }\n // hash password\n return Bcrypt.hash(user.get('password'), SALT_ROUNDS)\n .then(hash => user.set('password', hash));\n };\n```\n\nRight now, I am trying to migrate the code to `typeorm` and my translation is roughly\n\n```\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n // conditional to detect if password has changed goes here\n this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);\n}\n```\n\nThe issue is, I stuck at `!user.changed('password')`. Is there an equivalent function in `typeorm` to do this without rolling out my own solution?\n\n========================================\n\nTop Answer:\nYou can try this: \n\n```\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n if (this.password) {\n this.password = createHmac('sha256', this.password).digest('hex');\n }\n}\n```\n\nI just check if a password is present in the DTO (before update and insert). If it is present, I should hash it.\n\n========================================\n\nCode:\n```text\nUser.hashPassword = (user, options) => {\n    if (!user.changed('password')) {\n      return null;\n    }\n    // hash password\n    return Bcrypt.hash(user.get('password'), SALT_ROUNDS)\n      .then(hash => user.set('password', hash));\n  };\n```\n\n```text\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n    // conditional to detect if password has changed goes here\n    this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);\n}\n```\n\n```text\ntypeorm\n```\n\n```text\n!user.changed('password')\n```\n\n```text\ntypeorm\n```\n\n```text\n@Entity()\nexport class User extends BaseEntity {\n    @PrimaryColumn()\n    public username: string;\n\n    @Column()\n    public password: string;\n\n    @Column({ nullable: true })\n    public jwtToken: string;\n\n    private tempPassword: string;\n\n\n    @AfterLoad()\n    private loadTempPassword(): void {\n        this.tempPassword = this.password;\n    }\n\n    @BeforeUpdate()\n    private encryptPassword(): void {\n        if (this.tempPassword !== this.password) {\n            //\n        }\n    }\n```\n\n```text\n@AfterLoad\n```\n\n```text\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n  if (this.password) {\n    this.password = createHmac('sha256', this.password).digest('hex');\n  }\n}\n```\n\n```text\n----------\n\n    private tempPassword: string\n\n  /// commit to handle the password if i not change it it will be  not encription\n\n\n  @AfterLoad()\n  private loadTempPassword(): void {\n    this.tempPassword = this.password;\n  }\n\n\n\n\n  @BeforeInsert()\n  @BeforeUpdate()\n  async hashPassword(): Promise<void> {\n    // cheack if that password changing or not\n    if (this.tempPassword !== this.password) {\n\n      try {\n        this.password = await bcrypt.hash(this.password, 10)\n\n      } catch (e) {\n        throw new InternalServerErrorException('there are some issiue in the hash')\n\n      }\n    }\n\n\n  }\n```\n\n```text\n@Column('string', { select: false })\n   password:string\n```\n\n```text\nwe check if the password is found or not \n if (this.password) {\n//make hash \n}\n```\n\n```text\n@AfterLoad()\n  private loadTempPassword(): void {\n    this.tempPassword = this.password;\n  }\n```\n\n```text\n@BeforeInsert()\n  @BeforeUpdate()\n  async hashPassword(): Promise<void> {\n    // cheack if that password changing or not\n    if (this.password) {\n      if (this.tempPassword !== this.password) {\n\n        try {\n          this.password = await bcrypt.hash(this.password, 10)\n\n        } catch (e) {\n          throw new InternalServerErrorException('there are some issiue in the hash')\n\n        }\n      }\n    }\n```\n\n========================================\n\nComments:\n- Did you find some solution for this?\n- @Hammerbot No, I did not. What I did was to check if the `user.password` property is present in the update request. If it is present, confirm that it is a plain string to prevent a double hash. Then manually run the `bcrypt.hash()` on the plain string before persisting.\n- Have you tried using a subscriber? github.com/typeorm/typeorm/blob/master/docs/&hellip;\n- It's important to note here that Entity Listeners are not fired when using repository methods like `.update()` and `.delete()` since the entity is not loaded. If you want to make sure these methods fire, you need to load the entity (with `.findOne()`), update it and then use the `.save()` method. See this github thread for more details\n- But how do you validate password length etc with `class-validator` in encryptPassword? Would you do it manually instead?","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":208,"estimatedTokens":1204}}274{"id":"stack-51113506","source":"stackoverflow","questionId":51113506,"title":"NodeJS map Dtos to TypeORM Entities","tags":["node.js","dto","nestjs","typeorm","class-transformer"],"text":"Title: NodeJS map Dtos to TypeORM Entities\nTags: node.js, dto, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have a `nodejs` REST API backend running the `nestjs` framework, using **typeORM** as **ORM** for my entities.\n\nComing from a `C#/Entity Framework` background, I am very used to have my Dtos mapped to the database entities.\n\nIs there a similar approach with typeORM? \n\nI have seen the automapper-ts library, but those magic strings in the map declarations look kind of scary...\nBasically it would be amazing if I could :\n\n```\nlet user: TypeORMUserEntity = mapper.map(userDto);\n```\n\nWhat is the way to do this (or any alternative with same result) in nodejs/typeorm backend environment?\n\n========================================\n\nTop Answer:\nI am using `create` method from `getRepository`\n\n```\nexport async function save(booking: CreateBookingDto) {\n const bookingRepository = getRepository(Booking);\n\n const bookingEntity = bookingRepository.create({ ...booking });\n return bookingRepository.save(bookingEntity);\n}\n```\n\n========================================\n\nCode:\n```text\nlet user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);\n```\n\n```text\nnodejs\n```\n\n```text\nnestjs\n```\n\n```text\nC#/Entity Framework\n```\n\n```text\n@Exclude()\nclass SkillNewDto {\n  @Expose()\n  @ApiModelProperty({ required: true })\n  @IsString()\n  @MaxLength(60)\n  name: string;\n\n  @Expose()\n  @ApiModelProperty({\n    required: true,\n    type: Number,\n    isArray: true,\n  })\n  @IsArray()\n  @IsInt({ each: true })\n  @IsOptional()\n  categories: number[];\n}\n```\n\n```text\nconst skillDto = plainToClass(SkillNewDto, body);\nconst errors = await validate(skillDto);\nif (errors.length) {\n  throw new BadRequestException('Invalid skill', this.modelHelper.modelErrorsToReadable(errors));\n}\n```\n\n```text\nExclude\n```\n\n```text\nExpose\n```\n\n```text\nclass-transform\n```\n\n```text\nIsString\n```\n\n```text\nIsArray\n```\n\n```text\nIsOptional\n```\n\n```text\nIsInt\n```\n\n```text\nMaxLength\n```\n\n```text\nclass-validator\n```\n\n```text\nApiModelProperty\n```\n\n```text\nexport async function save(booking: CreateBookingDto) {\n  const bookingRepository = getRepository(Booking);\n\n  const bookingEntity = bookingRepository.create({ ...booking });\n  return bookingRepository.save(bookingEntity);\n}\n```\n\n```text\ncreate\n```\n\n```text\ngetRepository\n```\n\n```text\nclass LoginResDto {\n token?: string;\n\n addCustomProperty = (propertyName: AllowedKeys, propertyValue: any): this => {\n   this[propertyName] = propertyValue;\n   return this;\n };\n\n @Expose()\n type: UserType;\n\n @Expose()\n name: string;\n\n @Expose()\n surname: string;\n\n @Expose()\n publicId: number;\n\n @Expose({\n   name: 'I',\n })\n @Type(() => HumanResDto)\n detail: HumanResDto;\n}\n\nexport default LoginResDto;\n```\n\n```text\nconst convertData = TransformService.convert<LoginResDto, UserEntity>(\n           userExist,\n           LoginResDto,\n           'excludeAll'\n         ).addCustomProperty('token', tokenInstance.clientToken);\n```\n\n```text\nclass TransformService {\n  static convert<T, K>(\n    source: K,\n    destinationClass: ClassConstructor<T>,\n    strategy: 'excludeAll' | 'exposeAll'\n  ): T {\n    return plainToClass(destinationClass, source, { strategy });\n  }\n\n  static convertArray<T, K>(\n    source: K[],\n    destinationClass: ClassConstructor<T>,\n    strategy: 'excludeAll' | 'exposeAll'\n  ): T[] {\n    return plainToInstance(destinationClass, source, { strategy });\n  }\n}\n\nexport default TransformService;\n```\n\n========================================\n\nComments:\n- Isn't this a DTO -> DTO instead of a DTO -> Enity mapping ? `typescript const skillDto = plainToClass(SkillNewDto, body);`","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":205,"estimatedTokens":907}}275{"id":"stack-75674278","source":"stackoverflow","questionId":75674278,"title":"How to run NestJs app in Docker using nx/monorepo","tags":["docker","nestjs","monorepo","nrwl-nx"],"text":"Title: How to run NestJs app in Docker using nx/monorepo\nTags: docker, nestjs, monorepo, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nI have this Nrwl monorepo with a couple of apps. One of it is a NestJs app, which runs fine as long as I do everything inside my Monorepo.\n\nHowever, I need to run my NestJS app inside a Docker container. I noticed that I cannot simply copy the compiled NestJS code into an Image, because it still requires `node_modules`.\n\nThe only easy solution I can think of is to also copy the main `package.json` file into the image and run `npm install`. Is this the correct/only way or does Nrwl/nx has tooling for this?\n\n========================================\n\nTop Answer:\nAs `workspace.json` is now deprecated, `generatePackageJson` option moved to @nx/webpack:webpack package so a modern (as of 2023) way to make it work is to either:\n\n- Define a default in `nx.json`:\n\n```\n{\n \"targetDefaults\": {\n \"build\": {\n \"executor\": \"@nx/webpack:webpack\",\n \"options\": {\n \"generatePackageJson\": true\n },\n // ...\n },\n // ...\n },\n // ...\n}\n```\n\n- Define a project-specific setting in `project.json`:\n\n```\n{\n \"targets\": {\n \"build\": {\n \"executor\": \"@nx/webpack:webpack\",\n \"options\": {\n \"generatePackageJson\": true\n },\n //...\n },\n // ...\n }\n // ...\n}\n```\n\n- Define a project-specific setting in `package.json`:\n\n```\n{\n \"name\": \"...\",\n \"scripts\": {\n // ...\n },\n \"nx\": {\n \"targets\": {\n \"build\": {\n \"executor\": \"@nx/webpack:webpack\",\n \"options\": {\n \"generatePackageJson\": true\n },\n },\n // ...\n },\n // ...\n },\n // ...\n}\n```\n\n========================================\n\nCode:\n```text\nnode_modules\n```\n\n```text\npackage.json\n```\n\n```text\nnpm install\n```\n\n```text\n{\n  \"name\": \"your.app\",\n  \"targets\": {\n    \"build\": {\n      \"options\": {\n        \"generatePackageJson\": true \n      }\n    },\n  },\n}\n```\n\n```json\n{\n  \"targetDefaults\": {\n    \"build\": {\n      \"executor\": \"@nx/webpack:webpack\",\n      \"options\": {\n        \"generatePackageJson\": true\n      },\n      // ...\n    },\n    // ...\n  },\n  // ...\n}\n```\n\n```json\n{\n  \"targets\": {\n    \"build\": {\n      \"executor\": \"@nx/webpack:webpack\",\n      \"options\": {\n        \"generatePackageJson\": true\n      },\n      //...\n    },\n    // ...\n  }\n  // ...\n}\n```\n\n```json\n{\n  \"name\": \"...\",\n  \"scripts\": {\n    // ...\n  },\n  \"nx\": {\n    \"targets\": {\n      \"build\": {\n        \"executor\": \"@nx/webpack:webpack\",\n        \"options\": {\n          \"generatePackageJson\": true\n        },\n      },\n      // ...\n    },\n    // ...\n  },\n  // ...\n}\n```\n\n```text\nworkspace.json\n```\n\n```text\ngeneratePackageJson\n```\n\n```text\nnx.json\n```\n\n```text\nproject.json\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Although your solution works, I cannot run `npm ci`, it complains that `package.json` and `package-lock.json` are not in sync\n- I don't have an issue with that. you can try to delete all cached files (node_modules, dists, .next, etc..). after that run `npm install` in the root project to create a new package-lock.json file. and then run your build command for your backend. this should work\n- also what about extra dependencies from other projects?\n- @ciekawy Can you describe it in more detail?\n- Sure - having frontend and backend app and only single root level package.json building docker image makes some 1.5GB image in my case. I added poor man regexp to remove in place FE does to go down to 400MB but Iโ€™d expect it to be reasonably handled by nx. Actually Iโ€™d expect still package.json by app while keeping them in single root level node_modules - probably this is one of the reasonable option coming to my mindโ€ฆ\n- I build the frontend and the backend with nx. In addition, the package.json is also created for me by nx. My docker image is then organized as follows: - COPY binaries - COPY package.json - RUN npm i - CMD node main.js I don't know any other way. I have the disadvantage that some node_modules are installed twice. But that doesn't bother me. Alternatively, you can copy all node_modules to your docker image and then delete the unused node_modules. This may be faster. To delete unused node_modules with `npm prune`","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":187,"estimatedTokens":1026}}276{"id":"stack-61246764","source":"stackoverflow","questionId":61246764,"title":"Nest.JS graphql get requested fields","tags":["typescript","graphql","nestjs"],"text":"Title: Nest.JS graphql get requested fields\nTags: typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn Nest.js Graphql, is it possible to fetch the required list of fields from a resolver? To determine which joins to executed, and which not to, for example for this db schema:\n\n```\nEmployee\n id\n employer_id\n name\n\nEmployer\n id\n name\n```\n\nIn case of the following graphql query:\n\n```\nquery {\n employees {\n id\n name\n employer {\n id\n }\n }\n }\n```\n\nIt is not necessary to fetch/join the employer data from the database, since the employer id can be accessed from the employee table.\n\n========================================\n\nTop Answer:\nIn your case, I recommend you to use FieldResolver in order to resolve the employer field.\nYou can get more information in resolvers article\n\n\r\n\r\n\n```\n#...\n\n@ResolveField()\nasync employer(@Parent() employee) {\n const { employer_id } = employee;\n return this.employerService.findById(employer_id);\n}\n\n#...\n```\n\n========================================\n\nCode:\n```text\nEmployee\n id\n employer_id\n name\n\nEmployer\n id\n name\n```\n\n```text\nquery {\n    employees {\n      id\n      name\n      employer {\n        id\n      }\n    }\n  }\n```\n\n```text\n@Query(() => [PostObject])\nasync posts(\n  @FieldMap() fieldMap: FieldMap,\n) {\n  console.log(fieldMap);\n}\n```\n\n```text\n{\n  \"posts\": {\n    \"id\": {},\n    \"title\": {},\n    \"body\": {},\n    \"author\": {\n      \"id\": {},\n      \"username\": {},\n      \"firstName\": {},\n      \"lastName\": {}\n    },\n    \"comments\": {\n      \"id\": {},\n      \"body\": {},\n      \"author\": {\n        \"id\": {},\n        \"username\": {},\n        \"firstName\": {},\n        \"lastName\": {}\n      }\n    }\n  }\n}\n```\n\n```text\n{\n  post { # post: [Post]\n    id\n    author: {\n      id\n      firstName\n      lastName\n    }\n  }\n}\n```\n\n```text\nimport { fieldsList, fieldsMap } from 'graphql-fields-list';\nimport { Query, Info } from '@nestjs/graphql';\n\n@Query(() => [Post])\nasync post(\n  @Info() info,\n) {\n  console.log(fieldsList(info));       // [ 'id', 'firstName', 'lastName' ]\n  console.log(fieldsMap(info));        // { id: false, firstName: false, lastName: false }\n  console.log(fieldsProjection(info)); // { id: 1, firstName: 1, lastName: 1 };\n}\n```\n\n```text\ninfo\n```\n\n```js\n#...\n\n@ResolveField()\nasync employer(@Parent() employee) {\n  const { employer_id } = employee;\n  return this.employerService.findById(employer_id);\n}\n\n#...\n```\n\n========================================\n\nComments:\n- docs.nestjs.com/graphql/resolvers#graphql-argument-decorator&zwnj;&#8203;s - info?\n- This is basically a non-answer. The question was about how can one determine the necessity and avoid making this query if the only requested field is the id (which is already present in the `Employee` table.\n- I understand the point, but it is more convenient for FieldResolver to request all fields to EmployerService.getEmployerById. In that method, the result for the requested employer should be cached. EmployerService.getEmployerById is probably invoked from another part of the system and this is where we will really save execution cost in the database. On the other hand, if you really want to know what fields are requested to the api, you should add this argument decorator \"@Info (param ?: string)\" And get the list of selected attributes in this property: info.operation.selectionSet","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":165,"estimatedTokens":827}}277{"id":"stack-69735754","source":"stackoverflow","questionId":69735754,"title":"How to get nested URL query in Nest.js","tags":["javascript","node.js","typescript","nestjs","routeparams"],"text":"Title: How to get nested URL query in Nest.js\nTags: javascript, node.js, typescript, nestjs, routeparams\nSource: Stack Overflow\n\nQuestion:\nI have NestJS application I have to get the query from the URL. Problem is that my creationDate is an object and I can't get it as the nested object via @Query.\n\nHere is example of the route:\n\n```\nxxx/yyy/orders?key1=value&key2=value&key3=value&createdAt[lte]=2021-07-01&createdAt[gte]=2011-03-30&orderBy=desc&limit=500\n```\n\nI am trying to get createdAt[lte] and createdAt[gte] as the nested object\n\n```\nexport interface QueryI {\nkey1: string;\nkey2: string;\nkey3: string;\nkey4: string;\ncreatedAt: {\n lte: string,\n gte: string,\n}\norderBy: 'desc' | 'asc';\nlimit: number;\n}\n```\n\nHere is my controller:\n\n```\n@Get('route')\ngetAll(\n @Query() query: QueryI): Promise { \n return this.myService.findAll(query);\n}\n```\n\nbut this gives me following result\n\n```\n{\n\nkey1: 'value', \n key2: 'value',\n key3: 'value', \n key4: 'value',\n 'createdAt[lte]': 'some date',\n 'createdAt[gte]': 'some date',\n orderBy: 'desc',\n limit: '500'\n\n}\n```\n\nI have tried JSON.stringify and consulted similar questions on SOW but no luck.\n\nThank you\n\n========================================\n\nTop Answer:\n**Switch `QueryI` from an interface to a class.**\n\nWorking on NestJS 7.\n\n**Url used for testing**\n\n`http://localhost:3000/api/v1/store/search?nestedObj[key1]=yolo&nestedObj[key2]=sup%20bruh&el=test`\n\n**DTO Used**\n\n```\nexport class TestDto {\n el: string;\n nestedObj: {\n key1: string;\n key2: string;\n };\n}\n```\n\n**Controller**\n\n```\n@Controller('v1/store')\n@UsePipes(new ValidationPipe({ exceptionFactory: getFormattedErrors }))\n@UseFilters(DomainExceptionFilter)\nexport class TestController{\n@Get('search')\n public async searchStore(@Query() testDto: TestDto) {\n console.log(testDto);\n return 1;\n }\n}\n// Console log - { nestedObj: { key1: 'yolo', key2: 'sup bruh' }, el: 'test' }\n```\n\n========================================\n\nCode:\n```text\nxxx/yyy/orders?key1=value&key2=value&key3=value&createdAt[lte]=2021-07-01&createdAt[gte]=2011-03-30&orderBy=desc&limit=500\n```\n\n```text\nexport interface QueryI {\nkey1: string;\nkey2: string;\nkey3: string;\nkey4: string;\ncreatedAt: {\n    lte: string,\n    gte: string,\n}\norderBy: 'desc' | 'asc';\nlimit: number;\n}\n```\n\n```text\n@Get('route')\ngetAll(\n    @Query() query: QueryI): Promise<void> { \n    return this.myService.findAll(query);\n}\n```\n\n```text\n{\n\nkey1: 'value',        \n  key2: 'value',\n  key3: 'value',       \n  key4: 'value',\n  'createdAt[lte]': 'some date',\n  'createdAt[gte]': 'some date',\n  orderBy: 'desc',\n  limit: '500'\n\n}\n```\n\n```text\n@Injectable()\nexport class ValidateQueryPipe implements PipeTransform {\n  transform(value: any, metadata: ArgumentMetadata) {\n    let incomingQuery = value as IncomingQuery;\n    let mappedQuery = new QueryParameters()\n    mappedQuery.key1 = incomingQuery.key1\n    mappedQuery.key2= incomingQuery.key2\n    // other mapped valus\n    mappedQuery.createdAt = new CreatedAt(incomingQuery['createdAt[lte]'], incomingQuery['createdAt[gte]'])        \n    return mappedQuery;\n  }\n```\n\n```text\n@Get(':someurl/someurl')\ngetAllOrders(\n    @Query(ValidateQueryPipe) query: QueryParameters): Promise<Observable<any>> { \n    return this.service.findAll(erpCode, query);\n}\n```\n\n```text\nimport { CreatedAt } from \"./created-at\";\n\nexport class QueryParameters {\n    key1: string;\n    key2: string;\n    createdAt: CreatedAt;\n}\n```\n\n```text\nexport class CreatedAt {\n    lte: string;\n    gte: string;\n\n    constructor(lte: string, gte: string){\n        this.lte = lte;\n        this.gte = gte;\n    };\n}\n```\n\n```text\ngetAllOrders(\n    @Query() query,\n    @Query('createdAt[lte]') lte: string, \n    @Query('createdAt[gte]') gte: string): Promise<void> { \n    const mappedObject = new QueryParameters(query, lte, gte)\n    return this.orderService.findAll(erpCode, mappedObject);\n}\n```\n\n```text\nexport class CreatedAt {\n    lte: string;\n    gte: string;\n\n    constructor(lte: string, gte: string){\n        this.lte = lte;\n        this.gte = gte;\n    };\n}\n```\n\n```text\nimport { CreatedAt } from \"./created-at\";\n\nexport class QueryParameters {\n    //other keys\n    createdAt: CreatedAt;\n\n    constructor(query, lte, gte){\n        //other keys\n        this.createdAt = new CreatedAt(lte, gte)\n    }\n}\n```\n\n```text\nexport class TestDto {\n  el: string;\n  nestedObj: {\n    key1: string;\n    key2: string;\n  };\n}\n```\n\n```text\n@Controller('v1/store')\n@UsePipes(new ValidationPipe({ exceptionFactory: getFormattedErrors }))\n@UseFilters(DomainExceptionFilter)\nexport class TestController{\n@Get('search')\n  public async searchStore(@Query() testDto: TestDto) {\n    console.log(testDto);\n    return 1;\n  }\n}\n// Console log - { nestedObj: { key1: 'yolo', key2: 'sup bruh' }, el: 'test' }\n```\n\n```text\nQueryI\n```\n\n```text\nhttp://localhost:3000/api/v1/store/search?nestedObj[key1]=yolo&nestedObj[key2]=sup%20bruh&el=test\n```\n\n```text\nimport { parse } from 'qs';\n\nexport class ParseQueryStringPipe {\n  transform(value: string): object {\n    return parse(value);\n  }\n}\n```\n\n```text\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\napp.set('query parser', 'extended');\n```\n\n```text\nconst app = await NestFactory.create<NestFastifyApplication>(\n  AppModule,\n  new FastifyAdapter({\n    querystringParser: (str) => qs.parse(str),\n  }),\n);\n```\n\n========================================\n\nComments:\n- What's your HTTP engine? And what are you sending the request through? It may not be encoding the query parameters correctly\n- Not sure what do you mean by HTTP engine but I use postman to test it.\n- By HTTP engine, I mean express or fastify, which are the underlying engines Nest can use. Using `curl` to send the requests this worked: `curl 'http:&#47;&#47;localhost:3000&#47;?key1=value1&key2%5Binner1%5D=hello&k&zwnj;&#8203;ey2%5Binner2%5D=worl&zwnj;&#8203;d'` while this didn't: `'http:&#47;&#47;localhost:3000&#47;?key1=value&key2[inner1]=hello&key2[i&zwnj;&#8203;nner2]=world'`. So like I said, it might be a query parameter encoding issue\n- I use Fastify with NestJs. I can't change the encoding of the URL coming. I am building a connector that connect 3 different API. This is the incoming request that I have no control over. Any chance I can make it work? Thanks\n- Thank you for your answer but this doesn't work, I am not sure why ... Unless the decorators are important for it to work in which case plase add the imports. EDIT: my nestjs/common is 8.0.0\n- Did you use a validation pipe? If not, use one, then try.\n- I have just added this one @UsePipes(new ValidationPipe({ transform: true })), it still didn't work... I am new to NestJS can you give me more info pls\n- it works for me the problem was how to pass nested values via query string other things are same as post, so if anybody has same problem at first fix the issue via a post endpoint and use this method for sending nested fields.","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":292,"estimatedTokens":1719}}278{"id":"stack-54668910","source":"stackoverflow","questionId":54668910,"title":"alias was not found. Maybe you forget to join it","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: alias was not found. Maybe you forget to join it\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn my nectjs project I'm using TypeORM and I have 2 entities user and post,\nand I'm tying to make a relation between them\n\n### user.entity.ts\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 50, unique: true })\n name: string;\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n```\n\n### post.entity.ts\n\n```\n@Entity()\nexport class Post {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 30 })\n title: string;\n\n @ManyToOne(type => User, user => user.posts)\n user: User;\n}\n```\n\nSo I want to join these tables and get post by it's title for specific user\n\n```\nconst PostObject = await createQueryBuilder(\"post\")\n .leftJoinAndSelect(\n \"post.user\",\n \"user\",\n \"post.title = :title\",\n { title: \"title1\" }\n )\n .where(\"user.id = :id\", { id: id })\n .getOne();\n```\n\nbut when I run the project and execute this function I get this error:\n\n```\nError: \"post\" alias was not found. Maybe you forget to join it?\n```\n\n========================================\n\nTop Answer:\nCan also use getRepository like below.\n\n```\nconst PostObject = await getRepository(\"post\").createQueryBuilder(\"post\")\n .leftJoinAndSelect(\n \"post.user\",\n \"user\",\n \"post.title = :title\",\n { title: \"title1\" }\n )\n .where(\"user.id = :id\", { id: id })\n .getOne();\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ length: 50, unique: true })\n  name: string;\n\n  @OneToMany(type => Post, post => post.user)\n  posts: Post[];\n}\n```\n\n```text\n@Entity()\nexport class Post {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ length: 30 })\n  title: string;\n\n  @ManyToOne(type => User, user => user.posts)\n  user: User;\n}\n```\n\n```text\nconst PostObject = await createQueryBuilder(\"post\")\n      .leftJoinAndSelect(\n        \"post.user\",\n        \"user\",\n        \"post.title = :title\",\n        { title: \"title1\" }\n      )\n      .where(\"user.id = :id\", { id: id })\n      .getOne();\n```\n\n```text\nError: \"post\" alias was not found. Maybe you forget to join it?\n```\n\n```text\nconstructor(\n  @InjectRepository(Post) private readonly postRepository: Repository<Post>\n) {\n}\n```\n\n```text\nthis.postRepository.createQueryBuilder('post')\n// ^^^^^^^^^^^^^^^^\n   .leftJoinAndSelect(\n     'post.user',\n     'user',\n     'post.title = :title',\n     { title: 'title1' },\n   )\n   .where('user.id = :id', { id })\n   .getOne();\n```\n\n```text\nRepository\n```\n\n```text\nQueryBuilder\n```\n\n```text\nPost\n```\n\n```text\nconst PostObject = await getRepository(\"post\").createQueryBuilder(\"post\")\n      .leftJoinAndSelect(\n        \"post.user\",\n        \"user\",\n        \"post.title = :title\",\n        { title: \"title1\" }\n      )\n      .where(\"user.id = :id\", { id: id })\n      .getOne();\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":167,"estimatedTokens":726}}279{"id":"stack-57913047","source":"stackoverflow","questionId":57913047,"title":"NestJS - File upload to microservice","tags":["node.js","file-upload","axios","nestjs"],"text":"Title: NestJS - File upload to microservice\nTags: node.js, file-upload, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to upload a file to an API-Gateway. After adding some meta information, the file should be send to another (micro) service (as Content-Type: multipart/form-data). I am having some problems to build a FormData object within the API-Gateway. I do not want to persist the file on the gateway, so I am basically just trying to pass it through. \n\nFor creating the formData-object, I am using Form-Data\n\nThis is what a tried:\n\n```\n// Controller\n @Post()\n @UseInterceptors(FileInterceptor('file'))\n async create(@Res() res, @UploadedFile('file') file, @Body() body: any) {\n return await this.someService.create(file);\n }\n```\n\n```\n// Service\n async create(file: any) {\n const formData = new FormData();\n\n formData.append('file', file);\n formData.append('key', 'value');\n\n const formHeaders = formData.getHeaders();\n\n try {\n const result = await this.httpService\n\n .post('http://some-other-service/import', formData , {\n headers: {\n ...formHeaders,\n },\n })\n .toPromise();\n return result.data;\n } catch (e) {\n throw new BadGatewayException();\n }\n }\n```\n\nThis results in the following error:\n\n```\nTypeError: source.on is not a function\nat Function.DelayedStream.create (/usr/app/node_modules/delayed-stream/lib/delayed_stream.js:33:10)\nat FormData.CombinedStream.append (/usr/app/node_modules/combined-stream/lib/combined_stream.js:44:37)\nat FormData.append (/usr/app/node_modules/form-data/lib/form_data.js:74:3)\nat ImportService. (/usr/app/src/import/import.service.ts:47:18)\n```\n\n========================================\n\nCode:\n```text\n// Controller\n    @Post()\n    @UseInterceptors(FileInterceptor('file'))\n    async create(@Res() res, @UploadedFile('file') file, @Body() body: any) {\n        return await this.someService.create(file);\n    }\n```\n\n```text\n// Service\n    async create(file: any) {\n        const formData = new FormData();\n\n        formData.append('file', file);\n        formData.append('key', 'value');\n\n        const formHeaders = formData.getHeaders();\n\n        try {\n            const result = await this.httpService\n\n                .post('http://some-other-service/import', formData , {\n                    headers: {\n                        ...formHeaders,\n                    },\n                })\n                .toPromise();\n            return result.data;\n        } catch (e) {\n            throw new BadGatewayException();\n        }\n    }\n```\n\n```text\nTypeError: source.on is not a function\nat Function.DelayedStream.create (/usr/app/node_modules/delayed-stream/lib/delayed_stream.js:33:10)\nat FormData.CombinedStream.append (/usr/app/node_modules/combined-stream/lib/combined_stream.js:44:37)\nat FormData.append (/usr/app/node_modules/form-data/lib/form_data.js:74:3)\nat ImportService.<anonymous> (/usr/app/src/import/import.service.ts:47:18)\n```\n\n```text\nformData.append('file', file.buffer);\n\n//OR \nformData.append('file', file.buffer, file.originalname);\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":108,"estimatedTokens":753}}280{"id":"stack-60804946","source":"stackoverflow","questionId":60804946,"title":"Replace _id to id in NestJs + Typegoose","tags":["nestjs","typegoose"],"text":"Title: Replace _id to id in NestJs + Typegoose\nTags: nestjs, typegoose\nSource: Stack Overflow\n\nQuestion:\nI use NestJs + Typegoose. How to replace _id to id in NestJs + Typegoose? I didn't find a clear example. I've tried something but without any results.\n\n```\n@modelOptions({\n schemaOptions: {\n collection: 'users',\n },\n})\nexport class UserEntity {\n @prop()\n id?: string;\n\n @prop({ required: true })\n public email: string;\n\n @prop({ required: true })\n public password: string;\n\n @prop({ enum: UserRole, default: UserRole.User, type: String })\n public role: UserRole;\n\n @prop({ default: null })\n public subscription: string;\n}\n```\n\n```\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectModel(UserEntity) private readonly userModel: ModelType,\n ) {}\n\n getOneByEmail(email: string) {\n return from(\n this.userModel\n .findOne({ email })\n .select('-password')\n .lean(),\n );\n }\n}\n```\n\n========================================\n\nTop Answer:\nusing typegoose with class-transformer:\n\n```\nimport * as mongoose from 'mongoose';\nimport { Expose, Exclude, Transform } from 'class-transformer';\n\n@Exclude()\n// re-implement base Document to allow class-transformer to serialize/deserialize its properties\n// This class is needed, otherwise \"_id\" and \"__v\" would be excluded from the output\nexport class DocumentCT {\n @Expose({ name: '_id' })\n // makes sure that when deserializing from a Mongoose Object, ObjectId is serialized into a string\n @Transform((value: any) => {\n if ('value' in value) {\n return value.value instanceof mongoose.Types.ObjectId ? value.value.toHexString() : value.value.toString();\n }\n\n return 'unknown value';\n })\n public id: string;\n\n @Expose()\n public createdAt: Date;\n\n @Expose()\n public updatedAt: Date;\n}\n```\n\n========================================\n\nCode:\n```text\n@modelOptions({\n  schemaOptions: {\n    collection: 'users',\n  },\n})\nexport class UserEntity {\n  @prop()\n  id?: string;\n\n  @prop({ required: true })\n  public email: string;\n\n  @prop({ required: true })\n  public password: string;\n\n  @prop({ enum: UserRole, default: UserRole.User, type: String })\n  public role: UserRole;\n\n  @prop({ default: null })\n  public subscription: string;\n}\n```\n\n```text\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectModel(UserEntity) private readonly userModel: ModelType<UserEntity>,\n  ) {}\n\n  getOneByEmail(email: string) {\n    return from(\n      this.userModel\n        .findOne({ email })\n        .select('-password')\n        .lean(),\n    );\n  }\n}\n```\n\n```text\n@modelOptions({\n    schemaOptions: {\n        collection: 'Order',\n        timestamps: true,\n        toJSON: {\n            transform: (doc: DocumentType<TicketClass>, ret) => {\n                delete ret.__v;\n                ret.id = ret._id;\n                delete ret._id;\n            }\n        }\n    }\n})\n@plugin(AutoIncrementSimple, [{ field: 'version' }])\nclass TicketClass {\n\n    @prop({ required: true })\n    public title!: string\n\n    @prop({ required: true })\n    public price!: number\n\n    @prop({ default: 1 })\n    public version?: number\n}\n\n\nexport type TicketDocument = DocumentType<TicketClass>\n\n\nexport const Ticket = getModelForClass(TicketClass);\n```\n\n```text\n_id\n```\n\n```text\nid\n```\n\n```js\nexport const NotesSchema = new Schema({\n  title: String,\n  description: String,\n});\n\nNotesSchema.virtual('id')\n    .get(function() {\n      return this._id.toHexString();\n});\n```\n\n```js\nNotesSchema.method('toClient', function() {\n    var obj = this.toObject();\n\n    //Rename fields\n    obj.id = obj._id;\n    delete obj._id;\n\n    return obj;\n});\n```\n\n```text\nimport * as mongoose from 'mongoose';\nimport { Expose, Exclude, Transform } from 'class-transformer';\n\n@Exclude()\n// re-implement base Document to allow class-transformer to serialize/deserialize its properties\n// This class is needed, otherwise \"_id\" and \"__v\" would be excluded from the output\nexport class DocumentCT {\n  @Expose({ name: '_id' })\n  // makes sure that when deserializing from a Mongoose Object, ObjectId is serialized into a string\n  @Transform((value: any) => {\n    if ('value' in value) {\n      return value.value instanceof mongoose.Types.ObjectId ? value.value.toHexString() : value.value.toString();\n    }\n\n    return 'unknown value';\n  })\n  public id: string;\n\n  @Expose()\n  public createdAt: Date;\n\n  @Expose()\n  public updatedAt: Date;\n}\n```\n\n========================================\n\nComments:\n- you can declare id as public property of class type, and define getter and setter which associates to default factory _id.\n- Thanks for answer but how result of `this.userModel .findOne({ email }) .select('-password') .lean()` convert to object? Because it's not `Document` and there is no `toObject()` methor\n- By default, Mongoose queries return an instance of the Mongoose Document class. const leanDoc = await MyModel.findOne().lean(); If i am understand you leaning must give object if not help .toJSON(); must work\n- Great answer, does the trick!","metadata":{"transformedAt":"2026-08-18T18:33:02.428Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":226,"estimatedTokens":1236}}281{"id":"stack-72598718","source":"stackoverflow","questionId":72598718,"title":"Modifying the DTO name appearing in OpenAPI (Swagger) schemas in NestJS","tags":["swagger","nestjs","schema","openapi","dto"],"text":"Title: Modifying the DTO name appearing in OpenAPI (Swagger) schemas in NestJS\nTags: swagger, nestjs, schema, openapi, dto\nSource: Stack Overflow\n\nQuestion:\nI am facing a problem where my DTO types are named one thing, but I want them to appear with a different name in the OpenAPI doc page.\nFor example, I have a UserDto class that I use in my controller, but wanted it to appear as simply \"User\" in the schemas section (and everywhere else this applies). Is that possible? Is there any decorator I can use?\nI know I can simply modify the class name, but there is already a different user class used elsewhere.\nI have searched everywhere with no avail.\n\nhttps://i.sstatic.net/pkiHB.jpg\n\nBTW, I am using typescript and nestjs.\nEvery help will be appreciated, thanks!\n\n========================================\n\nTop Answer:\nUse the `ApiSchema` decorator:\n\n```\n@ApiSchema({ name: 'User' })\nclass UserDto {\n\n @ApiProperty()\n firstName: string;\n\n // ...\n}\n```\n\n========================================\n\nCode:\n```js\nclass UserDto {\n    static name = 'User';  // <- here\n\n    @ApiProperty()\n    firstName: string;\n\n    // ...\n  }\n```\n\n```js\ntype Constructor<T = object> = new(...args: any[]) => T;\n  type Wrapper<T = object> = { new(): (T & any), prototype: T };\n  type DecoratorOptions = { name: string };\n  type ApiSchemaDecorator = <T extends Constructor>(options: DecoratorOptions) => (constructor: T) => Wrapper<T>;\n\n  const ApiSchema: ApiSchemaDecorator = ({ name }) => {\n    return (constructor) => {\n      const wrapper = class extends constructor { };\n      Object.defineProperty(wrapper, 'name', {\n        value: name,\n        writable: false,\n      });\n      return wrapper;\n    }\n  }\n```\n\n```js\n@ApiSchema({ name: 'User' }) // <- here\n  class UserDto {\n    @ApiProperty()\n    firstName: string;\n\n    // ...\n  }\n```\n\n```text\nStatic property 'name' conflicts with built-in property 'Function.name' of constructor function 'UserDto'.\n```\n\n```text\n@ApiModel(value=\"MeuLindoDto\")\n    public class NameOriginalClassResponseDto ...\n```\n\n```text\n@ApiSchema({ name: 'User' })\nclass UserDto {\n\n  @ApiProperty()\n  firstName: string;\n\n  // ...\n}\n```\n\n```text\nApiSchema\n```\n\n========================================\n\nComments:\n- Could you please refer to the documentation? As far as I read, there is an open PR to solve this github.com/nestjs/swagger/pull/983, an issue github.com/nestjs/swagger/issues/1638 and other open PR for the docs github.com/nestjs/docs.nestjs.com/pull/1533. ApiModel is not a valid decorator.\n- By now, the proposal has been implemented and the last code snippet is supported, i.e. `@ApiSchema({ name: 'User' })`","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":102,"estimatedTokens":658}}282{"id":"stack-55578780","source":"stackoverflow","questionId":55578780,"title":"Test resolvers in NestJS","tags":["javascript","node.js","typescript","jestjs","nestjs"],"text":"Title: Test resolvers in NestJS\nTags: javascript, node.js, typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nThis is a sample of `resolver` in NestJs, and I'm about to write tests for this file. But there is no documentation for testing resolvers in nestjs docs.\n\nI already have a test for my `service`, but resolvers also may have little logic inside them, so it's better to have tests for them as well.\n\nHow I can test `resolver` files?\n\n```\nimport { ObjectId } from 'mongodb';\nimport { AuthGuard } from '../utils/Auth.guards';\nimport { UseGuards } from '@nestjs/common';\nimport { IUser } from '../users/users.service';\nimport { User } from '../utils/user.decorator';\nimport { Query, Resolver, Mutation, Args } from '@nestjs/graphql';\nimport { AccessService } from './access.service';\nimport { NeedAccess } from '../utils/needAccess.decorator';\nimport { HasAccess } from '../utils/access.decorator';\n\n@Resolver('Accesss')\n@UseGuards(AuthGuard)\nexport class AccessResolvers {\n constructor(private readonly accessService: AccessService) {}\n\n @Query()\n @NeedAccess()\n access(\n @Args('userId') userId: ObjectId,\n @User() user: IUser,\n @HasAccess(['access.view']) hasAccess,\n ) {\n if (userId && hasAccess) { // this might be a situation to concern about in tests\n return this.accessService.getUserAccess(userId);\n } else {\n return this.accessService.getUserAccess(user._id);\n }\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\nimport { ObjectId } from 'mongodb';\nimport { AuthGuard } from '../utils/Auth.guards';\nimport { UseGuards } from '@nestjs/common';\nimport { IUser } from '../users/users.service';\nimport { User } from '../utils/user.decorator';\nimport { Query, Resolver, Mutation, Args } from '@nestjs/graphql';\nimport { AccessService } from './access.service';\nimport { NeedAccess } from '../utils/needAccess.decorator';\nimport { HasAccess } from '../utils/access.decorator';\n\n@Resolver('Accesss')\n@UseGuards(AuthGuard)\nexport class AccessResolvers {\n  constructor(private readonly accessService: AccessService) {}\n\n  @Query()\n  @NeedAccess()\n  access(\n    @Args('userId') userId: ObjectId,\n    @User() user: IUser,\n    @HasAccess(['access.view']) hasAccess,\n  ) {\n    if (userId && hasAccess) { // this might be a situation to concern about in tests\n      return this.accessService.getUserAccess(userId);\n    } else {\n      return this.accessService.getUserAccess(user._id);\n    }\n  }\n\n}\n```\n\n```text\nresolver\n```\n\n```text\nservice\n```\n\n```text\nresolver\n```\n\n```text\nAccessResolvers\n```\n\n```text\nAccessService\n```\n\n========================================\n\nComments:\n- Do you want to write a unit test or an e2e test?\n- Nothing that I have decided right now, I actually look for an easy solution. Beside that knowing how to write unit test or e2e can be beneficial here. :) @KimKern\n- But repository and services are not the same.\n- It's just me or looks like there's a typo or missing words in \"in the case of your AccessResolvers the AccessService and then you test every public method\" ?\n- @Vencovsky it does not look like a typo to me. I think he meant that, in other words, AccessService is the dependency of the AccessResolver","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":108,"estimatedTokens":792}}283{"id":"stack-63109954","source":"stackoverflow","questionId":63109954,"title":"Running e2e tests with jest @ nestjs","tags":["jestjs","nestjs","e2e-testing"],"text":"Title: Running e2e tests with jest @ nestjs\nTags: jestjs, nestjs, e2e-testing\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run e2e tests with jest & nestjs and I've run into the weirdest error that doesn't return anything in my google searches (*ExpressAdapter is not a constructor*):\n\n```\n$ env-cmd -f .env.test jest --config ./test/jest-e2e.json\n FAIL test/sensor.e2e-spec.ts (29.498 s)\n SensorController (e2e)\n ร— /sensors (GET) (15165 ms)\n\n โ— SensorController (e2e) โ€บ /sensors (GET)\n\n Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.\n\n at mapper (../node_modules/jest-jasmine2/build/queueRunner.js:29:45)\n\n โ— SensorController (e2e) โ€บ /sensors (GET)\n\n TypeError: Cannot read property 'getHttpServer' of undefined\n\n 24 |\n 25 | it('/sensors (GET)', () => {\n > 26 | return request(app.getHttpServer()).get('/sensors').expect(200);\n | ^\n 27 | });\n 28 |\n 29 | afterAll(async () => {\n\n at Object. (sensor.e2e-spec.ts:26:24)\n\n Test Suites: 1 failed, 1 total\n Tests: 1 failed, 1 total\n Snapshots: 0 total\n Time: 29.69 s\n Ran all test suites.\n\n ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.\n\n 17 | }).compile();\n 18 |\n > 19 | app = moduleFixture.createNestApplication();\n | ^\n 20 |\n 21 | await app.init();\n 22 | fixture = await SensorFixture(app);\n\n at ../node_modules/@nestjs/testing/testing-module.js:25:117\n at Object.loadPackage (../node_modules/@nestjs/common/utils/load-package.util.js:9:27)\n at TestingModule.createHttpAdapter (../node_modules/@nestjs/testing/testing-module.js:25:56)\n at TestingModule.createNestApplication (../node_modules/@nestjs/testing/testing-module.js:13:43)\n at Object. (sensor.e2e-spec.ts:19:25)\n (node:1500) UnhandledPromiseRejectionWarning: TypeError: Caught error after test environment was torn down\n\n ExpressAdapter is not a constructor\n (node:1500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)\n (node:1500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n Jest did not exit one second after the test run has completed.\n\n This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.\n error Command failed with exit code 1.\n info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\nMy jest-e2e.json:\n\n```\n{\n \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n \"rootDir\": \".\",\n \"testEnvironment\": \"node\",\n \"testRegex\": \".e2e-spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"moduleNameMapper\": {\n \"~(.*)$\": \"/../src/$1\"\n }\n }\n```\n\njest.config.js:\n\n```\nmodule.exports = {\n verbose: true,\n preset: 'ts-jest',\n rootDir: 'src',\n moduleNameMapper: {\n '~(.*)$': '/$1',\n },\n moduleFileExtensions: ['js', 'json', 'ts'],\n moduleDirectories: [\n \"node_modules\", \n \"src\"\n ],\n };\n```\n\nI'm using typeorm and I'm pretty sure my test database config is correct since my unit tests execute without an issue (I'm running them against an actual test database).\n\normconfig.js:\n\n```\nmodule.exports = {\n type: process.env.DB_TYPE,\n host: process.env.DB_HOST,\n port: process.env.DB_PORT,\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_DATABASE,\n entities: process.env.DB_ENTITIES.split(' '),\n synchronize: process.env.DB_SYNCHRONIZE,\n autoLoadEntities: true,\n logging: process.env.DB_LOGGING,\n}\n```\n\nenv variables:\n\n```\nDB_TYPE = \"postgres\"\nDB_HOST = \"localhost\"\nDB_PORT = 5432\nDB_USERNAME = \"postgres\"\nDB_PASSWORD = \"postgres\"\nDB_DATABASE = \"sensor-dashboard-test\"\nDB_SYNCHRONIZE = true\nDB_LOGGING = true\nDB_ENTITIES = \"**/*.entity{.ts,.js} ../src/modules/**/*.entity{.ts,.js}\"\n```\n\nMy dependencies:\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^7.0.0\",\n \"@nestjs/core\": \"^7.0.0\",\n \"@nestjs/platform-express\": \"^7.0.0\",\n \"@nestjs/typeorm\": \"^7.1.0\",\n \"class-transformer\": \"^0.2.3\",\n \"class-validator\": \"^0.12.2\",\n \"date-fns\": \"^2.15.0\",\n \"env-cmd\": \"^10.1.0\",\n \"nestjs-admin\": \"^0.4.0\",\n \"nestjs-typeorm-paginate\": \"^2.1.1\",\n \"pg\": \"^8.3.0\",\n \"postgres\": \"^1.0.2\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^3.0.2\",\n \"rxjs\": \"^6.5.4\",\n \"typeorm\": \"^0.2.25\",\n \"uuid\": \"^8.2.0\"\n },\n```\n\nAnd the entire e2e test that fails:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { INestApplication } from '@nestjs/common';\nimport * as request from 'supertest';\nimport {\n SensorFixtureInterface,\n SensorFixture,\n} from '~modules/sensor/sensor.fixture';\nimport { AppModule } from '~app.module';\n\ndescribe('SensorController (e2e)', () => {\n let app: INestApplication;\n let fixture: SensorFixtureInterface;\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n\n await app.init();\n fixture = await SensorFixture(app);\n });\n\n it('/sensors (GET)', () => {\n return request(app.getHttpServer()).get('/sensors').expect(200);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\napp.module.ts:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { SensorModule } from '~/modules/sensor/sensor.module';\nimport { DefaultAdminModule } from 'nestjs-admin';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { MeasurementModule } from '~/modules/measurement/measurement.module';\n\n@Module({\n imports: [\n SensorModule,\n MeasurementModule,\n DefaultAdminModule,\n TypeOrmModule.forRoot(),\n ],\n controllers: [],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nLink to the entire project: https://github.com/xtrinch/sensor-dashboard-nestjs-backend\n\n========================================\n\nCode:\n```text\n$ env-cmd -f .env.test jest --config ./test/jest-e2e.json\n     FAIL  test/sensor.e2e-spec.ts (29.498 s)\n      SensorController (e2e)\n        ร— /sensors (GET) (15165 ms)\n\n      โ— SensorController (e2e) โ€บ /sensors (GET)\n\n        Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.\n\n          at mapper (../node_modules/jest-jasmine2/build/queueRunner.js:29:45)\n\n      โ— SensorController (e2e) โ€บ /sensors (GET)\n\n        TypeError: Cannot read property 'getHttpServer' of undefined\n\n          24 |\n          25 |   it('/sensors (GET)', () => {\n        > 26 |     return request(app.getHttpServer()).get('/sensors').expect(200);\n             |                        ^\n          27 |   });\n          28 |\n          29 |   afterAll(async () => {\n\n          at Object.<anonymous> (sensor.e2e-spec.ts:26:24)\n\n    Test Suites: 1 failed, 1 total\n    Tests:       1 failed, 1 total\n    Snapshots:   0 total\n    Time:        29.69 s\n    Ran all test suites.\n\n    ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.\n\n          17 |     }).compile();\n          18 |\n        > 19 |     app = moduleFixture.createNestApplication();\n             |                         ^\n          20 |\n          21 |     await app.init();\n          22 |     fixture = await SensorFixture(app);\n\n          at ../node_modules/@nestjs/testing/testing-module.js:25:117\n          at Object.loadPackage (../node_modules/@nestjs/common/utils/load-package.util.js:9:27)\n          at TestingModule.createHttpAdapter (../node_modules/@nestjs/testing/testing-module.js:25:56)\n          at TestingModule.createNestApplication (../node_modules/@nestjs/testing/testing-module.js:13:43)\n          at Object.<anonymous> (sensor.e2e-spec.ts:19:25)\n    (node:1500) UnhandledPromiseRejectionWarning: TypeError: Caught error after test environment was torn down\n\n    ExpressAdapter is not a constructor\n    (node:1500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)\n    (node:1500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n    Jest did not exit one second after the test run has completed.\n\n    This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.\n    error Command failed with exit code 1.\n    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\n```text\n{\n      \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n      \"rootDir\": \".\",\n      \"testEnvironment\": \"node\",\n      \"testRegex\": \".e2e-spec.ts$\",\n      \"transform\": {\n        \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n      },\n      \"moduleNameMapper\": {\n        \"~(.*)$\": \"<rootDir>/../src/$1\"\n      }\n    }\n```\n\n```text\nmodule.exports = {\n      verbose: true,\n      preset: 'ts-jest',\n      rootDir: 'src',\n      moduleNameMapper: {\n        '~(.*)$': '<rootDir>/$1',\n      },\n      moduleFileExtensions: ['js', 'json', 'ts'],\n      moduleDirectories: [\n        \"node_modules\", \n        \"src\"\n      ],\n    };\n```\n\n```text\nmodule.exports = {\n  type: process.env.DB_TYPE,\n  host: process.env.DB_HOST,\n  port: process.env.DB_PORT,\n  username: process.env.DB_USERNAME,\n  password: process.env.DB_PASSWORD,\n  database: process.env.DB_DATABASE,\n  entities: process.env.DB_ENTITIES.split(' '),\n  synchronize: process.env.DB_SYNCHRONIZE,\n  autoLoadEntities: true,\n  logging: process.env.DB_LOGGING,\n}\n```\n\n```text\nDB_TYPE = \"postgres\"\nDB_HOST = \"localhost\"\nDB_PORT = 5432\nDB_USERNAME = \"postgres\"\nDB_PASSWORD = \"postgres\"\nDB_DATABASE = \"sensor-dashboard-test\"\nDB_SYNCHRONIZE = true\nDB_LOGGING = true\nDB_ENTITIES = \"**/*.entity{.ts,.js} ../src/modules/**/*.entity{.ts,.js}\"\n```\n\n```text\n\"dependencies\": {\n    \"@nestjs/common\": \"^7.0.0\",\n    \"@nestjs/core\": \"^7.0.0\",\n    \"@nestjs/platform-express\": \"^7.0.0\",\n    \"@nestjs/typeorm\": \"^7.1.0\",\n    \"class-transformer\": \"^0.2.3\",\n    \"class-validator\": \"^0.12.2\",\n    \"date-fns\": \"^2.15.0\",\n    \"env-cmd\": \"^10.1.0\",\n    \"nestjs-admin\": \"^0.4.0\",\n    \"nestjs-typeorm-paginate\": \"^2.1.1\",\n    \"pg\": \"^8.3.0\",\n    \"postgres\": \"^1.0.2\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^6.5.4\",\n    \"typeorm\": \"^0.2.25\",\n    \"uuid\": \"^8.2.0\"\n  },\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { INestApplication } from '@nestjs/common';\nimport * as request from 'supertest';\nimport {\n  SensorFixtureInterface,\n  SensorFixture,\n} from '~modules/sensor/sensor.fixture';\nimport { AppModule } from '~app.module';\n\ndescribe('SensorController (e2e)', () => {\n  let app: INestApplication;\n  let fixture: SensorFixtureInterface;\n\n  beforeEach(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n\n    await app.init();\n    fixture = await SensorFixture(app);\n  });\n\n  it('/sensors (GET)', () => {\n    return request(app.getHttpServer()).get('/sensors').expect(200);\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { SensorModule } from '~/modules/sensor/sensor.module';\nimport { DefaultAdminModule } from 'nestjs-admin';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { MeasurementModule } from '~/modules/measurement/measurement.module';\n\n@Module({\n  imports: [\n    SensorModule,\n    MeasurementModule,\n    DefaultAdminModule,\n    TypeOrmModule.forRoot(),\n  ],\n  controllers: [],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nmodule.exports = {\n  type: DB_TYPE,\n  host: DB_HOST,\n  port: DB_PORT,\n  username: DB_USERNAME,\n  password: DB_PASSWORD,\n  database: DB_DATABASE,\n  migrations: ['**/migrations/*.{ts,js}'],\n  entities: NODE_ENV === 'test' ? ['**/*.entity.{ts}'] : ['**/*.entity.{ts,js}'],\n  cli: {\n    entitiesDir: 'src/database/entities',\n    migrationsDir: 'src/database/migrations',\n  },\n};\n```\n\n========================================\n\nComments:\n- I had the same issue and I've wasted some hours searching then I found this and fixed my issue. Thanks\n- @Gudari and user15964382, It works for me too, I just want to understand why it works?","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":440,"estimatedTokens":3300}}284{"id":"stack-65991182","source":"stackoverflow","questionId":65991182,"title":"NestJS - how to provide services of dynamic modules","tags":["javascript","dependency-injection","module","nestjs"],"text":"Title: NestJS - how to provide services of dynamic modules\nTags: javascript, dependency-injection, module, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm struggling to figure out on how to provide services from DynamicModule to regular Modules. Pseudocode below:\n\napp.module.ts\n\n```\n@Global()\n@Module({\n imports: [\n DynamicModule.forRoot(config),\n RegularModule,\n ],\n providers: [],\n exports: [],\n})\nexport class AppModule {}\n```\n\ndynamic.module.ts\n\n```\n@Module({})\nexport class DynamicModule implements OnModuleInit, OnModuleDestroy {\n constructor(private dynamicService: dynamicService) {}\n\n static forRoot(config: Config): DynamicModule {\n return {\n module: DynamicModule,\n imports: [],\n providers: [\n {\n provide: CONFIG_TOKEN,\n useValue: config,\n },\n DynamicService,\n ],\n exports: [\n DynamicService,\n ],\n };\n }\n}\n```\n\ndynamic.service.ts\n\n```\n@Injectable()\nexport class DynamicService {\n\n constructor(\n @Inject(CONFIG_TOKEN) private readonly config: Config,\n ) {}\n}\n```\n\nregular.module.ts\n\n```\n@Module({\n imports: [],\n providers: [RegularService, DynamicService],\n exports: [RegularService],\n})\nexport class RegularModule {}\n```\n\nregular.service.ts\n\n```\n@Injectable()\nexport class RegularService {\n\n constructor(\n private readonly dynamicService: DynamicService\n ) {}\n}\n```\n\nProviding DynamicService to RegularModule requires to provide CONFIG_TOKEN in RegularModule as well, which seems odd and not practical in case more modules would depend on DynamicService and doesn't seem to be the correct way.\n\nWhat concepts am I missing and what is correct approach to use services of a DynamicModule?\n\nWould something as forFeature in DynamicModule method would be the right direction?\n\n========================================\n\nCode:\n```text\n@Global()\n@Module({\n  imports: [\n    DynamicModule.forRoot(config),\n    RegularModule,\n  ],\n  providers: [],\n  exports: [],\n})\nexport class AppModule {}\n```\n\n```text\n@Module({})\nexport class DynamicModule implements OnModuleInit, OnModuleDestroy {\n  constructor(private dynamicService: dynamicService) {}\n\n  static forRoot(config: Config): DynamicModule {\n    return {\n      module: DynamicModule,\n      imports: [],\n      providers: [\n        {\n          provide: CONFIG_TOKEN,\n          useValue: config,\n        },\n        DynamicService,\n      ],\n      exports: [\n        DynamicService,\n      ],\n    };\n  }\n}\n```\n\n```text\n@Injectable()\nexport class DynamicService {\n\n  constructor(\n    @Inject(CONFIG_TOKEN) private readonly config: Config,\n  ) {}\n}\n```\n\n```text\n@Module({\n  imports: [],\n  providers: [RegularService, DynamicService],\n  exports: [RegularService],\n})\nexport class RegularModule {}\n```\n\n```text\n@Injectable()\nexport class RegularService {\n\n  constructor(\n    private readonly dynamicService: DynamicService\n  ) {}\n}\n```\n\n```text\nforRoot(input)\n```\n\n```text\nconfig\n```\n\n```text\nconfig\n```\n\n```text\ndynamicService\n```\n\n```text\nconfig\n```\n\n```text\nregularService\n```\n\n```text\nConfigModule\n```\n\n```text\nconfig\n```\n\n```text\nconfig\n```\n\n========================================\n\nComments:\n- Adding @Global decorator worked out for me. Although as it exposes services across the app and if the need is to make services available only for specific modules, loading module with forFeature (implementation depends on the goal) in specific modules might be the solution.","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":198,"estimatedTokens":830}}285{"id":"stack-54471331","source":"stackoverflow","questionId":54471331,"title":"How to ignore an interceptor for a particular route in NestJS","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: How to ignore an interceptor for a particular route in NestJS\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have set a controller level interceptor `@UseInterceptors(CacheInterceptor)`.\nNow I want one of the controller routes to ignore that interceptor, is there any way to achieve that in nest.js?\n\nFor this particular case I want to be able to disable `CacheInterceptor` for one of the routes.\n\n```\n@Controller()\n@UseInterceptors(CacheInterceptor)\nexport class AppController {\n @Get('route1')\n route1() {\n return ...;\n }\n\n @Get('route2')\n route2() {\n return ...;\n }\n @Get('route3')\n route3() {\n return ...;\n }\n @Get('route4')\n route4() {\n return ...; // do not want to cache this route\n }\n}\n```\n\n========================================\n\nTop Answer:\n```\nconst IgnoredPropertyName = Symbol('IgnoredPropertyName')\n \n export function CustomInterceptorIgnore() {\n return function(target, propertyKey: string, descriptor: PropertyDescriptor) {\n descriptor.value[IgnoredPropertyName] = true\n };\n }\n \n \n @Injectable()\n export class CustomInterceptor implements NestInterceptor {\n constructor() {}\n \n async intercept(context: ExecutionContext, next: CallHandler): Promise> {\n const request: ExtendedUserRequest = context.switchToHttp().getRequest()\n const isIgnored = context.getHandler()[IgnoredPropertyName]\n if (isIgnored) {\n return next.handle()\n }\n }\n }\n \n @Patch('route')\n @CustomInterceptorIgnore()\n async someHandle () {\n \n }\n```\n\n========================================\n\nCode:\n```text\n@Controller()\n@UseInterceptors(CacheInterceptor)\nexport class AppController {\n  @Get('route1')\n  route1() {\n    return ...;\n  }\n\n  @Get('route2')\n  route2() {\n    return ...;\n  }\n  @Get('route3')\n  route3() {\n    return ...;\n  }\n  @Get('route4')\n  route4() {\n    return ...; // do not want to cache this route\n  }\n}\n```\n\n```text\n@UseInterceptors(CacheInterceptor)\n```\n\n```text\nCacheInterceptor\n```\n\n```text\n@Injectable()\nclass HttpCacheInterceptor extends CacheInterceptor {\n  trackBy(context: ExecutionContext): string | undefined {\n    const request = context.switchToHttp().getRequest();\n    const isGetRequest = this.httpServer.getRequestMethod(request) === 'GET';\n    const excludePaths = ['path1', 'path2'];\n          ^^^^^^^^^^^^\n    if (\n      !isGetRequest ||\n      (isGetRequest && excludePaths.includes(this.httpServer.getRequestUrl))\n    ) {\n      return undefined;\n    }\n    return this.httpServer.getRequestUrl(request);\n  }\n}\n```\n\n```text\nCacheInterceptor\n```\n\n```text\nconst IgnoredPropertyName = Symbol('IgnoredPropertyName')\n  \n  export function CustomInterceptorIgnore() {\n    return function(target, propertyKey: string, descriptor: PropertyDescriptor) {\n      descriptor.value[IgnoredPropertyName] = true\n    };\n  }\n  \n  \n  @Injectable()\n  export class CustomInterceptor implements NestInterceptor {\n    constructor() {}\n  \n    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {\n      const request: ExtendedUserRequest = context.switchToHttp().getRequest()\n      const isIgnored = context.getHandler()[IgnoredPropertyName]\n      if (isIgnored) {\n        return next.handle()\n      }\n    }\n  }\n  \n  @Patch('route')\n  @CustomInterceptorIgnore()\n  async someHandle () {\n  \n  }\n```\n\n========================================\n\nComments:\n- I was searching in github issues but didn't found that one. Thanks for the help.\n- BTW can you set a specific ttl for each path using `custom&#47;extended` interceptor? Say I want `route1` and `route2` have `ttl` 5 hours, `route3` and `route4` 24 hours\n- For every handler(function) adds special property. And then if in interceptor this property was found interceptor will not work for this handler.\n- This may be a valid example, but unfortunately I couldn't get this approach to work.","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":162,"estimatedTokens":953}}286{"id":"stack-73344053","source":"stackoverflow","questionId":73344053,"title":"Getting \"The 'mongodb' provider is not supported with this command\" Error when try to do mongoDB migrate with Prisma","tags":["mongodb","nestjs","prisma"],"text":"Title: Getting \"The 'mongodb' provider is not supported with this command\" Error when try to do mongoDB migrate with Prisma\nTags: mongodb, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm developing some simple Todo App BE using NestJS with Prisma ORM and use MongoDB as the DB. I'm using a FREE and SHARED MongoDB cluster that is hosted in MongoDB Altas cloud. Also I added `0.0.0.0/0` to the network access tab so anyone can connect to the DB.\n\n**schema.prisma** file\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Task {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n name String?\n description String?\n status TaskStatus @default(TODO)\n}\n\nenum TaskStatus {\n TODO\n INPROGRESS\n DONE\n}\n```\n\n**.env** file\n\n```\nDATABASE_URL=\"mongodb+srv://:@todoappdb.jfo3m2c.mongodb.net/?retryWrites=true&w=majority\"\n```\n\nBut when I try to run `npx prisma migrate dev --name init` command it gives following output\n\n```\nD:\\todoapp-backend>npx prisma migrate dev --name init\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\"\n\nError: The \"mongodb\" provider is not supported with this command. For more info see https://www.prisma.io/docs/concepts/database-connectors/mongodb\n 0: migration_core::state::DevDiagnostic\n at migration-engine\\core\\src\\state.rs:250\n```\n\nCan someone point me what is the problem?\n\n========================================\n\nTop Answer:\nAccording to the official documentation (https://www.prisma.io/docs/concepts/components/prisma-migrate):\n\n**Prisma Migrate:**\n\nDoes not apply for MongoDB\nInstead of migrate dev and related commands, use db push for MongoDB.\n\ni.e\n\n```\nnpx prisma db push\n```\n\n========================================\n\nCode:\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ndatasource db {\n  provider = \"mongodb\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Task {\n  id      String   @id @default(auto()) @map(\"_id\") @db.ObjectId\n  name    String?\n  description String?\n  status  TaskStatus @default(TODO)\n}\n\nenum TaskStatus {\n  TODO\n  INPROGRESS\n  DONE\n}\n```\n\n```text\nDATABASE_URL=\"mongodb+srv://<username>:<password>@todoappdb.jfo3m2c.mongodb.net/?retryWrites=true&w=majority\"\n```\n\n```text\nD:\\todoapp-backend>npx prisma migrate dev --name init\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\"\n\nError: The \"mongodb\" provider is not supported with this command. For more info see https://www.prisma.io/docs/concepts/database-connectors/mongodb\n   0: migration_core::state::DevDiagnostic\n             at migration-engine\\core\\src\\state.rs:250\n```\n\n```text\n0.0.0.0/0\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nprisma migrate\n```\n\n```text\nprisma migrate\n```\n\n```bash\nnpx prisma db push\n```\n\n```text\n// Generate prisma/schema.prisma (and .env)\nnpx prisma init\n\n// Generate assets based on schema file\nnpx prisma generate \n\n// Save to the actual database server\nnpx prisma db push\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":152,"estimatedTokens":820}}287{"id":"stack-55339066","source":"stackoverflow","questionId":55339066,"title":"Is it ok to use controller and graphql resolver together in nestJs?","tags":["nestjs"],"text":"Title: Is it ok to use controller and graphql resolver together in nestJs?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nFor my next project I would like to use Graphql inside the FrontEnd. Furthermore this project should also offer a Rest-Api.\nNow I have discovered this extremely great framework \"nestjs\", where it is theoretically possible to combine a Graphql endpoint and a rest endpoint.\nUnfortunately I can't find anything in the documentation if this can lead to problems. Is the following code usable without problems?\n\nArtikel controller:\n\n```\n@Controller('article')\n@Resolver('Article')\nexport class ArticleController {\n constructor(private articleService: ArticleService){}\n\n @Get()\n @Query(returns => CArticle)\n async Article() {\n const dbElement=await this.articleService.getById(\"xy\");\n return dbElement;\n }\n}\n```\n\nArticle module:\n\n```\n@Module({\n controllers:[ArticleController],\n providers:[ArticleService,ArticleController]\n})\nexport class ArticleModule {}\n```\n\n========================================\n\nTop Answer:\nAs I understand nestjs now, there should be no problems, as the decorators do not change the code but only create new code.\n\n========================================\n\nCode:\n```text\n@Controller('article')\n@Resolver('Article')\nexport class ArticleController {\n    constructor(private articleService: ArticleService){}\n\n    @Get()\n    @Query(returns => CArticle)\n    async Article() {\n     const dbElement=await this.articleService.getById(\"xy\");\n     return dbElement;\n    }\n}\n```\n\n```text\n@Module({\n    controllers:[ArticleController],\n    providers:[ArticleService,ArticleController]\n})\nexport class ArticleModule {}\n```\n\n```js\n@Controller('article')\nexport class ArticleController {\n    constructor(private articleService: ArticleService){}\n\n    @Get()\n    async Article() {\n     return this.articleService.getById(\"xy\");\n    }\n}\n```\n\n```js\n@Resolver('Article')\nexport class ArticleResolver {\n    constructor(private articleService: ArticleService){}\n\n    @Query(returns => CArticle)\n    async Article() {\n     return this.articleService.getById(\"xy\");\n    }\n}\n```\n\n```js\n@Module({\n    controllers:[ArticleController, ArticleResolver],\n    providers:[ArticleService]\n})\nexport class ArticleModule {}\n```\n\n========================================\n\nComments:\n- Not going to provide an answer, but currently I am doing the same with nestjs, purely as a test. It seems to work great atm.\n- I am looking to do a similar thing with a current project. I've rolled out the graphql portion but now have requests from team to build some more traditional REST endpoints for some use cases. I'll let you know what i come up with.\n- any updates on your experiences?\n- I have answered the question","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":106,"estimatedTokens":680}}288{"id":"stack-57081132","source":"stackoverflow","questionId":57081132,"title":"Deploy nestjs in firebase cloud functions","tags":["angular","firebase","google-cloud-functions","nestjs"],"text":"Title: Deploy nestjs in firebase cloud functions\nTags: angular, firebase, google-cloud-functions, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to deploy angular app with ssr. I recently discovered that there are schematics of `nestjs` in angular that adds ssr functionality automatically but I didn't find any tutorial or explanation about how to deploy this project so I could get the ssr.\n\nmy steps were:\n\n- create a new angular app with the cli.\n\n- adding nestjs via \"ng add @nestjs/ng-universal\n\n- adding cloud functions and hosting with firebase cli\n\n- build everything\n\n- how do I deploy this so the app will be on the hosting and the `nestjs` server on the cloud function and will be called to prerender.\n\n========================================\n\nCode:\n```text\nnestjs\n```\n\n```text\nnestjs\n```\n\n```text\nimport * as express from 'express';\nimport * as functions from 'firebase-functions';\nimport { AppModule } from './app.module';\nimport { Express } from 'express';\nimport { ExpressAdapter } from '@nestjs/platform-express';\nimport { NestFactory } from '@nestjs/core';\n\nconst server: Express = express();\n\n// Create and init Nest server based on Express instance.\nconst createNestServer = async (expressInstance: Express) => {\n  const app = await NestFactory.create(\n    AppModule,\n    new ExpressAdapter(expressInstance)\n  );\n  app.listen(4048);\n};\n\ncreateNestServer(server);\nexports.angularUniversalFunction = functions.https.onRequest(server); // Export Firebase Cloud Functions to work on\n```\n\n```text\n/* Custom webpack server properties. */\nconst dotenv = require('dotenv-webpack');\nconst nodeExternals = require('webpack-node-externals');\nconst path = require('path');\nconst webpack = require('webpack');\nconst WebpackConfigFactory = require('@nestjs/ng-universal')\n  .WebpackConfigFactory;\n\n// Nest server's bundle for SSR.\nconst webpackConfig = WebpackConfigFactory.create(webpack, {\n  server: './server/main.ts'\n});\n\n// Ignore all \"node_modules\" when making bundle on the server.\nwebpackConfig.externals = nodeExternals({\n  // The whitelisted ones will be included in the bundle.\n  whitelist: [/^ng-circle-progress/, /^ng2-tel-input/]\n});\n\n// Set up output folder.\nwebpackConfig.output = {\n  filename: 'index.js', // Important in terms of Firebase Cloud Functions, because this is the default starting file to execute Cloud Functions.\n  libraryTarget: 'umd', // Important in terms of Firebase Cloud Functions, because otherwise function can't be triggered in functions directory.\n  path: path.join(__dirname, 'functions') // Output path.\n};\n\n// Define plugins.\nwebpackConfig.plugins = [\n  new dotenv(), // Handle environemntal variables on localhost.\n  // Fix WARNING \"Critical dependency: the request of a dependency is an expression\".\n  new webpack.ContextReplacementPlugin(\n    /(.+)?angular(\\\\|\\/)core(.+)?/,\n    path.join(__dirname, 'apps/MYPROJECT/src'), // Location of source files.\n    {} // Map of routes.\n  ),\n  // Fix WARNING \"Critical dependency: the request of a dependency is an expression\".\n  new webpack.ContextReplacementPlugin(\n    /(.+)?express(\\\\|\\/)(.+)?/,\n    path.join(__dirname, 'apps/MYPROJECT/src'), // Location of source files.\n    {}\n  )\n];\n\nwebpackConfig.target = 'node'; // It makes sure not to bundle built-in modules like \"fs\", \"path\", etc.\n\nmodule.exports = webpackConfig; // Export all custom Webpack configs.\n```\n\n```text\nfirebase deploy\n```\n\n```text\nindex.js\n```\n\n========================================\n\nComments:\n- Is this literally all you need to do after running ng add @nestjs/ng-universal and installing firebase tools? Do I still need to mess with webpack.config?\n- @TayambaMwanza you need to use WebpackConfigFactory.create for the SSR part.\n- Ok, there are just some errors, I'm using this config: stackoverflow.com/questions/58447458/&hellip; I've figured out already you need this.externals = [/^firebase/] instead of externals: [/^firebase/ ] but ouput is giving me issues, should I open another question?\n- @TayambaMwanza please see the edit, hope so it helps. This is my all server-related webpack logic I had. I didn't have to deal with `firebase` in `externals` at all to have it working. Maybe opening a new question would help.\n- Thank you, \"apps/MYPROJECT/src\" should I change this to my project name?\n- @TayambaMwanza yes :)\n- Thanks a bunch, this works with tweaks combination of the article I posted above, would it be alright if I send you a word document or google doc, with steps from the article posted above and your material as well, then can update the post with full instructions?\n- @TayambaMwanza could you the instructions please. I tried to deploy angular ssr using nestjs. but I have problem with firebase functions\n- @SulaimanTriarjo Hi, I assumed it worked because it successfully deployed but when I visited the site it didn't work, I was under a deadline so I switched to a non ssr mode. I see that for firebase they are planning a schematic for universal, maybe we should open an issue for a nestjs universal schematic for angularfire too. github.com/angular/angularfire/issues/2304","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":122,"estimatedTokens":1269}}289{"id":"stack-64860307","source":"stackoverflow","questionId":64860307,"title":"Differentiate 2 routes of a controller (NestJS)","tags":["javascript","node.js","nestjs"],"text":"Title: Differentiate 2 routes of a controller (NestJS)\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\n**EDIT: When I move the @Get('/random') above the 2 other routes, it's working... Weird**\n\nI'm doing a NestJS server that just get some routes of the Breaking Bad API and displays the JSON in the routes of the server,\n\nI want to create 3 routes :\n\n- 1 that returns a JSON of all characters of the show (/characters/all)\n\n- 1 that returns a JSON of a single character of the show (/characters/:id)\n\n- 1 that returns a JSON of a random character of the show (/character/random)\n\nThe 2 firsts routes are working, but **I can't get the last one**,\n**I get an error 500 that says Error: Request failed with status code 500 and the url targeted is 'https://www.breakingbadapi.com/api/characters/random', I d on't know why it's 'characters' and not 'character'**\n\nHere is my code :\n\ncharacters.controller.ts\n\n```\nimport { Controller, Get, Post, Body, Param } from '@nestjs/common';\nimport { CharactersService } from './characters.service';\n\n@Controller('characters')\nexport class CharactersController {\n constructor(private readonly charactersService: CharactersService) {}\n\n @Get('/all')\n getAll() {\n return this.charactersService.getAll();\n }\n\n @Get(':id')\n getOne(@Param('id') id: string) {\n return this.charactersService.getOne(id);\n }\n\n @Get('/random')\n getRandom() {\n return this.charactersService.getRandom();\n }\n}\n```\n\ncharacters.service.ts\n\n```\nimport axios from \"axios\";\n\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class CharactersService {\n getAll() {\n return axios.get(`${process.env.ENDPOINT_BASE_URL}/characters`, {\n params: {\n limit: null,\n offset: null,\n name: \"\"\n }\n }).then(function (response) {\n return response.data;\n })\n .catch(function (error) {\n console.log(error);\n });\n }\n\n getOne(id: string) {\n return axios.get(`${process.env.ENDPOINT_BASE_URL}/characters/${id}`).then(function (response) {\n return response.data;\n })\n .catch(function (error) {\n console.log(error);\n });\n }\n\n getRandom() {\n return axios.get(`${process.env.ENDPOINT_BASE_URL}/character/random`).then(function (response) {\n return response.data;\n })\n .catch(function (error) {\n console.log(error);\n });\n }\n}\n```\n\n.env\n\n```\nENDPOINT_BASE_URL=https://www.breakingbadapi.com/api\n```\n\n========================================\n\nTop Answer:\nIf you want access `/character/random` you need create another controller which serves `character` route. Example\n\n```\n@Controller('characters')\nexport class CharactersController {\n constructor(private readonly charactersService: CharactersService) {}\n\n @Get('/all')\n getAll() {\n return this.charactersService.getAll();\n }\n\n @Get(':id')\n getOne(@Param('id') id: string) {\n return this.charactersService.getOne(id);\n }\n}\n\n@Controller('character')\nexport class CharacterController {\n constructor(private readonly charactersService: CharactersService) {}\n\n @Get('/random')\n getRandom() {\n return this.charactersService.getRandom();\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Controller, Get, Post, Body, Param } from '@nestjs/common';\nimport { CharactersService } from './characters.service';\n\n@Controller('characters')\nexport class CharactersController {\n    constructor(private readonly charactersService: CharactersService) {}\n\n    @Get('/all')\n    getAll() {\n        return this.charactersService.getAll();\n    }\n\n    @Get(':id')\n    getOne(@Param('id') id: string) {\n        return this.charactersService.getOne(id);\n    }\n\n    @Get('/random')\n    getRandom() {\n        return this.charactersService.getRandom();\n    }\n}\n```\n\n```text\nimport axios from \"axios\";\n\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class CharactersService {\n    getAll() {\n      return axios.get(`${process.env.ENDPOINT_BASE_URL}/characters`, {\n        params: {\n          limit: null,\n          offset: null,\n          name: \"\"\n        }\n      }).then(function (response) {\n          return response.data;\n        })\n        .catch(function (error) {\n          console.log(error);\n        });\n    }\n\n    getOne(id: string) {\n      return axios.get(`${process.env.ENDPOINT_BASE_URL}/characters/${id}`).then(function (response) {\n        return response.data;\n      })\n      .catch(function (error) {\n        console.log(error);\n      });\n    }\n\n    getRandom() {\n      return axios.get(`${process.env.ENDPOINT_BASE_URL}/character/random`).then(function (response) {\n        return response.data;\n      })\n      .catch(function (error) {\n        console.log(error);\n      });\n    }\n}\n```\n\n```text\nENDPOINT_BASE_URL=https://www.breakingbadapi.com/api\n```\n\n```text\n@Get(':id')\n```\n\n```text\n@Get('/random')\n```\n\n```text\n/random\n```\n\n```text\n\"random\"\n```\n\n```text\nid\n```\n\n```text\n':id'\n```\n\n```text\nrandom\n```\n\n```text\nid\n```\n\n```text\n@Get('/random')\n```\n\n```text\n@Get(':id')\n```\n\n```js\n@Controller('characters')\nexport class CharactersController {\n    constructor(private readonly charactersService: CharactersService) {}\n\n    @Get('/all')\n    getAll() {\n        return this.charactersService.getAll();\n    }\n\n    @Get(':id')\n    getOne(@Param('id') id: string) {\n        return this.charactersService.getOne(id);\n    }\n}\n\n@Controller('character')\nexport class CharacterController {\n    constructor(private readonly charactersService: CharactersService) {}\n\n    @Get('/random')\n    getRandom() {\n        return this.charactersService.getRandom();\n    }\n}\n```\n\n```text\n/character/random\n```\n\n```text\ncharacter\n```\n\n```text\nexport class COntentController {\n    @Get(':id')\n    async findOneById(@Param('id') id: string): Promise<any> {\n        // Handle request for specific ID\n    }\n\n    @Get(':url')\n    async handleUrl(@Param('url') url: string): Promise<any> {\n        // Handle more generic URL requests\n    }\n}\n```\n\n```text\n@Get('*')\nasync handleUrl(@Param('url') url: string): Promise<any> {\n    // Handle more generic URL requests\n}\n```\n\n========================================\n\nComments:\n- Hey @Jay, I have two get methods `@Get('&#47;get:networkId&#47;:namespace') async getCurrentBalance(){}` and `@Get(':networkId&#47;:namespace') async getAllDeployments(){}` I am not able to call the endpoint with the name \"get\" but the endpoints with only params is getting called! Is that any reason why it is not getting called?\n- Is it `get:networkId&#47;:namespace` or `get&#47;:networkId&#47;:namespace`? Important diference\n- It is `get&#47;:networkId&#47;:namespace`\n- Like my answer mentions, check the order of the routes, It is very important here.\n- \"order of routes defined matters... in a Nest server\" - you just saved me another 2 hours on similar problem. thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":309,"estimatedTokens":1669}}290{"id":"stack-58582886","source":"stackoverflow","questionId":58582886,"title":"What is the difference between @UseGuards and Middleware in nestJS","tags":["typescript","nestjs"],"text":"Title: What is the difference between @UseGuards and Middleware in nestJS\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nRecently I switched to nestJS for its decoration. But I found there are two things `Middleware` and `@UseGuards`. I worked with Middleware when I used expressjs only.\nNow my concern is what is the actual difference between these two. In my case these look like the same.\n\n========================================\n\nCode:\n```text\nMiddleware\n```\n\n```text\n@UseGuards\n```\n\n```text\nPipes\n```\n\n```text\nFilters\n```\n\n```text\nGuards\n```\n\n```text\nInterceptors\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":34,"estimatedTokens":147}}291{"id":"stack-62641382","source":"stackoverflow","questionId":62641382,"title":"Cannot find module 'passport' or its corresponding type declarations","tags":["typescript","jwt","nestjs","nestjs-passport","nestjs-jwt"],"text":"Title: Cannot find module 'passport' or its corresponding type declarations\nTags: typescript, jwt, nestjs, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI am using @nestjs/passport. After running `npm run start:dev` I got an error, but the editor doesn't show an error\n\n```\nnode_modules/@nestjs/passport/dist/passport/passport.serializer.d.ts:1:27 - error TS2307: Cannot find module 'passport' or its corresponding type declarations.\n\n1 import * as passport from 'passport';\n```\n\nInput Code:\n\n```\nimport { PassportModule } from '@nestjs/passport';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { UserRepository } from './user.repository';\nimport { JwtModule } from '@nestjs/jwt';\n\n@Module({\n imports:[\n PassportModule.register({defaultStrategy:'jwt'}),\n JwtModule.register({\n secret: 'topSecret51',\n signOptions:{\n expiresIn:3600,\n },\n }),\n TypeOrmModule.forFeature([UserRepository]),\n ],\n controllers: [AuthController],\n providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\nAny idea what the problem could be?\n\n========================================\n\nTop Answer:\nI had the same problem. But I did a rebuild and everything worked.\nRemoved the `dist` folder and then start again\n\n```\nrm -r dist\nnpm run start:dev\n```\n\n========================================\n\nCode:\n```text\nnode_modules/@nestjs/passport/dist/passport/passport.serializer.d.ts:1:27 - error TS2307: Cannot find module 'passport' or its corresponding type declarations.\n\n1 import * as passport from 'passport';\n```\n\n```typescript\nimport { PassportModule } from '@nestjs/passport';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { UserRepository } from './user.repository';\nimport { JwtModule } from '@nestjs/jwt';\n\n\n@Module({\n  imports:[\n    PassportModule.register({defaultStrategy:'jwt'}),\n    JwtModule.register({\n      secret: 'topSecret51',\n      signOptions:{\n        expiresIn:3600,\n      },\n    }),\n    TypeOrmModule.forFeature([UserRepository]),\n  ],\n  controllers: [AuthController],\n  providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nnpm i --save @nestjs/passport passport\n```\n\n```text\n$ npm i --save @nestjs/passport passport\n```\n\n```text\nrm -r dist\nnpm run start:dev\n```\n\n```text\ndist\n```\n\n```text\nnpm i @types/passport --save\n```\n\n========================================\n\nComments:\n- Question NestJS jwt-passport Authentication looks related.\n- What does `--save` do? Is there a reason that `npm install` doesn't work for this package?\n- This works for me, make sure you also installed the next dependences: `@nestjs&#47;passport` `passport` `passport-jwt`","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":121,"estimatedTokens":727}}292{"id":"stack-57116789","source":"stackoverflow","questionId":57116789,"title":"Is it possible to override global scoped guard with controller/method scoped one","tags":["nestjs"],"text":"Title: Is it possible to override global scoped guard with controller/method scoped one\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm writing webAPI using NestJS framework. I was not able to override global scoped guard with the one placed on method or controller level. All of my endpoints will use JWT verification guard except one used for logging into the system. Is it possible to create one guard on root level and only override this global guard with `@UseGuard()` decorator on single method level?\n\nI tried to use guard before `listen` function call and also use `APP_GUARD`provider, but in both cases I'm not able to override this behavior.\n\nCode example:\nhttps://codesandbox.io/embed/nest-yymkf\n\n========================================\n\nTop Answer:\nJust to add my 2 cents.\n\nInstead of defining 2 guards (`reject` and `accept`) as the OP have done, I have defined a custom decorator:\n\n```\nimport { SetMetadata } from '@nestjs/common'\n\nexport const NoAuth = () => SetMetadata('no-auth', true)\n```\n\nThe reject guard (`AuthGuard`) uses `Reflector` to be able to access the decorator's metadata and decides to activate or not based on it.\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport { Observable } from 'rxjs'\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n constructor(private readonly reflector: Reflector) {}\n\n canActivate(\n context: ExecutionContext,\n ): boolean | Promise | Observable {\n\n const noAuth = this.reflector.get('no-auth', context.getHandler())\n\n if(noAuth) return true\n\n // else your logic here\n }\n}\n```\n\nI then bind the `reject` guard globally in some module:\n\n```\n@Module({\n providers: [{\n provide: APP_GUARD,\n useClass: AuthGuard\n }]\n})\n```\n\nand proceed to use the decorator where needed:\n\n```\n@NoAuth()\n@Get() // anyone can access this\ngetHello(): string {\n return 'Hello Stranger!'\n}\n\n@Get('secret') // protected by the global guard\ngetSecret(): string {\n return 'ssshhh!' \n}\n```\n\n========================================\n\nCode:\n```text\n@UseGuard()\n```\n\n```text\nlisten\n```\n\n```text\nAPP_GUARD\n```\n\n```js\nimport { SetMetadata } from '@nestjs/common'\n\nexport const NoAuth = () => SetMetadata('no-auth', true)\n```\n\n```js\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport { Observable } from 'rxjs'\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector) {}\n\n  canActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n\n    const noAuth = this.reflector.get<boolean>('no-auth', context.getHandler())\n\n    if(noAuth) return true\n\n    // else your logic here\n  }\n}\n```\n\n```js\n@Module({\n  providers: [{\n    provide: APP_GUARD,\n    useClass: AuthGuard\n  }]\n})\n```\n\n```js\n@NoAuth()\n@Get() // anyone can access this\ngetHello(): string {\n  return 'Hello Stranger!'\n}\n\n@Get('secret') // protected by the global guard\ngetSecret(): string {\n  return 'ssshhh!' \n}\n```\n\n```text\nreject\n```\n\n```text\naccept\n```\n\n```text\nAuthGuard\n```\n\n```text\nReflector\n```\n\n```text\nreject\n```\n\n========================================\n\nComments:\n- Guards applied on controller will only run after the global guard. So to \"override\" the global guard we have to add this custom metadata using a decorator, and in the global guard logic bypass the rest of the check by first checking for the metadata.","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":164,"estimatedTokens":868}}293{"id":"stack-66437004","source":"stackoverflow","questionId":66437004,"title":"Is there a way to hide all the end-point in the controller.ts using a single decorator?","tags":["nestjs","nestjs-swagger"],"text":"Title: Is there a way to hide all the end-point in the controller.ts using a single decorator?\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nCurrently, I am using **@ApiExcludeEndpoint()** ### on top of all methods to hide the end-point in the swagger-ui, like this:\n\n\r\n\r\n\n```\nimport { Controller, Get, Query, Param } from '@nestjs/common';\nimport { ResourceService } from './resource.service';\nimport { Auth } from 'src/auth/auth.decorator';\nimport {\n ApiTags,\n ApiSecurity,\n ApiOkResponse,\n ApiForbiddenResponse,\n ApiCreatedResponse,\n ApiExcludeEndpoint\n} from '@nestjs/swagger';\n\n@Controller()\n@ApiTags('Resources')\n@ApiSecurity('apiKey')\nexport class ResourceController {\n constructor(private readonly resourceService: ResourceService) {}\n\n @Get('get_url')\n @ApiExcludeEndpoint()\n @Get()\n @ApiOkResponse({\n description: 'Resources list has succesfully been returned',\n })\n @ApiForbiddenResponse({ description: 'You are not allowed' })\n @Auth(...common_privileges)\n findAll(@Query() query: any): any {\n ......\n }\n\n \n @Get('get_url/:id')\n @ApiExcludeEndpoint()\n @ApiOkResponse({ description: 'Resource has succesfully been returned' })\n @ApiForbiddenResponse({ description: 'You are not allowed' })\n @Auth(...common_privileges)\n findById(@Param('id') id: string, @Query() query: any): any {\n ......\n }\n\n}\n```\n\n\r\n\r\n\r\n\n**I Need to know is there a way to hide all the end-point in the controller using a single decorator**, I checked some documents it says to use @ApiIgnore() and @Hidden() but I can't find those in nestjs-swagger. Please comment on this\n\n========================================\n\nTop Answer:\nTo hide all the end-point in the controller.ts, you must use ApiExcludeController instead of ApiExcludeEndpoint as in the example.\n\nhttps://docs.nestjs.com/openapi/decorators\n\n\r\n\r\n\n```\nimport { Controller, Get, Query, Param } from '@nestjs/common';\nimport { ResourceService } from './resource.service';\nimport { Auth } from 'src/auth/auth.decorator';\nimport {\n ApiTags,\n ApiSecurity,\n ApiOkResponse,\n ApiForbiddenResponse,\n ApiCreatedResponse,\n ApiExcludeController\n // ApiExcludeEndpoint\n} from '@nestjs/swagger';\n\n@Controller()\n@ApiTags('Resources')\n@ApiSecurity('apiKey')\n@ApiExcludeController()\nexport class ResourceController {\n constructor(private readonly resourceService: ResourceService) {}\n\n @Get('get_url')\n // @ApiExcludeEndpoint()\n @Get()\n @ApiOkResponse({\n description: 'Resources list has succesfully been returned',\n })\n @ApiForbiddenResponse({ description: 'You are not allowed' })\n @Auth(...common_privileges)\n findAll(@Query() query: any): any {\n ......\n }\n\n \n @Get('get_url/:id')\n // @ApiExcludeEndpoint()\n @ApiOkResponse({ description: 'Resource has succesfully been returned' })\n @ApiForbiddenResponse({ description: 'You are not allowed' })\n @Auth(...common_privileges)\n findById(@Param('id') id: string, @Query() query: any): any {\n ......\n }\n\n}\n```\n\n========================================\n\nCode:\n```js\nimport { Controller, Get, Query, Param } from '@nestjs/common';\nimport { ResourceService } from './resource.service';\nimport { Auth } from 'src/auth/auth.decorator';\nimport {\n  ApiTags,\n  ApiSecurity,\n  ApiOkResponse,\n  ApiForbiddenResponse,\n  ApiCreatedResponse,\n  ApiExcludeEndpoint\n} from '@nestjs/swagger';\n\n\n@Controller()\n@ApiTags('Resources')\n@ApiSecurity('apiKey')\nexport class ResourceController {\n  constructor(private readonly resourceService: ResourceService) {}\n\n  @Get('get_url')\n  @ApiExcludeEndpoint()\n  @Get()\n  @ApiOkResponse({\n    description: 'Resources list has succesfully been returned',\n  })\n  @ApiForbiddenResponse({ description: 'You are not allowed' })\n  @Auth(...common_privileges)\n  findAll(@Query() query: any): any {\n    ......\n  }\n\n  \n  @Get('get_url/:id')\n  @ApiExcludeEndpoint()\n  @ApiOkResponse({ description: 'Resource has succesfully been returned' })\n  @ApiForbiddenResponse({ description: 'You are not allowed' })\n  @Auth(...common_privileges)\n  findById(@Param('id') id: string, @Query() query: any): any {\n    ......\n  }\n\n}\n```\n\n```ts\nconst options = new DocumentBuilder()\n    .setTitle('Cats example')\n    .setDescription('The cats API description')\n    .setVersion('1.0')\n    .addTag('cats')\n    .build();\n\n  const catDocument = SwaggerModule.createDocument(app, options, {\n    include: [LionsModule, TigersModule], // don't include, say, BearsModule\n  });\n  SwaggerModule.setup('api/cats', app, catDocument);\n```\n\n```text\ninclude:[]\n```\n\n```text\nLionsModule\n```\n\n```text\nTigersModule\n```\n\n```text\nBearsModule\n```\n\n```js\nimport { Controller, Get, Query, Param } from '@nestjs/common';\nimport { ResourceService } from './resource.service';\nimport { Auth } from 'src/auth/auth.decorator';\nimport {\n  ApiTags,\n  ApiSecurity,\n  ApiOkResponse,\n  ApiForbiddenResponse,\n  ApiCreatedResponse,\n  ApiExcludeController\n  // ApiExcludeEndpoint\n} from '@nestjs/swagger';\n\n\n@Controller()\n@ApiTags('Resources')\n@ApiSecurity('apiKey')\n@ApiExcludeController()\nexport class ResourceController {\n  constructor(private readonly resourceService: ResourceService) {}\n\n  @Get('get_url')\n // @ApiExcludeEndpoint()\n  @Get()\n  @ApiOkResponse({\n    description: 'Resources list has succesfully been returned',\n  })\n  @ApiForbiddenResponse({ description: 'You are not allowed' })\n  @Auth(...common_privileges)\n  findAll(@Query() query: any): any {\n    ......\n  }\n\n  \n  @Get('get_url/:id')\n // @ApiExcludeEndpoint()\n  @ApiOkResponse({ description: 'Resource has succesfully been returned' })\n  @ApiForbiddenResponse({ description: 'You are not allowed' })\n  @Auth(...common_privileges)\n  findById(@Param('id') id: string, @Query() query: any): any {\n    ......\n  }\n\n}\n```\n\n```js\n@ApiExcludeController(true)\n@Controller('cats')\nexport class CatsController {}\n```\n\n```text\n@ApiExcludeController(true)\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":250,"estimatedTokens":1443}}294{"id":"stack-52753376","source":"stackoverflow","questionId":52753376,"title":"How to use parameters in routes with nestjs?","tags":["routes","nestjs"],"text":"Title: How to use parameters in routes with nestjs?\nTags: routes, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to use 3 routes: โ€˜projectโ€™; โ€˜project/1โ€™; โ€˜project/authorsโ€™. \nBut when I call โ€˜project/authorsโ€™, triggered โ€˜project/1โ€™ and I get an error. How to awoid it?\n\n```\n@Controller('project')\n export class ProjectController {\n\n @Get()\n async getProjects(@Res() res): Promise {\n return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));\n }\n @Get(':id')\n async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise {\n return await this.projectService.getProjects(id).then(project => res.json(project[0]));\n }\n\n @Get('/authors')\n async getAuthors(@Res() res): Promise {\n return await this.projectService.getAuthors().then(authors => res.json(authors));\n }\n\n}\n```\n\n========================================\n\nTop Answer:\nIn fact in all express app the order of the definitions of all the routes is matter.\n\nIn a simple way, it is a first come first serve, the first route matched is the one used to respond your request.\n\nSo as much as possible put the static parameters first then the dynamic one.\n\nThe only thing that you have to keep in mind is `first come first serve` :)\n\n========================================\n\nCode:\n```text\n@Controller('project')\n    export class ProjectController {\n\n        @Get()\n        async getProjects(@Res() res): Promise<ProjectDto[]> {\n            return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));\n        }\n        @Get(':id')\n        async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise<ProjectDto> {\n            return await this.projectService.getProjects(id).then(project => res.json(project[0]));\n        }\n\n        @Get('/authors')\n        async getAuthors(@Res() res): Promise<AuthorDto[]> {\n            return await this.projectService.getAuthors().then(authors => res.json(authors));\n        }\n\n}\n```\n\n```js\n@Controller('project')\nexport class ProjectController {\n\n    @Get()\n    async getProjects(@Res() res): Promise<ProjectDto[]> {\n        return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));\n    }\n    @Get('/project/:id')\n    async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise<ProjectDto> {\n        return await this.projectService.getProjects(id).then(project => res.json(project[0]));\n    }\n\n    @Get('/authors')\n    async getAuthors(@Res() res): Promise<AuthorDto[]> {\n        return await this.projectService.getAuthors().then(authors => res.json(authors));\n    }\n\n}\n```\n\n```text\n@Get('/nameOfItem/:id')\n```\n\n```text\nfirst come first serve\n```\n\n========================================\n\nComments:\n- I found another answer github.com/nestjs/nest/issues\n- @alexDuck Thanks for the link, it actually explains better than the accepted solution.\n- Little improvement on getProject method decorator: do not duplicate 'project' path, instead use @Get('/:id')","metadata":{"transformedAt":"2026-08-18T18:33:02.429Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":99,"estimatedTokens":745}}295{"id":"stack-74542474","source":"stackoverflow","questionId":74542474,"title":"How to create custom (separate file) repository in NestJS 9 with TypeORM 0.3.x","tags":["nestjs","typeorm","repository-pattern"],"text":"Title: How to create custom (separate file) repository in NestJS 9 with TypeORM 0.3.x\nTags: nestjs, typeorm, repository-pattern\nSource: Stack Overflow\n\nQuestion:\n*This is not a duplicate Q. Please don't mark this as that.*\n\nFollowing is not I want\n\n```\nimport { EntityRepository, Repository } from \"typeorm\";\nimport { Test } from \"./test.model\";\nimport { Injectable } from \"@nestjs/common\";\n\n@EntityRepository(Test)\nexport class TestRepository extends Repository {}\n```\n\nthe `@EntityRepository` decorator is now deprecated.\n\nI also don't want to make a fake repository like in here:\nhttps://stackoverflow.com/a/73352265/5420070\n\nDon't want this either as I've to extract `manager` from `dataSource`, I don't want this because I think this is not the best way.\n\n```\nexport const UserRepository = dataSource.getRepository(User).extend({\n // ^^^^^^^^^^ from where this came from\n findByName(firstName: string, lastName: string) {\n return this.createQueryBuilder(\"user\")\n .where(\"user.firstName = :firstName\", { firstName })\n .andWhere(\"user.lastName = :lastName\", { lastName })\n .getMany()\n },\n })\n```\n\nFound above in: https://orkhan.gitbook.io/typeorm/docs/custom-repository#how-to-create-custom-repository\n\nI don't think this is in NestJS context.\n\nWhat I want\nWant to know right way to make custom repository in latest version of NestJS (v9) & TypeORM (v0.3). In `@EntityRepository` deprecation note, they said that need to extend the repo to create custom repo like `someRepo.extend({})`. I want to know how to do it in NestJS way\n\n========================================\n\nTop Answer:\n```\nimport { Column, Entity, JoinColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { CustomBaseEntity } from \"../core/custom-base.entity\";//custom-made\n@Entity({name: 'rcon_log', schema: 'dbo'})\nexport class LogEntity extends CustomBaseEntity{\n------------your code-----------\n}\n```\n\n========================================\n\nCode:\n```js\nimport { EntityRepository, Repository } from \"typeorm\";\nimport { Test } from \"./test.model\";\nimport { Injectable } from \"@nestjs/common\";\n\n@EntityRepository(Test)\nexport class TestRepository extends Repository<Test> {}\n```\n\n```js\nexport const UserRepository = dataSource.getRepository(User).extend({\n        //                        ^^^^^^^^^^ from where this came from\n        findByName(firstName: string, lastName: string) {\n            return this.createQueryBuilder(\"user\")\n                .where(\"user.firstName = :firstName\", { firstName })\n                .andWhere(\"user.lastName = :lastName\", { lastName })\n                .getMany()\n        },\n    })\n```\n\n```text\n@EntityRepository\n```\n\n```text\nmanager\n```\n\n```text\ndataSource\n```\n\n```text\n@EntityRepository\n```\n\n```text\nsomeRepo.extend({})\n```\n\n```js\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class UserEntity {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstName: string;\n\n  @Column()\n  lastName: string;\n\n  @Column({ default: true })\n  isActive: boolean;\n}\n```\n\n```js\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { UserEntity } from './user.entity';\n\nexport class UserRepository extends Repository<UserEntity> {\n    constructor(\n        @InjectRepository(UserEntity)\n        private userRepository: Repository<UserEntity>\n    ) {\n        super(userRepository.target, userRepository.manager, userRepository.queryRunner);\n    }\n\n    // sample method for demo purposes\n    async findByEmail(email: string): Promise<UserEntity> {\n        return await this.userRepository.findOneBy({ email }); // could also be this.findOneBy({ email });, but depending on your IDE/TS settings, could warn that userRepository is not used though. Up to you to use either of the 2 methods\n    }\n    \n    // your other custom methods in your repo...\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UserRepository } from './user.repository';\nimport { UserEntity } from './user.entity';\n\n@Injectable()\nexport class UserService {\n  constructor(\n    private readonly userRepository: UserRepository, // import as usual\n  ) {}\n\n  findAll(): Promise<UserEntity[]> {\n    return this.userRepository.find();\n  }\n  \n  // call your repo method\n  findOneByEmail(email: string): Promise<UserEntity> {\n    return this.userRepository.findByEmail({ email });\n  }\n\n  findOne(id: number): Promise<UserEntity> {\n    return this.userRepository.findOneBy({ id });\n  }\n\n  async remove(id: string): Promise<void> {\n    await this.userRepository.delete(id);\n  }\n  \n  // your other custom methods in your service...\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserService } from './user.service';\nimport { UserController } from './user.controller';\nimport { UserEntity } from './user.entity';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([UserEntity])], // here we provide the TypeOrm support as usual, specifically for our UserEntity in this case\n  providers: [UserService, UserRepository], // here we provide our custom repo\n  controllers: [UserController],\n  exports: [UserService, UserRepository] // add this only if you use service and/or custom repo within another module/service\n})\nexport class UserModule {}\n```\n\n```text\nUserEntity\n```\n\n```text\nUserRepository\n```\n\n```text\nUserService\n```\n\n```text\nUserRepository\n```\n\n```text\nUserService\n```\n\n```text\nUserModule\n```\n\n```text\nUserRepository\n```\n\n```text\nUserEntity\n```\n\n```text\nUserModule\n```\n\n```text\nUserModule\n```\n\n```text\nAppModule\n```\n\n```text\nUserRepository\n```\n\n```text\nUserService\n```\n\n```text\nmanager\n```\n\n```text\nqueryRunnner\n```\n\n```text\nUserRepository\n```\n\n```text\nUserModule\n```\n\n```text\nUserRepository\n```\n\n```text\nimport { Column, Entity, JoinColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { CustomBaseEntity } from \"../core/custom-base.entity\";//custom-made\n@Entity({name: 'rcon_log', schema: 'dbo'})\nexport class LogEntity extends CustomBaseEntity{\n------------your code-----------\n}\n```\n\n========================================\n\nComments:\n- I tried this solution and I get the error Error: Nest can't resolve dependencies of the CustomerRepository (?). Please make sure that the argument CustomerEntityRepository at index [0] is available in the CustomerModule context. Potential solutions: - Is CustomerModule a valid NestJS module? - If CustomerEntityRepository is a provider, is it part of the current CustomerModule? - If CustomerEntityRepository is exported from a separate @Module, is that module imported within CustomerModule? @Module({ imports: [ /* the Module containing CustomerEntityRepository */ ] })\n- Please provide more context to the comments, maybe a link to some repo in order to better understand your code :) Otherwise your error tells it all, you're missing something, somewhere =)\n- Pretty good solution for global repositories, but you cannot use this custom repository in a transaction. It would be nice to have an alternative for the old `entityManager.getCustomRepository(Foo)`.\n- Make sure *not* to use `@InjectRepository(UserEntity)` when you are creating the Repository class yourself.","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":278,"estimatedTokens":1798}}296{"id":"stack-68394971","source":"stackoverflow","questionId":68394971,"title":"How to mock NestJS built-in Logger in Jest","tags":["nestjs","ts-jest"],"text":"Title: How to mock NestJS built-in Logger in Jest\nTags: nestjs, ts-jest\nSource: Stack Overflow\n\nQuestion:\nI have a controller that uses NestJS built-in Logger via dependency injection in constructor of the controller:\n\n```\nconstructor(private readonly logger: Logger)\n```\n\nI want to be able to mock it in my Jest tests to see which methods and with what arguments are being called during logging. I tried this syntax:\n\n```\nproviders[{\n provide: Logger,\n useValue: {\n log: jest.fn(),\n }\n}]\n```\n\nIn that case this line:\n\n```\nexpect(Logger).toHaveBeenCalledTimes(1);\n```\n\nReturns:\n*Matcher error: received value must be a mock or spy function*\n\nAny help will be highly appreciated!\n\n========================================\n\nTop Answer:\nI use this for private loggers in unit tests:\n\n```\nimport { Logger } from '@nestjs/common';\n\nconst loggerSpyLog = jest.spyOn(Logger.prototype, 'log');\nconst loggerSpyWarn = jest.spyOn(Logger.prototype, 'warn');\n\nexpect(loggerSpyLog).toHaveBeenCalledTimes(3);\nexpect(loggerSpyWarn).not.toHaveBeenCalled();\n```\n\n========================================\n\nCode:\n```text\nconstructor(private readonly logger: Logger)\n```\n\n```text\nproviders[{\n    provide: Logger,\n    useValue: {\n      log: jest.fn(),\n    }\n}]\n```\n\n```text\nexpect(Logger).toHaveBeenCalledTimes(1);\n```\n\n```text\nimport { Test } from '@nestjs/testing';\nlet logger: Logger;\n\nbeforeEach(async () => {\n  const moduleRef = await Test.createTestingModule({\n    providers: [  \n      {\n        provide: Logger,\n        useValue: {\n          log: jest.fn(),\n        },\n      },\n    ],\n  }).compile();\n  logger = moduleRef.get<Logger>(Logger);\n});\n```\n\n```text\nexpect(logger.log).toHaveBeenCalledTimes(1);\nexpect(logger.log).toHaveBeenCalledWith('Your log message here')\n```\n\n```text\nmoduleFixture.get(Logger)\n```\n\n```text\nexpect(logger.log).toHaveBeenCalledTimes(1)\n```\n\n```text\nLogger\n```\n\n```js\njest.mock('@nestjs/common', () => ({\n  ...jest.requireActual('@nestjs/common'),\n  Logger: jest.fn(),\n}))\n```\n\n```js\nimport { ConsoleLogger } from '@nestjs/common'\n\nexport class CustomLogger extends ConsoleLogger {}\n```\n\n```js\nimport { SomeConsumer } from './some-consumer'\nimport { CustomLogger } from './custom.logger'\nimport { Test } from '@nestjs/testing'\nimport { mockDeep } from 'jest-mock-extended'\n\ndescribe('SomeConsumer', () => {\n  let someConsumer: SomeConsumer\n  const logger = mockDeep<CustomLogger>()\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      providers: [\n        SomeConsumer,\n        {\n          provide: CustomLogger,\n          useValue: logger,\n        },\n      ],\n    }).compile()\n\n    someConsumer = module.get(SomeConsumer)\n  })\n\n  it('should do something', () => {\n    const result = someConsumer.doSomething()\n\n    expect(result).toEqual('something returned')\n  })\n\n  it('should log something', () => {\n    someConsumer.doSomething()\n\n    expect(logger.log).toHaveBeenCalledWith('something')\n  })\n})\n```\n\n```js\nimport { Injectable } from '@nestjs/common'\nimport { CustomLogger } from './custom-logger'\n\n@Injectable()\nexport class SomeConsumer {\n  constructor(private readonly logger: CustomLogger) {}\n\n  public doSomething(): string {\n    this.logger.log('something')\n\n    return 'something returned'\n  }\n}\n```\n\n```js\nimport { Injectable, Logger } from '@nestjs/common'\n\n@Injectable()\nexport class SomeConsumerImported {\n  private logger = new Logger(SomeConsumerImported.name)\n\n  public doSomething(): string {\n    this.logger.log('something logged')\n\n    return 'something returned'\n  }\n}\n```\n\n```js\nimport { SomeConsumerImported } from './some-consumer-imported'\nimport { Logger } from '@nestjs/common'\nimport { Test } from '@nestjs/testing'\nimport { mockDeep } from 'jest-mock-extended'\n\ndescribe('SomeConsumerImported', () => {\n  let someConsumerImported: SomeConsumerImported\n  const logger = mockDeep<Logger>()\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      providers: [SomeConsumerImported],\n    }).compile()\n\n    module.useLogger(logger)\n\n    someConsumerImported = module.get(SomeConsumerImported)\n  })\n\n  it('should do something', () => {\n    const result = someConsumerImported.doSomething()\n\n    expect(result).toEqual('something returned')\n  })\n\n  it('should log something', () => {\n    someConsumerImported.doSomething()\n\n    expect(logger.log).toHaveBeenCalledWith('something logged', SomeConsumerImported.name)\n  })\n})\n```\n\n```text\njest.mock\n```\n\n```text\njest.mock\n```\n\n```text\nLogger\n```\n\n```text\n@nest/common\n```\n\n```text\ncustom.logger.ts\n```\n\n```text\nsome-consumer.spec.ts\n```\n\n```text\njest-mock-extended\n```\n\n```text\n@Jay McDoniel\n```\n\n```text\nsome-consumer.ts\n```\n\n```text\nLogger\n```\n\n```text\n@nestjs/common\n```\n\n```text\nsome-consumer-imported.ts\n```\n\n```text\nsome-consumer-imported.spec.ts\n```\n\n```text\njest.spyOn(Logger, 'log');\n\n expect(Logger.Log).toHaveBeenCalledTimes('error', 'SmsService.sendSMS');\n```\n\n```text\njest.SpyOn\n```\n\n```text\nLogger\n```\n\n```ts\nimport { Injectable, Logger, LoggerService } from '@nestjs/common';\n\n@Injectable()\nexport class AppLogger implements LoggerService {\n  private readonly options = { timestamp: true };\n  private context?: string;\n\n  constructor(private readonly logger: Logger) {}\n\n  setContext(contextName: string): void {\n    this.context = contextName;\n  }\n\n  error(message: unknown): void {\n    this.logger.error(message, this.context, this.options);\n  }\n\n  warn(message: unknown): void {\n    this.logger.warn(message, this.context, this.options);\n  }\n\n  log(message: unknown): void {\n    this.logger.log(message, this.context, this.options);\n  }\n\n  debug(message: unknown): void {\n    this.logger.debug(message, this.context, this.options);\n  }\n\n  verbose(message: unknown): void {\n    this.logger.verbose(message, this.context, this.options);\n  }\n}\n```\n\n```ts\n@Injectable()\nexport class TestService {\n  constructor(\n    private readonly logger: AppLogger,\n  ) {\n    logger.setContext(TestService.name);\n  }\n  \n  doStuff(): void {\n    this.logger.log('hello!');\n  }\n}\n```\n\n```ts\nexport const mockAppLogger: Record<keyof AppLogger, typeof jest.fn> = {\n  setContext: jest.fn(),\n  error: jest.fn(),\n  log: jest.fn(),\n  warn: jest.fn(),\n  debug: jest.fn(),\n  verbose: jest.fn(),\n};\n```\n\n```ts\ndescribe('TestService', () => {\n  let service: TestService;\n  let logger: AppLogger;\n  let repo: Repository<TestEntity>;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        TestService,\n        { provide: AppLogger, useValue: mockAppLogger }, //<-- provide the mock logger here\n      ],\n    }).compile();\n\n    service = module.get(TestService);\n    logger = module.get<AppLogger>(AppLogger);\n  });\n  \n  it('should log a value', () => {\n    jest.spyOn(logger, 'log');\n    service.doStuff();\n    \n    expect(logger.log).toHaveBeenCalledWith('hello!');\n  });\n});\n```\n\n```text\nsrc/app-logger.ts\n```\n\n```text\nsetContext()\n```\n\n```text\nmockAppLogger\n```\n\n```text\nsrc/test-helpers.ts\n```\n\n```text\nimport { Logger } from '@nestjs/common';\n\nconst loggerSpyLog = jest.spyOn(Logger.prototype, 'log');\nconst loggerSpyWarn = jest.spyOn(Logger.prototype, 'warn');\n\nexpect(loggerSpyLog).toHaveBeenCalledTimes(3);\nexpect(loggerSpyWarn).not.toHaveBeenCalled();\n```\n\n```text\njest.mock('@nestjs/common/services/logger.service');\n```\n\n========================================\n\nComments:\n- Indeed, I was trying so many options that got confused in them. What worked is: logger = moduleRef.get(Logger); And then: expect(logger.log).toHaveBeenCalledTimes(1);\n- I still couldn't get it to work for whatever reason, so I ended up creating a new logger class that extends `ConsoleLogger` and dependency injected it in since that was a standard for testing anyways. It ended up working nicely because I could put Sentry in that extended class abstracted out of other locations which made testing easier down the road ๐Ÿ‘.\n- It's frustrating that their documentation is lacking around how to use the built-in logger. I end up back here a few months later looking again ๐Ÿ˜† I'm not sure why their logger doesn't seem to their own dependency injection model which would make this like testing anything else in the NestJS DI ecosystem.\n- @CTS_AE most likely it depends on how the logger is used. I use a custom logger I wrote called ogma most of the time.\n- The last option here is promising, however since `logger` is defined once, whenever I use `expect(logger.log).toHaveBeenCalledWith(...)` within a test, it fails because it is called multiple times due to other tests also triggering it.\n- @ChrisBarr Look into having jest reset your mocks between tests via the configuration jestjs.io/docs/configuration#resetmocks-boolean, or explicitly call `.mockReset()` on your mock. We have it reset mocks between all tests for our default since that is not normal functionality for whatever reason. I guess it depends how how you like to write your tests.\n- Thanks, I was not aware of that. I'm used to testing with Jasmine, so Jest's oddities are a little new to me.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but itโ€™d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who arenโ€™t as familiar with the syntax or struggling to understand the concepts. **Would you kindly edit your answer to include additional details for the benefit of the community?**\n- very nice, neat and concise\n- This is the correct solution on my test. No need for using DI to do `createTestingModule` and the logger object like the highest voted solution. ***// mock to make it not log*** jest.mock('@nestjs/common'); ***// create the spy (ex on debug method)*** const loggerSpyDebug = jest.spyOn(Logger.prototype, 'debug'); ***//in your test*** expect(loggerSpyDebug).toHaveBeenCalledWith({ method: 'GET', path: '/test-path', query: { key: 'value' }, body: { test: 'data' }, });","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":418,"estimatedTokens":2496}}297{"id":"stack-51045980","source":"stackoverflow","questionId":51045980,"title":"how to serve assets from Nest.js and add middleware to detect image request","tags":["node.js","express","nestjs"],"text":"Title: how to serve assets from Nest.js and add middleware to detect image request\nTags: node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to serve image from Nest.js server and add middleware to track all request but the only way I could make it work was with express\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport * as bodyParser from \"body-parser\";\nimport {AppModule} from \"./app.module\";\nimport * as path from \"path\";\nimport * as express from 'express';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.use(bodyParser.json({limit: '50mb'}));\n\n app.use(function(req, res, next){\n next();\n });\n //\n app.use('/api/track/',express.static(path.join(__dirname, '/public'))); //Serves resources from public folder\n app.use('/api/track/:img', function (req, res, next) {\n console.log('do something');\n next();\n });\n\n await app.listen(3333);\n}\n\nbootstrap();\n```\n\nHow can I implement it with using the controller or middleware?\n\n========================================\n\nTop Answer:\nIt worked for me. Just inject this controller in app module.\n\n```\nimport { Controller, Get, Req, Res } from '@nestjs/common';\n\n@Controller('uploads')\nexport class ServeFilesController {\n @Get('products/images/:imageName')\n invoke(@Req() req, @Res() res) {\n return res.sendFile(req.path, { root: './' });\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { NestFactory } from '@nestjs/core';\nimport * as bodyParser from \"body-parser\";\nimport {AppModule} from \"./app.module\";\nimport * as path from \"path\";\nimport * as express from 'express';\n\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.use(bodyParser.json({limit: '50mb'}));\n\n  app.use(function(req, res, next){\n    next();\n  });\n  //\n  app.use('/api/track/',express.static(path.join(__dirname, '/public'))); //Serves resources from public folder\n  app.use('/api/track/:img', function (req, res, next) {\n    console.log('do something');\n    next();\n  });\n\n  await app.listen(3333);\n}\n\nbootstrap();\n```\n\n```text\napp.useStaticAssets(path.join(__dirname, '/../public'));\n```\n\n```text\n@Get('track/:imgId')\ntest(@Param('imgId') imgId, @Res() res) {\n  const imgPath = getImgPath(imgId);\n  return res.sendFile(imgPath, { root: 'public' });\n}\n```\n\n```text\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\n```\n\n```text\nmain.ts\n```\n\n```text\nimport { Controller, Get, Req, Res } from '@nestjs/common';\n\n@Controller('uploads')\nexport class ServeFilesController {\n    @Get('products/images/:imageName')\n    invoke(@Req() req, @Res() res) {\n        return res.sendFile(req.path, { root: './' });\n    }\n}\n```\n\n========================================\n\nComments:\n- Where getImgPath comes from?\n- @DiegoSarmiento e.g. you store the path (or link) to the image in the database and getImgPath retrieves that path by imgId.","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":125,"estimatedTokens":737}}298{"id":"stack-61148959","source":"stackoverflow","questionId":61148959,"title":"FileInterceptor and Body Issue in NestJS (upload a file and data in a request)","tags":["postman","nestjs","nestjs-swagger"],"text":"Title: FileInterceptor and Body Issue in NestJS (upload a file and data in a request)\nTags: postman, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI have the following controller :\n\n```\ncreateCollection(\n @UploadedFile() file,\n @Body() createCollectionDto: CreateCollectionDto,\n @GetUser() user: User,\n ): Promise {\n this.logger.verbose(\n `User \"${\n user.username\n }\" creating a new collection. Data: ${JSON.stringify(\n createCollectionDto,\n )} of \"${user.username}\"`,\n );\n if (file) {\n return this.collectionService.createCollection(\n createCollectionDto,\n user,\n file,\n );\n } else {\n throw new InternalServerErrorException('File needed');\n }\n }\n```\n\nI need to upload a file and In the same query give some data.\nhttps://i.sstatic.net/1jDAo.png\n\nBecause I want to upload a file, I set up Postman like this:\nhttps://i.sstatic.net/73K5E.png\n\n**First Question** : How can I send the **file** along with the **data** showed in picture nยฐ1 ?\n\nI searched another tool for API requests and I found Postwoman\n\nHere is the config I used : \nhttps://i.sstatic.net/4XJuA.png\n\nBut the response is always the same: It doesn't detects the data. (i.e. `{ name: foo, color: bar}` )\n\nhttps://i.sstatic.net/F4dXl.png\n\n**Second Question** : How can I solve this issue ? Is it possible to put data along a file ? If it is possible how can I achieve that in NestJS ?\n\nThank you very much for reading my question :) Any help would be appreciated.\n\n========================================\n\nCode:\n```js\ncreateCollection(\n    @UploadedFile() file,\n    @Body() createCollectionDto: CreateCollectionDto,\n    @GetUser() user: User,\n  ): Promise<Collection> {\n    this.logger.verbose(\n      `User \"${\n        user.username\n      }\" creating a new collection. Data: ${JSON.stringify(\n        createCollectionDto,\n      )} of \"${user.username}\"`,\n    );\n    if (file) {\n      return this.collectionService.createCollection(\n        createCollectionDto,\n        user,\n        file,\n      );\n    } else {\n      throw new InternalServerErrorException('File needed');\n    }\n  }\n```\n\n```text\n{ name: foo, color: bar}\n```\n\n```js\nimport { Body, Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';\nimport { FileInterceptor } from '@nestjs/platform-express';\n\n@Controller('upload-stack-overflow')\nexport class UploadStackOverflowController {\n\n  @Post('upload')\n  @UseInterceptors(FileInterceptor('file'))\n  uploadSingleFileWithPost(@UploadedFile() file, @Body() body) {\n    console.log(file);\n    console.log(body.firstName);\n    console.log(body.favoriteColor);\n  }\n}\n```\n\n```text\nform-data\n```\n\n```text\nx-www-form-urlencoded\n```\n\n========================================\n\nComments:\n- I found out the problem thanks, as always it's a stupid error : I expected 'image' but in postman I gave the name 'file'\n- How to upload data and file in same request in database using nestjs. can you help me with this please? stackoverflow.com/questions/69849722/&hellip;\n- @PaulMest do you have a solution for nested file handling. stackoverflow.com/questions/72490730/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":116,"estimatedTokens":765}}299{"id":"stack-59403893","source":"stackoverflow","questionId":59403893,"title":"NestJs - ParseUUIDPipe - Validation failed (uuid vundefined is expected)","tags":["nestjs"],"text":"Title: NestJs - ParseUUIDPipe - Validation failed (uuid vundefined is expected)\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a basic controller setup:\n\n```\n@Controller('')\nexport class AController {\n @Get(':id')\n async getThing(@Param('id', ParseUUIDPipe) id: string): Promise {\n return id\n }\n}\n```\n\nAnd I get the following error:\n\n```\n{\n \"statusCode\": 400,\n \"error\": \"Bad Request\",\n \"message\": \"Validation failed (uuid vundefined is expected)\"\n}\n```\n\nAlso see: https://github.com/nestjs/nest/issues/2960\n\n========================================\n\nTop Answer:\nWith decorator helper:\n\n```\nimport { Param, ParseUUIDPipe } from '@nestjs/common';\n\nexport const UUIDParam = (name: string) => Param(name, new ParseUUIDPipe());\n\n// Your controller endpoint\n@Patch(':id')\npublic async updateOne(@UUIDParam('id') id: string): any;\n```\n\n๐Ÿ“Œ Docs link here\n\n========================================\n\nCode:\n```text\n@Controller('')\nexport class AController {\n @Get(':id')\n  async getThing(@Param('id', ParseUUIDPipe) id: string): Promise<RegisterRead[] | IntervalRead[]> {\n      return id\n  }\n}\n```\n\n```text\n{\n    \"statusCode\": 400,\n    \"error\": \"Bad Request\",\n    \"message\": \"Validation failed (uuid vundefined is expected)\"\n}\n```\n\n```text\nnew ParseUUIDPipe({version: '4'})\n```\n\n```text\nimport { Param, ParseUUIDPipe } from '@nestjs/common';\n\nexport const UUIDParam = (name: string) => Param(name, new ParseUUIDPipe());\n\n// Your controller endpoint\n@Patch(':id')\npublic async updateOne(@UUIDParam('id') id: string): any;\n```\n\n========================================\n\nComments:\n- could you accept your own answer - if you can - please ? :)\n- Just an update to this - the version is apparently no longer required, and `@Param('id', ParseUUIDPipe) id: string` should work","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":86,"estimatedTokens":442}}300{"id":"stack-70168350","source":"stackoverflow","questionId":70168350,"title":"Prevent multiple cron running in nest.js on docker","tags":["docker","concurrency","cron","nestjs"],"text":"Title: Prevent multiple cron running in nest.js on docker\nTags: docker, concurrency, cron, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn docker we have used `deploy: replicas: 3` for our microservice. We have some Cronjob & the problem is the system in running all cronjob is getting called 3 times which is not what we want. We want to run it only one time. Sample of cron in nest.js :\n\n```\n@Cron(CronExpression.EVERY_5_MINUTES)\n async runBiEventProcessor() {\n const calculationDate = new Date()\n Logger.log(`Bi Event Processor started at ${calculationDate}`)\n```\n\nHow can I run this cron only once without changing the replicas to 1?\n\n========================================\n\nTop Answer:\nThere are two practical approachs that I would pick:\n\nIf you use k8s, then it support CronJob out of the box:\nhttps://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/\nFirst, expose the cronjob as an endpoint and configure it so it only allow network from internal k8s cluster (you don't want someone from the internet trigger it).\nk8s let you schedule to run a container, in this case, you can use https://hub.docker.com/r/curlimages/curl to make a request to the endpoint.\nThe code would look like this:\n\n```\napiVersion: batch/v1\nkind: CronJob\nmetadata:\n name: http-call-job\nspec:\n schedule: \"0 * * * *\" # Runs at the beginning of every hour\n jobTemplate:\n spec:\n template:\n spec:\n containers:\n - name: http-caller\n image: curlimages/curl:latest\n args:\n - /bin/sh\n - -c\n - \"curl -X GET http://example.com/endpoint\"\n restartPolicy: OnFailure\n successfulJobsHistoryLimit: 0\n failedJobsHistoryLimit: 1\n # this will make sure only one Job run is executed at a time\n concurrencyPolicy: Forbid\n```\n\n- If you don't use k8s, then make your own locking mechanism. Yes, it's not that hard, it actually pretty easy. Just create table, open a transaction to verify that you're the first one before creating a new record.\n\n```\nCREATE TABLE CronJobRuns (\n JobName VARCHAR(255)\n StarteddAt DateTime\n);\n```\n\n========================================\n\nCode:\n```text\n@Cron(CronExpression.EVERY_5_MINUTES)\n  async runBiEventProcessor() {\n    const calculationDate = new Date()\n    Logger.log(`Bi Event Processor started at ${calculationDate}`)\n```\n\n```text\ndeploy: replicas: 3\n```\n\n```text\nconst app = await NestFactory.create(\n  WorkerModule,\n);\nawait app.init();\n```\n\n```text\nWorkerModule\n```\n\n```text\nbackend:\n  image: scalable-container-image\n  build:\n    context: ./../\n    dockerfile: ./docker/Dockerfile\n    target: production\n  expose:\n    - \"3000\"\n  networks:\n    - mainnet\n  deploy:\n    replicas: 2\nbackend-cron-manager:\n  container_name: cron-manager\n  image: scalable-container-image\n  build:\n    context: ./../\n    dockerfile: ./docker/Dockerfile\n    target: production\n  environment:\n    INSTANCE_ID: instance1\n  expose:\n    - \"3000\"\n  networks:\n    - mainnet\n```\n\n```text\nimport { Cron, CronExpression } from '@nestjs/schedule';\n\nexport class DeleteFilesCronService {\n  @Cron(CronExpression.EVERY_4_HOURS)\n  private async handleDeleteFiles() {\n    if (process.env.INSTANCE_ID) {\n      // handle delete files\n    }\n  }\n}\n```\n\n```text\napiVersion: batch/v1\nkind: CronJob\nmetadata:\n  name: http-call-job\nspec:\n  schedule: \"0 * * * *\"  # Runs at the beginning of every hour\n  jobTemplate:\n    spec:\n      template:\n        spec:\n          containers:\n          - name: http-caller\n            image: curlimages/curl:latest\n            args:\n            - /bin/sh\n            - -c\n            - \"curl -X GET http://example.com/endpoint\"\n          restartPolicy: OnFailure\n  successfulJobsHistoryLimit: 0\n  failedJobsHistoryLimit: 1\n  # this will make sure only one Job run is executed at a time\n  concurrencyPolicy: Forbid\n```\n\n```text\nCREATE TABLE CronJobRuns (\n   JobName VARCHAR(255)\n   StarteddAt DateTime\n);\n```\n\n========================================\n\nComments:\n- I don't want to create a microservice for this. Need another way to do it.\n- Then the same approach, use some shared DB and store the result of the cronjob with a timestamp. If it is present, skip running.\n- If you have any further queries or if you didn't understand a particular part. Let me know; I will edit the answer to make it more clear.\n- Bull queue is not skipping repeatable task but only postpones it, so if you have heavy task the queue will become larger and larger with time, for me custom locking mechanism worked best","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":166,"estimatedTokens":1100}}301{"id":"stack-69411838","source":"stackoverflow","questionId":69411838,"title":"Nest class-validator minDate throws error even when the date is greater","tags":["nestjs","class-validator"],"text":"Title: Nest class-validator minDate throws error even when the date is greater\nTags: nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm using Nest with class-validator and attempting to validate that the date provided by the UI is no earlier than today using `@isDateString()` and `@MinDate()`\n\n \n\n```\nexport class SchemaDto {\n @IsOptional()\n @IsDateString()\n @MinDate(new Date())\n myDate?: Date;\n}\n```\n\nThe data I am sending in is a Date Objected with the following date:\n\n```\nMon Oct 04 2021 00:00:00 GMT-0400 (Eastern Daylight Time)\n```\n\nThe error I am getting from class-validator is:\n\n```\nminimal allowed date for myDate is Fri Oct 01 2021 15:57:18 GMT-0400 (Eastern Daylight Time)\n```\n\n**The problem:**\n\n \nIf I remove the minDate decorator, everything works fine but I would rather validate this common case.\n\ninfo:\ntypescript: ~4.1.4\n\nnode: 12.4.0\n\nclass-validator: 0.13.1\n\nnest: 7.0.0\n\n========================================\n\nTop Answer:\nThe `@Transform` approach in Hai An's answer works because it omits `@IsDateString` decorator which is included in the OP's question. If you intend to keep the `@IsDateString` decorator, you'll run into new errors when you use it alongside the `@Transform` decorator (`@Transform( ({ value }) => new Date(value))`).\n\nThe use of `@IsDateString` implies that you expect a date string in ISO8601 format as input. The issue is that `@MinDate` accepts an argument of type `Date` whereas what is passed to it at runtime in your case is a string. A look at the validator implementation for MinDate reveals that validation will fail if the value of the decorated property is not an instance of `Date`. Using the `@Transform` decorator to transform the date string into a date object is still a problem with `@IsDateString` because you get an error that the input received is not a valid ISO8601 date string. This happens because transformation occurs before decorators are applied. The good news is that an issue with a PR attached is open here in the typestack/class-validator GitHub repo to fix the conflict that comes with using `@IsDateString` and `@MinDate` validators together โ€” but it doesn't look like it'll be merged soon.\n\nSolution? I suggest that you implement a custom decorator. You could keep the name of the decorator as MinDate so that when the feat: Make minDate and maxDate support specifying dynamic date PR gets merged/released, you only need to update your class-validator version and change your MinDate import path. Below is my implementation which makes a one-line change to the original implementation to allow MinDate receive a date string:\n\n**custom-min-date.decorator.ts**\n\n```\nimport { buildMessage, ValidateBy, ValidationOptions } from 'class-validator';\n\nexport const MIN_DATE = 'minDate';\n\n/**\n * Checks if the value is a date that's after the specified date.\n */\nexport function minDate(date: unknown, minDate: Date): boolean {\n const dateObject: Date = typeof date === 'string' ? new Date(date) : date;\n return dateObject instanceof Date && dateObject.getTime() >= minDate.getTime();\n}\n\n/**\n * Checks if the value is a date that's after the specified date.\n */\nexport function MinDate(date: Date, validationOptions?: ValidationOptions): PropertyDecorator {\n return ValidateBy(\n {\n name: MIN_DATE,\n constraints: [date],\n validator: {\n validate: (value, args): boolean => minDate(value, args.constraints[0]),\n defaultMessage: buildMessage(\n (eachPrefix) => 'minimal allowed date for ' + eachPrefix + '$property is $constraint1',\n validationOptions,\n ),\n },\n },\n validationOptions,\n );\n}\n```\n\nI hope this helps someone.\n\n========================================\n\nCode:\n```text\nexport class SchemaDto {\n    @IsOptional()\n    @IsDateString()\n    @MinDate(new Date())\n    myDate?: Date;\n}\n```\n\n```text\nMon Oct 04 2021 00:00:00 GMT-0400 (Eastern Daylight Time)\n```\n\n```text\nminimal allowed date for myDate is Fri Oct 01 2021 15:57:18 GMT-0400 (Eastern Daylight Time)\n```\n\n```text\n@isDateString()\n```\n\n```text\n@MinDate()\n```\n\n```text\nexport class SchemaDto {\n    @IsNotEmpty()\n    @Transform( ({ value }) => new Date(value))\n    @IsDate()\n    @MinDate(new Date())\n    myDate: Date;\n}\n```\n\n```text\nexport class SchemaDto {\n    @IsOptional()\n    @Transform( ({ value }) => value && new Date(value))\n    @IsDate()\n    @MinDate(new Date())\n    myDate?: Date;\n}\n```\n\n```text\nimport { buildMessage, ValidateBy, ValidationOptions } from 'class-validator';\n\nexport const MIN_DATE = 'minDate';\n\n/**\n * Checks if the value is a date that's after the specified date.\n */\nexport function minDate(date: unknown, minDate: Date): boolean {\n  const dateObject: Date = typeof date === 'string' ? new Date(date) : <Date>date;\n  return dateObject instanceof Date && dateObject.getTime() >= minDate.getTime();\n}\n\n/**\n * Checks if the value is a date that's after the specified date.\n */\nexport function MinDate(date: Date, validationOptions?: ValidationOptions): PropertyDecorator {\n  return ValidateBy(\n    {\n      name: MIN_DATE,\n      constraints: [date],\n      validator: {\n        validate: (value, args): boolean => minDate(value, args.constraints[0]),\n        defaultMessage: buildMessage(\n          (eachPrefix) => 'minimal allowed date for ' + eachPrefix + '$property is $constraint1',\n          validationOptions,\n        ),\n      },\n    },\n    validationOptions,\n  );\n}\n```\n\n```text\n@Transform\n```\n\n```text\n@IsDateString\n```\n\n```text\n@IsDateString\n```\n\n```text\n@Transform\n```\n\n```text\n@Transform( ({ value }) => new Date(value))\n```\n\n```text\n@IsDateString\n```\n\n```text\n@MinDate\n```\n\n```text\nDate\n```\n\n```text\nDate\n```\n\n```text\n@Transform\n```\n\n```text\n@IsDateString\n```\n\n```text\n@IsDateString\n```\n\n```text\n@MinDate\n```\n\n========================================\n\nComments:\n- The PR you linked to support dynamic dates has been merged by now, but I do not see how this helps with the stated problem, could you elaborate? To me it seems the fundamental conflict persists that IsISO8601 works on strings, and MinDate works on Date objects, so I can only use one or the other.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":230,"estimatedTokens":1570}}302{"id":"stack-67262155","source":"stackoverflow","questionId":67262155,"title":"what is the difference between DTO's,Interfaces,and schema in nest js","tags":["nestjs"],"text":"Title: what is the difference between DTO's,Interfaces,and schema in nest js\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am new to Nest js in this we have some topics like Dto,interfaces,and schema can anyone provide clear Information on these topics.\n\n========================================\n\nCode:\n```text\n//signUp.dto.ts\nexport class signUpDto {\n    @IsNotEmpty({message: \"Email cannot be empty.\"})\n    @IsEmail() //class-validators can be ignored here.\n    email: string;\n\n    @IsNotEmpty({message: \"Password cannot be Empty.\"})\n    @MinLength(6,{message: \"Password must be 6 characters.\"})\n    @MaxLength(128,{message: \"Password must be less than 128.\"})\n    password: string;\n}\n```\n\n```text\ninterface Human {\n    eyeColor: string;\n    hairColor: string;\n}\nclass Doctor implements Human{\n    eyeColor: string;\n    hairColor: string;\n}\n```\n\n========================================\n\nComments:\n- May this answer your question models-vs-dto-in-nestjs\n- @Youba there we don't have any real time examples.","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":40,"estimatedTokens":253}}303{"id":"stack-70671382","source":"stackoverflow","questionId":70671382,"title":"Throw HttpException at service in nestjs","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Throw HttpException at service in nestjs\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs it good way to throw Http Exeption at service in nestjs?\nWhat is the best way to processing error at service in nestjs?\n\n========================================\n\nTop Answer:\nTo elaborate on this answer, https://stackoverflow.com/a/73211663/1500042, you can use it to automatically configure http codes:\n\nmy.controller.ts:\n\n```\n@Get()\nasync getIt(@Req() req) {\ntry {\n return await this.myService.getThe(req.thing);\n} catch (error) {\n throw new HttpException(error.message, HttpStatus.BAD_REQUEST);\n}\n```\n\nThis sends a '400' response and blames the user (as you do). As a bonus it resists crashing on bad requests.\n\n========================================\n\nCode:\n```text\n@Get()\nasync getIt(@Req() req) {\ntry {\n  return await this.myService.getThe(req.thing);\n} catch (error) {\n  throw new HttpException(error.message, HttpStatus.BAD_REQUEST);\n}\n```\n\n========================================\n\nComments:\n- Services should contain the business logic of your application. So there should be meaningful errors thrown. This can be mapped onto an HTTP Error in the controller layer. But in the end, you can decide how to structure your own backend. If your usecase is fine with throwing HTTP exceptions in the service layer you do no harm to anybody.\n- Thanks for answer\n- I asked myself same question, and in my opinion throwing http exceptions in services does not seems to be right. HTTP exceptions are related to controllers, so they need to be used in controller. Services are reusable piece of code which can be called beside controllers, and in some cases may cause unexpected behaviour.\n- You are right.)","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":47,"estimatedTokens":434}}304{"id":"stack-70041367","source":"stackoverflow","questionId":70041367,"title":"End-to-end testing NestJS with Fastify: \"@nestjs/platform-express\" package is missing\" error","tags":["node.js","typescript","nestjs","fastify","nestjs-fastify"],"text":"Title: End-to-end testing NestJS with Fastify: \"@nestjs/platform-express\" package is missing\" error\nTags: node.js, typescript, nestjs, fastify, nestjs-fastify\nSource: Stack Overflow\n\nQuestion:\nI have fresh NestJS application using Fastify. When trying to `npm run test:e2e` I got the following error:\n\n```\n[Nest] 14894 - 11/19/2021, 10:29:10 PM [ExceptionHandler] The \"@nestjs/platform-express\" package is missing. Please, make sure to install this library ($ npm install @nestjs/platform-express) to take advantage of NestFactory.\n โ— process.exit called with \"1\"\n\n 12 | }).compile();\n 13 | \n > 14 | app = moduleFixture.createNestApplication();\n | ^\n 15 | await app.init();\n 16 | });\n 17 | \n\n at Object.loadPackage (../node_modules/@nestjs/common/utils/load-package.util.js:13:17)\n at TestingModule.createHttpAdapter (../node_modules/@nestjs/testing/testing-module.js:25:56)\n at TestingModule.createNestApplication (../node_modules/@nestjs/testing/testing-module.js:13:43)\n at Object. (app.e2e-spec.ts:14:25)\n\n RUNS test/app.e2e-spec.ts\n\nProcess finished with exit code 1\n```\n\nSeems odd, because why would platform-express be needed for fastify-based app?\n\n========================================\n\nCode:\n```text\n[Nest] 14894   - 11/19/2021, 10:29:10 PM   [ExceptionHandler] The \"@nestjs/platform-express\" package is missing. Please, make sure to install this library ($ npm install @nestjs/platform-express) to take advantage of NestFactory.\n  โ—  process.exit called with \"1\"\n\n      12 |     }).compile();\n      13 | \n    > 14 |     app = moduleFixture.createNestApplication();\n         |                         ^\n      15 |     await app.init();\n      16 |   });\n      17 | \n\n      at Object.loadPackage (../node_modules/@nestjs/common/utils/load-package.util.js:13:17)\n      at TestingModule.createHttpAdapter (../node_modules/@nestjs/testing/testing-module.js:25:56)\n      at TestingModule.createNestApplication (../node_modules/@nestjs/testing/testing-module.js:13:43)\n      at Object.<anonymous> (app.e2e-spec.ts:14:25)\n\n RUNS  test/app.e2e-spec.ts\n\nProcess finished with exit code 1\n```\n\n```text\nnpm run test:e2e\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppModule } from '../src/app.module';\nimport { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';\n\ndescribe('AppController (e2e)', () => {\n  let app: NestFastifyApplication;\n\n  beforeEach(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n\n    app = moduleFixture.createNestApplication<NestFastifyApplication>(new FastifyAdapter());\n    await app.init();\n    await app.getHttpAdapter().getInstance().ready();\n  });\n\n  afterEach(async () => {\n    await app.close();\n  });\n\n  it('/ (GET)', () => {\n    return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');\n  });\n});\n```\n\n```text\ntest/app.e2e-spec.ts\n```\n\n========================================\n\nComments:\n- docs.nestjs.com/fundamentals/testing#end-to-end-testing","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":97,"estimatedTokens":770}}305{"id":"stack-77347982","source":"stackoverflow","questionId":77347982,"title":"NX Monorepo (NestJS/Angular)","tags":["angular","nestjs","monorepo"],"text":"Title: NX Monorepo (NestJS/Angular)\nTags: angular, nestjs, monorepo\nSource: Stack Overflow\n\nQuestion:\nI'd like to create a monorepo to manage a fullstack application with a NestJS backend and an Angular frontend that a package called \"shared\".\n\nI'd like to do this using NX.\n\nActually I have checked the NX documentation but I'm a bit confused about the options to chose, there are many (package based monorepos, Angular monorepo, NestJS monorepo), I'm not sure what steps I should to use NX properly.\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nSo to reiterate what's the goal, in your NX monorepo, you want to have the following:\n\n- `my-angular` app\n\n- `my-nestjs` app\n\n- `shared` lib\n\n- some other libs.\n\nIMO, to get to that point, you have two options, each with some upsides and downsides.\n\nI'd try solution 1 only in case your existing projects are very simple. Otherwise, solution 2 has a better chance to work out well without significant complications.\n\n### Solution 1:\n\nTry to do the straightforward thing, which might be quicker, but might also cause you to unknowingly generate a mess that will not actually work because of unexpected or poorly understood problems/interactions between your first and second app. Which you will then have to spend time to resolve.\n\nSet up a new, fresh NX monorepo: https://nx.dev/recipes/adopting-nx/manual#exploring-your-workspace\n\nManually copypaste your Angular app to the `apps` directory and hook it up to NX: https://nx.dev/recipes/angular/migration/angular-manual\n\nManually copypaste your Nest app and hook it up to NX (in whatever way it needs to be, rougly described here: https://nx.dev/recipes/adopting-nx/manual#configuration-files). Because that's your second app in the monorepo, it'll require more attention - you'll need to ensure it's supported by NX without breaking the first app, and uses correct versions of packages it needs.\n\nCreate a new `shared` NX library and reuse it between your apps.\n\n### Solution 1a:\n\nIf your Angular app is up to date and uses Angular CLI, you can replace steps 1 and 2 with:\n\n- Migrate your Angular app to an NX monorepo using the official conversion tools: https://nx.dev/recipes/angular/migration/angular\n\nThis might make the process a bit simpler, though it also gives you less control and a worse learning experience.\n\n### Solution 2:\n\nTake the time to do things slowly and carefully, which will also give you more space to understand what NX is and how it actually works.\n\nMigrate your Angular app to an NX monorepo. Split its code to libs and organize them correctly.\n\nMigrate your Nest app to a *separate* NX monorepo. Split its code to libs and organize them correctly.\n\nMerge those two NX monorepos and resolve any remaining conflicts between CI/CD flows, package versions, etc.\n\nCreate a new `shared` NX library and reuse it between your apps.\n\nThis will be probably longer, but will also give you a better understanding of how each of your apps functions within NX, and how it should be integrated with NX, before you stick them together in a single NX repo that has to support them both.\n\n(As a sidenote, I just want you to know, I was in a similar situation with little to none NX knowledge and only one app to handle, and it wasn't easy. NX is not very beginner-friendly and you will usually not find tutorials and docs that will perfectly cover your use cases. There's plenty of problems to solve, and at many points you will have to make do with the existing docs and the existing scarce examples. If you are deterred at this point at the beginning already, I advise you and/or your company to consider carefully what you want to achieve using NX, and if you're willing to go through a demanding integration process to get it. NX is very worth the effort in some cases, but in some it's not and it's wiser to recognize that before you're too invested.)\n\n========================================\n\nCode:\n```text\nimport { sharedLib } from \"@my-project/shared-lib\"\n```\n\n```text\nnpm i -g nx\n```\n\n```text\nmy-project\n```\n\n```text\ncd my-project\n```\n\n```text\nnpm i -D @nx/angular @nx/nest @nx/js\n```\n\n```text\nnx g @nx/angular:app angular-app\n```\n\n```text\nnx g @nx/nest:app nest-app\n```\n\n```text\nnx g @nx/js:lib shared-lib\n```\n\n```text\nshared-lib\n```\n\n```text\nmy-angular\n```\n\n```text\nmy-nestjs\n```\n\n```text\nshared\n```\n\n```text\napps\n```\n\n```text\nshared\n```\n\n```text\nshared\n```\n\n```text\nnpx create-nx-workspace --preset=apps\n```\n\n```text\nnpm i -D @nx/angular @nx/nest @nx/js\nnx g @nx/angular:app apps/angular-app-name\nnx g @nx/nest:app apps/nestjs-app-name\n```\n\n========================================\n\nComments:\n- The question is off-topic. Please make it focused\n- I finally found a clear description of the process!\n- Just wanna add that adding @nx/angular after creating bare workspace gives error as of today: `The \"@nx&#47;angular:application\" generator doesn't yet support the existing TypeScript setup`; I ended up creating an angular app first and adding nest later.","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":145,"estimatedTokens":1252}}306{"id":"stack-74221005","source":"stackoverflow","questionId":74221005,"title":"Mongodb connection failed in local with node version 18.12.0?","tags":["node.js","mongodb","mongoose","nestjs"],"text":"Title: Mongodb connection failed in local with node version 18.12.0?\nTags: node.js, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am seeing one issue with node version `18.12.0` and mongodb `6.0.2`. I already build a nestjs application with mongodb. Here I use `@nestjs/mongoose(v- 9.0.2)` and `mongoose (v-6.7.0)`\n\nHere I can see that when I upgrade node js to latest lts version then I am not able to connect to mongodb. It show an error like `unable to connect to database`.\n\nBut When I downgrade to node version `16.18.0` then it working fine. My question is that you guys already face this issue or I am only person getting this issue. If you know that then actually where is the problem occurred?\n\nHere is my connection code-\n\n```\nMongooseModule.forRoot(\"mongodb://localhost:27017/nekmart\", {\n connectionFactory: (connection) => {\n connection.plugin(slug, { number: true });\n return connection\n }\n}),\n```\n\n========================================\n\nTop Answer:\n`**mongodb://0.0.0.0:27017/?**`\n\nTry with this in the new version of the node and the mongoose lib it will work fine\nThe same thing works in My many system which has the new version of the node.\n\nAnd Most of the time entering you ipv4 ip address at the place of the localhost will make it work\n\nAnd if by chance it want work then try with every ipconfig ip which is cofigured in your pc.\n\nEthernet adapter Ethernet:\n\nConnection-specific DNS Suffix . :\n\nLink-local IPv6 Address . . . . . : fe40::2830:7f6b:e242:7232%6\n\nIPv4 Address. . . . . . . . . . . : 192.168.10.---\n\nSubnet Mask . . . . . . . . . . . : 255.255.255.0\n\nDefault Gateway . . . . . . . . . : 192.165.10.5\n\nThe above config depends on your computer setting\n\n========================================\n\nCode:\n```text\nMongooseModule.forRoot(\"mongodb://localhost:27017/nekmart\", {\n      connectionFactory: (connection) => {\n        connection.plugin(slug, { number: true });\n        return connection\n      }\n}),\n```\n\n```text\n18.12.0\n```\n\n```text\n6.0.2\n```\n\n```text\n@nestjs/mongoose(v- 9.0.2)\n```\n\n```text\nmongoose (v-6.7.0)\n```\n\n```text\nunable to connect to database\n```\n\n```text\n16.18.0\n```\n\n```text\nmongodb://localhost:27017/test_db\n```\n\n```text\nmongodb://127.0.0.1:27017/test_db\n```\n\n```text\nlocalhost\n```\n\n```text\n**mongodb://0.0.0.0:27017/?**\n```\n\n========================================\n\nComments:\n- What's JM Lord above comment talking about. this is not an english lesson. the answer is useful and complete\n- Tremmillicious is right. While using proper sentences, with punctuation and capitalization are important attributes of writing, not everyone in the world is a student of English language. Also, this is not english.stackexchange.com The answer needs to be understandable and question be addressed properly to the point. Solving problems is the reason this site exists. Thanks @yoav-agmon for the answer which solves the problem at hand.\n- Though this solution works, it might be better to update the mongod.conf file as in this answer: stackoverflow.com/a/69964742/4045731 . The reason is, that the issue is due to NodeJs default to IPv6, and it's more robust to leave \"localhost\" instead of setting explicit IP that is only supported in IPv4. Btw, for Windows users the mongod.conf is where the Mongo binaries are.","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":106,"estimatedTokens":819}}307{"id":"stack-62120993","source":"stackoverflow","questionId":62120993,"title":"Store a value in redis store using Nestjs","tags":["redis","nestjs"],"text":"Title: Store a value in redis store using Nestjs\nTags: redis, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a simple nestjs application, where I have set up a `CacheModule` using `Redis` store as follows:\n\n```\nimport * as redisStore from 'cache-manager-redis-store';\n\nCacheModule.register({\n store: redisStore,\n host: 'redis',\n port: 6379,\n }),\n```\n\nI would like to use it to store a single value, however, I do not want to do it the built-in way by attaching an interceptor to a controller method, but instead I want to control it manually and be able to set and retrieve the value in the code.\n\nHow would I go about doing that and would I even use cache manager for that?\n\n========================================\n\nTop Answer:\nYou can use the official way from Nest.js:\n\n### 1. Create your RedisCacheModule:\n\n### 1.1. `redisCache.module.ts`:\n\n```\nimport { Module, CacheModule } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport * as redisStore from 'cache-manager-redis-store';\nimport { RedisCacheService } from './redisCache.service';\n\n@Module({\n imports: [\n CacheModule.registerAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n store: redisStore,\n host: configService.get('REDIS_HOST'),\n port: configService.get('REDIS_PORT'),\n ttl: configService.get('CACHE_TTL'),\n }),\n }),\n ],\n providers: [RedisCacheService],\n exports: [RedisCacheService] // This is IMPORTANT, you need to export RedisCacheService here so that other modules can use it\n})\nexport class RedisCacheModule {}\n```\n\n### 1.2. `redisCache.service.ts`:\n\n```\nimport { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';\nimport { Cache } from 'cache-manager';\n\n@Injectable()\nexport class RedisCacheService {\n constructor(\n @Inject(CACHE_MANAGER) private readonly cache: Cache,\n ) {}\n\n async get(key) {\n await this.cache.get(key);\n }\n\n async set(key, value) {\n await this.cache.set(key, value);\n }\n}\n```\n\n### 2. Inject RedisCacheModule wherever you need it:\n\nLet's just assume we will use it in module `DailyReportModule`:\n\n### 2.1. `dailyReport.module.ts`:\n\n```\nimport { Module } from '@nestjs/common';\nimport { RedisCacheModule } from '../cache/redisCache.module';\nimport { DailyReportService } from './dailyReport.service';\n\n@Module({\n imports: [RedisCacheModule],\n providers: [DailyReportService],\n})\nexport class DailyReportModule {}\n```\n\n### 2.2. `dailyReport.service.ts`:\n\nWe will use the `redisCacheService` here:\n\n```\nimport { Injectable, Logger } from '@nestjs/common';\nimport { Cron } from '@nestjs/schedule';\nimport { RedisCacheService } from '../cache/redisCache.service';\n\n@Injectable()\nexport class DailyReportService {\n private readonly logger = new Logger(DailyReportService.name);\n\n constructor(\n private readonly redisCacheService: RedisCacheService, // REMEMBER TO INJECT THIS\n ) {}\n\n @Cron('0 1 0 * * *') // Run cron job at 00:01:00 everyday\n async handleCacheDailyReport() {\n this.logger.debug('Handle cache to Redis');\n }\n}\n```\n\nYou can check my sample code here.\n\n========================================\n\nCode:\n```js\nimport * as redisStore from 'cache-manager-redis-store';\n\nCacheModule.register({\n      store: redisStore,\n      host: 'redis',\n      port: 6379,\n    }),\n```\n\n```text\nCacheModule\n```\n\n```text\nRedis\n```\n\n```text\nnestjs-redis\n```\n\n```text\nimport * as redis from 'async-redis';\nimport redisConfig from '../../config/redis';\n```\n\n```text\nexport default {\n   host: 'your Host',\n   port: parseInt('Your Port Conection'),\n   // Put the first value in hours\n   // Time to expire a data on redis\n   expire: 1 * 60 * 60,\n   auth_pass: 'password',\n};\n```\n\n```text\nvar dbConnection = redis.createClient(config.db.port, config.db.host, \n{no_ready_check: true});\n```\n\n```js\nimport { Module, CacheModule } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport * as redisStore from 'cache-manager-redis-store';\nimport { RedisCacheService } from './redisCache.service';\n\n@Module({\n  imports: [\n    CacheModule.registerAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: async (configService: ConfigService) => ({\n        store: redisStore,\n        host: configService.get('REDIS_HOST'),\n        port: configService.get('REDIS_PORT'),\n        ttl: configService.get('CACHE_TTL'),\n      }),\n    }),\n  ],\n  providers: [RedisCacheService],\n  exports: [RedisCacheService] // This is IMPORTANT,  you need to export RedisCacheService here so that other modules can use it\n})\nexport class RedisCacheModule {}\n```\n\n```js\nimport { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';\nimport { Cache } from 'cache-manager';\n\n@Injectable()\nexport class RedisCacheService {\n  constructor(\n    @Inject(CACHE_MANAGER) private readonly cache: Cache,\n  ) {}\n\n  async get(key) {\n    await this.cache.get(key);\n  }\n\n  async set(key, value) {\n    await this.cache.set(key, value);\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { RedisCacheModule } from '../cache/redisCache.module';\nimport { DailyReportService } from './dailyReport.service';\n\n@Module({\n  imports: [RedisCacheModule],\n  providers: [DailyReportService],\n})\nexport class DailyReportModule {}\n```\n\n```js\nimport { Injectable, Logger } from '@nestjs/common';\nimport { Cron } from '@nestjs/schedule';\nimport { RedisCacheService } from '../cache/redisCache.service';\n\n@Injectable()\nexport class DailyReportService {\n  private readonly logger = new Logger(DailyReportService.name);\n\n  constructor(\n    private readonly redisCacheService: RedisCacheService, // REMEMBER TO INJECT THIS\n  ) {}\n\n  @Cron('0 1 0 * * *') // Run cron job at 00:01:00 everyday\n  async handleCacheDailyReport() {\n    this.logger.debug('Handle cache to Redis');\n  }\n}\n```\n\n```text\nredisCache.module.ts\n```\n\n```text\nredisCache.service.ts\n```\n\n```text\nDailyReportModule\n```\n\n```text\ndailyReport.module.ts\n```\n\n```text\ndailyReport.service.ts\n```\n\n```text\nredisCacheService\n```\n\n========================================\n\nComments:\n- If you want to use redis with your nest application, its better to use redis module already provided by someone. This module has a service through which you can set and get aything you want into your redis. nestjs-redis\n- The project looks abandoned and it is not compatible with NestJS 8+.\n- `nestjs-redis` uses `ioredis` behind the scene and not the `node-redis` module!\n- I am getting error after installing. Could not find a declaration file for module 'cache-manager-redis-store'\n- @har17bar try to install this package: npmjs.com/package/cache-manager-redis-store\n- I am getting error after installing. Could not find a declaration file for module 'cache-manager-redis-store'\n- @har17bar npm install cache-manager-redis-store should do the trick for you","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":278,"estimatedTokens":1701}}308{"id":"stack-61261860","source":"stackoverflow","questionId":61261860,"title":"How to enable DTO validators in NEST JS","tags":["node.js","typescript","nestjs"],"text":"Title: How to enable DTO validators in NEST JS\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm new in NEST JS, and now i'm try to include some validator in DTO'S\nlooks like:\n\n```\n// /blog-backend/src/blog/dto/create-post.dto.ts\nimport { IsEmail, IsNotEmpty, IsDefined } from 'class-validator';\nexport class CreatePostDTO {\n @IsDefined()\n @IsNotEmpty()\n title: string;\n @IsDefined()\n @IsNotEmpty()\n description: string;\n @IsDefined()\n @IsNotEmpty()\n body: string;\n @IsEmail()\n @IsNotEmpty()\n author: string;\n @IsDefined()\n @IsNotEmpty()\n datePosted: string;\n}\n```\n\nBut when i excute the post service like:\n\n```\n{\n \"title\":\"juanita\"\n}\n```\n\nIts return good!\nBut the validators should show and error rigth?\n\nMy post controloler\n\n```\n@Post('/post')\n async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {\n console.log(createPostDTO)\n const newPost = await this.blogService.addPost(createPostDTO);\n return res.status(HttpStatus.OK).json({\n message: 'Post has been submitted successfully!',\n post: newPost,\n });\n }\n```\n\nMy main.ts\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n \n await app.listen(5000);\n}\nbootstrap();\n```\n\n========================================\n\nTop Answer:\nYou also can register global pipes in `app.module.ts` file like this:\n\n```\nproviders: [\n {\n provide: APP_PIPE,\n useValue: new ValidationPipe({\n // validation options\n whitelist: true,\n }),\n },\n ],\n```\n\n========================================\n\nCode:\n```text\n// /blog-backend/src/blog/dto/create-post.dto.ts\nimport { IsEmail, IsNotEmpty, IsDefined } from 'class-validator';\nexport class CreatePostDTO {\n  @IsDefined()\n  @IsNotEmpty()\n  title: string;\n  @IsDefined()\n  @IsNotEmpty()\n  description: string;\n  @IsDefined()\n  @IsNotEmpty()\n  body: string;\n  @IsEmail()\n  @IsNotEmpty()\n  author: string;\n  @IsDefined()\n  @IsNotEmpty()\n  datePosted: string;\n}\n```\n\n```text\n{\n    \"title\":\"juanita\"\n}\n```\n\n```text\n@Post('/post')\n  async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {\n    console.log(createPostDTO)\n    const newPost = await this.blogService.addPost(createPostDTO);\n    return res.status(HttpStatus.OK).json({\n      message: 'Post has been submitted successfully!',\n      post: newPost,\n    });\n  }\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  \n  await app.listen(5000);\n}\nbootstrap();\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ValidationPipe } from '@nestjs/common'; // import built-in ValidationPipe\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe()); // enable ValidationPipe`\n  await app.listen(5000);\n}\nbootstrap();\n```\n\n```text\nValidationPipe\n```\n\n```text\nValidationPipe\n```\n\n```text\nproviders: [\n    {\n      provide: APP_PIPE,\n      useValue: new ValidationPipe({\n        // validation options\n        whitelist: true,\n      }),\n    },\n  ],\n```\n\n```text\napp.module.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.430Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":177,"estimatedTokens":802}}309{"id":"stack-68686034","source":"stackoverflow","questionId":68686034,"title":"Jest tests failing with ENOENT no such file or directory (referring to the spec files themselves)","tags":["typescript","jestjs","nestjs"],"text":"Title: Jest tests failing with ENOENT no such file or directory (referring to the spec files themselves)\nTags: typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nWe have a NestJS project with several modules. Suddenly, some tests stopped working with errors all like\n\nFAIL libs/backend/nest/pipes/src/lib/iso-date-validation.pipe.spec.ts\n\nโ— Test suite failed to run\n\nENOENT: no such file or directory, open\nD:\\git\\my-nest-project\\libs\\backend\\nest\\pipes\\src\\lib\\iso-date-validation.pipe.spec.ts'\n\nIt knows what test to run, but then it claims it can't find the test file. Sometimes we get a couple of these errors, sometimes dozens.\n\nThese errors are happening randomly (not always on the same tests) locally on my machine as well as on our Jenkins server and on other developer environments as well. I can reproduce this on Windows/Mac/Linux.\n\nThere were no changes to the test or project configuration files that would have triggered this change. In fact, I have checked out previous versions of the codebase that built reliably in Jenkins and now they have the same random test errors.\n\nI have tested on clean nodejs environments with nothing installed globally except npm.\n\nUsing the jest --verbose flag gives me no further details.\n\nThe jest config in a NestJS project is multi-layered, so it's hard to display the whole thing here, but I don't understand how this could be a configuration issue because the tests used to run fine and the configuration files have not changed.\n\nI have tried clearing the jest cache, but the results are not consistent. On some occasions I can get a clean test run after clearing the cache.\n\nMore often than not, the test failures occur in a module that has some React .tsx templates, but not always. Sometimes a pure Typescript module will fail.\n\n========================================\n\nTop Answer:\nCanceling the test watch and restarting it worked for me. with `Ctrl-D` then `npm test`\n\n========================================\n\nCode:\n```text\nCtrl-D\n```\n\n```text\nnpm test\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":45,"estimatedTokens":507}}310{"id":"stack-71408726","source":"stackoverflow","questionId":71408726,"title":"NestJS: How to customise log messages to include request id and name of the file the log message occurred","tags":["logging","nestjs","winston","nestjs-config","nest-winston"],"text":"Title: NestJS: How to customise log messages to include request id and name of the file the log message occurred\nTags: logging, nestjs, winston, nestjs-config, nest-winston\nSource: Stack Overflow\n\nQuestion:\nI am new to NestJS and would like to customise the log messages to include the x-request-id/x-correlation-id and the name of the file the log message originated but am not sure if there is anything in NestJS to do that.\n\nMy application is using NestJS with the Fastify adapter and has the following configuration in the bootstrap() function\n\n\r\n\r\n\n```\nconst app = await NestFactory.create(\n AppModule,\n new FastifyAdapter(),\n {\n logger: WinstonModule.createLogger(winston.createLogger({\n exitOnError: false,\n level: 'debug',\n handleExceptions: true,\n format: winston.format.combine(\n winston.format.timestamp(),\n winston.format.ms(),\n winston.format.colorize(),\n winston.format.align(),\n winston.format.splat(),\n winston.format.printf((info) => {\n return `${info.timestamp} [ ${info.level} ] : ${info.message}`;\n }),\n ),\n transports: [\n new (winston.transports.Console)()\n ]\n }),\n )\n }\n );\n```\n\n\r\n\r\n\r\n\nThis seems to format the logs using winston as expected.\n\n`2022-03-09T11:21:22.131Z [ info ] : Starting Nest application...`\n\nHowever, I would also like to include the request/correlation id in the message and the name of the file the log message occurred e.g.\n\n`2022-03-09T11:21:22.131Z 2cfd4eee-ca2b-4869-b66b-2b7da291f567 [ info ] [ Main.ts ]: Starting Nest application...`\n\nIs there anything in NestJS itself to allow this or any external libraries that I could use to achieve the desired result ?\n\n========================================\n\nTop Answer:\n- Assign a request ID. Make this your first `middleware`.\n\n- Bind the request context with `logger`. Make a class of `Logger`, bind the `request context` to logger. It will act basically as wrapper for `WinstonLogger`. Override all the methods of winston logger to print the request ID in form an manner which you want (preferred way is using JSON as it will be easier for you to query in logs).\n\n========================================\n\nCode:\n```js\nconst app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter(),\n    {\n        logger: WinstonModule.createLogger(winston.createLogger({\n          exitOnError: false,\n          level: 'debug',\n          handleExceptions: true,\n          format: winston.format.combine(\n            winston.format.timestamp(),\n            winston.format.ms(),\n            winston.format.colorize(),\n            winston.format.align(),\n            winston.format.splat(),\n            winston.format.printf((info) => {\n                return `${info.timestamp} [ ${info.level} ] : ${info.message}`;\n            }),\n          ),\n          transports: [\n            new (winston.transports.Console)()\n          ]\n        }),\n      )\n    }\n  );\n```\n\n```text\n2022-03-09T11:21:22.131Z [ info ] :     Starting Nest application...\n```\n\n```text\n2022-03-09T11:21:22.131Z 2cfd4eee-ca2b-4869-b66b-2b7da291f567 [ info ] [ Main.ts ]:     Starting Nest application...\n```\n\n```js\n// main.ts\n\nimport { Logger } from 'nestjs-pino';\n\nasync function bootstrap() {\n\nconst app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter(),\n    { bufferLogs: true }\n  );\n\n  app.useLogger(app.get(Logger));\n  \n}\nbootstrap();\n```\n\n```js\n// app.module.ts\n\nimport { LoggerModule } from 'nestjs-pino';\n\n@Module({\n  imports: [\n    LoggerModule.forRoot({\n      pinoHttp: {\n        level: process.env.LOG_LEVEL || 'debug',\n        redact: ['request.headers.authorization'],\n        prettyPrint: {\n          colorize: true,\n          singleLine: true,\n          levelFirst: false,\n          translateTime: \"yyyy-MM-dd'T'HH:mm:ss.l'Z'\",\n          messageFormat: \"{req.headers.x-correlation-id} [{context}] {msg}\",\n          ignore: \"pid,hostname,context,req,res,responseTime\",\n          errorLikeObjectKeys: ['err', 'error']\n        }\n      }\n    }),\n  ],\n  controllers: [MyController],\n})\nexport class AppModule {}\n```\n\n```js\n// my.controller.ts\nimport { Controller, Get, Param, Logger } from '@nestjs/common';\n\n@Controller()\nexport class MyController {\n    private readonly logger: Logger = new Logger(MyController.name);\n\n    @Get('/:id')\n    async getCustomerDetails(@Headers() headers, @Param('id') id: string): Promise<Customer> {\n        this.logger.log(`Accepted incoming request with id: ${id}`);\n\n        // Do some processing ....\n\n        return customer;\n    }\n}\n```\n\n```js\n[2022-11-14T11:03:07.100Z] INFO: 428f0df9-d12b-4fca-9b11-805a13ff41be [MyController] Accepted incoming request with id: 1\n```\n\n```js\n// app.module.ts\n\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { LoggerModule } from 'nestjs-pino';\n\n@Module({\n  imports: [\n    LoggerModule.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        pinoHttp: {\n          level: process.env.LOG_LEVEL || 'info',\n          redact: configService.get<string[]>('logger.redacted.fields'),\n          prettyPrint: {\n            colorize: false,\n            singleLine: true,\n            levelFirst: false,\n            translateTime: \"yyyy-mm-dd'T'HH:MM:ss.l'Z'\",\n            messageFormat: '{req.headers.x-correlation-id} [{context}] {msg}',\n            ignore: 'pid,hostname,context,req,res,responseTime',\n            errorLikeObjectKeys: ['err', 'error'],\n          },\n        },\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n  controllers: [MyController],\n})\nexport class AppModule {}\n```\n\n```text\nlogger:\n    redacted:\n        fields:\n            - 'headers.Authorization'\n            - 'headers[\"X-Api-Key\"]'\n```\n\n```text\nmiddleware\n```\n\n```text\nlogger\n```\n\n```text\nLogger\n```\n\n```text\nrequest context\n```\n\n```text\nWinstonLogger\n```\n\n```text\nconst { format} = require(\"winston\");\nvar reqId = '123123' //function or const request id\nconst addRequestId = format((info, opts) => {\n    if(reqId)\n        info.reqId= reqId;\n    return info;\n});\n```\n\n```text\nvar config = {\nformat: format.combine(\n  addRequestId(),\n  format.timestamp(new Date().toISOString()),\n  format.json(),\n),\ntransports: [new transports.Console()],\nlevel: 'debug'\n }\nconst logger = createLogger(config);\n```\n\n```js\nimport { utilities } from 'nest-winston';\nimport winston, { createLogger } from 'winston';\n\nimport { environment } from '../../environments/environment';\n\nexport const appLogger = createLogger({\n  level: environment.logLevel,\n  format: winston.format.combine(\n    winston.format.timestamp(),\n    winston.format.ms(),\n  ),\n  transports: [\n    new winston.transports.Console({\n      forceConsole: environment.logForceConsole,\n      format: winston.format.combine(\n        environment.logAsJson\n          ? winston.format.json()\n          : utilities.format.nestLike('YOUR-APP', {\n              colors: true,\n              prettyPrint: true,\n            }),\n      ),\n    }),\n    ...(environment.enableLogFile\n      ? [\n          new winston.transports.DailyRotateFile({\n            json: environment.logAsJson,\n            filename: environment.pathToLogFile,\n            level: environment.logLevel,\n            datePattern: 'YYYY-MM-DD-HH',\n            zippedArchive: true,\n            maxSize: '20m',\n            maxFiles: '14d',\n          }),\n        ]\n      : []),\n  ],\n});\n```\n\n```js\nimport { Inject, Injectable, LoggerService, Scope } from '@nestjs/common';\nimport type { Logger as WinstonLogger } from 'winston';\n\nimport { CustomRequest } from '../../context-propagation/types/custom-request.type';\n\nimport { appLogger } from '../utils/app-logger.util';\n\n@Injectable({ scope: Scope.TRANSIENT })\nexport class TrackableLogger implements LoggerService {\n  constructor(\n    @Inject('INQUIRER') inquirer: object,\n    @Inject('NJRS_REQUEST')\n    private readonly request: CustomRequest | null | undefined,\n  ) {\n    this.logger = appLogger.child({ context: inquirer.constructor.name });\n  }\n\n  private getTraceId() {\n    if (!this.request) {\n      return crypto.randomUUID();\n    }\n\n    if (!this.request.traceId) {\n      this.request.traceId = crypto.randomUUID();\n    }\n\n    return this.request.traceId;\n  }\n\n  private readonly logger: WinstonLogger;\n\n  log(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.info(message, { traceId, ...params });\n  }\n\n  info(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.info(message, { traceId, ...params });\n  }\n\n  fatal(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.error(message, { traceId, ...params });\n  }\n\n  error(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.error(message, { traceId, ...params });\n  }\n\n  warn(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.warn(message, { traceId, ...params });\n  }\n\n  debug(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.debug(message, { traceId, ...params });\n  }\n\n  verbose(message: string, params?: object) {\n    const traceId = this.getTraceId();\n    this.logger.verbose(message, { traceId, ...params });\n  }\n}\n```\n\n```js\n@Resolver(Foo)\nexport class FooResolver {\n  constructor(\n    private readonly service: FooService,\n    private readonly logger: TrackableLogger,\n  ) {}\n}\n```\n\n```json\n{\"context\":\"FooResolver\",\"level\":\"info\",\"message\":\"foo\",\"ms\":\"+1ms\",\"timestamp\":\"2025-01-27T15:59:53.347Z\",\"traceId\":\"e20451d0-089f-41fd-bdbd-88773c6c71e5\"}\n```\n\n```text\ninquierer\n```\n\n```text\nnj-request-scope\n```\n\n========================================\n\nComments:\n- Underrated answer\n- Do you mind providing a snipped on how to do this: \"Make a class of Logger, bind the request context to logger.\" ? :)\n- @DanielEberl some of the snippets are here: github.com/Adityagaddhyan/logger-snippet-node They are in JS but you can write your own on same lines in NestJS or TS. Nest has library function for request context.\n- The above answer is correct. But if anyone wants to use Pino as their logger and not the default Logger provided by NestJS, then add the below line in the constructor of your controller or provider: `@InjectPinoLogger(MyController.name) private readonly logger: PinoLogger` Now simply using `this.logger.info({msg: 'controller data'})` would work like a charm.\n- Hi there, I want add same request id for typeorm log. How can I do this? Because I just want to get all log of a request (process controller, data and orm log as well)\n- That Medium article is paywalled. Here's the archived version archive.ph/Q67nv\n- @NguyenRuby I tried it and it turned out that serializer won't change the request object we can get by using `@Req` in our controller. Look at this GH repo to learn more.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":396,"estimatedTokens":2704}}311{"id":"stack-63785711","source":"stackoverflow","questionId":63785711,"title":"Jest Matcher error: received value must be a promise or a function returning a promise","tags":["typescript","exception","promise","jestjs","nestjs"],"text":"Title: Jest Matcher error: received value must be a promise or a function returning a promise\nTags: typescript, exception, promise, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am a TDD practitioner and I am trying to implement an Exception.\n\nHere is the test code:\n\n```\nit.each([[{ id: '', token: '', skills: [''] }, 'Unknown resource']])(\n 'should return an Exception when incorrect dto data',\n async (addSkillsDto: AddSkillsDto) => {\n await expect(() => {\n controller.addSkills(addSkillsDto)\n }).rejects.toThrow()\n }\n )\n```\n\nHere is the related code:\n\n```\n@Post('candidate/add-skills')\n async addSkills(\n @Body() skills: AddSkillsDto,\n ): Promise> {\n const data = await this.candidateService.addSkills(skills)\n console.log(data, !data)\n if (!data) throw new HttpException('Unknown resource', HttpStatus.NOT_FOUND)\n else\n return {\n success: true,\n data,\n meta: null,\n message: ResponseMessage.SKILLS_ADDED,\n }\n }\n```\n\nHere is the console output when running Jest:\n\n```\nโ— Candidate Controller โ€บ should return an Exception when incorrect dto data\n\n expect(received).rejects.toThrow()\n\n Matcher error: received value must be a promise or a function returning a promise\n\n Received has type: function\n Received has value: [Function anonymous]\n\n 88 | await expect(() => {\n 89 | controller.addSkills(addSkillsDto)\n > 90 | }).rejects.toThrow()\n | ^\n 91 | }\n 92 | )\n 93 |\n\n at Object.toThrow (../node_modules/expect/build/index.js:226:11)\n at candidate/candidate.controller.spec.ts:90:18\n\n console.log\n null true\n\n at CandidateController.addSkills (candidate/candidate.controller.ts:75:13)\n\nTest Suites: 1 failed, 1 total\n```\n\nI am not sure what I am suppose to write to make it pass.\n\n========================================\n\nCode:\n```text\nit.each([[{ id: '', token: '', skills: [''] }, 'Unknown resource']])(\n    'should return an Exception when incorrect dto data',\n    async (addSkillsDto: AddSkillsDto) => {\n      await expect(() => {\n        controller.addSkills(addSkillsDto)\n      }).rejects.toThrow()\n    }\n  )\n```\n\n```text\n@Post('candidate/add-skills')\n  async addSkills(\n    @Body() skills: AddSkillsDto,\n  ): Promise<StandardResponseObject<[]>> {\n    const data = await this.candidateService.addSkills(skills)\n    console.log(data, !data)\n    if (!data) throw new HttpException('Unknown resource', HttpStatus.NOT_FOUND)\n    else\n      return {\n        success: true,\n        data,\n        meta: null,\n        message: ResponseMessage.SKILLS_ADDED,\n      }\n  }\n```\n\n```text\nโ— Candidate Controller โ€บ should return an Exception when incorrect dto data\n\n    expect(received).rejects.toThrow()\n\n    Matcher error: received value must be a promise or a function returning a promise\n\n    Received has type:  function\n    Received has value: [Function anonymous]\n\n      88 |       await expect(() => {\n      89 |         controller.addSkills(addSkillsDto)\n    > 90 |       }).rejects.toThrow()\n         |                  ^\n      91 |     }\n      92 |   )\n      93 |\n\n      at Object.toThrow (../node_modules/expect/build/index.js:226:11)\n      at candidate/candidate.controller.spec.ts:90:18\n\n  console.log\n    null true\n\n      at CandidateController.addSkills (candidate/candidate.controller.ts:75:13)\n\nTest Suites: 1 failed, 1 total\n```\n\n```text\nawait expect(() => {\n  controller.addSkills(addSkillsDto)\n}).rejects.toThrow()\n```\n\n```text\nawait expect(controller.addSkills(addSkillsDto)).rejects.toThrow()\n```\n\n```text\nexpect\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":147,"estimatedTokens":859}}312{"id":"stack-60575295","source":"stackoverflow","questionId":60575295,"title":"How to get handler route in NestJS Interceptor (For both Express and Fastify)","tags":["express","nestjs","fastify"],"text":"Title: How to get handler route in NestJS Interceptor (For both Express and Fastify)\nTags: express, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI am having issues trying to get a hold of the NestJS handler's route in an interceptor I am writing. For instance, if a Controller had a route as such:\n\n```\n@Get('/params/:p1/:p2')\n routeWithParams(@Param() params): string {\n return `params are ${params.p1} and ${params.p2}`;\n }\n```\n\nI would like the ability to grab the value `/param/:p1/:p2` programatically. Using the url and deparameterizing is NOT an option, as there is not really a way to do so in a %100 airtight manner. Did some digging and have not found a documented way to grab the route for the handler. Wondering if anyone else has had luck? Here is some example code I stripped down from my project:\n\n```\nimport { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { Request } from 'express';\nimport { FastifyRequest } from 'fastify';\n\nfunction isExpressRequest(request: Request | FastifyRequest): request is Request {\n return (request as FastifyRequest).req === undefined;\n}\n\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n const request: Request | FastifyRequest = context.switchToHttp().getRequest();\n\n if( !isExpressRequest(request) ) { // if req fufills the FastifyRequest interface, we will rename the transaction\n const req = request as FastifyRequest;\n const route = `` // TODO how can I grab the route either using the FastifyRequest or ExecutionContext??\n } // otherwise, we are in express request\n const route = `` // TODO how can I grab the route either using the Request or ExecutionContext?\n\n return next.handle();\n }\n}\n```\n\nIf it turns out that an interceptor won't do the trick and something else like a Guard could work to grab this information I'm all ears.\n\n========================================\n\nTop Answer:\nTo retrieve the request full path without directly using the `Request`, you can make use of `Reflector` and the `ApplicationConfig` injectable in the following way :\n\n```\nimport { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';\nimport { ApplicationConfig, Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { PATH_METADATA } from '@nestjs/common/constants';\nimport * as path from 'path';\n\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n constructor(\n private readonly reflector: Reflector,\n private readonly appConfig: ApplicationConfig\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n\n const globalPath = this.appConfig.getGlobalPrefix();\n const controllerPath = this.reflector.get(PATH_METADATA, context.getClass());\n const routeHandlerPath = this.reflector.get(PATH_METADATA, context.getHandler());\n \n const path = path.join(globalPath, controllerPath, routeHandlerPath)\n \n // Do something with path\n\n return next.handle();\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Get('/params/:p1/:p2')\n  routeWithParams(@Param() params): string {\n    return `params are ${params.p1} and ${params.p2}`;\n  }\n```\n\n```text\nimport { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { Request } from 'express';\nimport { FastifyRequest } from 'fastify';\n\nfunction isExpressRequest(request: Request | FastifyRequest): request is Request {\n  return (request as FastifyRequest).req === undefined;\n}\n\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const request: Request | FastifyRequest = context.switchToHttp().getRequest();\n\n    if( !isExpressRequest(request) ) { // if req fufills the FastifyRequest interface, we will rename the transaction\n      const req = request as FastifyRequest;\n      const route = `` // TODO how can I grab the route either using the FastifyRequest or ExecutionContext??\n    } // otherwise, we are in express request\n    const route = `` // TODO how can I grab the route either using the Request or ExecutionContext?\n\n    return next.handle();\n  }\n}\n```\n\n```text\n/param/:p1/:p2\n```\n\n```js\nimport { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { Request } from 'express';\nimport { FastifyRequest } from 'fastify';\nimport { PATH_METADATA } from '@nestjs/common/constants';\n\nfunction isExpressRequest(request: Request | FastifyRequest): request is Request {\n  return (request as FastifyRequest).req === undefined;\n}\n\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n  constructor(private readonly reflector: Reflector) {}\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const request: Request | FastifyRequest = context.switchToHttp().getRequest();\n\n    const path = this.reflector.get<string[]>(PATH_METADATA, context.getHandler()); \n    const method = isExpressRequest(request) ? request.method : (request as FastifyRequest).req.method;\n\n    // can now do something with the path and method\n\n    return next.handle();\n  }\n}\n```\n\n```text\nReflectors\n```\n\n```text\nPATH_METADATA\n```\n\n```text\nimport { Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';\nimport { ApplicationConfig, Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { PATH_METADATA } from '@nestjs/common/constants';\nimport * as path from 'path';\n\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n  constructor(\n    private readonly reflector: Reflector,\n    private readonly appConfig: ApplicationConfig\n  ) {}\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n\n    const globalPath = this.appConfig.getGlobalPrefix();\n    const controllerPath = this.reflector.get<string>(PATH_METADATA, context.getClass());\n    const routeHandlerPath = this.reflector.get<string>(PATH_METADATA, context.getHandler());\n    \n    const path = path.join(globalPath, controllerPath, routeHandlerPath)\n    \n    // Do something with path\n\n    return next.handle();\n  }\n}\n```\n\n```text\nRequest\n```\n\n```text\nReflector\n```\n\n```text\nApplicationConfig\n```\n\n========================================\n\nComments:\n- I found that this approach wouldn't quite work if you wanted to get the full path (including controller level path and global prefix). For that, I resorted to using `const path = context.switchToHttp().getRequest().route?.path`, which seems to work fine.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":203,"estimatedTokens":1732}}313{"id":"stack-60361397","source":"stackoverflow","questionId":60361397,"title":"setting up a one to many relationship for a self referencing table","tags":["sql","postgresql","orm","nestjs","typeorm"],"text":"Title: setting up a one to many relationship for a self referencing table\nTags: sql, postgresql, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a `Project` entity with a non-autogenerated id field and a successor field. This successor is the project that follows next. But maybe there is no following project so this might be null.\n\n```\n@Entity()\nexport class Project extends BaseEntity {\n @PrimaryColumn({ unique: true })\n public id: string;\n\n @OneToMany(() => Project, project => project.id, { nullable: true })\n public successorId?: string;\n}\n```\n\nWhen creating a new project via\n\n```\npublic createProject(id: string, successorId?: string): Promise {\n const project: Project = new Project();\n project.id = id;\n project.successorId = successorId;\n return project.save();\n}\n```\n\nthere are multiple cases I have to take care for.\n\nPassing in an id that already exists:\n\nThis will not throw an error. It just overrides the existing entity.\n\nPassing in `undefined` for the `successorId`:\n\nThe code works fine then but it does not create a `successorId` column with `null` then. The column simply does not exist in the database.\n\nPassing in the same id for `id` and `successorId` (this should be possible):\n\nTypeORM throws the error \n\n TypeError: Cannot read property 'joinColumns' of undefined\n\nPassing in a `successorId` of another existing project:\n\nI'm getting the same error as above\n\nPassing in a `successorId` of a project that doesn't exist:\n\nI'm getting the same error as above\n\nSo how can I fix that? I think my entity design seems to be wrong. Basically it should be\n\n- One project might have one successor\n\n- A project can be the successor of many projects\n\nWould be awesome if someone could help!\n\n**Update**\n\nI also tried this\n\n```\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\n@Column()\npublic successorId?: string;\n```\n\nbut whenever I want to call the `createProject` method I'm getting this error\n\n QueryFailedError: null value in column \"successorId\" violates not-null\n constraint\n\nand this\n\n```\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\npublic successorId?: string;\n```\n\nbut then I'm getting this error\n\n TypeError: relatedEntities.forEach is not a function\n\n========================================\n\nTop Answer:\nYou can try this\n\n```\nexport class RolesPermission {\n @PrimaryGeneratedColumn('uuid')\n @PrimaryColumn({ type: 'varchar', length: 36, default: 'UUID()' })\n entityId?: string;\n\n @Column({ unique: true })\n name: string;\n\n @OneToMany(() => RolesPermission, (rolePermission) => rolePermission.parent)\n rolePermissions?: RolesPermission[];\n\n @ManyToOne(() => RolesPermission, (rolePermission) => rolePermission.rolePermissions, { nullable: true, createForeignKeyConstraints: false })\n parent?: RolesPermission;\n\n @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })\n createdAt?: Date;\n\n @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' })\n updatedAt?: Date;}\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Project extends BaseEntity {\n  @PrimaryColumn({ unique: true })\n  public id: string;\n\n  @OneToMany(() => Project, project => project.id, { nullable: true })\n  public successorId?: string;\n}\n```\n\n```text\npublic createProject(id: string, successorId?: string): Promise<Project> {\n  const project: Project = new Project();\n  project.id = id;\n  project.successorId = successorId;\n  return project.save();\n}\n```\n\n```text\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\n@Column()\npublic successorId?: string;\n```\n\n```text\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\npublic successorId?: string;\n```\n\n```text\nProject\n```\n\n```text\nundefined\n```\n\n```text\nsuccessorId\n```\n\n```text\nsuccessorId\n```\n\n```text\nnull\n```\n\n```text\nid\n```\n\n```text\nsuccessorId\n```\n\n```text\nsuccessorId\n```\n\n```text\nsuccessorId\n```\n\n```text\ncreateProject\n```\n\n```text\n@Entity()\nexport class Project extends BaseEntity {\n  @PrimaryColumn({ unique: true })\n  public id: string;\n\n  @Column({ nullable: true })\n  public successorId?: string;\n\n  @ManyToOne(() => Project, project => project.id)\n  @JoinColumn({ name: \"successorId\" })\n  public successor?: Project;\n}\n```\n\n```text\npublic successor?: Project;\n```\n\n```text\npublic successorId?: string;\n```\n\n```text\nManyToOne\n```\n\n```text\npropertyName\n```\n\n```text\nreferencedColumnName\n```\n\n```text\nsuccessorId\n```\n\n```text\n@Column\n```\n\n```text\nexport class RolesPermission {\n  @PrimaryGeneratedColumn('uuid')\n  @PrimaryColumn({ type: 'varchar', length: 36, default: 'UUID()' })\n  entityId?: string;\n\n  @Column({ unique: true })\n  name: string;\n\n  @OneToMany(() => RolesPermission, (rolePermission) => rolePermission.parent)\n  rolePermissions?: RolesPermission[];\n\n  @ManyToOne(() => RolesPermission, (rolePermission) => rolePermission.rolePermissions, { nullable: true, createForeignKeyConstraints: false })\n  parent?: RolesPermission;\n\n  @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })\n  createdAt?: Date;\n\n  @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' })\n  updatedAt?: Date;}\n```\n\n========================================\n\nComments:\n- I tested your solution and I think this seems to work. Would you mind explaining why two fields are required? And it knows how to map that field to a variable via string?\n- The only case still failing was the first part. Creating an entity with the same id just overrides the existing one ..\n- yes, I was able to reproduce it with this sample repo :) github.com/mhcomp/&hellip;\n- ok, one last question: The code seems to work fine but are you sure a `ManyToOne` relation should be used instead of a `OneToMany` relation?\n- yep, in TypeORM `@OneToMany` is an inverse side of `@ManyToOne` and cannot exist without `@ManyToOne`. Also `@OneToMany` is not required and can be ommited in this case. For example if you need \"projects which before successor\" or in other words \"projects in which this project is specified as successor\" then you need to use `OneToMany` as inverse side. It will look like `@OneToMany(() => Project, project => project.successor) public projects: Project[]`\n- btw, I don't know your requirements about successor. If a one successor can be specified in many projects, then `@ManyToOne` is right approach. Otherwise if one succesor can only one project, then you should use `@OneToOne` relation instead.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":262,"estimatedTokens":1627}}314{"id":"stack-44078305","source":"stackoverflow","questionId":44078305,"title":"Running nest.js from VS Code","tags":["node.js","typescript","nestjs"],"text":"Title: Running nest.js from VS Code\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo, I'm playing around with this new framework http://nestjs.com/ who seems pretty awesome since it allows the usage of Typescript on Node, very likely to angular.\n\nUsing the starter https://github.com/kamilmysliwiec/nest-typescript-starter, I can run it with `npm run start` without any problem, but since there is a .vscode on the project, I assumed I could use VS Code to run and gain some debug abilities.\n\nThe problem is that when I run directly from VS Code, without changing anything in the code, I get the following problem:\n\n`Error: Cannot find module 'nest.js'`\n\nI tried to run from VS Code with and without it running from NPM, no success.\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nTo debug with nestjs app.\nIn 2020, after I first-step.\nIn VS code change default setting from:\n\n```\n\"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch Program\",\n \"skipFiles\": [\n \"/**\"\n ],\n \"program\": \"${workspaceFolder}/start\",\n \"preLaunchTask\": \"tsc: build - tsconfig.json\",\n \"outFiles\": [\n \"${workspaceFolder}/dist/**/*.js\"\n ]\n }\n ]\n```\n\nto this:\n\n```\n\"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Launch Program\",\n \"skipFiles\": [\"/**\"],\n \"program\": \"${workspaceFolder}/src/main.ts\",\n \"preLaunchTask\": \"tsc: build - tsconfig.json\",\n \"outFiles\": [\"${workspaceFolder}/dist/**/*.js\"]\n }\n ]\n```\n\nAnd press F5 to debug.\nIt works perfectly with me.\n\n========================================\n\nCode:\n```text\nnpm run start\n```\n\n```text\nError: Cannot find module 'nest.js'\n```\n\n```text\nnest-typescript-starter\n```\n\n```text\ndist\n```\n\n```text\nnpm run start:prod\n```\n\n```text\n{\n    // Use IntelliSense to learn about possible attributes.\n    // Hover to view descriptions of existing attributes.\n    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"type\": \"node\",\n            \"request\": \"launch\",\n            \"name\": \"Launch Program\",\n            \"program\": \"${workspaceFolder}\\\\src\\\\main.ts\",\n            \"preLaunchTask\": \"tsc: build - tsconfig.json\",\n            \"outFiles\": [\n                \"${workspaceFolder}/dist/**/*.js\"\n            ]\n        }\n    ]\n}\n```\n\n```text\nlaunch.json\n```\n\n```text\n\"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"node\",\n      \"request\": \"launch\",\n      \"name\": \"Launch Program\",\n      \"skipFiles\": [\n        \"<node_internals>/**\"\n      ],\n      \"program\": \"${workspaceFolder}/start\",\n      \"preLaunchTask\": \"tsc: build - tsconfig.json\",\n      \"outFiles\": [\n        \"${workspaceFolder}/dist/**/*.js\"\n      ]\n    }\n  ]\n```\n\n```text\n\"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"node\",\n      \"request\": \"launch\",\n      \"name\": \"Launch Program\",\n      \"skipFiles\": [\"<node_internals>/**\"],\n      \"program\": \"${workspaceFolder}/src/main.ts\",\n      \"preLaunchTask\": \"tsc: build - tsconfig.json\",\n      \"outFiles\": [\"${workspaceFolder}/dist/**/*.js\"]\n    }\n  ]\n```\n\n========================================\n\nComments:\n- Apparently changing the launch.json to be `\"program\": \"${workspaceRoot}\\\\index.js\"` instead of `\"program\": \"${workspaceRoot}\\\\src\\\\server.ts\"` and removing `outFiles` did the job. I will leave it here to see if it's correct.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":149,"estimatedTokens":855}}315{"id":"stack-67547621","source":"stackoverflow","questionId":67547621,"title":"CannotDetermineEntityError when saving entities with TypeORM","tags":["nestjs","typeorm"],"text":"Title: CannotDetermineEntityError when saving entities with TypeORM\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI created a NestJS and used TypeORM for the RDBMS(I used postgres in my project).\n\n`Post` is an `@Entity` class, `PostRepository` is a `Repository` class for `Post`.\n\nI was trying to create `OnModuleInit` service to initialize some data.\n\n```\n@Injectable()\nexport class PostsDataInitializer implements OnModuleInit {\n private data: Post[] = [\n {\n title: 'Generate a NestJS project',\n content: 'content',\n },\n {\n title: 'Create GrapQL APIs',\n content: 'content',\n },\n {\n title: 'Connect to Postgres via TypeORM',\n content: 'content',\n },\n ];\n\n constructor(private readonly postRepository: PostRepository) {}\n async onModuleInit(): Promise {\n await this.postRepository.manager.transaction(async (manager) => {\n // NOTE: you must perform all database operations using the given manager instance\n // it's a special instance of EntityManager working with this transaction\n // and don't forget to await things here\n await manager.delete(Post, {});\n console.log('deleted: {} ');\n this.data.forEach(async (d) => await manager.save(d as Post));\n const savedPosts = await manager.find(Post);\n savedPosts.forEach((p) => {\n console.log('saved: {}', p);\n });\n });\n }\n}\n```\n\nWhen starting up the application, I got the following error.\n\n```\nCannotDetermineEntityError: Cannot save, given value must be instance of entity class, instead object literal is given. Or you must specify an entity target to method call.\n```\n\n*But the above `save` was accepting an instance of `Post`*.\n\n========================================\n\nTop Answer:\nYou can alternatively specify the target type as per the error message like so:\n\n```\nawait manager.save(Post, d)\n```\n\nFrom the documentation of save() I see there is such a method as:\n\n```\nsave>(targetOrEntity: EntityTarget, entity: T, options?: SaveOptions): Promise;\n```\n\nnest version 9.1.8\n\n========================================\n\nCode:\n```java\n@Injectable()\nexport class PostsDataInitializer implements OnModuleInit {\n  private data: Post[] = [\n    {\n      title: 'Generate a NestJS project',\n      content: 'content',\n    },\n    {\n      title: 'Create GrapQL APIs',\n      content: 'content',\n    },\n    {\n      title: 'Connect to Postgres via TypeORM',\n      content: 'content',\n    },\n  ];\n\n  constructor(private readonly postRepository: PostRepository) {}\n  async onModuleInit(): Promise<void> {\n    await this.postRepository.manager.transaction(async (manager) => {\n      // NOTE: you must perform all database operations using the given manager instance\n      // it's a special instance of EntityManager working with this transaction\n      // and don't forget to await things here\n      await manager.delete(Post, {});\n      console.log('deleted: {} ');\n      this.data.forEach(async (d) => await manager.save(d as Post));\n      const savedPosts = await manager.find<Post>(Post);\n      savedPosts.forEach((p) => {\n        console.log('saved: {}', p);\n      });\n    });\n  }\n}\n```\n\n```sh\nCannotDetermineEntityError: Cannot save, given value must be instance of entity class, instead object literal is given. Or you must specify an entity target to method call.\n```\n\n```text\nPost\n```\n\n```text\n@Entity\n```\n\n```text\nPostRepository\n```\n\n```text\nRepository\n```\n\n```text\nPost\n```\n\n```text\nOnModuleInit\n```\n\n```text\nsave\n```\n\n```text\nPost\n```\n\n```js\nprivate data = [\n    {\n      title: 'Generate a NestJS project',\n      content: 'content',\n    },\n    {\n      title: 'Create GrapQL APIs',\n      content: 'content',\n    },\n    {\n      title: 'Connect to Postgres via TypeORM',\n      content: 'content',\n    },\n  ].map(data => {\n    const post = new Post();\n    Object.assign(post, data);\n    return post;\n  })\n```\n\n```text\n.save\n```\n\n```js\nawait manager.save(Post, d)\n```\n\n```js\nsave<Entity, T extends DeepPartial<Entity>>(targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions): Promise<T & Entity>;\n```\n\n========================================\n\nComments:\n- I used `d as Post` to cast it to `Post`, why this does not work. What is the difference between object literal and instance in typescript?\n- the difference isn't up to ts but to js. `new Foo()` objects will be `instance of Foo`, while a literal object that just has the shape of `Foo` won't. And TypeORM expect to work with instances of `Foo`\n- btw typecasting in strongly typed languages allow us to convert types. Since javascript is not strongly typed, the *type assertion* that you used will no longer exist at runtime. See this example\n- Works better for me than the accepted answer\n- This answer worked well for me.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":188,"estimatedTokens":1161}}316{"id":"stack-51313852","source":"stackoverflow","questionId":51313852,"title":"Docker Compose cannot connect to database","tags":["docker","docker-compose","typeorm","nestjs"],"text":"Title: Docker Compose cannot connect to database\nTags: docker, docker-compose, typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using nestjs for my backend and using typeorm as ORM.\nI tried to define my database and my application in an docker-compose file. \n\nIf I'm running my database as a container and my application from my local machine it works well. My program connects and creates the tables etc.\n\nBut if I try to connect the database from within my container or to start the container with docker-compose up it fails.\n\nAlways get an ECONNREFUSED Error.\n\nWhere is my mistake ?\n\ndocker-compose.yml\n\n```\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n db:\n image: postgres:10\n volumes:\n - ./dbData/:/var/lib/postgresql/data\n restart: always\n environment:\n - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n - POSTGRES_USER=${TYPEORM_USERNAME}\n - POSTGRES_DB=${TYPEORM_DATABASE}\n ports:\n - ${TYPEORM_PORT}:5432\n\n backend:\n build: .\n ports:\n - \"3001:3000\"\n command: npm run start\n volumes:\n - .:/src\n```\n\nDockerfile\n\n```\nFROM node:10.5\n\nWORKDIR /home\n\n# Bundle app source\nCOPY . /home\n\n# Install app dependencies\n#RUN npm install -g nodemon\n# If you are building your code for production\n# RUN npm install --only=production\nRUN npm i -g @nestjs/cli\nRUN npm install\n\nEXPOSE 3000\n```\n\n.env\n\n```\n# .env\nHOST=localhost\nPORT=3000\nNODE_ENV=development\nLOG_LEVEL=debug\n\nTYPEORM_CONNECTION=postgres\nTYPEORM_HOST=localhost\nTYPEORM_USERNAME=postgres\nTYPEORM_PASSWORD=postgres\nTYPEORM_DATABASE=mariokart\nTYPEORM_PORT=5432\nTYPEORM_SYNCHRONIZE=true\nTYPEORM_DROP_SCHEMA=true\nTYPEORM_LOGGING=all\nTYPEORM_ENTITIES=src/database/entity/*.ts\nTYPEORM_MIGRATIONS=src/database/migrations/**/*.ts\nTYPEORM_SUBSCRIBERS=src/database/subscribers/**/*.ts\n```\n\nI tried to use links but it don't work in the container.\n\n========================================\n\nTop Answer:\nYou can create a network and among two services.\n\nCreate network for db and backend services:\n\n```\nnetworks:\n common-net: {}\n```\n\nand add the network to these two services. So your .yml file would like below after edit:\n\n```\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n db:\n image: postgres:10\n volumes:\n - ./dbData/:/var/lib/postgresql/data\n restart: always\n environment:\n - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n - POSTGRES_USER=${TYPEORM_USERNAME}\n - POSTGRES_DB=${TYPEORM_DATABASE}\n ports:\n - ${TYPEORM_PORT}:5432\n networks:\n - common-net\n\n backend:\n build: .\n ports:\n - \"3001:3000\"\n command: npm run start\n volumes:\n - .:/src\n networks:\n - common-net\n\nnetworks:\n common-net: {}\n```\n\n### Note1: After this change, there is no need to expose the Postgres port externally unless you have a reason for it. You can remove that section.\n\n### Note2: TYPEORM_HOST should be renamed to db. Docker would resolve the IP address of db service by itself.\n\n========================================\n\nCode:\n```text\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n  db:\n    image: postgres:10\n    volumes:\n      - ./dbData/:/var/lib/postgresql/data\n    restart: always\n    environment:\n      - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n      - POSTGRES_USER=${TYPEORM_USERNAME}\n      - POSTGRES_DB=${TYPEORM_DATABASE}\n    ports:\n      - ${TYPEORM_PORT}:5432\n\n  backend:\n    build: .\n    ports:\n      - \"3001:3000\"\n    command: npm run start\n    volumes:\n      - .:/src\n```\n\n```text\nFROM node:10.5\n\nWORKDIR /home\n\n# Bundle app source\nCOPY . /home\n\n# Install app dependencies\n#RUN npm install -g nodemon\n# If you are building your code for production\n# RUN npm install --only=production\nRUN npm i -g @nestjs/cli\nRUN npm install\n\nEXPOSE 3000\n```\n\n```text\n# .env\nHOST=localhost\nPORT=3000\nNODE_ENV=development\nLOG_LEVEL=debug\n\nTYPEORM_CONNECTION=postgres\nTYPEORM_HOST=localhost\nTYPEORM_USERNAME=postgres\nTYPEORM_PASSWORD=postgres\nTYPEORM_DATABASE=mariokart\nTYPEORM_PORT=5432\nTYPEORM_SYNCHRONIZE=true\nTYPEORM_DROP_SCHEMA=true\nTYPEORM_LOGGING=all\nTYPEORM_ENTITIES=src/database/entity/*.ts\nTYPEORM_MIGRATIONS=src/database/migrations/**/*.ts\nTYPEORM_SUBSCRIBERS=src/database/subscribers/**/*.ts\n```\n\n```text\n192.0.18.1    dir_db_1\n```\n\n```text\nservices:\n  db:\n    container_name: project_db\n    ...\n  backend:\n    container_name: project_backend\n```\n\n```text\n/etc/hosts\n```\n\n```text\nbackend\n```\n\n```text\ndir\n```\n\n```text\nTYPEORM_HOST=localhost\n```\n\n```text\nTYPEORM_HOST=dir_db_1\n```\n\n```text\nTYPEORM_HOST=project_db\n```\n\n```text\nnetworks:\n  common-net: {}\n```\n\n```text\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n  db:\n    image: postgres:10\n    volumes:\n      - ./dbData/:/var/lib/postgresql/data\n    restart: always\n    environment:\n      - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n      - POSTGRES_USER=${TYPEORM_USERNAME}\n      - POSTGRES_DB=${TYPEORM_DATABASE}\n    ports:\n      - ${TYPEORM_PORT}:5432\n    networks:\n      - common-net\n\n  backend:\n    build: .\n    ports:\n      - \"3001:3000\"\n    command: npm run start\n    volumes:\n      - .:/src\n    networks:\n      - common-net\n\n\nnetworks:\n  common-net: {}\n```\n\n```text\nversion: '0.0.1'\nservices:\n  postgresdb:\n    container_name: postgresdb\n    image: postgres:14\n    restart: always\n    environment:\n      - POSTGRES_PASSWORD=mysecretpassword\n      - POSTGRES_DB=dummy_db\n      - POSTGRES_USER=postgres\n  web:\n    image: server01:tag01\n    ports:\n      - 3000:3000\n    environment:\n      - POSTGRES_HOST=postgresdb\n```\n\n========================================\n\nComments:\n- doesn't docker compose create a common network for the containers by default ?\n- Yes! You're right. Changing the typeorm_hostname will solve the issue.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":312,"estimatedTokens":1373}}317{"id":"stack-70994389","source":"stackoverflow","questionId":70994389,"title":"Is it possible to validate that one of 2 parameters are present using class-validator?","tags":["javascript","typescript","validation","nestjs","class-validator"],"text":"Title: Is it possible to validate that one of 2 parameters are present using class-validator?\nTags: javascript, typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nUsing class-validator along with NestJS I want to validate that a user provides either `propertyA` or a `propertyB` but they don't need to provide both.\n\nCurrently, I'm doing something like:\n\n```\nexport class TestDto {\n @ValidateIf(obj => !obj.propertyB)\n @IsString()\n @IsNotEmpty()\n propertyA\n\n @ValidateIf(obj => !obj.propertyA)\n @IsString()\n @IsNotEmpty()\n propertyB\n}\n```\n\nIf they provide none of the parameters there will be multiple errors saying that `propertyA` and `propertyB` are required and should be strings etc.\n\nIn the case that they provide neither property, I would want only a single error saying something like: \"You must provide propertyA or propertyB.\"\n\nCan this be accomplished using NestJS/class-validator?\n\n========================================\n\nTop Answer:\nIf you don't want to create custom Property Decorators, this is the solution I came up with for one of my projects.\n\nSimply set the fields to optional and then add an additional 'undefined' field that will do the check\n\n```\nexport class TestDto {\n @IsString()\n @IsOptional()\n a?: string;\n\n @IsString()\n @IsOptional()\n b?: string;\n\n // if nothing has been provided\n @ValidateIf(o => !o.a && !o.b)\n @IsDefined({message: 'At least one of a or b must be provided'})\n protected readonly atLeastOne: undefined;\n\n // if both have been provided\n @ValidateIf(o => o.a && o.b)\n @IsDefined({message: 'Only one of a or b may be provided'})\n protected readonly atMostOne: undefined;\n\n // the 2 checks above combined\n @ValidateIf(o => (!o.a && !o.b) || (o.a && o.b))\n @IsDefined({message: 'Provide either a or b, and only one of them'})\n protected readonly exactlyOne: undefined;\n}\n```\n\nps. you wont need to use all these checks at the same time :)\n\n========================================\n\nCode:\n```js\nexport class TestDto {\n  @ValidateIf(obj => !obj.propertyB)\n  @IsString()\n  @IsNotEmpty()\n  propertyA\n\n  @ValidateIf(obj => !obj.propertyA)\n  @IsString()\n  @IsNotEmpty()\n  propertyB\n}\n```\n\n```text\npropertyA\n```\n\n```text\npropertyB\n```\n\n```text\npropertyA\n```\n\n```text\npropertyB\n```\n\n```text\nimport { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';\n\n@Injectable()\nexport class CustomValidationPipe implements PipeTransform {\n  transform(value: TestDto , metadata: ArgumentMetadata) {\n    if(value.porpertyA && value.porpertyB) throw new BadRequestException(\"You must provide propertyA or propertyB\")\n    else return value;\n  }\n}\n```\n\n```text\n@Post()\n  create(@Body( new CustomValidationPipe()) testDto: TestDto) {\n    return \"create Resource\"\n  }\n```\n\n```text\n@Post()\n  create(@Body(ValidationPipe ,  new CustomValidationPipe()) testDto: TestDto) {\n    return \"create Resource\"\n  }\n```\n\n```text\nexport class TestDto {\n    @IsString()\n    @IsOptional()\n    a?: string;\n\n    @IsString()\n    @IsOptional()\n    b?: string;\n\n    // if nothing has been provided\n    @ValidateIf(o => !o.a && !o.b)\n    @IsDefined({message: 'At least one of a or b must be provided'})\n    protected readonly atLeastOne: undefined;\n\n    // if both have been provided\n    @ValidateIf(o => o.a && o.b)\n    @IsDefined({message: 'Only one of a or b may be provided'})\n    protected readonly atMostOne: undefined;\n\n    // the 2 checks above combined\n    @ValidateIf(o => (!o.a && !o.b) || (o.a && o.b))\n    @IsDefined({message: 'Provide either a or b, and only one of them'})\n    protected readonly exactlyOne: undefined;\n}\n```\n\n========================================\n\nComments:\n- Hello. Your solution has another bottleneck too. Actually I opened a feat request in the class-validator and I provide there a proposal for our problem too. You can vote me up there too: github.com/typestack/class-validator/issues/1581\n- Link-only answers are usually deleted, you should add an example of code in your answer","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":156,"estimatedTokens":997}}318{"id":"stack-53394758","source":"stackoverflow","questionId":53394758,"title":"NestJS How to add custom Logger to custom ExceptionFilter","tags":["node.js","nest","nestjs"],"text":"Title: NestJS How to add custom Logger to custom ExceptionFilter\nTags: node.js, nest, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS 5.4.0\nI have custom LoggerService, it's working perfectly. But, how can I add this LoggerService to ExceptionFilter.\n\n```\n// logger.service.ts\nimport {Injectable, LoggerService} from '@nestjs/common';\n@Injectable()\nexport class Logger implements LoggerService {\n log(message: string) {\n console.log(message);\n }\n error(message: string, trace: string) {\n console.error(message);\n }\n warn(message: string) {\n console.warn(message);\n }\n}\n\n//logger.module.ts\nimport { Module } from '@nestjs/common';\nimport {Logger} from '../services/logger.service';\n@Module({\n providers: [Logger],\n exports: [Logger],\n})\nexport class LoggerModule {}\n\n// user.module.ts\nimport { Module } from '@nestjs/common';\nimport {UserService} from '../services/user.service';\nimport {LoggerModule} from './logger.module';\n\n@Module({\n imports: [LoggerModule],\n providers: [UserService],\n exports: [UserService],\n})\nexport class UserModule {}\n```\n\nIt's working perfectly.\n\n```\nimport {Logger} from './logger.service';\nexport class UserService {\n constructor(\n private logger: Logger\n ) {}\n private test = () => {\n this.logger.log(\"test\"); // log success \"test\" to console\n }\n}\n```\n\nBut how can I add my custom Logger to ExceptionFilter\n\n```\n// forbidden.exception.filter.ts\nimport {HttpException, HttpStatus, Injectable} from '@nestjs/common';\n\n@Injectable()\nexport class ForbiddenException extends HttpException {\n constructor(message?: string) {\n super(message || 'Forbidden', HttpStatus.FORBIDDEN);\n // I want to add my custom logger here!\n }\n}\n```\n\nThank for reading.\n\n========================================\n\nTop Answer:\nFirst of all, to use dependency injection with Exception filters you cannot register them using the `useGlobalFilters()` method:\n\n```\nconst app = await NestFactory.create(MainModule, {\n logger: false,\n});\n\nconst logger = app.get(MyLogger);\napp.useLogger(logger);\n\n//Remove this line\n//app.useGlobalFilters(new HttpExceptionFilter(logger));\n```\n\nNext in your `MainModule`, add your custom exception filter as a provider (note: filters are automatically set as global no matter what module you add them to but as a best practice, add them to your top level module):\n\n```\nimport { Module } from '@nestjs/common';\nimport { APP_FILTER } from '@nestjs/core';\nimport { LoggerModule } from './logger.module';\nimport { ForbiddenException } from './forbidden.exception.filter.ts';\n\n@Module({\n imports: [\n LoggerModule //this is your logger module\n ],\n providers: [\n {\n provide: APP_FILTER, //you have to use this custom provider\n useClass: ForbiddenException //this is your custom exception filter\n }\n ]\n})\nexport class MainModule {}\n```\n\nNow you can inject the logger into your custom exception filter:\n\n```\nimport {HttpException, HttpStatus, Injectable} from '@nestjs/common';\nimport { Logger } from './path/to/logger';\n\n@Injectable()\nexport class ForbiddenException extends HttpException {\n\n constructor(private logger: Logger) {}\n\n catch(exception: HttpException, response) {\n this.logger.log('test');\n }\n}\n```\n\nPseudo code but I think you get the idea.\n\n========================================\n\nCode:\n```text\n// logger.service.ts\nimport {Injectable, LoggerService} from '@nestjs/common';\n@Injectable()\nexport class Logger implements LoggerService {\n    log(message: string) {\n        console.log(message);\n    }\n    error(message: string, trace: string) {\n        console.error(message);\n    }\n    warn(message: string) {\n        console.warn(message);\n    }\n}\n\n//logger.module.ts\nimport { Module } from '@nestjs/common';\nimport {Logger} from '../services/logger.service';\n@Module({\n    providers: [Logger],\n    exports: [Logger],\n})\nexport class LoggerModule {}\n\n\n// user.module.ts\nimport { Module } from '@nestjs/common';\nimport {UserService} from '../services/user.service';\nimport {LoggerModule} from './logger.module';\n\n@Module({\n    imports: [LoggerModule],\n    providers: [UserService],\n    exports: [UserService],\n})\nexport class UserModule {}\n```\n\n```text\nimport {Logger} from './logger.service';\nexport class UserService {\n    constructor(\n        private logger: Logger\n    ) {}\n    private test = () => {\n        this.logger.log(\"test\"); // log success \"test\" to console\n    }\n}\n```\n\n```text\n// forbidden.exception.filter.ts\nimport {HttpException, HttpStatus, Injectable} from '@nestjs/common';\n\n@Injectable()\nexport class ForbiddenException extends HttpException {\n    constructor(message?: string) {\n        super(message || 'Forbidden', HttpStatus.FORBIDDEN);\n        // I want to add my custom logger here!\n    }\n}\n```\n\n```text\n// HttpExceptionFilter.ts\n\nimport { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport {MyLogger} from '../MyLogger'\n\n@Catch(HttpException)\nexport class HttpExceptionFilter implements ExceptionFilter {\n  constructor(private readonly logger: MyLogger) {}\n\n  catch(exception: HttpException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n    const status = exception.getStatus();\n\n    if (status >= 500) {\n      this.logger.error({ request, response });\n    }\n\n    response\n      .status(status)\n      .json({\n        statusCode: status,\n        timestamp: new Date().toISOString(),\n        path: request.url,\n      });\n  }\n}\n```\n\n```text\n// bootstrap.ts\n\nconst app = await NestFactory.create(MainModule, {\n  logger: false,\n});\n\nconst logger = app.get<MyLogger>(MyLogger);\napp.useLogger(logger);\napp.useGlobalFilters(new HttpExceptionFilter(logger));\n```\n\n```text\nclass ForbiddenException extends HttpException\n```\n\n```text\nExceptionFilter\n```\n\n```text\nExceptionFilter\n```\n\n```text\nHttpException\n```\n\n```text\nExceptionFilter\n```\n\n```text\nExceptionFilter\n```\n\n```text\nconstructor\n```\n\n```text\napp.get<T>(...)\n```\n\n```text\nbootstrap.ts\n```\n\n```text\nINestApplication\n```\n\n```text\nconst app = await NestFactory.create(MainModule, {\n  logger: false,\n});\n\nconst logger = app.get<MyLogger>(MyLogger);\napp.useLogger(logger);\n\n//Remove this line\n//app.useGlobalFilters(new HttpExceptionFilter(logger));\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { APP_FILTER } from '@nestjs/core';\nimport { LoggerModule } from './logger.module';\nimport { ForbiddenException } from './forbidden.exception.filter.ts';\n\n@Module({\n  imports: [\n    LoggerModule //this is your logger module\n  ],\n  providers: [\n    {\n      provide: APP_FILTER, //you have to use this custom provider\n      useClass: ForbiddenException //this is your custom exception filter\n    }\n  ]\n})\nexport class MainModule {}\n```\n\n```text\nimport {HttpException, HttpStatus, Injectable} from '@nestjs/common';\nimport { Logger } from './path/to/logger';\n\n@Injectable()\nexport class ForbiddenException extends HttpException {\n\n  constructor(private logger: Logger) {}\n\n  catch(exception: HttpException, response) {\n    this.logger.log('test');\n  }\n}\n```\n\n```text\nuseGlobalFilters()\n```\n\n```text\nMainModule\n```\n\n========================================\n\nComments:\n- The last part of the question makes it seem like you are trying to add logging to the `Exception` classes because you show the `ForbiddenException`. Is that what you're trying to accomplish (i.e. log every time an `Exception` instance is instantiated), or do you instead want to use exception filters? The nestjs documentation provides an example of an `HTTPExceptionFilter`: docs.nestjs.com/exception-filters\n- Those docs don't show how to inject a custom logger to a custom exception filter. I'm running into the same problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.431Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":346,"estimatedTokens":1929}}319{"id":"stack-56097187","source":"stackoverflow","questionId":56097187,"title":"Nestjs Apollo graphql upload scalar","tags":["javascript","node.js","graphql","apollo","nestjs"],"text":"Title: Nestjs Apollo graphql upload scalar\nTags: javascript, node.js, graphql, apollo, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using nestjs graphql framework and I want to use apollo scalar upload\n\nI have been able to use the scalar in another project that did not include nestjs.\n\nschema.graphql\nApp.module.ts register graphql\n\n```\nGraphQLModule.forRoot({\n typePaths: ['./**/*.graphql'],\n resolvers: { Upload: GraphQLUpload },\n installSubscriptionHandlers: true,\n context: ({ req }) => ({ req }),\n playground: true,\n definitions: {\n path: join(process.cwd(), './src/graphql.classes.ts'),\n outputAs: 'class',\n },\n uploads: {\n maxFileSize: 10000000, // 10 MB\n maxFiles: 5\n }\n }),\n```\n\npets.resolver.ts mutation createPet\n\n```\n@Mutation('uploadFile')\n async uploadFile(@Args('fileUploadInput') fileUploadInput: FileUploadInput) {\n console.log(\"TCL: PetsResolver -> uploadFile -> file\", fileUploadInput);\n return {\n id: '123454',\n path: 'www.wtf.com',\n filename: fileUploadInput.file.filename,\n mimetype: fileUploadInput.file.mimetype\n }\n }\n```\n\npets.type.graphql\n\n```\ntype Mutation {\n uploadFile(fileUploadInput: FileUploadInput!): File!\n}\ninput FileUploadInput{\n file: Upload!\n}\n\ntype File {\n id: String!\n path: String!\n filename: String!\n mimetype: String!\n}\n```\n\nI expect that scalar works with nestjs but my actual result is\n\n```\n{\"errors\":[{\"message\":\"Promise resolver undefined is not a function\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"createPet\"],\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"exception\":{\"stacktrace\":[\"TypeError: Promise resolver undefined is not a function\",\" at new Promise ()\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:119:32)\",\" at E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:62:40\",\" at Array.forEach ()\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:41:30)\",\" at _loop_1 (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:226:43)\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\class-transformer\\\\TransformOperationExecutor.js:240:17)\",\" at ClassTransformer.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\ClassTransformer.ts:43:25)\",\" at Object.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\index.ts:37:29)\",\" at ValidationPipe.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\common\\\\pipes\\\\validation.pipe.js:50:41)\",\" at transforms.reduce (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\core\\\\pipes\\\\pipes-consumer.js:15:28)\",\" at process._tickCallback (internal/process/next_tick.js:68:7)\"]}}}],\"data\":null}\n```\n\n========================================\n\nTop Answer:\n**Use** import {GraphQLUpload} from \"**apollo-server-express**\"\n\n**Not** from 'graphql-upload'\n\n```\nimport { Resolver, Mutation, Args } from '@nestjs/graphql';\nimport { createWriteStream } from 'fs';\n\nimport {GraphQLUpload} from \"apollo-server-express\"\n\n@Resolver('Download')\nexport class DownloadResolver {\n @Mutation(() => Boolean)\n async uploadFile(@Args({name: 'file', type: () => GraphQLUpload})\n {\n createReadStream,\n filename\n }): Promise {\n return new Promise(async (resolve, reject) => \n createReadStream()\n .pipe(createWriteStream(`./uploads/${filename}`))\n .on('finish', () => resolve(true))\n .on('error', () => reject(false))\n );\n }\n \n}\n```\n\nhttps://i.sstatic.net/bgm01.png\n\n========================================\n\nCode:\n```text\nGraphQLModule.forRoot({\n      typePaths: ['./**/*.graphql'],\n      resolvers: { Upload: GraphQLUpload },\n      installSubscriptionHandlers: true,\n      context: ({ req }) => ({ req }),\n      playground: true,\n      definitions: {\n        path: join(process.cwd(), './src/graphql.classes.ts'),\n        outputAs: 'class',\n      },\n      uploads: {\n        maxFileSize: 10000000, // 10 MB\n        maxFiles: 5\n      }\n    }),\n```\n\n```text\n@Mutation('uploadFile')\n    async uploadFile(@Args('fileUploadInput') fileUploadInput: FileUploadInput) {\n        console.log(\"TCL: PetsResolver -> uploadFile -> file\", fileUploadInput);\n        return {\n            id: '123454',\n            path: 'www.wtf.com',\n            filename: fileUploadInput.file.filename,\n            mimetype: fileUploadInput.file.mimetype\n        }\n    }\n```\n\n```text\ntype Mutation {\n        uploadFile(fileUploadInput: FileUploadInput!): File!\n}\ninput FileUploadInput{\n    file: Upload!\n}\n\ntype File {\n        id: String!\n        path: String!\n        filename: String!\n        mimetype: String!\n}\n```\n\n```text\n{\"errors\":[{\"message\":\"Promise resolver undefined is not a function\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"createPet\"],\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"exception\":{\"stacktrace\":[\"TypeError: Promise resolver undefined is not a function\",\"    at new Promise (<anonymous>)\",\"    at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:119:32)\",\"    at E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:62:40\",\"    at Array.forEach (<anonymous>)\",\"    at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:41:30)\",\"    at _loop_1 (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:226:43)\",\"    at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\class-transformer\\\\TransformOperationExecutor.js:240:17)\",\"    at ClassTransformer.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\ClassTransformer.ts:43:25)\",\"    at Object.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\index.ts:37:29)\",\"    at ValidationPipe.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\common\\\\pipes\\\\validation.pipe.js:50:41)\",\"    at transforms.reduce (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\core\\\\pipes\\\\pipes-consumer.js:15:28)\",\"    at process._tickCallback (internal/process/next_tick.js:68:7)\"]}}}],\"data\":null}\n```\n\n```text\nimport { Scalar } from '@nestjs/graphql';\n\nimport { GraphQLUpload } from 'graphql-upload';\n\n@Scalar('Upload')\nexport class Upload {\n  description = 'Upload custom scalar type';\n\n  parseValue(value) {\n    return GraphQLUpload.parseValue(value);\n  }\n\n  serialize(value: any) {\n    return GraphQLUpload.serialize(value);\n  }\n\n  parseLiteral(ast) {\n    return GraphQLUpload.parseLiteral(ast);\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n  ...\n    DateScalar,\n    Upload,\n    GraphQLModule.forRoot({\n      typePaths: ['./**/*.graphql'],\n     ...\n      uploads: {\n        maxFileSize: 10000000, // 10 MB\n        maxFiles: 5,\n      },\n    }),\n  ...\n  ],\n...\n})\nexport class ApplicationModule {}\n```\n\n```text\nscalar Upload\n...\ntype Mutation {\n  uploadFile(file: Upload!): String\n}\n```\n\n```text\n@Mutation()\n  async uploadFile(@Args('file') file,) {\n    console.log('Hello file',file)\n    return \"Nice !\";\n  }\n```\n\n```text\ngraphql-upload\n```\n\n```text\nGraphQLUpload\n```\n\n```text\ngraphql-upload\n```\n\n```text\nimport { Resolver, Mutation, Args } from '@nestjs/graphql';\nimport { createWriteStream } from 'fs';\n\nimport {GraphQLUpload} from \"apollo-server-express\"\n\n@Resolver('Download')\nexport class DownloadResolver {\n    @Mutation(() => Boolean)\n    async uploadFile(@Args({name: 'file', type: () => GraphQLUpload})\n    {\n        createReadStream,\n        filename\n    }): Promise<boolean> {\n        return new Promise(async (resolve, reject) => \n            createReadStream()\n                .pipe(createWriteStream(`./uploads/${filename}`))\n                .on('finish', () => resolve(true))\n                .on('error', () => reject(false))\n        );\n    }\n    \n}\n```\n\n```js\nimport { graphqlUploadExpress } from \"graphql-upload\"\nimport { MiddlewareConsumer, Module, NestModule } from \"@nestjs/common\"\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      uploads: false, // disable built-in upload handling (for apollo 3+ not needed)\n    }),\n  ],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(graphqlUploadExpress()).forRoutes(\"graphql\")\n  }\n}\n```\n\n```text\n// import { GraphQLUpload } from \"apollo-server-core\" <-- remove this\nimport { FileUpload, GraphQLUpload } from \"graphql-upload\"\n```\n\n```text\nGraphQLUpload\n```\n\n```text\napollo-server-core\n```\n\n```text\ngraphql-upload\n```\n\n========================================\n\nComments:\n- Hello, did you solve your problem? i'm in the exact same situation :)\n- no sorry, there was a guy that have it working but he was busy and i just change to rest :D. try in the discord discordapp.com/channels/520622812742811698/60153692626826039&zwnj;&#8203;2\n- Lary you encounter a problem with parseLiteral expect 2 arguments ?parseLiteral(valueNode: ValueNode, variables: Maybe) { return GraphQLUpload.parseLiteral(valueNode, variables); }\n- maybe you can help in this discord channel discordapp.com/channels/520622812742811698/52064948792498588&zwnj;&#8203;5\n- no, i used : \"apollo-server-express\": \"2.8.0\", \"graphql-upload\": \"^8.0.7\" \"@types/graphql-upload\": \"^8.0.0\", What about you? (im already on this discord PM me if you want @Lard-man )\n- For those trying this now, `graphql-upload` is included in `apollo-server-express`.\n- Can't find GraphQLUpload with apollo-server-fastify, do you know if this can work with Fastify ? Thanks in advance\n- Apollo Server 3 has removed \"GraphQLUpload\" in favor of enabling users to provide their own mechanisms for these features.","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":300,"estimatedTokens":2429}}320{"id":"stack-60311071","source":"stackoverflow","questionId":60311071,"title":"Nest can't resolve dependencies of repository","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of repository\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI got error on my nestjs app. I cant figure out whats wring with my code. I \nThe codes is something like this\n\n**AppModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AdminModule } from './components/admin.modules';\n\n@Module({\n imports: [\n AdminModule,\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: process.env.DATABASE_HOST,\n username: process.env.DATABASE_USERNAME,\n password: process.env.DATABASE_PASSWORD,\n database: process.env.DATABASE_NAME,\n port: parseInt(process.env.DATABASE_PORT),\n }),\n ],\n})\nexport class AppModule {}\n```\n\n**AdminModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { Admin } from './admin.entity';\nimport { AdminRepository } from './admin.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Admin])],\n providers: [AdminRepository],\n})\nexport class AdminModule {}\n```\n\n**AdminRepository**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { RepositoryBase } from '../../common/base/repository.base';\nimport { Admin } from './admin.entity';\n\n@Injectable()\nexport class AdminRepository extends RepositoryBase {\n constructor(@InjectRepository(Admin) private readonly repo: Repository) {\n super(repo);\n}\n```\n\nAnd what i get is error like this\n\n Error: Nest can't resolve dependencies of the AdminRepository (?). Please make sure that the argument AdminRepository at index [0] is available in the AdminModule context.\n\n \n Potential solutions:\n - If AdminRepository is a provider, is it part of the current AdminModule?\n - If AdminRepository is exported from a separate @Module, is that module imported within AdminModule?\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AdminModule } from './components/admin.modules';\n\n@Module({\n    imports: [\n        AdminModule,\n        TypeOrmModule.forRoot({\n          type: 'postgres',\n          host: process.env.DATABASE_HOST,\n          username: process.env.DATABASE_USERNAME,\n          password: process.env.DATABASE_PASSWORD,\n          database: process.env.DATABASE_NAME,\n          port: parseInt(process.env.DATABASE_PORT),\n        }),\n    ],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { Admin } from './admin.entity';\nimport { AdminRepository } from './admin.repository';\n\n@Module({\n    imports: [TypeOrmModule.forFeature([Admin])],\n    providers: [AdminRepository],\n})\nexport class AdminModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { RepositoryBase } from '../../common/base/repository.base';\nimport { Admin } from './admin.entity';\n\n@Injectable()\nexport class AdminRepository extends RepositoryBase<Admin> {\n    constructor(@InjectRepository(Admin) private readonly repo: Repository<Admin>) {\n        super(repo);\n}\n```\n\n```text\nAdminRepository\n```\n\n```text\nTypeOrm\n```\n\n```text\nAdmin\n```\n\n```text\nAdminRepo\n```\n\n```text\nAdminService\n```\n\n```text\nAdmin\n```\n\n```text\n${EntityClassName}Repository\n```\n\n========================================\n\nComments:\n- Hi! Can you provide a repository.base file?\n- Damn... reserved names should throw an error or something.","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":159,"estimatedTokens":909}}321{"id":"stack-54229131","source":"stackoverflow","questionId":54229131,"title":"How to log all Axios external http requests in NestJS","tags":["javascript","node.js","typescript","axios","nestjs"],"text":"Title: How to log all Axios external http requests in NestJS\nTags: javascript, node.js, typescript, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to be able to log each axios request with full url, headers, etc but currently didn't find a way to do so.\n\nWhat I did achieve so far is to writhe an Http Interceptor based on this answer\n\n```\nexport class HttpLoggerInterceptor implements NestInterceptor {\n intercept(\n context: ExecutionContext,\n call$: Observable,\n ): Observable {\n return call$.pipe(\n map(data => {\n // pipe call to add / modify header(s) after remote method\n const req = context.switchToHttp().getRequest();\n return data;\n }),\n );\n }\n}\n```\n\nNow I browse through the objects `req` and `context` props on debug but could not see Asios request url, etc. Unless I missed that.\n\nMy controller route (`api/data` in that case) have N number of http external calls taking place but interceptor intercepts only controller controller call not Axios calls.\n\nAny thoughts?\n\nThat is `context` object:\n\n```\nargs:Array(2) [IncomingMessage, ServerResponse]\nconstructorRef:class AppController { โ€ฆ }\ngetRequest:() => โ€ฆ\ngetResponse:() => โ€ฆ\nhandler:data() { โ€ฆ }\n__proto__:Object {constructor: , getClass: , getHandler: , โ€ฆ}\n```\n\nthat is `req`:\n\n```\n_dumped:false\n_events:Object {}\n_eventsCount:0\n_maxListeners:undefined\n_parsedOriginalUrl:Url {protocol: null, slashes: null, auth: null, โ€ฆ}\n_parsedUrl:Url {protocol: null, slashes: null, auth: null, โ€ฆ}\n_readableState:ReadableState {objectMode: false, highWaterMark: 16384, buffer: BufferList, โ€ฆ}\nbaseUrl:\"\"\nbody:Object {}\nclient:Socket {connecting: false, _hadError: false, _handle: TCP, โ€ฆ}\ncomplete:true\nconnection:Socket {connecting: false, _hadError: false, _handle: TCP, โ€ฆ}\ndestroyed:false\nfresh:false\nheaders:Object {accept: \"application/json, text/plain, */*\", user-agent: \"axios/0.18.0\", host: \"localhost:3000\", โ€ฆ}\nhost:\"localhost\"\nhostname:\"localhost\"\nhttpVersion:\"1.1\"\nhttpVersionMajor:1\nhttpVersionMinor:1\nip:\"::ffff:127.0.0.1\"\nips:Array(0)\nmethod:\"GET\"\nnext:function next(err) { โ€ฆ }\noriginalUrl:\"/api/data\"\nparams:Object {}\n__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , โ€ฆ}\npath:\"/api/data\"\nprotocol:\"http\"\nquery:Object {}\nrawHeaders:Array(8) [\"Accept\", \"application/json, text/plain, */*\", \"User-Agent\", โ€ฆ]\nrawTrailers:Array(0) []\nreadable:true\nreadableBuffer:BufferList\nreadableFlowing:null\nreadableHighWaterMark:16384\nreadableLength:0\nres:ServerResponse {_events: Object, _eventsCount: 1, _maxListeners: undefined, โ€ฆ}\nroute:Route {path: \"/api/data\", stack: Array(1), methods: Object}\nsecure:false\nsocket:Socket {connecting: false, _hadError: false, _handle: TCP, โ€ฆ}\nstale:true\nstatusCode:null\nstatusMessage:null\nsubdomains:Array(0)\ntrailers:Object {}\nupgrade:false\nurl:\"/api/data\"\nxhr:false\n```\n\n========================================\n\nTop Answer:\nFor those looking for a centralised solution with no extra library, this is how I added my bearer token to all external api calls, with a log when it happens:\n\n```\n@Injectable()\nexport class IdkAxiosInterceptor implements OnModuleInit {\n private readonly logger = new Logger(IdkAxiosInterceptor.name);\n private token = undefined;\n\n constructor(\n @Inject(HttpService)\n private httpService: HttpService,\n @Inject(TokenExchangeService)\n private tokenExchangeService: TokenExchangeService,\n ) {\n this.refreshToken();\n }\n\n onModuleInit(): any {\n const { axiosRef: axios } = this.httpService;\n\n axios.interceptors.request.use((config) => {\n return this.onRequest(config);\n }, Promise.reject);\n }\n\n onRequest(config) {\n this.logger.log('external call for ' + config.url);\n config.headers['Authorization'] = `Bearer ${this.token}`;\n\n return config;\n }\n\n @Cron(EVERY_50_MINUTES)\n refreshToken() {\n this.tokenExchangeService.getAccessToken(Environment.PRODUCTION).subscribe(({ access_token }) => {\n this.token = access_token;\n });\n }\n}\n```\n\nNow you just need to add it to your main module as a provider and thats it.\n\nIf you want I can post the test for it :D\n\n========================================\n\nCode:\n```text\nexport class HttpLoggerInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    return call$.pipe(\n      map(data => {\n        // pipe call to add / modify header(s) after remote method\n        const req = context.switchToHttp().getRequest();\n        return data;\n      }),\n    );\n  }\n}\n```\n\n```text\nargs:Array(2) [IncomingMessage, ServerResponse]\nconstructorRef:class AppController { โ€ฆ }\ngetRequest:() => โ€ฆ\ngetResponse:() => โ€ฆ\nhandler:data() { โ€ฆ }\n__proto__:Object {constructor: , getClass: , getHandler: , โ€ฆ}\n```\n\n```text\n_dumped:false\n_events:Object {}\n_eventsCount:0\n_maxListeners:undefined\n_parsedOriginalUrl:Url {protocol: null, slashes: null, auth: null, โ€ฆ}\n_parsedUrl:Url {protocol: null, slashes: null, auth: null, โ€ฆ}\n_readableState:ReadableState {objectMode: false, highWaterMark: 16384, buffer: BufferList, โ€ฆ}\nbaseUrl:\"\"\nbody:Object {}\nclient:Socket {connecting: false, _hadError: false, _handle: TCP, โ€ฆ}\ncomplete:true\nconnection:Socket {connecting: false, _hadError: false, _handle: TCP, โ€ฆ}\ndestroyed:false\nfresh:false\nheaders:Object {accept: \"application/json, text/plain, */*\", user-agent: \"axios/0.18.0\", host: \"localhost:3000\", โ€ฆ}\nhost:\"localhost\"\nhostname:\"localhost\"\nhttpVersion:\"1.1\"\nhttpVersionMajor:1\nhttpVersionMinor:1\nip:\"::ffff:127.0.0.1\"\nips:Array(0)\nmethod:\"GET\"\nnext:function next(err) { โ€ฆ }\noriginalUrl:\"/api/data\"\nparams:Object {}\n__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , โ€ฆ}\npath:\"/api/data\"\nprotocol:\"http\"\nquery:Object {}\nrawHeaders:Array(8) [\"Accept\", \"application/json, text/plain, */*\", \"User-Agent\", โ€ฆ]\nrawTrailers:Array(0) []\nreadable:true\nreadableBuffer:BufferList\nreadableFlowing:null\nreadableHighWaterMark:16384\nreadableLength:0\nres:ServerResponse {_events: Object, _eventsCount: 1, _maxListeners: undefined, โ€ฆ}\nroute:Route {path: \"/api/data\", stack: Array(1), methods: Object}\nsecure:false\nsocket:Socket {connecting: false, _hadError: false, _handle: TCP, โ€ฆ}\nstale:true\nstatusCode:null\nstatusMessage:null\nsubdomains:Array(0)\ntrailers:Object {}\nupgrade:false\nurl:\"/api/data\"\nxhr:false\n```\n\n```text\nreq\n```\n\n```text\ncontext\n```\n\n```text\napi/data\n```\n\n```text\ncontext\n```\n\n```text\nreq\n```\n\n```text\nthis.httpService.axiosRef.interceptors.request.use(config => { /*...*/ return config })\n```\n\n```text\n@Injectable()\nexport class MyHttpService {\n  private logger: Logger = new Logger(MyHttpService.name);\n\n  constructor (private httpService: HttpService) {}\n  \n  public get<T = any>(url: string, config?: AxiosRequestConfig): Observable<AxiosResponse<T>> {\n    this.logger.log({url, config});\n    return this.httpService.get(url, config)\n       .pipe(tap(response => this.logger.log(response)));\n  }\n\n  // ... all the other methods you need.\n\n}\n```\n\n```text\nHttpService\n```\n\n```text\naxios\n```\n\n```text\nget axiosRef()\n```\n\n```text\naxios interceptor\n```\n\n```text\nonModuleInit()\n```\n\n```text\nAppModule\n```\n\n```text\nHttpService\n```\n\n```text\nHttpService\n```\n\n```text\nLoggingHttpModule\n```\n\n```text\nHttpModule\n```\n\n```text\nMyHttpService\n```\n\n```text\nnpm i @types/morgan\n\nnpm i morgan\n```\n\n```text\nimport * as morgan from 'morgan';\n\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(morgan('combined'))\n      .forRoutes('*');\n  }\n}\n```\n\n```text\n@Injectable()\nexport class IdkAxiosInterceptor implements OnModuleInit {\n  private readonly logger = new Logger(IdkAxiosInterceptor.name);\n  private token = undefined;\n\n  constructor(\n    @Inject(HttpService)\n    private httpService: HttpService,\n    @Inject(TokenExchangeService)\n    private tokenExchangeService: TokenExchangeService,\n  ) {\n    this.refreshToken();\n  }\n\n  onModuleInit(): any {\n    const { axiosRef: axios } = this.httpService;\n\n    axios.interceptors.request.use((config) => {\n      return this.onRequest(config);\n    }, Promise.reject);\n  }\n\n  onRequest(config) {\n    this.logger.log('external call for ' + config.url);\n    config.headers['Authorization'] = `Bearer ${this.token}`;\n\n    return config;\n  }\n\n  @Cron(EVERY_50_MINUTES)\n  refreshToken() {\n    this.tokenExchangeService.getAccessToken(Environment.PRODUCTION).subscribe(({ access_token }) => {\n      this.token = access_token;\n    });\n  }\n}\n```\n\n========================================\n\nComments:\n- which approach would you recommend? Seems like the second approach involves a bit more code. If you go with the `Axios Interceptor` approach where would you stick the `this.httpService.axiosRef.interceptors.request.use(config => console.log(config));` code ? `>You can for example do that in the onModuleInit() of your AppModule` - would you give a bit more background on that?\n- Have a look at this answer's second part where `OnModuleInit` is explained. stackoverflow.com/a/53484892/4694994 And yes, I would recommend using the axios Interceptor solution.\n- In typescript version of NestJS I was required to use slightly altered interceptor `this.httpService.axiosRef.interceptors.request.use((config: AxiosRequestConfig) => { console.log(config); return config; });`\n- Just trying to implement axios interceptor, having an issue with this one stackoverflow.com/questions/68869611/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":376,"estimatedTokens":2320}}322{"id":"stack-61637468","source":"stackoverflow","questionId":61637468,"title":"How to stub EntityManager and Connection in TypeORM with Jest","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: How to stub EntityManager and Connection in TypeORM with Jest\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI got an app on NestJS in Typescript using TypeORM and unit-tests written with Jest. I have a function that uses transactions like this:\n\n```\nasync createMany(users: User[]) {\n await this.connection.transaction(async manager => {\n await manager.save(users[0]);\n await manager.save(users[1]);\n });\n}\n```\n\nThat's an example from NestJS docs. I do it roughly in the same way via `this.connection.transaction` but the business-logic is different.\n\nThe thing is I want to make a unit-test to test this service function. So I need to somehow mock both `this.connection` and its `manager`. Or at least the manager. I'm not sure how to do it using Jest. I can't create a manager without a connection. I can't create a mock connection with no manager to return inside it.\n\nUsing both TypeORM and Jest is standard in NestJS. There have to be a way to write unit-tests with transactions. But I am not sure how to do it.\n\nNote that I am asking about unit-test mocking ORM. Not integration tests that would directly use a testing db instance.\n\n========================================\n\nTop Answer:\nI believe you can also:\n\n```\nimport { getConnectionToken } from '@nestjs/typeorm';\n\n{\n provide: getConnectionToken(),\n useClass: Connection,\n},\n```\n\n========================================\n\nCode:\n```js\nasync createMany(users: User[]) {\n  await this.connection.transaction(async manager => {\n    await manager.save(users[0]);\n    await manager.save(users[1]);\n  });\n}\n```\n\n```text\nthis.connection.transaction\n```\n\n```text\nthis.connection\n```\n\n```text\nmanager\n```\n\n```text\nimport { Test } from \"@nestjs/testing\";\n\ndescribe(\"UsersService\", () => {\n    let usersService;\n    let connection;\n    const mockConnection = () => ({\n        transaction: jest.fn()\n    });\n\n    beforeEach(async () => {\n        const module = await Test.createTestingModule({\n            providers: [\n                UsersService,\n                {\n                    provide: Connection,\n                    useFactory: mockConnection\n                }\n            ],\n        }).compile();\n\n        usersService = await module.get<UsersService>(UsersService); \n        connection = await modle.get<Connection>(Connection);\n    });\n\n    describe(\"some tests\", () => {\n        it(\"should test something\", async () => {\n            const someMockedUsers = [/* some users */];\n            const mockedManager = {\n                save: jest.fn()\n            }\n            connection.transaction.mockImplementation((cb) => {\n                cb(mockedManager);\n            });\n\n            await userService.createMany(someMockedUsers);\n\n            expect(connection.transaction).toHaveBeenCalled();\n            expect(mockedManager.save).toHaveBeenCalledTimes(2);\n            // ...\n\n        });\n    });\n\n\n});\n```\n\n```text\nTestingModule\n```\n\n```text\nConnection\n```\n\n```text\nimport { getConnectionToken } from '@nestjs/typeorm';\n\n{\n  provide: getConnectionToken(),\n  useClass: Connection,\n},\n```\n\n========================================\n\nComments:\n- This should work. However using `Test.createTestingModule` caused me a lot of problems hogging loads of RAM. I ended not using it and going for `sinon.js` instead.\n- @kkkkkkk your solution works very well thank you ! There is jus something that i'm not getting, when I expect the connection to be called I get an error. Even though the mock is correctly called. Do you know why jest wouldn't record the calls etc... ?\n- I get Received: [Function mockConstructor], instead of the expected value. Looks like Jest ignores the mock.\n- facing this error after your code , TypeError: Cannot read properties of undefined (reading 'name') at new Connection (connection/Connection.ts:119:29)\n- I'm also facing the same error when utilizing `getConnectionToken()`. Any ideas?","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":135,"estimatedTokens":983}}323{"id":"stack-61066950","source":"stackoverflow","questionId":61066950,"title":"Unable to inject winston's logger instance with NestJS","tags":["node.js","nestjs","winston"],"text":"Title: Unable to inject winston's logger instance with NestJS\nTags: node.js, nestjs, winston\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS `7.0.7` and Winston `3.2.1` (with nest-winston `1.3.3`).\n\nI'm trying to integrate Winston into NestJS, but so far, I'm unable to inject a logger instance (to actually log anything) into any controller/service.\n\nSince I would like to use Winston across the application **AND** during bootstrapping, I'm using the approach *as the main Nest logger*:\n\n```\n// main.ts\nimport { NestFactory } from \"@nestjs/core\";\nimport { WinstonModule } from \"nest-winston\";\nimport { format, transports } from \"winston\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap(): Promise {\n const app = await NestFactory.create(AppModule, {\n logger: WinstonModule.createLogger({\n exitOnError: false,\n format: format.combine(format.colorize(), format.timestamp(), format.printf(msg => {\n return `${msg.timestamp} [${msg.level}] - ${msg.message}`;\n })),\n transports: [new transports.Console({ level: \"debug\" })], // alert > error > warning > notice > info > debug\n }),\n });\n app.use(helmet());\n await app.listen(process.env.PORT || 3_000);\n}\n\nbootstrap().then(() => {\n // ...\n});\n```\n\nI'm not doing anything in regard to the logging in `app.module.ts`:\n\n```\n// app.module.ts\nimport { SomeController } from \"@controller/some.controller\";\nimport { Module } from \"@nestjs/common\";\nimport { SomeService } from \"@service/some.service\";\n\n@Module({\n controllers: [SomeController],\n imports: [],\n providers: [SomeService],\n})\nexport class AppModule {\n // ...\n}\n```\n\n```\n// some.controller.ts\nimport { Controller, Get, Inject, Param, ParseUUIDPipe, Post } from \"@nestjs/common\";\nimport { SomeService } from \"@service/some.service\";\nimport { WINSTON_MODULE_PROVIDER } from \"nest-winston\";\nimport { Logger } from \"winston\";\n\n@Controller(\"/api/some-path\")\nexport class SomeController {\n constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger, private readonly service: SomeService) {\n // ...\n }\n\n ...\n}\n```\n\nThe application tries to start but fails at some point:\n\n```\n2020-04-06T18:51:08.779Z [info] - Starting Nest application...\n2020-04-06T18:51:08.787Z [error] - Nest can't resolve dependencies of the SomeController (?, SomeService). Please make sure that the argument winston at index [0] is available in the AppModule context.\n\nPotential solutions:\n- If winston is a provider, is it part of the current AppModule?\n- If winston is exported from a separate @Module, is that module imported within AppModule?\n @Module({\n imports: [ /* the Module containing winston */ ]\n })\n```\n\n========================================\n\nTop Answer:\n### Implement Winston custom logger in NestJs project\n\nPrerequisit:\n\nnpm install --save nest-winston winston winston-daily-rotate-file\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { WinstonModule } from 'nest-winston';\nimport * as winston from 'winston';\nimport * as winstonDailyRotateFile from 'winston-daily-rotate-file';\n\nimport { AppModule } from './app.module';\n\nconst transports = {\n console: new winston.transports.Console({\n level: 'silly',\n format: winston.format.combine(\n winston.format.timestamp({\n format: 'YYYY-MM-DD HH:mm:ss',\n }),\n winston.format.colorize({\n colors: {\n info: 'blue',\n debug: 'yellow',\n error: 'red',\n },\n }),\n winston.format.printf((info) => {\n return `${info.timestamp} [${info.level}] [${\n info.context ? info.context : info.stack\n }] ${info.message}`;\n }),\n // winston.format.align(),\n ),\n }),\n combinedFile: new winstonDailyRotateFile({\n dirname: 'logs',\n filename: 'combined',\n extension: '.log',\n level: 'info',\n }),\n errorFile: new winstonDailyRotateFile({\n dirname: 'logs',\n filename: 'error',\n extension: '.log',\n level: 'error',\n }),\n};\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useLogger(\n WinstonModule.createLogger({\n format: winston.format.combine(\n winston.format.timestamp({\n format: 'YYYY-MM-DD HH:mm:ss',\n }),\n winston.format.errors({ stack: true }),\n winston.format.splat(),\n winston.format.json(),\n ),\n transports: [\n transports.console,\n transports.combinedFile,\n transports.errorFile,\n ],\n }),\n );\n await app.listen(4000);\n}\nbootstrap();\n```\n\nNestJs Custom Logger\n\nNestJs Winston NPM Documentation\n\n`Note` Log Levels, file names, dateformat you may edit as per your requirement. officials documentations with more option.\n\n========================================\n\nCode:\n```js\n// main.ts\nimport { NestFactory } from \"@nestjs/core\";\nimport { WinstonModule } from \"nest-winston\";\nimport { format, transports } from \"winston\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap(): Promise<void> {\n  const app = await NestFactory.create(AppModule, {\n    logger: WinstonModule.createLogger({\n      exitOnError: false,\n      format: format.combine(format.colorize(), format.timestamp(), format.printf(msg => {\n        return `${msg.timestamp} [${msg.level}] - ${msg.message}`;\n      })),\n      transports: [new transports.Console({ level: \"debug\" })], // alert > error > warning > notice > info > debug\n    }),\n  });\n  app.use(helmet());\n  await app.listen(process.env.PORT || 3_000);\n}\n\nbootstrap().then(() => {\n  // ...\n});\n```\n\n```js\n// app.module.ts\nimport { SomeController } from \"@controller/some.controller\";\nimport { Module } from \"@nestjs/common\";\nimport { SomeService } from \"@service/some.service\";\n\n@Module({\n  controllers: [SomeController],\n  imports: [],\n  providers: [SomeService],\n})\nexport class AppModule {\n  // ...\n}\n```\n\n```js\n// some.controller.ts\nimport { Controller, Get, Inject, Param, ParseUUIDPipe, Post } from \"@nestjs/common\";\nimport { SomeService } from \"@service/some.service\";\nimport { WINSTON_MODULE_PROVIDER } from \"nest-winston\";\nimport { Logger } from \"winston\";\n\n@Controller(\"/api/some-path\")\nexport class SomeController {\n  constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger, private readonly service: SomeService) {\n    // ...\n  }\n\n  ...\n}\n```\n\n```sh\n2020-04-06T18:51:08.779Z [info] - Starting Nest application...\n2020-04-06T18:51:08.787Z [error] - Nest can't resolve dependencies of the SomeController (?, SomeService). Please make sure that the argument winston at index [0] is available in the AppModule context.\n\nPotential solutions:\n- If winston is a provider, is it part of the current AppModule?\n- If winston is exported from a separate @Module, is that module imported within AppModule?\n  @Module({\n    imports: [ /* the Module containing winston */ ]\n  })\n```\n\n```text\n7.0.7\n```\n\n```text\n3.2.1\n```\n\n```text\n1.3.3\n```\n\n```text\napp.module.ts\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { WinstonModule } from 'nest-winston';\nimport * as winston from 'winston';\n\nconst logger: LoggerConfig = new LoggerConfig();    \n\n@Module({\n  imports: [WinstonModule.forRoot(logger.console())],\n})\nexport class AppModule {}\n```\n\n```js\nimport winston, { format, transports } from \"winston\";\n\nexport class LoggerConfig {\n  private readonly options: winston.LoggerOptions;\n\n  constructor() {\n    this.options = {\n      exitOnError: false,\n      format: format.combine(format.colorize(), format.timestamp(), format.printf(msg => {\n        return `${msg.timestamp} [${msg.level}] - ${msg.message}`;\n      })),\n      transports: [new transports.Console({ level: \"debug\" })], // alert > error > warning > notice > info > debug\n    };\n  }\n\n  public console(): object {\n    return this.options;\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { WinstonModule } from 'nest-winston';\nimport * as winston from 'winston';\nimport * as winstonDailyRotateFile from 'winston-daily-rotate-file';\n\nimport { AppModule } from './app.module';\n\nconst transports = {\n  console: new winston.transports.Console({\n    level: 'silly',\n    format: winston.format.combine(\n      winston.format.timestamp({\n        format: 'YYYY-MM-DD HH:mm:ss',\n      }),\n      winston.format.colorize({\n        colors: {\n          info: 'blue',\n          debug: 'yellow',\n          error: 'red',\n        },\n      }),\n      winston.format.printf((info) => {\n        return `${info.timestamp} [${info.level}] [${\n          info.context ? info.context : info.stack\n        }] ${info.message}`;\n      }),\n      // winston.format.align(),\n    ),\n  }),\n  combinedFile: new winstonDailyRotateFile({\n    dirname: 'logs',\n    filename: 'combined',\n    extension: '.log',\n    level: 'info',\n  }),\n  errorFile: new winstonDailyRotateFile({\n    dirname: 'logs',\n    filename: 'error',\n    extension: '.log',\n    level: 'error',\n  }),\n};\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useLogger(\n    WinstonModule.createLogger({\n      format: winston.format.combine(\n        winston.format.timestamp({\n          format: 'YYYY-MM-DD HH:mm:ss',\n        }),\n        winston.format.errors({ stack: true }),\n        winston.format.splat(),\n        winston.format.json(),\n      ),\n      transports: [\n        transports.console,\n        transports.combinedFile,\n        transports.errorFile,\n      ],\n    }),\n  );\n  await app.listen(4000);\n}\nbootstrap();\n```\n\n```text\nNote\n```\n\n========================================\n\nComments:\n- Indeed, that's what I ended up doing: a class that returns a `winston.LoggerOptions` and reuse the config in both places. That's the only way I found to make it work.\n- Oh ok - afaik that's the way to go if you really need the winston logger during nestjs bootstrapping. But let's see what the others have to say :)\n- I found it super-weird that it must be declared in both places, but not a deal-breaker :monkey:\n- With that approach, when I use logger.log function, it throws an TS error and I try to extend LoggerConfig class but I am not able to implement that, any tips?","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":373,"estimatedTokens":2445}}324{"id":"stack-62306451","source":"stackoverflow","questionId":62306451,"title":"Nestjs IsEnum dto validation and swagger","tags":["nestjs","nestjs-swagger"],"text":"Title: Nestjs IsEnum dto validation and swagger\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nThis is working fine:\n\n```\nimport { IsIn } from 'class-validator';\n import { ApiProperty } from '@nestjs/swagger';\n\n export class createEventDto {\n @IsIn([0, 1, 2, 3, 4, 5])\n @ApiProperty({\n description: 'description of the severity property',\n })\n severity: number;\n }\n```\n\nand looks like this in swagger:\nhttps://i.sstatic.net/VZLfr.png\n\nI am trying to understand how can I change severity type to enum, what I've tried:\n\n```\nexport enum Severity {\n Critical = 1,\n Major = 2,\n Minor = 3,\n Warning = 2,\n Info = 1,\n Clear = 0,\n}\n```\n\n```\nimport { IsEnum } from 'class-validator';\n import { ApiProperty } from '@nestjs/swagger';\n import { Severity} from '../enums/severities';\n\n export class createEventDto {\n @IsEnum(Severity)\n @ApiProperty({\n description: 'description of the severity property',\n })\n severity: Severity;\n }\n```\n\nAlthough it is working, swagger looks a bit off (example is incorrect and the description for severity in schema becomes nested in brackets:\nhttps://i.sstatic.net/6icgT.png\n\n========================================\n\nCode:\n```js\nimport { IsIn } from 'class-validator';\n    import { ApiProperty } from '@nestjs/swagger';\n\n    export class createEventDto {\n      @IsIn([0, 1, 2, 3, 4, 5])\n      @ApiProperty({\n        description: 'description of the severity property',\n      })\n      severity: number;\n    }\n```\n\n```js\nexport enum Severity {\n  Critical = 1,\n  Major = 2,\n  Minor = 3,\n  Warning = 2,\n  Info = 1,\n  Clear = 0,\n}\n```\n\n```js\nimport { IsEnum } from 'class-validator';\n    import { ApiProperty } from '@nestjs/swagger';\n    import { Severity} from '../enums/severities';\n\n    export class createEventDto {\n      @IsEnum(Severity)\n      @ApiProperty({\n        description: 'description of the severity property',\n      })\n      severity: Severity;\n    }\n```\n\n```js\nimport { IsEnum } from 'class-validator';\n import { ApiProperty } from '@nestjs/swagger';\n import { Severity} from '../enums/severities';\n\n export class createEventDto {\n   @IsEnum(Severity)\n   @ApiProperty({\n     description: 'description of the severity property',\n     enum: Severity\n   })\n   severity: Severity;\n }\n```\n\n```text\nenum\n```\n\n```text\nApiProperty\n```\n\n========================================\n\nComments:\n- Thanks, I was looking into that doc, but that specific example somehow escaped my eyes.. :/\n- Actually that link now gets redirected to docs.nestjs.com/openapi/introduction, where there is no mention about enums. Nest's swagger integration seems to be a poorly documented topic","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":122,"estimatedTokens":653}}325{"id":"stack-72272265","source":"stackoverflow","questionId":72272265,"title":"How can my class-validator validate union string | number?","tags":["typescript","nestjs","typeorm","class-validator"],"text":"Title: How can my class-validator validate union string | number?\nTags: typescript, nestjs, typeorm, class-validator\nSource: Stack Overflow\n\nQuestion:\nI have an simple DTO class for validation\n\n```\nclass SearchIssuerDto {\n search: string | number;\n}\n```\n\nWhat is the correct way to validate the search param that it can accept an string or a number ?\n\n========================================\n\nCode:\n```js\nclass SearchIssuerDto {\n    search: string | number;\n}\n```\n\n```text\n@ValidatorConstraint({ name: 'string-or-number', async: false })\nexport class IsNumberOrString implements ValidatorConstraintInterface {\n  validate(text: any, args: ValidationArguments) {\n    return typeof text === 'number' || typeof text === 'string';\n  }\n\n  defaultMessage(args: ValidationArguments) {\n    return '($value) must be number or string';\n  }\n}\n```\n\n```text\nclass SearchIssuerDto {\n  @IsDefined()\n  @Validate(IsNumberOrString)\n  search: number | string;\n}\n```\n\n========================================\n\nComments:\n- I was wondering if it's possible to do it without custom validator, but if it's impossible thanks mate\n- I looked around for other solution, but sadly did not find anything else","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":295}}326{"id":"stack-55175262","source":"stackoverflow","questionId":55175262,"title":"Nest JS two instances of the same provider","tags":["javascript","node.js","typescript","jestjs","nestjs"],"text":"Title: Nest JS two instances of the same provider\nTags: javascript, node.js, typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nHi on a test suite it appears to me that I have 2 living instances of a same provider, one for the implementation and another one for the real implementation.\n\nI base my conclusion in a fact that on my test I tried replace a method by a jest.fn call but still, on the service I am testing the method still points to the original implementation.\n\nWhat makes it even more odd is that I was able to mock another service performing exactly the same procedure, as if, depending on how those services were injected (where they came from in the container graph) it would or not work.\n\nI'll try to some snippets, but of course, only a small repo could actually reproduce it, but perhaps someone has an insight:\n\n```\nbeforeAll(async done => {\n app = await Test.createTestingModule({\n imports: [\n SOME_MODULES,\n ],\n providers: [\n EssayApplicationService,\n ReviewFacade,\n ExamCacheResultService,\n ],\n }).compile();\n\n essayApplicationService = app.get(EssayApplicationService)\n reviewFacade = app.get(ReviewFacade)\n examCacheResult = app.get(ExamCacheResultService)\n await app.init()\n done()\n })\n```\n\n```\nit('should invoke review only once', async done => {\n\n reviewFacade.startReview = jest.fn() --> this works\n examCacheResult.clearCachedResult = jest.fn() --> this fails\n\n await essayApplicationService.finishApplication()\n\n expect(reviewFacade.startReview).toHaveBeenCalledTimes(1)\n expect(reviewFacade.startReview).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }))\n expect(examCacheResult.clearCachedResult).toHaveBeenCalledTimes(1) ---> here this fails, although it's called!!\n```\n\nSo,the issue boils down to the fact that I'm 100% positive that both methods were called on the service under test, but the second for some reason wasn't replaced by the mock\n\n========================================\n\nCode:\n```text\nbeforeAll(async done => {\n    app = await Test.createTestingModule({\n      imports: [\n        SOME_MODULES,\n      ],\n      providers: [\n        EssayApplicationService,\n        ReviewFacade,\n        ExamCacheResultService,\n      ],\n    }).compile();\n\n    essayApplicationService = app.get<EssayApplicationService>(EssayApplicationService)\n    reviewFacade = app.get<ReviewFacade>(ReviewFacade)\n    examCacheResult = app.get<ExamCacheResultService>(ExamCacheResultService)\n    await app.init()\n    done()\n  })\n```\n\n```text\nit('should invoke review only once', async done => {\n\n    reviewFacade.startReview = jest.fn() --> this works\n    examCacheResult.clearCachedResult = jest.fn() --> this fails\n\n    await essayApplicationService.finishApplication()\n\n    expect(reviewFacade.startReview).toHaveBeenCalledTimes(1)\n    expect(reviewFacade.startReview).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }))\n    expect(examCacheResult.clearCachedResult).toHaveBeenCalledTimes(1) ---> here this fails, although it's called!!\n```\n\n```text\nexport class UsersService {\n  constructor(private connection: DatabaseConnection) {}\n  // ...\n}\n```\n\n```text\nmodule = await Test.createTestingModule({\n  providers: [\n    UsersService,\n    { provide: DatabaseConnection, useClass: DbConnectionMock },\n  ],\n}).compile();\ndatabaseMock = module.get(DatabaseConnection);\ndatabaseMock.findMany.mockReturnValue([]);\n```\n\n```text\nconst moduleFixture = await Test.createTestingModule({\n      imports: [AppModule],\n    }).overrideProvider(DatabaseConnection).useClass(InMemoryDatabaseConnection)\n      .overrideProvider(ExternalApiService).useValue(externalApiMock)\n      .compile();\n    app = moduleFixture.createNestApplication();\n    externalApiMock.get.mockReturnValueOnce({data: [...]});\n    await app.init();\n```\n\n```text\nExamCacheResultService\n```\n\n```text\napp.get(ExamCacheResultService)\n```\n\n```text\nfinishApplication\n```\n\n```text\nUserService\n```\n\n```text\nUsersController\n```\n\n```text\nUsersService\n```\n\n```text\nDatabaseConnection\n```\n\n```text\nUsersService\n```\n\n```text\nDatabaseConnection\n```\n\n```text\nUsersModule\n```\n\n```text\nAppModule\n```\n\n========================================\n\nComments:\n- Although it doesn't really solves the question is a very useful piece of information!\n- I had imported the providers due to another issue I had with some unclear unresolved dependencies. After restructuring the app a bit to remove some \"cycles\" I was able to setup in a very similar fashion to the e2e (i.e only the modules). There are, though, some very obscure error messages for some dependency resolution scenarios, and the worst, only for tests. But nonetheless, still, nest rocks after one learns some tweaks\n- This did lead me to realize I had specified my dependency in two places: once in the `providers` of the module where it was defined, and a second time in the `providers` of another module consuming the first, making Nest resolve two separate instances. The solution was to indicate the dependency as `exports` on the first module, and avoid specifying it in `providers` of the consuming module. Basically, **if you want a single instance of something, make sure it's only listed in a single module's `providers` list** (for your entire app).\n- @Paul Good find! There is a dedicated thread about exporting providers, see here: stackoverflow.com/a/51821523/4694994","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":166,"estimatedTokens":1329}}327{"id":"stack-78106894","source":"stackoverflow","questionId":78106894,"title":"ERROR [MailerService] Transporter is ready. Nest.js. @nestjs-modules/mailer","tags":["nestjs","nodemailer"],"text":"Title: ERROR [MailerService] Transporter is ready. Nest.js. @nestjs-modules/mailer\nTags: nestjs, nodemailer\nSource: Stack Overflow\n\nQuestion:\nIn the terminal, an error occurs: [Nest] 21016 - 05.03.2024, 19:05:42 ERROR [MailerService] Transporter is ready. Emails are being sent. I don't know what the problem is, I need help.\n\nThe code has been checked, there are no errors.enter image description here\n\n========================================\n\nTop Answer:\nAre working to fix this issue :)\n\nhttps://github.com/nest-modules/mailer/issues/1131\n\n========================================\n\nCode:\n```text\nprivate verifyTransporter(transporter: Transporter, name?: string): void {\nconst transporterName = name ?  '${name}' : '';\ntransporter.verify()\n.then(() => this.mailerLogger.error(Transporter${transporterName} is ready))\n```\n\n```text\nโœ….then(() => this.mailerLogger.log(Transporter${transporterName} is ready))\n```\n\n```text\n.then(() => this.mailerLogger.error(Transporter${transporterName} is ready))\n```\n\n```text\nnpm i @nestjs-modules/mailer@1.10.3\n```\n\n========================================\n\nComments:\n- I am using Mailer module on local an in a docker container. Inside docker container this error appears, but not on local. I used the same env on local that I am using inside docker and it's the same thing.\n- The same for me, work fine on localhost, fail with \"ERROR [MailerService] Transporter is ready\" in docker container\n- For me even locally says `ERROR Transporter is redy`\n- Maybe it is related to Node version you are running, localhost often differs from docker container.\n- That's a bug in the `@nestjs-modules&#47;mailer` indeed. There's already a fix merged into `main` but it's not released yet. Here's a GitHub issue and a PR that are related to that bug.\n- When will this fix be released?","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":453}}328{"id":"stack-58970970","source":"stackoverflow","questionId":58970970,"title":"Nestjs log response data object","tags":["javascript","typescript","express","nestjs"],"text":"Title: Nestjs log response data object\nTags: javascript, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to log the incoming requests and outgoing responses in NestJs. I took information from here Logging request/response in Nest.js and from the docs NestJs Aspect Interception.\n\nIt would be awesome to achieve this by not using external packages, so I would highly prefer a native \"Nest\" solution.\n\nFor the request logging I currently use this code\n\n```\n@Injectable()\nexport class RequestInterceptor implements NestInterceptor {\n private logger: Logger = new Logger(RequestInterceptor.name);\n\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n const {\n originalUrl,\n method,\n params,\n query,\n body,\n } = context.switchToHttp().getRequest();\n\n this.logger.log({\n originalUrl,\n method,\n params,\n query,\n body,\n });\n\n return next.handle();\n }\n}\n```\n\nThis would log the following result for `GET /users`\n\nhttps://i.sstatic.net/Zlv2g.png\n\nI also want to log the outgoing response. Currently I use this interceptor\n\n```\n@Injectable()\nexport class ResponseInterceptor implements NestInterceptor {\n private logger: Logger = new Logger(ResponseInterceptor.name);\n\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n const { statusCode } = context.switchToHttp().getResponse();\n\n return next.handle().pipe(\n tap(() =>\n this.logger.log({\n statusCode,\n }),\n ),\n );\n }\n}\n```\n\nThis would log the following result for `GET /users`\n\nhttps://i.sstatic.net/j9CsQ.png\n\nbut how can I access the data that was sent back to the client?\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class RequestInterceptor implements NestInterceptor {\n  private logger: Logger = new Logger(RequestInterceptor.name);\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const {\n      originalUrl,\n      method,\n      params,\n      query,\n      body,\n    } = context.switchToHttp().getRequest();\n\n    this.logger.log({\n      originalUrl,\n      method,\n      params,\n      query,\n      body,\n    });\n\n    return next.handle();\n  }\n}\n```\n\n```text\n@Injectable()\nexport class ResponseInterceptor implements NestInterceptor {\n  private logger: Logger = new Logger(ResponseInterceptor.name);\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const { statusCode } = context.switchToHttp().getResponse();\n\n    return next.handle().pipe(\n      tap(() =>\n        this.logger.log({\n          statusCode,\n        }),\n      ),\n    );\n  }\n}\n```\n\n```text\nGET /users\n```\n\n```text\nGET /users\n```\n\n```js\n@Injectable()\nexport class AspectLogger implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler) {\n    const req = context.switchToHttp().getRequest();\n    const { statusCode } = context.switchToHttp().getResponse();\n    const { originalUrl, method, params, query, body } = req;\n\n    console.log({\n      originalUrl,\n      method,\n      params,\n      query,\n      body,\n    });\n\n    return next.handle().pipe(\n      tap((data) =>\n        console.log({\n          statusCode,\n          data,\n        })\n      )\n    );\n  }\n}\n```\n\n```text\ntap\n```\n\n========================================\n\nComments:\n- This might help someone: stackoverflow.com/a/79908802/5686493\n- as formatted the response body logger didn't work for me, I had to write it as `return next.handle().pipe(tap(data => console.log({ statusCode, data })));` in case anyone else has a linter that is fighting them","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":163,"estimatedTokens":876}}329{"id":"stack-48638420","source":"stackoverflow","questionId":48638420,"title":"Nest JS - Unable to inject service to middlewere","tags":["node.js","nestjs"],"text":"Title: Nest JS - Unable to inject service to middlewere\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have created an auth middlewere for checking each request, the middlewere is using server (only if data was not found in the req.connection).\nI'm trying to inject the service into my middlewere and I keep getting the same error \"Nest can't resolve dependencies of the AuthenticationMiddleware (?). Please verify whether [0] argument is available in the current context.\"\n\nAuthenticationModule:\n\n```\n@Module({\n imports: [ServerModule],\n controllers: [AuthenticationMiddleware],\n})\nexport class AuthenticationModule {\n}\n```\n\nAuthenticationMiddleware:\n\n```\n@Injectable()\nexport class AuthenticationMiddleware implements NestMiddleware {\n\nconstructor(private readonly service : UserService) {}\n\nresolve(): (req, res, next) => void {\n return (req, res, next) => {\n if (req.connection.user)\n next();\n\n this.service.getUsersPermissions() \n }\n}\n```\n\nServerModule:\n\n```\n@Module({\n components: [ServerService],\n controllers: [ServerController],\n exports: [ServerService]\n}) \n export class ServerModule {}\n```\n\nApplicationModule:\n\n```\n@Module({\n imports: [\n CompanyModule,\n ServerModule,\n AuthenticationModule\n ]\n})\n\nexport class ApplicationModule implements NestModule{\n configure(consumer: MiddlewaresConsumer): void {\n consumer.apply(AuthenticationMiddleware).forRoutes(\n { path: '/**', method: RequestMethod.ALL }\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n   imports: [ServerModule],\n   controllers: [AuthenticationMiddleware],\n})\nexport class AuthenticationModule {\n}\n```\n\n```text\n@Injectable()\nexport class AuthenticationMiddleware implements NestMiddleware {\n\nconstructor(private readonly service : UserService) {}\n\nresolve(): (req, res, next) => void {\n return (req, res, next) => {\n   if (req.connection.user)\n    next();\n\n  this.service.getUsersPermissions()     \n  }\n}\n```\n\n```text\n@Module({\n components: [ServerService],\n controllers: [ServerController],\n exports: [ServerService]\n})    \n export class ServerModule {}\n```\n\n```text\n@Module({\n  imports: [\n    CompanyModule,\n    ServerModule,\n    AuthenticationModule\n  ]\n})\n\nexport class ApplicationModule implements NestModule{\n  configure(consumer: MiddlewaresConsumer): void {\n  consumer.apply(AuthenticationMiddleware).forRoutes(\n      { path: '/**', method: RequestMethod.ALL }\n   );\n }\n}\n```\n\n```text\n@Injectable()\nexport class AuthenticationMiddleware implements NestMiddleware {\n\n  constructor(private readonly service : ServerService) {}\n\n  resolve(): (req, res, next) => void {\n    return (req, res, next) => {\n      if (req.connection.user)\n        next();\n\n    this.service.getUsersPermissions()     \n  }\n}\n```\n\n```text\nAuthMiddleware\n```\n\n```text\nUserService\n```\n\n```text\nServerModule\n```\n\n```text\nAuthenticationModule\n```\n\n```text\nServerService\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":158,"estimatedTokens":716}}330{"id":"stack-60857548","source":"stackoverflow","questionId":60857548,"title":"How to pass state during Nest.js Authentication flow","tags":["oauth","passport.js","nestjs"],"text":"Title: How to pass state during Nest.js Authentication flow\nTags: oauth, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nwhile performing a Google OAuth flow, it is possible to pass an encrypted state (base64) that will be passed as parameter to the final callback. This was useful when you want to redirect your user to a specific page for example. (https://developers.google.com/identity/protocols/oauth2/web-server)\n\nIs it possible to use the OAuth state with the Nest.js authentication library? It seems that the state parameter is ignored and I can't find anything on the documentation.\n\n```\n@Injectable()\nexport class GoogleStrategy extends PassportStrategy(Strategy, 'google') {\n constructor(readonly configService: ConfigService) {\n super({\n clientID: configService.get('google.clientId'),\n clientSecret: configService.get('google.clientSecret'),\n callbackURL: `${configService.get('apiUri')}${configService.get('google.callbackUrl')}`,\n passReqToCallback: true,\n scope: ['profile', 'email'],\n });\n }\n}\n```\n\n========================================\n\nTop Answer:\n```\n@Injectable()\nexport class GoogleAuthGuard extends AuthGuard('google') {\n getAuthenticateOptions(context: ExecutionContext) {\n // you can get access to the request object.\n // const request = this.getRequest(context);\n\n return {\n state: `my-custom-state_${Date.now()}`,\n };\n }\n}\n```\n\nand in your `auth.controller` you can get access to this `state` param though query values.\n\n```\n@UseGuards(GoogleAuthGuard)\n@Get('google/callback')\nasync googleCallback(@Query('state') state: string): Promise {\n console.log({ state });\n\n return state;\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class GoogleStrategy extends PassportStrategy(Strategy, 'google') {\n  constructor(readonly configService: ConfigService) {\n    super({\n      clientID: configService.get('google.clientId'),\n      clientSecret: configService.get('google.clientSecret'),\n      callbackURL: `${configService.get('apiUri')}${configService.get('google.callbackUrl')}`,\n      passReqToCallback: true,\n      scope: ['profile', 'email'],\n    });\n  }\n}\n```\n\n```text\nauthenticate(req, options) {\n  options.state = 'your state value here'\n  super.authenticate(req, options)\n}\n```\n\n```text\nauthenticate\n```\n\n```js\n@Injectable()\nexport class GoogleAuthGuard extends AuthGuard('google') {\n  getAuthenticateOptions(context: ExecutionContext) {\n    // you can get access to the request object.\n    // const request = this.getRequest(context);\n\n    return {\n      state: `my-custom-state_${Date.now()}`,\n    };\n  }\n}\n```\n\n```js\n@UseGuards(GoogleAuthGuard)\n@Get('google/callback')\nasync googleCallback(@Query('state') state: string): Promise<string> {\n  console.log({ state });\n\n  return state;\n}\n```\n\n```text\nauth.controller\n```\n\n```text\nstate\n```\n\n========================================\n\nComments:\n- Thank you for your answer! I'll wait for a real solution from NestJS but this work and is what we ended up doing.\n- **Important for those reading this answer** you must **not** set `store: true` or `state: true` in the strategy configuration for this to work. It would've saved me a half hour to realize this earlier","metadata":{"transformedAt":"2026-08-18T18:33:02.432Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":119,"estimatedTokens":797}}331{"id":"stack-69120748","source":"stackoverflow","questionId":69120748,"title":"NestJS conditional module import","tags":["node.js","typescript","nestjs"],"text":"Title: NestJS conditional module import\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there a way to import a module conditionally?\nI want to check if the .env file exists, so I configure the env variables using the ConfigModule.\n\n```\nimports: [\n UsersModule,\n ConfigModule.forRoot({ load: [configuration] }), //I want to use this just if the .env file exists\n MongooseModule.forRoot(\n `mongodb+srv://${process.env.DATABASE_USER}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_URL}`,\n ),\n ],\n```\n\nWhy: I deployed an api and configured the environment variables using heroku, and in production it works, but I dont have this variables to run the code in development, and I can't expose the .env in my public repository because this contains my database credentials. Because of this, I thinked to create a .env file and put it on .gitignore to don't publish with this file\n\n========================================\n\nTop Answer:\nhere's a small snippet that does importing within a code construct (dynamic importing, like how require's would allow):\n\n```\nconst events = files.filter(file => file.endsWith('.mjs'));\n for (const file of events) {\n import(`${eventDir}${file}`)\n .then(function({ default: event }) {\n const eventName = file.split('.')[0];\n dBot.on(eventName, event.bind(null, dBot));\n console.log(`${success} Loaded event ${eventName}`);\n })\n .catch(function(err) {\n console.error(`${error}: Error loading event: ${err}`);\n return;\n });\n```\n\nI think this gets you what you want, just put the conditions around it as needed, instead of my for loop, use an if statement, or whatever.\n\n========================================\n\nCode:\n```text\nimports: [\n    UsersModule,\n    ConfigModule.forRoot({ load: [configuration] }), //I want to use this just if the .env file exists\n    MongooseModule.forRoot(\n      `mongodb+srv://${process.env.DATABASE_USER}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_URL}`,\n    ),\n  ],\n```\n\n```js\n@Module({\n  imports: [\n   ...(isEnvPresent ? [ConfigModule.forRoot({ load: [configuration] })] : []),\n   UsersModule,\n  ],\n})\n```\n\n```text\nspread\n```\n\n```text\nconst events = files.filter(file => file.endsWith('.mjs'));\n        for (const file of events) {\n            import(`${eventDir}${file}`)\n                .then(function({ default: event }) {\n                    const eventName = file.split('.')[0];\n                    dBot.on(eventName, event.bind(null, dBot));\n                    console.log(`${success} Loaded event ${eventName}`);\n                })\n                .catch(function(err) {\n                    console.error(`${error}: Error loading event: ${err}`);\n                    return;\n                });\n```\n\n========================================\n\nComments:\n- or, to be a little more idiomatic (I guess), you could create a dynamic module that returns `ConfigModule.forRoot({ load: [configuration] })` if `isEnvPresent === true`, and `[]` otherwise\n- That would be a bunch more (unnecessary, IMO) code to just do a simple conditional import.\n- I used your spread idea and I setted \"NODE_ENV=dev\" on my \"start:dev\" script, so I check using ...(process.env.NODE_ENV == 'dev' ? [ConfigModule.forRoot({ load: [configuration] })] : []), Thank you so much\n- How did you handle injection in the service(s) when the module is optional? I could not make it work so far.","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":841}}332{"id":"stack-72253499","source":"stackoverflow","questionId":72253499,"title":"Module '\"rxjs\"' has no exported member 'firstValueFrom'","tags":["node.js","angularjs","rxjs","nestjs"],"text":"Title: Module '\"rxjs\"' has no exported member 'firstValueFrom'\nTags: node.js, angularjs, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nApp.service file looks like this:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { HttpService } from '@nestjs/axios';\nimport { Observable, firstValueFrom } from 'rxjs';\n// import { firstValueFrom } from 'rxjs';\n\n@Injectable()\nexport class AppService {\n constructor(private httpService: HttpService) {}\n async getWeatherForecasts() {\n const url =\n 'http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json';\n const { data } = await firstValueFrom(this.httpService.get(url));\n return data;\n }\n}\n```\n\nPackage.json File looks like this:\n\n```\n\"dependencies\": {\n \"@fmr-pr103625/nest-scaffold\": \"^1.5.5\",\n \"@nestjs/apollo\": \"^10.0.9\",\n \"@nestjs/axios\": \"0.0.7\",\n \"@nestjs/common\": \"^7.6.18\",\n \"@nestjs/core\": \"^7.6.18\",\n \"@nestjs/graphql\": \"^10.0.9\",\n \"@nestjs/platform-express\": \"^7.6.18\",\n \"apollo-server-express\": \"^3.6.7\",\n \"axios\": \"^0.27.2\",\n \"graphql\": \"^16.3.0\",\n \"graphql-tools\": \"^8.2.8\",\n \"isomorphic-fetch\": \"^3.0.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^3.0.2\",\n \"rxjs\": \"^5.5.10\",\n \"rxjs-compat\": \"^6.6.7\",\n \"ts-morph\": \"^14.0.0\"\n },\n```\n\n-----------------**********************--------------------------------\n\nI am not able to import firstValueForm from rxjs.\n\nThings i already tried:\n\n- to downgrade the version of rxjs from 6.\n\n========================================\n\nTop Answer:\nIf you're using TypeScript, make sure your tsconfig.json configuration is correct and compatible with the ECMAScript features you're using. Particularly check the module, target, and lib options.\n\nFor example, your tsconfig.json might look similar to this (adjust as needed for your project):\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"esnext\",\n \"target\": \"es2015\",\n \"lib\": [\"es2018\", \"dom\"]\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { HttpService } from '@nestjs/axios';\nimport { Observable, firstValueFrom } from 'rxjs';\n// import { firstValueFrom } from 'rxjs';\n\n@Injectable()\nexport class AppService {\n  constructor(private httpService: HttpService) {}\n  async getWeatherForecasts() {\n    const url =\n      'http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json';\n    const { data } = await firstValueFrom(this.httpService.get(url));\n    return data;\n  }\n}\n```\n\n```text\n\"dependencies\": {\n    \"@fmr-pr103625/nest-scaffold\": \"^1.5.5\",\n    \"@nestjs/apollo\": \"^10.0.9\",\n    \"@nestjs/axios\": \"0.0.7\",\n    \"@nestjs/common\": \"^7.6.18\",\n    \"@nestjs/core\": \"^7.6.18\",\n    \"@nestjs/graphql\": \"^10.0.9\",\n    \"@nestjs/platform-express\": \"^7.6.18\",\n    \"apollo-server-express\": \"^3.6.7\",\n    \"axios\": \"^0.27.2\",\n    \"graphql\": \"^16.3.0\",\n    \"graphql-tools\": \"^8.2.8\",\n    \"isomorphic-fetch\": \"^3.0.0\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^5.5.10\",\n    \"rxjs-compat\": \"^6.6.7\",\n    \"ts-morph\": \"^14.0.0\"\n  },\n```\n\n```text\nfirstValueFrom\n```\n\n```text\nRxjs 7\n```\n\n```text\ntoPromise\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"module\": \"esnext\",\n    \"target\": \"es2015\",\n    \"lib\": [\"es2018\", \"dom\"]\n  }\n}\n```\n\n========================================\n\nComments:\n- looks like `firstValueForm` is available on rxjs v7.","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":143,"estimatedTokens":829}}333{"id":"stack-71035309","source":"stackoverflow","questionId":71035309,"title":"file upload using Axios in React","tags":["javascript","reactjs","axios","nestjs"],"text":"Title: file upload using Axios in React\nTags: javascript, reactjs, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am uploading a file in `React` using `Axios`.\nWhen I am doing\n\n`alert(values.attachedFile[0]);`, it displays:\n\nhttps://i.sstatic.net/QhYeV.png\n\nbut when I am sending `values.attachedFile[0]` in an `Axios` post request, an empty object is being sent.\n\n```\nconst { result } = await axios.post(app.resourceServerUrl + '/file/upload', {\n data: values.attachedFile[0],\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n});\n```\n\nYou can see the request data being empty:\n\nhttps://i.sstatic.net/jPn9I.png\n\nWhat is my mistake?\n\n========================================\n\nCode:\n```text\nconst { result } = await axios.post(app.resourceServerUrl + '/file/upload', {\n    data: values.attachedFile[0],\n    headers: {\n        'Content-Type': 'multipart/form-data',\n    },\n});\n```\n\n```text\nReact\n```\n\n```text\nAxios\n```\n\n```text\nalert(values.attachedFile[0]);\n```\n\n```text\nvalues.attachedFile[0]\n```\n\n```text\nAxios\n```\n\n```text\nconst formData = new FormData();\n\n// ...\n\nformData.append(\"data\", values.attachedFile[0]);\naxios.post(app.resourceServerUrl + '/file/upload', formData, {\n    headers: {\n      'Content-Type': 'multipart/form-data'\n    }\n})\n```\n\n========================================\n\nComments:\n- Show source code of nest.js controller who manage the route `file&#47;upload`","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":78,"estimatedTokens":348}}334{"id":"stack-55414165","source":"stackoverflow","questionId":55414165,"title":"Why does whitelist dont get error with wrong model NestJs","tags":["javascript","node.js","angular","typescript","nestjs"],"text":"Title: Why does whitelist dont get error with wrong model NestJs\nTags: javascript, node.js, angular, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use a white list in my route's body validation. I expect that only data is accepted that confirms to my model and if some parameter is sent that is not part of my model DTO an error must be thrown.\n\n**This is my DTO :** \n\n```\nexport class RegisterDTO {\n @MinLength(5)\n userName: string;\n\n @MinLength(8)\n password: string;\n\n @IsNotEmpty()\n seller: boolean;\n\n address: {\n city: string;\n street: string;\n apartment?: string;\n };\n}\n```\n\n**This is my controller :**\n\n```\n@Post('register')\n@UsePipes(new ValidationPipe({ transform: true, whitelist: true}))\nasync register(@Body() userDTO: RegisterDTO) {\n const user = await this.userService.create(userDTO);\n const payload: Payload = {\n userName: user.userName,\n seller: user.seller,\n };\n\n const token = await this.authService.signPayload(payload);\n return {user, token};\n}\n```\n\n**But when I sent this data I dont get an error:**\n\n```\n{\n \"userName\": \"userdasdnasdasdadad\",\n \"password\": \"passwdasdasdasadasdasda\",\n \"address\": {\n \"city\": \"kiev\",\n \"street\": \"amosova\"\n },\n \"seller\": false,\n \"test\": \"test\"\n}\n```\n\n**\"test\": \"test\" must be not allowed as a parameter; I expect an error to be thrown but there is none**\n\n========================================\n\nCode:\n```text\nexport class RegisterDTO {\n    @MinLength(5)\n    userName: string;\n\n    @MinLength(8)\n    password: string;\n\n    @IsNotEmpty()\n    seller: boolean;\n\n    address: {\n        city: string;\n        street: string;\n        apartment?: string;\n    };\n}\n```\n\n```text\n@Post('register')\n@UsePipes(new ValidationPipe({ transform: true, whitelist: true}))\nasync register(@Body() userDTO: RegisterDTO) {\n    const user = await this.userService.create(userDTO);\n    const payload: Payload = {\n        userName: user.userName,\n        seller: user.seller,\n    };\n\n    const token = await this.authService.signPayload(payload);\n    return {user, token};\n}\n```\n\n```text\n{\n   \"userName\": \"userdasdnasdasdadad\",\n   \"password\": \"passwdasdasdasadasdasda\",\n   \"address\": {\n      \"city\": \"kiev\",\n      \"street\": \"amosova\"\n   },\n   \"seller\": false,\n   \"test\": \"test\"\n}\n```\n\n```text\n@UsePipes(\n    new ValidationPipe({\n      transform: true,\n      whitelist: true,\n      forbidNonWhitelisted: true,\n    }),\n  )\n```\n\n```text\nwhitelist\n```\n\n```text\ntest\n```\n\n```text\nforbidNonWhitelisted\n```\n\n========================================\n\nComments:\n- Thanks for answer. I have added forbidNonWhitelisted: true; It remove test from responce, but doesnt throw an error snag.gy/ideuRb.jpg\n- It is work as all fine and give me token , but i sent wrong model and wanna to get an error\n- Mh, that's weird. I've tried it here and it works: codesandbox.io/s/&hellip;\n- When you sent a POST request to 9jlkpxv744.sse.codesandbox.io with `{ \"username\": \"kiwi\", \"firstname\": \"123456\" }` you'll get a 400 with `\"whitelistValidation\": \"property firstname should not exist\"`\n- Thanks. It help me. Problem was that i define to use globalPipe adn add forbidNonWhitelisted only local to controler but forgot to add to globaluse\n- It is happen because my globalUsePipe dont work(( and i add ValidationPipe to controler\n- But also I saw. That props without _@Decorator from validation class also dont allowed and you must use _@Allow\n- Yup, that's true! Please also see this answer, if you want to use nested validation (for example for your address): stackoverflow.com/a/53685045/4694994","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":145,"estimatedTokens":880}}335{"id":"stack-64285189","source":"stackoverflow","questionId":64285189,"title":"How to save array of json object in postgres using typeorm","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to save array of json object in postgres using typeorm\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to save an array of object in jsonb type in postgres\n\n**Entity**\n\n```\n@Column({type: 'jsonb', array: true, nullable: true})\ntestJson: object[];\n```\n\nThe json I am sending in postman\n\n```\n{\n \n \"testJson\": [\n {\"skill\": \"docker\", \"experience\": true},\n {\"skill\": \"kubernetes\", \"experience\": false}\n ]\n}\n```\n\nI am getting error 'malformed array literal:'\n\nAlso kindly tell if I can query such data types?\n\n========================================\n\nTop Answer:\nAbove answer is helpful.\nBut it needs some update.\nFollowing code worked for me in nest.js.\n\n```\ninterface dataType {\n key: number;\n asset: string;\n owner: string;\n value: string;\n}\n\n@Entity()\nexport class Will {\n @Column({\n type: \"json\",\n nullable: true,\n transformer: {\n to(value: dataType[]): string {\n return JSON.stringify(value);\n },\n from(value: string): dataType[] {\n return JSON.parse(value);\n },\n },\n })\n dataOutSideWill?: dataType[];\n}\n```\n\n========================================\n\nCode:\n```text\n@Column({type: 'jsonb', array: true, nullable: true})\ntestJson: object[];\n```\n\n```text\n{\n    \n    \"testJson\": [\n        {\"skill\": \"docker\", \"experience\": true},\n        {\"skill\": \"kubernetes\", \"experience\": false}\n    ]\n}\n```\n\n```text\n@Column('jsonb', {nullable: true})\ntestJson?: object[];\n```\n\n```text\ninterface dataType {\n  key: number;\n  asset: string;\n  owner: string;\n  value: string;\n}\n\n@Entity()\nexport class Will {\n  @Column({\n    type: \"json\",\n    nullable: true,\n    transformer: {\n      to(value: dataType[]): string {\n        return JSON.stringify(value);\n      },\n      from(value: string): dataType[] {\n        return JSON.parse(value);\n      },\n    },\n  })\n  dataOutSideWill?: dataType[];\n}\n```\n\n========================================\n\nComments:\n- Quick question, why are you doing the transformation here, wouldn't that slow down the time it takes to fetch the data in terms of complex queries?","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":506}}336{"id":"stack-68948248","source":"stackoverflow","questionId":68948248,"title":"Find rows using foreign key in TypeORM","tags":["postgresql","nestjs","typeorm"],"text":"Title: Find rows using foreign key in TypeORM\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an OneToMany relation from `User` to `Message`.\n\nWhen I insert register a user with a message, it adds the user to the `User` table, and the message to the `Message` table with a `userId` pointing to the user's id.\n\nThis is done automatically using the following setup.\n\n`User` entity:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn() \n id: number;\n\n @Column()\n name: string;\n\n @Column()\n email: string;\n\n @JoinTable()\n @OneToMany((type) => Message, (message) => message.user, {\n cascade: true,\n })\n messages: Message[];\n}\n```\n\n`Message` entity:\n\n```\n@Entity()\nexport class Message {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n text: string;\n @ManyToOne((type) => User, (user) => user.messages, { eager: true })\n user: User[];\n}\n```\n\nIf I want to find all messages from a user via `userId` with:\n\n```\nconst existing_msgs = await this.messageRepository.find({\n where: { userId: user.id },\n});\n```\n\nIt tells me that it cannot find the `userId` column, which is understandable as I did not specifically include `userId` to the `Message` entity.\n\nBut how would we query it in this case?\n\n========================================\n\nTop Answer:\nI was able to do it with the following querybuilder.\n\n```\nconst msg_arr = await this.userRepository\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.messages', 'messages')\n .where('user.id = :userId', { userId: user.id })\n .andWhere('messages.text LIKE :text', { text: message })\n .select('messages.text')\n .execute();\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn() \n  id: number;\n\n  @Column()\n  name: string;\n\n  @Column()\n  email: string;\n\n  @JoinTable()\n  @OneToMany((type) => Message, (message) => message.user, {\n    cascade: true,\n  })\n  messages: Message[];\n}\n```\n\n```text\n@Entity()\nexport class Message {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  text: string;\n  @ManyToOne((type) => User, (user) => user.messages, { eager: true })\n  user: User[];\n}\n```\n\n```text\nconst existing_msgs = await this.messageRepository.find({\n    where: { userId: user.id },\n});\n```\n\n```text\nUser\n```\n\n```text\nMessage\n```\n\n```text\nUser\n```\n\n```text\nMessage\n```\n\n```text\nuserId\n```\n\n```text\nUser\n```\n\n```text\nMessage\n```\n\n```text\nuserId\n```\n\n```text\nuserId\n```\n\n```text\nuserId\n```\n\n```text\nMessage\n```\n\n```text\nconst existing_msgs = await this.messageRepository.find({\n    where: { user: { id: user.id }},\n});\n```\n\n```text\n@Entity()\nexport class Message {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  text: string;\n\n  @ManyToOne((type) => User, (user) => user.messages, { eager: true })\n  @JoinColumn() // <-- Add this\n  user: User[];\n}\n```\n\n```text\nconst msg_arr = await this.userRepository\n          .createQueryBuilder('user')\n          .leftJoinAndSelect('user.messages', 'messages')\n          .where('user.id = :userId', { userId: user.id })\n          .andWhere('messages.text LIKE :text', { text: message })\n          .select('messages.text')\n          .execute();\n```\n\n========================================\n\nComments:\n- good but you missed ':' at --> where: { user : { id: user.id} }\n- you're right, just fixed it\n- Shouldn't it be `user: User;` - i.e. Message entity has column `user` pointing to single User entity?","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":198,"estimatedTokens":850}}337{"id":"stack-57463523","source":"stackoverflow","questionId":57463523,"title":"NestJS can't resolve dependencies of the JWT_MODULE_OPTIONS","tags":["typescript","module","nestjs"],"text":"Title: NestJS can't resolve dependencies of the JWT_MODULE_OPTIONS\nTags: typescript, module, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm failed to compile with this error:\n\n*Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument at index [0] is available in the JwtModule context. +52ms*\n\nI saw similar dependencies problems with modules & services, but they didn't work for me. Using JwtModule in my **auth.module.ts**:\n\n```\nimport { JwtModule } from '@nestjs/jwt';\n@Module({\n imports: [\n TypeOrmModule.forFeature([User, Role]),\n ConfigModule,\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.registerAsync({\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n secretOrPrivateKey: config.jwtSecret,\n type: configService.dbType as any,\n host: configService.dbHost,\n port: configService.dbPort,\n username: configService.dbUsername,\n password: configService.dbPassword,\n database: configService.dbName,\n entities: ['./src/data/entities/*.ts'],\n signOptions: {\n expiresIn: config.expiresIn,\n },\n }),\n }),\n\n ],\n providers: [AuthService, JwtStrategy],\n controllers: [AuthController],\n})\nexport class AuthModule { }\n```\n\nI have no idea how to fix this bug... Using **jwt 6.1.1**\n\n**Edit:** In my previous project use jwt 6.0.0, so I downgrade it, but problem not fix.\n\n========================================\n\nTop Answer:\nI somehow got it to work by adding \n\n```\nJwtModule.registerAsync({\n imports: [ConfigModule], // Missing this\n useFactory: async (configService: ConfigService) => ({\n signOptions: {\n expiresIn: config.expiresIn,\n },\n secretOrPrivateKey: config.jwtSecret,\n }),\n inject: [ConfigService], \n}),\n```\n\nin the **app.module.ts** and **auth.module.ts**\n\n========================================\n\nCode:\n```text\nimport { JwtModule } from '@nestjs/jwt';\n@Module({\n    imports: [\n        TypeOrmModule.forFeature([User, Role]),\n        ConfigModule,\n        PassportModule.register({ defaultStrategy: 'jwt' }),\n        JwtModule.registerAsync({\n            inject: [ConfigService],\n            useFactory: async (configService: ConfigService) => ({\n                secretOrPrivateKey: config.jwtSecret,\n                type: configService.dbType as any,\n                host: configService.dbHost,\n                port: configService.dbPort,\n                username: configService.dbUsername,\n                password: configService.dbPassword,\n                database: configService.dbName,\n                entities: ['./src/data/entities/*.ts'],\n                signOptions: {\n                    expiresIn: config.expiresIn,\n                },\n            }),\n        }),\n\n    ],\n    providers: [AuthService, JwtStrategy],\n    controllers: [AuthController],\n})\nexport class AuthModule { }\n```\n\n```text\nJwtModule.registerAsync({\n  imports: [ConfigModule], // Missing this\n  useFactory: async (configService: ConfigService) => ({\n    signOptions: {\n       expiresIn: config.expiresIn,\n    },\n    secretOrPrivateKey: config.jwtSecret,\n  }),\n  inject: [ConfigService], \n}),\n```\n\n```text\n@nestjs/jwt\n```\n\n```text\nsecretOrPrivateKey\n```\n\n```text\nsignOptions\n```\n\n```text\nConfigModule\n```\n\n```text\nJwtModule.registerAsync({\n  imports: [ConfigModule], // Missing this\n  useFactory: async (configService: ConfigService) => ({\n    signOptions: {\n       expiresIn: config.expiresIn,\n    },\n    secretOrPrivateKey: config.jwtSecret,\n  }),\n  inject: [ConfigService], \n}),\n```\n\n```text\nnpm i --save @nestjs/jwt\nnpm i --save @nestjs/passport\n```\n\n```text\nnpm i --save @nestjs/mongoose\n```\n\n```text\n@NgModule({\n   imports: [\n      PassportModule.register({\n          defaultStrategy: 'jwt',\n        }),\n        JwtModule.register({\n          secret: process.env.JWT_SECRET_KEY,\n          signOptions: {\n            expiresIn: '2 days',\n          },\n        }),\n    \n   ],\n   providers: [JwtStrategy],\n   exports: [JwtStrategy, PassportModule]\n})\n```\n\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(@InjectModel('User') private collection: Model<User>) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: process.env.JWT_SECRET_KEY,\n    });\n  }\n\n  async validate(payload: JwtPayload): Promise<User> {\n    const { username } = payload;\n    const user = await this.collection.findOne({ username });\n\n    if (!user) {\n      throw new UnauthorizedException('JwtStrategy unauthorized');\n    }\n\n    return user;\n  }\n}\n```\n\n```text\n@UseGuards(AuthGuard())\n```\n\n========================================\n\nComments:\n- Really quick question: why are you passing database options to your JWT module?\n- Thanks for detailed help (bow). But work in my appModule is global wrong. I receive compile errors for every controllers and providers.. stackoverflow.com/questions/57473726/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":202,"estimatedTokens":1213}}338{"id":"stack-74430982","source":"stackoverflow","questionId":74430982,"title":"What is the significance of @nestjs/schematics? Do we need the package even after creation of an NestJs app?","tags":["javascript","node.js","nestjs"],"text":"Title: What is the significance of @nestjs/schematics? Do we need the package even after creation of an NestJs app?\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nCan we remove the following dependancy once we created the Nest App with CLI?\n\nI'm working on a legacy project, it seems the @nestjs/schematics package is unused.\nI'm not sure about it's significance as there isn't much content available on internet.\n\n========================================\n\nCode:\n```text\n@nestjs/schematics\n```\n\n```text\nnest g\n```\n\n```text\nnest generate\n```\n\n========================================\n\nComments:\n- That does give some insight about the package, thanks for sharing!","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":29,"estimatedTokens":171}}339{"id":"stack-59527847","source":"stackoverflow","questionId":59527847,"title":"Input Object type `TypeName` must define one or more fields","tags":["graphql","nestjs","typegraphql"],"text":"Title: Input Object type `TypeName` must define one or more fields\nTags: graphql, nestjs, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am experimenting with `NestJS` and `TypeGraphQL`. And I have an example model of a cat.\n\n```\nimport { Document } from 'mongoose';\nimport { ObjectType, InputType, Field, ID } from 'type-graphql';\n\nexport interface Cat extends Document {\n readonly name: string;\n readonly age?: number;\n}\n\nclass CatBase {\n @Field()\n name: string;\n\n @Field({ nullable: true })\n age?: number;\n}\n\n@ObjectType()\nexport class CatObjectType extends CatBase implements Cat {\n @Field(type => ID)\n id: string;\n}\n\n@InputType()\nexport class CatInputType extends CatBase implements Cat {\n}\n```\n\nHere I am trying to reuse `BaseCat` in `CatObjectType` and `CatInputType`. But I getting this error:\n\n```\n[ { GraphQLError: Input Object type CatInputType must define one or more fields.\n at SchemaValidationContext.reportError (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:90:19)\n at validateInputFields (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:432:13)\n at validateTypes (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:240:7)\n at validateSchema (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:54:3)\n at graphqlImpl (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:79:62)\n at /Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:28:59\n at new Promise ()\n at Object.graphql (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:26:10)\n at Function. (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:18:52)\n at Generator.next ()\n at /Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:110:75\n at new Promise ()\n at Object.__awaiter (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:106:16)\n at Function.generateFromMetadata (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n at /Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/utils/buildSchema.js:11:65\n at Generator.next ()\n message:\n 'Input Object type CatInputType must define one or more fields.' } ]\n(node:72485) UnhandledPromiseRejectionWarning: Error: Generating schema error\n at Function. (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:20:27)\n at Generator.next ()\n at fulfilled (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:107:62)\n at processTicksAndRejections (internal/process/next_tick.js:81:5)\n(node:72485) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:72485) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nWhen in `CatInputType` are described all fields from `BaseCat` all work as expected. What I am doing wrong?\n\n========================================\n\nCode:\n```text\nimport { Document } from 'mongoose';\nimport { ObjectType, InputType, Field, ID } from 'type-graphql';\n\nexport interface Cat extends Document {\n  readonly name: string;\n  readonly age?: number;\n}\n\nclass CatBase {\n  @Field()\n  name: string;\n\n  @Field({ nullable: true })\n  age?: number;\n}\n\n@ObjectType()\nexport class CatObjectType extends CatBase implements Cat {\n  @Field(type => ID)\n  id: string;\n}\n\n@InputType()\nexport class CatInputType extends CatBase implements Cat {\n}\n```\n\n```text\n[ { GraphQLError: Input Object type CatInputType must define one or more fields.\n      at SchemaValidationContext.reportError (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:90:19)\n      at validateInputFields (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:432:13)\n      at validateTypes (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:240:7)\n      at validateSchema (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:54:3)\n      at graphqlImpl (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:79:62)\n      at /Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:28:59\n      at new Promise (<anonymous>)\n      at Object.graphql (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:26:10)\n      at Function.<anonymous> (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:18:52)\n      at Generator.next (<anonymous>)\n      at /Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:110:75\n      at new Promise (<anonymous>)\n      at Object.__awaiter (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:106:16)\n      at Function.generateFromMetadata (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n      at /Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/utils/buildSchema.js:11:65\n      at Generator.next (<anonymous>)\n    message:\n     'Input Object type CatInputType must define one or more fields.' } ]\n(node:72485) UnhandledPromiseRejectionWarning: Error: Generating schema error\n    at Function.<anonymous> (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:20:27)\n    at Generator.next (<anonymous>)\n    at fulfilled (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:107:62)\n    at processTicksAndRejections (internal/process/next_tick.js:81:5)\n(node:72485) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:72485) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nNestJS\n```\n\n```text\nTypeGraphQL\n```\n\n```text\nBaseCat\n```\n\n```text\nCatObjectType\n```\n\n```text\nCatInputType\n```\n\n```text\nCatInputType\n```\n\n```text\nBaseCat\n```\n\n```text\n@ObjectType({ isAbstract: true })\n@InputType({ isAbstract: true })\nclass CatBase {\n  @Field()\n  name: string;\n\n  @Field({ nullable: true })\n  age?: number;\n}\n```\n\n```text\n@Field\n```\n\n```text\n@InputType\n```\n\n```text\n@ObjectType\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":179,"estimatedTokens":1625}}340{"id":"stack-57404341","source":"stackoverflow","questionId":57404341,"title":"Can we use all node npm packages in Nestjs","tags":["node.js","npm","nestjs"],"text":"Title: Can we use all node npm packages in Nestjs\nTags: node.js, npm, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn current, I am learning Nestjs, I found that Nestjs have a list of its own npm package like @nestjs/cqrs, @nestjs/jwt etc. Full list of all packages is https://www.npmjs.com/org/nestjs.\nNow I have a doubt that can we use all npm packages in nestjs that we use in any Node.js application like morgan, windston etc.\nOr we can only use the packages that mention in nestjs documentation list.\n\n========================================\n\nTop Answer:\nNest will expose the http adapter so that you can hook into it, here is an example using the morgan & body-parser npm package:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from './config/config.service';\nimport { ConfigModule } from './config/config.module';\nimport bodyParser from 'body-parser';\nimport morgan from 'morgan';\n\nasync function bootstrap() {\n\n const app = await NestFactory.create(AppModule);\n const configService = app.select(ConfigModule).get(ConfigService);\n\n app.use(bodyParser.json());\n app.use(morgan('dev'));\n app.enableCors();\n\n await app.listen(configService.PORT, () => console.log(`Server listening on port ${configService.PORT}`));\n}\n\nbootstrap();\n```\n\nIn this instance above `app`is an express instance.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { cloudinaryProvider } from './cloudinary.provider';\nimport { CloudinaryService } from './cloudinary.service';\n\n@Module({\n  providers: [cloudinaryProvider, CloudinaryService],\n  exports: [cloudinaryProvider],\n})\n\nexport class CloudinaryModule {}\n```\n\n```text\nimport { Provider } from '@nestjs/common';\nimport * as CloudinaryLib from 'cloudinary';\n\nexport const Cloudinary = 'lib:cloudinary';\n\nexport const cloudinaryProvider: Provider = {\n  provide: Cloudinary,\n  useValue: CloudinaryLib,\n};\n```\n\n```text\nimport { Injectable, Inject } from '@nestjs/common';\nimport { Cloudinary } from './cloudinary.provider';\n\n@Injectable()\nexport class CloudinaryService {\n\n  constructor(\n    @Inject(Cloudinary) private cloudinary\n  ) {\n    // console.log('This is the cloudinary instance:');\n    // console.log(this.cloudinary);\n  }\n}\n```\n\n```text\nimport { CloudinaryModule } from './cloudinary/cloudinary.module'\n\n@Module({\n  imports: [\n    CloudinaryModule,\n    ...\n```\n\n```text\nNest\n```\n\n```text\nFastify\n```\n\n```text\nExpress\n```\n\n```text\nExpress\n```\n\n```text\nMorgan\n```\n\n```text\nPino\n```\n\n```text\nWinston\n```\n\n```text\nkoa-router\n```\n\n```text\n@hapi/joi\n```\n\n```text\nhapi\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nNest\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from './config/config.service';\nimport { ConfigModule } from './config/config.module';\nimport bodyParser from 'body-parser';\nimport morgan from 'morgan';\n\nasync function bootstrap() {\n\n    const app = await NestFactory.create(AppModule);\n    const configService = app.select(ConfigModule).get(ConfigService);\n\n    app.use(bodyParser.json());\n    app.use(morgan('dev'));\n    app.enableCors();\n\n    await app.listen(configService.PORT, () => console.log(`Server listening on port ${configService.PORT}`));\n}\n\nbootstrap();\n```\n\n```text\napp\n```\n\n========================================\n\nComments:\n- I'm not sure I understand the question. You could use any NPM package supported by the nestjs runtime environment (which would mean pretty much any normal NPM package you could normally use in something like Express). What, exactly, is your doubt?","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":175,"estimatedTokens":918}}341{"id":"stack-67554794","source":"stackoverflow","questionId":67554794,"title":"QueryRunnerAlreadyReleasedError when executing a series of queries in a single transaction","tags":["nestjs","typeorm"],"text":"Title: QueryRunnerAlreadyReleasedError when executing a series of queries in a single transaction\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI add an `OnMoudleInit`service to initialize some sample data in my NestJS application.\n\nTypeORM provides several approaches to wrap the queries into a single transcation.\n\nI tried to use `EntityManager.transaction` to wrap the operations.\n\n```\nawait this.manager.transaction(async (manager) => {\n // NOTE: you must perform all database operations using the given manager instance\n // it's a special instance of EntityManager working with this transaction\n // and don't forget to await things here\n const del = await manager.delete(PostEntity, {});\n console.log('posts deleted: ', del.affected);\n\n const userDel = await manager.delete(UserEntity, {});\n console.log('users deleted: ', userDel.affected);\n\n const user = new UserEntity();\n Object.assign(user, {\n firstName: 'hantsy',\n lastName: 'bai',\n email: 'hantsy@gmail.com',\n });\n const savedUser = await manager.save(user);\n console.log('saved user: ', JSON.stringify(savedUser));\n this.data.forEach(async (d) => {\n const p = new PostEntity();\n p.author = savedUser;\n \n // comment out these relation settings it will work well.\n // \n // const comment = new CommentEntity();\n // comment.content = 'test comment at:' + new Date();\n // p.comments = Promise.resolve([comment]);\n Object.assign(p, d);\n await manager.save(p);\n });\n });\n\n const savedPosts = await this.postRepository.find({});\n console.log('saved:', JSON.stringify(savedPosts));\n }\n```\n\nWhen the application is starting up, the following error occurred.\n\n```\nposts deleted: 2\nusers deleted: 1\nsaved user: {\"firstName\":\"hantsy\",\"lastName\":\"bai\",\"email\":\"hantsy@gmail.com\",\"id\":\"04d5cc63-d36a-4d80-a37f-97424ef168a8\"}\nD:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10\n var _this = _super.call(this) || this;\n ^\n\nQueryRunnerAlreadyReleasedError: Query runner already released. Cannot run queries anymore.\n at new QueryRunnerAlreadyReleasedError (D:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10:28)\n```\n\n**Update**: I found this is caused by the post/comment `cascade` settings, I was trying to use one command to save post/comments.\n\n```\n@OneToMany((type) => CommentEntity, (comment) => comment.post, {\n cascade: true,\n })\n comments?: Promise;\n```\n\n**Update 2**: If I use the `Repository` class to execute the `save` task, it seems it works.\n\n```\nconst post = new PostEntity();\n post.title = 'test title';\n post.content = 'test content';\n const comment = new CommentEntity();\n comment.content = 'test comment';\n post.comments = Promise.resolve([comment]);\n await this.postRepository.save(post);\n //console.log('saved from repository: ', JSON.stringify(savedPost));\n```\n\nWhen I added the above codes before the manager transaction block, and I found the `manager.delete(Post, {})` did not apply the `cascade` settings?\n\n========================================\n\nTop Answer:\nIt's silly, but for me, the issue was that I simply was trying to reuse a QueryRunner that's already \"released\". If you check TypeORM documentation https://orkhan.gitbook.io/typeorm/docs/query-runner you will see each QueryRunner has a function to release() it manually, and there is also a boolean **property called \"isReleased\"** on the QueryRunner instance so if it is released you just have to **create a new QueryRunner** before running your queries.\n\nHope this helps someone.\n\n========================================\n\nCode:\n```js\nawait this.manager.transaction(async (manager) => {\n      // NOTE: you must perform all database operations using the given manager instance\n      // it's a special instance of EntityManager working with this transaction\n      // and don't forget to await things here\n      const del = await manager.delete(PostEntity, {});\n      console.log('posts deleted: ', del.affected);\n\n      const userDel = await manager.delete(UserEntity, {});\n      console.log('users deleted: ', userDel.affected);\n\n      const user = new UserEntity();\n      Object.assign(user, {\n        firstName: 'hantsy',\n        lastName: 'bai',\n        email: 'hantsy@gmail.com',\n      });\n      const savedUser = await manager.save(user);\n      console.log('saved user: ', JSON.stringify(savedUser));\n      this.data.forEach(async (d) => {\n        const p = new PostEntity();\n        p.author = savedUser;\n        \n        // comment out these relation settings it will work well.\n        // \n        // const comment = new CommentEntity();\n        // comment.content = 'test comment at:' + new Date();\n        // p.comments = Promise.resolve([comment]);\n        Object.assign(p, d);\n        await manager.save(p);\n      });\n    });\n\n    const savedPosts = await this.postRepository.find({});\n    console.log('saved:', JSON.stringify(savedPosts));\n  }\n```\n\n```sh\nposts deleted:  2\nusers deleted:  1\nsaved user:  {\"firstName\":\"hantsy\",\"lastName\":\"bai\",\"email\":\"hantsy@gmail.com\",\"id\":\"04d5cc63-d36a-4d80-a37f-97424ef168a8\"}\nD:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10\n        var _this = _super.call(this) || this;\n                           ^\n\nQueryRunnerAlreadyReleasedError: Query runner already released. Cannot run queries anymore.\n    at new QueryRunnerAlreadyReleasedError (D:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10:28)\n```\n\n```js\n@OneToMany((type) => CommentEntity, (comment) => comment.post, {\n    cascade: true,\n  })\n  comments?: Promise<CommentEntity[]>;\n```\n\n```js\nconst post = new PostEntity();\n    post.title = 'test title';\n    post.content = 'test content';\n    const comment = new CommentEntity();\n    comment.content = 'test comment';\n    post.comments = Promise.resolve([comment]);\n    await this.postRepository.save(post);\n    //console.log('saved from repository: ', JSON.stringify(savedPost));\n```\n\n```text\nOnMoudleInit\n```\n\n```text\nEntityManager.transaction\n```\n\n```text\ncascade\n```\n\n```text\nRepository\n```\n\n```text\nsave\n```\n\n```text\nmanager.delete(Post, {})\n```\n\n```text\ncascade\n```\n\n```js\nthis.data.forEach(async (d) => {\n        const p = new PostEntity();\n        p.author = savedUser;\n        \n        // comment out these relation settings it will work well.\n        // \n        // const comment = new CommentEntity();\n        // comment.content = 'test comment at:' + new Date();\n        // p.comments = Promise.resolve([comment]);\n        Object.assign(p, d);\n        await manager.save(p);\n      });\n```\n\n```js\nawait Promise.all(\n        this.data.map(async (d) => {\n          const p = new PostEntity();\n          Object.assign(p, d);\n          p.author = user;\n\n          const c = CommentEntity.of('test comment at:' + new Date());\n          p.comments = Promise.resolve([c]);\n          await mgr.save(p);\n        }),\n      );\n    });\n```\n\n```text\nPromise.all\n```\n\n```text\nawait Promise.all(\n     grn_items.map(async item => {\nconst itemdata = { grn: { ...grnData }, ...item };\nconst grnItemData = await queryRunner.manager.save(GrnItem, itemdata);\n}),\n            );\n```\n\n```text\n@Injectable()\nexport class UserRepository extends Repository<UserEntity> {\n    constructor(private dataSource: DataSource) {\n        - super(dataSource.getRepository(UserEntity).target, dataSource.manager, dataSource.createQueryRunner());\n        + super(UserEntity, dataSource.manager);\n    }\n}\n```\n\n========================================\n\nComments:\n- OMG, I love you. I have been looking for a solution for two hours now. This is exactly what I was looking for. Thanks.\n- @AfsharMohebi here's how: In the first example `forEach` fires all async functions and the code continues with execution, eventually exiting the function, and the transaction. The manager.save(p) method probably has some promise chain inside which executes long after the transaction is gone. `await Promise.all`, on the other hand, does not let the execution resume until all of the promises passed to Promise.all are resolved. You can also achieve a similar (but sequential) result like this: `for (const d of this.data) {await manager.save(new PostEntity())}`\n- Promise and data.map instead of forEach works perfectly!\n- superb, but would like to know more on why data.map works and foreach does not works\n- I may be late to the party but, @msonowal, that's because map() would return the values of iterable which Promise.all() requires while forEach() doesn't.\n- Thank you Hantsy. Love you. You saved my life.","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":255,"estimatedTokens":2142}}342{"id":"stack-65441260","source":"stackoverflow","questionId":65441260,"title":"NestJs GraphQL playground access","tags":["node.js","graphql","nestjs"],"text":"Title: NestJs GraphQL playground access\nTags: node.js, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI can't seem to access the GraphQL Playground using NestJS. I'm exploring the documentation and have followed this https://docs.nestjs.com/graphql/quick-start up to the Resolvers section to generate the `schema.gql`, but attempting to reach `localhost:3000/graphql` is not able to connect.\n\nAt first I thought my code was setup incorrectly, but I spent some time digging into Nest's examples and found that those also do not work when trying to access the `/graphql` endpoint. It does work if I setup a `get` endpoint to return a JSON body using the REST method.\n\n```\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { RecipesModule } from './recipes/recipes.module';\n\n@Module({\n imports: [\n RecipesModule,\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: 'schema.gql',\n }),\n ],\n})\nexport class AppModule {}\n```\n\nThis is directly from the NestJS example. My understanding is that the GraphQLModule should be setting up the connection to the `/graphql` endpoint. Following the docs, `graphql, apollo-server-express, and graphql-tools` were all installed.\n\nAny idea why the graphql route is not connecting?\n\n[Edit]:\nThings I've tried so far:\n\n- setting `playground: true` explicitly with GraphQLModule.forRoot\n\n- verified `NODE_ENV` is not 'production'\n\n- confirmed server works when creating resolvers using REST\n\n- curl'd `localhost:3000/graphql` and receive a graphql validation error, so confirm that connects correctly\n\n========================================\n\nTop Answer:\nsometimes `helmet` causes this same issue. if you have helmet loaded as a middleware, it might probably also cause this.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { RecipesModule } from './recipes/recipes.module';\n\n@Module({\n  imports: [\n    RecipesModule,\n    GraphQLModule.forRoot({\n      installSubscriptionHandlers: true,\n      autoSchemaFile: 'schema.gql',\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nschema.gql\n```\n\n```text\nlocalhost:3000/graphql\n```\n\n```text\n/graphql\n```\n\n```text\nget\n```\n\n```text\n/graphql\n```\n\n```text\ngraphql, apollo-server-express, and graphql-tools\n```\n\n```text\nplayground: true\n```\n\n```text\nNODE_ENV\n```\n\n```text\nlocalhost:3000/graphql\n```\n\n```text\nimports: [\n    UsersModule,\n    GraphQLModule.forRoot({\n      // autoSchemaFile: true,    did not work!\n      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n      // schema.gql will automatically be created\n      debug: true,\n      playground: true,\n    }),\n  ],\n  providers: [AppResolver],   // all resolvers & service should be in providers\n```\n\n```text\nhelmet\n```\n\n```text\nprocess.env.CURRENT_ENV === 'dev' && app.use(helmet())\n```\n\n```text\nhelmet()\n```\n\n```text\nCURRENT_ENV\n```\n\n```text\nNODE_ENV\n```\n\n```text\nconst isGqlEnvProd = process.env.GQL_ENV === 'prod';\nif(isGqlEnvProd){\n app.use(helmet());\n}\n```\n\n========================================\n\nComments:\n- Check what your `process.env.NODE_ENV` is. If it is `PRODUCTION` then I think `apollo-server` disables the playground. If not, try adding `playground: true` explicitly\n- @JayMcDoniel I should've specified what I've tried already on the post, sorry. I've tried both and unfortunately, wasn't able to connect to the endpoint. I just curl'ed the endpoint to see if it is connecting to graphql and seems like it is since it returns GraphQL validation errors.\n- Are you able to provide a reproduction then? Can't see from what you've shared why that would be happening\n- So, I've tried with nest's example in their github repo (github.com/nestjs/nest/tree/master/sample/23-graphql-code-f&zwnj;&#8203;irst). It's about as basic as it can get and is essentially the same as the documentation's example. Nothing modified, just unable to connect to gql playground. Same result curling, able to see the gql validation errors, so it's connecting on the server though.\n- With that sample, the curl fails, but a browser requests to the same location succeeds. Probably looking at the user agent. It doesn't make much sense to send an interactive playground to the command line\n- Of course, for the command line I was just referring to sending a Post request to run a query, not trying to access the playground. But those requests worked and the queries in the schema were correctly being referenced. Odd that playground was accessible to you but not on my end, will dig a bit more and see if I figure it out. Thanks!\n- disabling helmet solves the issue in NestJs, but I'm wondering what causes it? And if that is the problem is that an option to disable helmet in the dev mode?\n- Helmet was a problem in my case too\n- does anybody know why helmet cause this issue ?","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":155,"estimatedTokens":1222}}343{"id":"stack-66501485","source":"stackoverflow","questionId":66501485,"title":"Is it possible to keep scheduled tasks from overlapping in NestJS?","tags":["javascript","scheduled-tasks","nestjs"],"text":"Title: Is it possible to keep scheduled tasks from overlapping in NestJS?\nTags: javascript, scheduled-tasks, nestjs\nSource: Stack Overflow\n\nQuestion:\nCurrently, long running tasks will overlap (same task runs multiple instances at the same time) if the time necessary to finish the ask is greater than the interval. *example NestJS service below*\n\n```\nimport { Injectable, Logger } from '@nestjs/common';\nimport { Interval } from '@nestjs/schedule';\n\nfunction timeout(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nlet c = 1\n\n@Injectable()\nexport class TasksService {\n private readonly logger = new Logger(TasksService.name);\n\n @Interval(1000)\n async handleCron() {\n this.logger.debug(`start ${c}`);\n await timeout(3000)\n this.logger.debug(`end ${c}`);\n c += 1\n }\n}\n```\n\nIs it possible to keep these tasks from overlapping and only calling the task with one instance at a time? Technically, we could keep track of a `lock` variable, but this would only allow us to skip an instance, if one is already running. Ideally, we could call set an option to allow intervals based on task end-time, rather than fixed intervals (aka start-time).\n\n========================================\n\nTop Answer:\nNestJS has added a `waitForCompletion` option in version 5.0.1.\n\nhttps://github.com/nestjs/schedule/pull/1870\n\n```\n@Cron(CronExpression.EVERY_SECOND, {\n waitForCompletion: true,\n})\nasync handleCron() {\n this.logger.debug(`start ${c}`);\n await timeout(3000)\n this.logger.debug(`end ${c}`);\n c += 1;\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, Logger } from '@nestjs/common';\nimport { Interval } from '@nestjs/schedule';\n\nfunction timeout(ms) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nlet c = 1\n\n@Injectable()\nexport class TasksService {\n  private readonly logger = new Logger(TasksService.name);\n\n  @Interval(1000)\n  async handleCron() {\n    this.logger.debug(`start ${c}`);\n    await timeout(3000)\n    this.logger.debug(`end ${c}`);\n    c += 1\n  }\n}\n```\n\n```text\nlock\n```\n\n```text\n@Interval(1000)\n  async handleCron() {\n    this.logger.debug(`start ${c}`);\n    await timeout(3000)\n    this.logger.debug(`end ${c}`);\n    c += 1\n  }\n```\n\n```text\n@Cron(CronExpression.EVERY_SECOND, {\n     name: 'cron_job_name_here',\n   })\nasync handleCron() {\n        this.logger.debug(`start ${c}`);\n        await timeout(3000)\n        this.logger.debug(`end ${c}`);\n        c += 1\n   }\n```\n\n```text\n@Cron(CronExpression.EVERY_SECOND, {\n     name: 'cron_job_name_here',\n   })\nasync handleCron() {\n        const job = this.schedulerRegistry.getCronJob('cron_job_name_here');\n        job.stop(); // pausing the cron job\n\n        this.logger.debug(`start ${c}`);\n        await timeout(3000)\n        this.logger.debug(`end ${c}`);\n        c += 1;\n\n        job.start(); // restarting the cron job\n   }\n```\n\n```text\nprivate schedulerRegistry: SchedulerRegistry,\n```\n\n```text\nimport { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule'\n```\n\n```text\n@Interval\n```\n\n```text\n@Cron\n```\n\n```text\nexport class ExampleService {\n  private readonly logger = new Logger(ExampleService.name);\n  private readonly runningTasks = new Set();\n\n  @Interval(10000)\n  async exampleFunction() {\n    this.runTaskOnce(\"exampleFunction\", async () => {\n      return new Promise((resolve) => {\n        setTimeout(() => {\n          resolve();\n        }, 5000);\n      });\n    });\n  }\n\n  private async runTaskOnce(\n    taskName: string,\n    task: () => Promise<void>\n  ): Promise<void> {\n    if (this.runningTasks.has(taskName)) {\n      this.logger.warn(`Task \"${taskName}\" is running now, skip this tick`);\n      return;\n    } else {\n      this.runningTasks.add(taskName);\n      return task().finally(() => {\n        this.runningTasks.delete(taskName);\n      });\n    }\n  }\n}\n```\n\n```text\n@Cron(CronExpression.EVERY_SECOND, {\n  waitForCompletion: true,\n})\nasync handleCron() {\n  this.logger.debug(`start ${c}`);\n  await timeout(3000)\n  this.logger.debug(`end ${c}`);\n  c += 1;\n}\n```\n\n```text\nwaitForCompletion\n```\n\n========================================\n\nComments:\n- You should probably being using a pub/sub messaging infrastructure to support the dynamic nature of the calls. Any of the messaging platforms under \"Microservices\" in the docs. Or something simpler like EventEmitter.\n- Thanks, it works, though not very elegant IMHO. nestjs scheduler should add an option to do that.\n- NestJS does have an option for this now (see Steve's answer, which should now be the preferred solution (and upvote it)).","metadata":{"transformedAt":"2026-08-18T18:33:02.433Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":193,"estimatedTokens":1136}}344{"id":"stack-60927609","source":"stackoverflow","questionId":60927609,"title":"Nest can't resolve dependencies of the [ServiceName]","tags":["typescript","nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of the [ServiceName]\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe error that says that the dependency can't be resolved is not clear enough. Currently, the error output says: \n\n```\n[ExceptionHandler] Nest can't resolve dependencies of the LeadService (LeadRepository, ?). Please make sure that the argument dependency at index [1] is available in the LeadModule context.\n```\n\nFrom this output, I can conclude that the dependency `ConsentService` of my `LeadService`. See `LeadService` constructor below.\n\nAdditionally, the output also puts the following suggestion:\n\n*Potential solutions:*\n\n \n \n- If dependency is a provider, is it part of the current LeadModule?\n \n\n**My answer:** It is a provider, but it's not part of the current module. It's a provider from the ConsentModule. See ConsentModule definition. \n\n \n \n- If dependency is exported from a separate @Module, is that module imported within LeadModule?\n \n\n```\n@Module({\n imports: [ /* the Module containing dependency */ ]\n })\n```\n\n**My answer:** Yes, it is exported from the ConsentModule and it is imported in the LeadModule thus I don't understand why is this failing.\n\n### Input Code\n\n**ConsentService** \n\n```\n@Injectable()\nexport class ConsentService {\n constructor(@InjectRepository(Consent) private repository: Repository) {}\n}\n```\n\n**LeadService**\n\n```\n@Injectable()\nexport class LeadService {\n constructor(\n @InjectRepository(Lead)\n private leadRepository: Repository,\n @Inject()\n private consentService: ConsentService\n ) {}\n}\n```\n\n**ConsentModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConsentService } from './consent.service';\nimport { Consent } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Consent])],\n providers: [ConsentService],\n exports: [ConsentService]\n})\nexport class ConsentModule {}\n```\n\n**LeadModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { LeadService } from './lead.service';\nimport { Lead } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConsentModule } from './consent.module';\n\n@Module({\n imports: [ConsentModule, TypeOrmModule.forFeature([Lead])],\n providers: [LeadService],\n exports: [LeadService]\n})\nexport class LeadModule {}\n```\n\n**AppModule**\n\n```\n@Global()\n@Module({\n imports: [\n ConsentModule,\n LeadModule,\n TypeOrmModule.forRoot({\n ...getDbConnectionProperties(),\n entities: [Consent, Lead]\n })\n ],\n controllers: [\n DevController,\n HealthController\n ],\n providers: []\n})\nexport class AppModule {}\n```\n\nI would like to know why exactly is the error happening because I think I have declared everything correctly\n\n========================================\n\nCode:\n```text\n[ExceptionHandler] Nest can't resolve dependencies of the LeadService (LeadRepository, ?). Please make sure that the argument dependency at index [1] is available in the LeadModule context.\n```\n\n```text\n@Module({\n     imports: [ /* the Module containing dependency */ ]\n   })\n```\n\n```text\n@Injectable()\nexport class ConsentService {\n  constructor(@InjectRepository(Consent) private repository: Repository<Consent>) {}\n}\n```\n\n```text\n@Injectable()\nexport class LeadService<T extends LeadPayload> {\n  constructor(\n    @InjectRepository(Lead)\n    private leadRepository: Repository<Lead>,\n    @Inject()\n    private consentService: ConsentService\n  ) {}\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConsentService } from './consent.service';\nimport { Consent } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Consent])],\n  providers: [ConsentService],\n  exports: [ConsentService]\n})\nexport class ConsentModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { LeadService } from './lead.service';\nimport { Lead } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConsentModule } from './consent.module';\n\n@Module({\n  imports: [ConsentModule, TypeOrmModule.forFeature([Lead])],\n  providers: [LeadService],\n  exports: [LeadService]\n})\nexport class LeadModule {}\n```\n\n```text\n@Global()\n@Module({\n  imports: [\n    ConsentModule,\n    LeadModule,\n    TypeOrmModule.forRoot({\n      ...getDbConnectionProperties(),\n      entities: [Consent, Lead]\n    })\n  ],\n  controllers: [\n    DevController,\n    HealthController\n  ],\n  providers: []\n})\nexport class AppModule {}\n```\n\n```text\nConsentService\n```\n\n```text\nLeadService\n```\n\n```text\nLeadService\n```\n\n```text\n@Inject\n```\n\n```text\ntoken\n```\n\n```text\n@Inject(\"name\")\n```\n\n```text\nLeadService\n```\n\n```text\nconsentService\n```\n\n```text\n@Inject(ConsentService)\n```\n\n```text\nConsentService\n```\n\n```text\nLeadService\n```\n\n```text\n@Inject(ConsentService)\n```\n\n```text\n@Inject()\n```\n\n```text\nconsentService\n```\n\n```text\n@Inject()\n```\n\n```text\nLeadService\n```\n\n```text\nConsentService\n```\n\n```text\nLeadService\n```\n\n```text\nLeadService\n```\n\n```text\n@Inject()\n```\n\n```text\nLeadService\n```\n\n```text\nConsentService\n```\n\n========================================\n\nComments:\n- Thanks @kierans. I completely agree with your argument that `@Inject` shouldn't be used at all. In fact removing this solved my problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":292,"estimatedTokens":1309}}345{"id":"stack-57581334","source":"stackoverflow","questionId":57581334,"title":"Separate swagger implementation from controller code","tags":["node.js","swagger","nestjs"],"text":"Title: Separate swagger implementation from controller code\nTags: node.js, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to document my api in NestJS. I have followed NestJS documentation and it works very well but I would like to know if there is anyway to separate the swagger decorators from the controller code. Because the api starts to grow, the controller code starts to get a little bit confusing because having the decorators in between the request methods interferes with the way the flow it is seen.\n\nI have used the decorators but when you need in an endpoint guards validation, pipes it gets pretty big and unfocused, because of the amount of decorators that get added and I am not confused swagger is not that important in the actual execution flow as it is guards, validators, etc.\n\n```\n@Post()\n@Roles('user')\n@ApiResponse({ status: 201, description: 'The token has been successfully created.'})\n@ApiResponse({ status: 403, description: 'Forbidden.'})\n@UsePipes(new ValidationPipe())\n@HttpCode(200)\nasync createToken(@Body() createTokenDto: CreateTokenDto) {\n this.tokenBuilderService.createToken(createTokenDto);\n}\n```\n\n========================================\n\nTop Answer:\nNo.You can't separate the swagger decorators from the controller code.\nI usually place it at the end to separate them from pipes and guards:\n\n```\n@Post()\n@Roles('user')\n@UsePipes(new ValidationPipe())\n@HttpCode(201)\n@ApiResponse({ status: 201, description: 'The token has been successfully created.'})\n@ApiResponse({ status: 403, description: 'Forbidden.'})\nasync createToken(@Body() createTokenDto: CreateTokenDto) {\n this.tokenBuilderService.createToken(createTokenDto);\n}\n```\n\n========================================\n\nCode:\n```text\n@Post()\n@Roles('user')\n@ApiResponse({ status: 201, description: 'The token has been successfully created.'})\n@ApiResponse({ status: 403, description: 'Forbidden.'})\n@UsePipes(new ValidationPipe())\n@HttpCode(200)\nasync createToken(@Body() createTokenDto: CreateTokenDto) {\n  this.tokenBuilderService.createToken(createTokenDto);\n}\n```\n\n```text\n// controller.decorator.ts\nexport function SwaggerDecorator() {\n  return applyDecorators(\n    ApiResponse({ status: 201, description: 'The token has been successfully created.' }),\n    ApiResponse({ status: 403, description: 'Forbidden.' })\n  );\n}\nNote that the decorators are without the @ symbol.\n```\n\n```text\nimport { SwaggerDecorator } from './controller.decorator'\n\n@Post()\n@Roles('user')\n@SwaggerDecorator()\n@UsePipes(new ValidationPipe())\n@HttpCode(200)\nasync createToken(@Body() createTokenDto: CreateTokenDto) {\n  this.tokenBuilderService.createToken(createTokenDto);\n}\n```\n\n```text\napplyDecorators\n```\n\n```text\n@nestjs/common\n```\n\n```js\n@Post()\n@Roles('user')\n@UsePipes(new ValidationPipe())\n@HttpCode(201)\n@ApiResponse({ status: 201, description: 'The token has been successfully created.'})\n@ApiResponse({ status: 403, description: 'Forbidden.'})\nasync createToken(@Body() createTokenDto: CreateTokenDto) {\n  this.tokenBuilderService.createToken(createTokenDto);\n}\n```\n\n========================================\n\nComments:\n- Thanks for the reply It would be great to implement it separately maybe they could implement a middleware where it scopes all the functionality by now I think I would create the docs manually with swagger-jsdoc\n- It would be great if swagger depended on our controllers. I mean something like this: `builder.addController(controller1).addController(controller2&zwnj;&#8203;)`","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":103,"estimatedTokens":874}}346{"id":"stack-56097750","source":"stackoverflow","questionId":56097750,"title":"Nestjs - There is no matching event handler defined in the remote service","tags":["mqtt","nestjs"],"text":"Title: Nestjs - There is no matching event handler defined in the remote service\nTags: mqtt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to handle the message published on topic `test_ack` from online MQTT broker using microservices. But I'm getting the error.\n\n`There is no matching event handler defined in the remote service.`\n\nMy Code:\n\n**main.ts**\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Transport } from '@nestjs/common/enums/transport.enum';\nvar url = 'mqtt://test.mosquitto.org';\n\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(AppModule, {\n transport: Transport.MQTT,\n options: {\n url: url\n }\n });\n await app.listenAsync();\n}\nbootstrap();\n```\n\n**app.controller.ts**\n\n```\nimport { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n constructor() {}\n\n @MessagePattern('test') \n ackMessageTestData(data:unknown) {\n console.log(data.toString());\n return 'Message Received';\n }\n}\n```\n\n========================================\n\nTop Answer:\nIn my case the event pattern was undefined. I had a Nestjs service and python service communicating via RMQ.\n\nThe solution for me was quite simple. Nestjs expects incoming pubsub message bodies to have a pattern field, so in whatever service you're publishing from, make sure the body is structured a bit like this.\n\n```\nresponse = {\n \"pattern\": \"scraper.results\",\n \"data\": {\n \"id\": 12345,\n \"status\": \"ok\"\n }\n}\nchannel.basic_publish(\n exchange=\"\", \n routing_key=\"scraper\", \n body=json.dumps(response)\n)\n```\n\nThis is in python but obviously the pattern is broadly applicable. The data field is also expected. Then in your nestjs service you'll now find that this message matches the \"scraper.results\" event pattern.\n\n```\n@EventPattern('scraper.results')\nhandleScraperResults() {\n console.log('beep boop');\n}\n```\n\nHope this helps!\n\n========================================\n\nCode:\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Transport } from '@nestjs/common/enums/transport.enum';\nvar url = 'mqtt://test.mosquitto.org';\n\nasync function bootstrap() {\n    const app = await NestFactory.createMicroservice(AppModule, {\n        transport: Transport.MQTT,\n        options: {\n            url: url\n        }\n    });\n    await app.listenAsync();\n}\nbootstrap();\n```\n\n```js\nimport { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n    constructor() {}\n\n    @MessagePattern('test') \n    ackMessageTestData(data:unknown) {\n        console.log(data.toString());\n        return 'Message Received';\n    }\n}\n```\n\n```text\ntest_ack\n```\n\n```text\nThere is no matching event handler defined in the remote service.\n```\n\n```text\n@EventPattern('test_ack')\n```\n\n```text\n{data: 'Your message'}\n```\n\n```text\nclient.publish('test_ack', JSON.stringify({data: 'test data'}))\n```\n\n```text\nclient.send(\n          { cmd: 'some_command' },\n          {\n            identity: adminIdentity,\n            event: {\n              // some payload\n            },\n          }\n        )\n```\n\n```text\nexport enum ResourcingCommand {\n  IMPORT = 'import_resourcing',\n  EXPORT = 'export_resourcing'\n}\n```\n\n```text\nimport { Controller } from '@nestjs/common'\nimport { MessagePattern, Payload } from '@nestjs/microservices'\n\nimport { ResourcingCommand } from '@/core/commands/resourcing.commands'\nimport { ImportResourcingFileEvent } from '@/core/events/import-resourcing-file.event'\nimport { UserIdentity } from '@/core/interfaces/user-identity.interface'\nimport { ResourcingService } from '@/services/use-cases/resourcing/resourcing.service'\n\n@Controller('resourcing')\nexport class ResourcingController {\n  constructor(private readonly resourcingService: ResourcingService) {}\n\n  @MessagePattern({ cmd: ResourcingCommand.IMPORT })\n  async importResourcingFile(\n    @Payload('identity') identity: UserIdentity,\n    @Payload('event') event: ImportResourcingFileEvent\n  ) {\n    return this.resourcingService.importResourcingFile(identity, event)\n  }\n}\n```\n\n```text\n\"There is no matching message handler defined in the remote service.\"\n```\n\n```text\ncmd\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { Transport, MicroserviceOptions } from '@nestjs/microservices';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice<MicroserviceOptions>(\n    AppModule,\n    {\n      transport: Transport.TCP,\n      options: {\n        host: 'localhost',\n        port: 8877,\n      },\n    },\n  );\n  await app.listen();\n}\n\nbootstrap();\n\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\n\n@Module({\n  imports: [],\n  controllers: [UserController],\n  providers: [],\n})\nexport class AppModule {}\n\nimport { Controller } from '@nestjs/common';\nimport { EventPattern } from '@nestjs/microservices';\n\n    @Controller('user')\n    export class UserController {\n      @EventPattern('user_created')\n      async createUser(data: Record<string, unknown>) {\n        console.log('user_created event received:', data);\n      }\n    }\n```\n\n```py\nresponse = {\n    \"pattern\": \"scraper.results\",\n    \"data\": {\n        \"id\": 12345,\n        \"status\": \"ok\"\n    }\n}\nchannel.basic_publish(\n    exchange=\"\", \n    routing_key=\"scraper\", \n    body=json.dumps(response)\n)\n```\n\n```js\n@EventPattern('scraper.results')\nhandleScraperResults() {\n  console.log('beep boop');\n}\n```\n\n========================================\n\nComments:\n- What strikes me about your error message. Mine actually gives a similar error message: \"There is no matching message handler defined in the remote service.\" Almost exactly the same, but it says \"message handler\" instead of \"event handler\". Wondering if that's the same thing.\n- Did you able to solve your problem?\n- Yes, I was actually sending the wrong message pattern after all. Our slight difference in error message could be due to the fact that I used Transport.TCP , which may be regarded more as a \"message handler\" than an \"event handler\" I guess.\n- I'm getting the same error message but it's happening randomly not every time while a call has been produced from origin service to target service.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This is really helpful answer, cause native `amqplib` doesn't create `pattern` field inside payload, but NestJS microservice expects this field to bind `@EventPattern(...)`. So, without `{pattern: \"lol\", data: data}` NestJS will not call your `@EventPattern(\"lol\")`","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":263,"estimatedTokens":1720}}347{"id":"stack-60511317","source":"stackoverflow","questionId":60511317,"title":"Argon2 with node docker container","tags":["node.js","docker","node-modules","nestjs","argon2-ffi"],"text":"Title: Argon2 with node docker container\nTags: node.js, docker, node-modules, nestjs, argon2-ffi\nSource: Stack Overflow\n\nQuestion:\nI have NestJs application that works perfectly on my local machine (windows).\nNow I would like to create a docker container for my application.\nWhen i try to start my container i have one issue with Argon2.\nI install on the container all the argon needs.\nwhere's my mistake?\n\nThank\n\n```\ninternal/modules/cjs/loader.js:1025\n return process.dlopen(module, path.toNamespacedPath(filename));\n ^\n\nError: Error loading shared library /usr/src/app/node_modules/argon2/build/Release/argon2.node: Exec format error\n at Object.Module._extensions..node (internal/modules/cjs/loader.js:1025:18)\n at Module.load (internal/modules/cjs/loader.js:815:32)\n at Function.Module._load (internal/modules/cjs/loader.js:727:14)\n at Module.require (internal/modules/cjs/loader.js:852:19)\n at require (internal/modules/cjs/helpers.js:74:18)\n at load (/usr/src/app/node_modules/node-gyp-build/index.js:20:10)\n at Object. (/usr/src/app/node_modules/argon2/argon2.js:5:81)\n at Module._compile (internal/modules/cjs/loader.js:959:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)\n at Module.load (internal/modules/cjs/loader.js:815:32)\n```\n\n### Dockerfile :\n\n```\nFROM node:12.13-alpine As development\n\nWORKDIR /usr/src/app\n\nCOPY package*.json ./\n\n# --no-cache: download package index on-the-fly, no need to cleanup afterwards\n# --virtual: bundle packages, remove whole bundle at once, when done\nRUN apk --no-cache --virtual build-dependencies add \\\n python \\\n make \\\n g++ \\\n && npm install \\\n && apk del build-dependencies\nRUN npm install -g node-gyp\nRUN npm install argon2\nRUN npm install --only=development\n\nCOPY . .\n\nRUN npm run build\n\nFROM node:12.13-alpine as production\n\nARG NODE_ENV=production\nENV NODE_ENV=${NODE_ENV}\n\nWORKDIR /usr/src/app\n\nCOPY package*.json ./\n\n# --no-cache: download package index on-the-fly, no need to cleanup afterwards\n# --virtual: bundle packages, remove whole bundle at once, when done\nRUN apk --no-cache --virtual build-dependencies add \\\n python \\\n make \\\n g++ \\\n && npm install \\\n && apk del build-dependencies\nRUN npm install -g node-gyp\nRUN npm install argon2\nRUN npm install --only=production\n\nCOPY . .\n\nCOPY --from=development /usr/src/app/dist ./dist\n\nCMD [\"node\", \"dist/main\"]\n```\n\n### docker-compose :\n\n```\nversion: \"3.7\"\n\nservices:\n main:\n container_name: NestApp\n build:\n context: .\n target: development\n volumes:\n - .:/usr/src/app\n #- /usr/src/app/node_modules\n ports:\n - 3001:3001\n command: npm run start:dev\n networks:\n - webnet\n depends_on:\n - mysql\n mysql:\n image: mysql:5\n restart: always\n networks:\n - webnet\n environment:\n MYSQL_ROOT_PASSWORD: root\n MYSQL_DATABASE: bdd\n ports:\n - \"3306:3306\"\n volumes:\n - my-db:/var/lib/mysql\n adminer:\n image: adminer\n restart: always\n ports:\n - 8085:8080\n networks:\n - webnet\nnetworks:\n webnet:\n driver: bridge\n# Names our volume\nvolumes:\n my-db:\n```\n\n========================================\n\nTop Answer:\nI also had this issue I did the above tip by Jay McDoniel. Although for me I also had another problem that seemed to have thrown the same error. The problem for me was I accidentally `npm install`ed something in my project while using a yarn project where I should have `yarn add`ed this gave a warning that said:\n\n```\nwarning package-lock.json found. Your project contains lock files generated by \ntools other than Yarn. It is advised not to mix package managers in order to avoid \nresolution inconsistencies caused by unsynchronized lock files. To clear this. \nwarning, remove package-lock.json.\n```\n\nThe problem wasn't yet fixed until I removed `package-lock.json` (lesson learned: pick your least favorite of the two lockfiles (`yarn.lock` or `package-lock.json`) to remove from you project and always keep just one type of package manager in use between `yarn` and `npm`)\n\n========================================\n\nCode:\n```text\ninternal/modules/cjs/loader.js:1025\n  return process.dlopen(module, path.toNamespacedPath(filename));\n                 ^\n\nError: Error loading shared library /usr/src/app/node_modules/argon2/build/Release/argon2.node: Exec format error\n    at Object.Module._extensions..node (internal/modules/cjs/loader.js:1025:18)\n    at Module.load (internal/modules/cjs/loader.js:815:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:727:14)\n    at Module.require (internal/modules/cjs/loader.js:852:19)\n    at require (internal/modules/cjs/helpers.js:74:18)\n    at load (/usr/src/app/node_modules/node-gyp-build/index.js:20:10)\n    at Object.<anonymous> (/usr/src/app/node_modules/argon2/argon2.js:5:81)\n    at Module._compile (internal/modules/cjs/loader.js:959:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)\n    at Module.load (internal/modules/cjs/loader.js:815:32)\n```\n\n```text\nFROM node:12.13-alpine As development\n\nWORKDIR /usr/src/app\n\nCOPY package*.json ./\n\n# --no-cache: download package index on-the-fly, no need to cleanup afterwards\n# --virtual: bundle packages, remove whole bundle at once, when done\nRUN apk --no-cache --virtual build-dependencies add \\\n    python \\\n    make \\\n    g++ \\\n    && npm install \\\n    && apk del build-dependencies\nRUN npm install -g node-gyp\nRUN npm install argon2\nRUN npm install --only=development\n\nCOPY . .\n\nRUN npm run build\n\nFROM node:12.13-alpine as production\n\nARG NODE_ENV=production\nENV NODE_ENV=${NODE_ENV}\n\nWORKDIR /usr/src/app\n\nCOPY package*.json ./\n\n# --no-cache: download package index on-the-fly, no need to cleanup afterwards\n# --virtual: bundle packages, remove whole bundle at once, when done\nRUN apk --no-cache --virtual build-dependencies add \\\n    python \\\n    make \\\n    g++ \\\n    && npm install \\\n    && apk del build-dependencies\nRUN npm install -g node-gyp\nRUN npm install argon2\nRUN npm install --only=production\n\nCOPY . .\n\nCOPY --from=development /usr/src/app/dist ./dist\n\nCMD [\"node\", \"dist/main\"]\n```\n\n```text\nversion: \"3.7\"\n\nservices:\n  main:\n    container_name: NestApp\n    build:\n      context: .\n      target: development\n    volumes:\n      - .:/usr/src/app\n      #- /usr/src/app/node_modules\n    ports:\n      - 3001:3001\n    command: npm run start:dev\n    networks:\n      - webnet\n    depends_on:\n      - mysql\n  mysql:\n    image: mysql:5\n    restart: always\n    networks:\n      - webnet\n    environment:\n      MYSQL_ROOT_PASSWORD: root\n      MYSQL_DATABASE: bdd\n    ports:\n      - \"3306:3306\"\n    volumes:\n      - my-db:/var/lib/mysql\n  adminer:\n    image: adminer\n    restart: always\n    ports:\n      - 8085:8080\n    networks:\n      - webnet\nnetworks:\n  webnet:\n    driver: bridge\n# Names our volume\nvolumes:\n  my-db:\n```\n\n```text\n.dockerignore\n```\n\n```text\nCOPY . .\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install argon2\n```\n\n```text\n.dockerignore\n```\n\n```text\n/node_modules\n```\n\n```text\nnode_modules\n```\n\n```text\nwarning package-lock.json found. Your project contains lock files generated by    \ntools other than Yarn. It is advised not to mix package managers in order to avoid \nresolution inconsistencies caused by unsynchronized lock files. To clear this. \nwarning, remove package-lock.json.\n```\n\n```text\nnpm install\n```\n\n```text\nyarn add\n```\n\n```text\npackage-lock.json\n```\n\n```text\nyarn.lock\n```\n\n```text\npackage-lock.json\n```\n\n```text\nyarn\n```\n\n```text\nnpm\n```\n\n========================================\n\nComments:\n- Do you have a `.dockerignore` file that is ignoring your `node_modules` directory?\n- Thank you , that solved my problem","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":332,"estimatedTokens":1881}}348{"id":"stack-67672251","source":"stackoverflow","questionId":67672251,"title":"NestJS Interceptor - Append data to incoming request Header or Body","tags":["javascript","node.js","nestjs"],"text":"Title: NestJS Interceptor - Append data to incoming request Header or Body\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to modify an NestJS incoming request and append some data either to header or Body. I was able to replace all the body data with my data but i would like to append and not remove the incoming body data.\n\nHere is the code i have\n\n```\nexport class MyInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n const request = context.switchToHttp().getRequest();\n \n \n const token = request.headers['authorization'];\n if (token) {\n const decoded = jwt_decode(token);\n request.body['userId'] = decoded['id'];\n }\n\n return next.handle();\n }\n}\n```\n\nThanks in advance\n\n========================================\n\nTop Answer:\n```\n@Injectable()\n export class JwtInterceptor implements NestInterceptor {\n\n constructor(private readonly jwtService: JwtService, private readonly \n userService: UserService) { }\n async intercept(context: ExecutionContext, next: CallHandler): \n Promise> {\n var request: WsArgumentsHost = context.switchToWs();\n var { handshake: { headers: { authorization } } } = \n request.getClient();\ntry {\n var jwt = authorization.split(\" \")[1];\n var { phone } = await this.jwtService.verify(jwt, jwtConstraints)\n var user: User = await this.userService.findUserByPhoneNumber(phone);\n \n \n request.getData()[\"user\"]=user;\n return next.handle().pipe(map((data) => { return { ...data, 'user': \"david\" }; }));\n```\n\ni hope this will help someone in future while working with socket.i wanted the user object in the body after they pass authentication .the above trick worked out for me\n\n========================================\n\nCode:\n```text\nexport class MyInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const request = context.switchToHttp().getRequest();\n    \n    \n    const token = request.headers['authorization'];\n    if (token) {\n      const decoded = jwt_decode(token);\n      request.body['userId'] = decoded['id'];\n    }\n\n    return next.handle();\n  }\n}\n```\n\n```text\ntest('should not mutate entire request body object', () => {\n    const dto = {\n      username: 'testuser',\n      email: 'test@domain.com',\n    };\n\n    const headers = {\n      authorization: 'Bearer sdkfjdsakfjdkjfdal',\n    };\n\n    return request(app.getHttpServer())\n      .post('/')\n      .send(dto)\n      .set(headers)\n      .expect(({ body }) => {\n        expect(body.userId).toBeDefined();\n        delete body.userId;\n\n        expect(body).toStrictEqual(dto);\n      });\n  });\n```\n\n```text\n@Injectable()\nexport class HttpRequestBodyInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable {\n    const request = context.switchToHttp().getRequest();\n    const token = request.headers['authorization'];\n\n    if (token) {\n      // decode token\n      request.body['userId'] = 'user_123456789';\n    }\n\n    return next.handle();\n  }\n}\n```\n\n```text\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Post()\n  @UseInterceptors(HttpRequestBodyInterceptor)\n  getHello(@Req() req): string {\n    return req.body;\n  }\n}\n```\n\n```text\n@Injectable()\nexport class HttpRequestBodyInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable {\n    const request = context.switchToHttp().getRequest();\n    const token = request.headers['authorization'];\n\n    if (token) {\n      // decode token\n      request.userId = 'user_123456789';\n    }\n\n    return next.handle();\n  }\n}\n```\n\n```text\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Post()\n  @UseInterceptors(HttpRequestBodyInterceptor)\n  getHello(@Req() req) {\n    return {\n      userId: req.userId,\n      ...req.body,\n    };\n  }\n}\n```\n\n```text\nrequest.body\n```\n\n```text\nuserId\n```\n\n```text\n@Injectable()\n export class JwtInterceptor implements NestInterceptor {\n\n constructor(private readonly jwtService: JwtService, private readonly \n  userService: UserService) { }\n async intercept(context: ExecutionContext, next: CallHandler): \n  Promise<Observable<any>> {\n  var request: WsArgumentsHost = context.switchToWs();\n   var { handshake: { headers: { authorization } } } = \n    request.getClient();\ntry {\n  var jwt = authorization.split(\" \")[1];\n  var { phone } = await this.jwtService.verify(jwt, jwtConstraints)\n  var user: User = await this.userService.findUserByPhoneNumber(phone);\n  \n \n   request.getData()[\"user\"]=user;\n  return next.handle().pipe(map((data) => { return { ...data, 'user': \"david\" }; }));\n```\n\n========================================\n\nComments:\n- This above code replaces all the incoming body with what i am adding. I need to append to body and not replace\n- Instead of mutating the original request body, have you tried copying it, appending the new property and then re-assigning the copy to the original body property?\n- incoming body differs for every request but is generally like {'data': \"value\"}\n- Alternatively you can avoid re-assigning body and use the request object (request.userId) and then access that property from your controller as required.\n- @Isolated, yes i tried but that failed as well.\n- @Amit did you see my second comment?\n- @Isolated, I am trying that right now\n- @Isolated, How do i access this userId from the controller. As part of the header or body or how?\n- Add `@Req() req` to your controller method arguments and then use `req.userId`","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":202,"estimatedTokens":1400}}349{"id":"stack-64796640","source":"stackoverflow","questionId":64796640,"title":"Nestjs test e2e ECONNREFUSED 127.0.0.1:80","tags":["nestjs","e2e-testing"],"text":"Title: Nestjs test e2e ECONNREFUSED 127.0.0.1:80\nTags: nestjs, e2e-testing\nSource: Stack Overflow\n\nQuestion:\nI am having the error `ECONNREFUSED 127.0.0.1:80` when running a test e2e with Nestjs to test a dto.\n\nHere is my code:\n\n```\nconst TEST_URL = 'test';\n\n@Controller(TEST_URL)\nclass TestController {\n @Post()\n public test(@Body() param: TimeTableParam) {\n // nothing\n }\n}\n\ndescribe('TimeTableParam', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [TestController],\n }).compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await app.close();\n });\n\n describe('...', () => {\n it(`should ...`, () => {\n //...\n });\n });\n});\n```\n\n========================================\n\nCode:\n```text\nconst TEST_URL = 'test';\n\n@Controller(TEST_URL)\nclass TestController {\n  @Post()\n  public test(@Body() param: TimeTableParam) {\n    // nothing\n  }\n}\n\ndescribe('TimeTableParam', () => {\n  let app: INestApplication;\n\n  beforeAll(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      controllers: [TestController],\n    }).compile();\n\n    app = module.createNestApplication();\n    await app.init();\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n\n  describe('...', () => {\n    it(`should ...`, () => {\n      //...\n    });\n  });\n});\n```\n\n```text\nECONNREFUSED 127.0.0.1:80\n```\n\n```text\nconst TEST_URL = '/test';\n                  ^ add a '/'\n```\n\n========================================\n\nComments:\n- Thanks. That would have taken a long time for me to figure out!","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":95,"estimatedTokens":408}}350{"id":"stack-69000993","source":"stackoverflow","questionId":69000993,"title":"Nestjs overrideProvider vs provider in unit testing","tags":["unit-testing","nestjs","nestjs-testing"],"text":"Title: Nestjs overrideProvider vs provider in unit testing\nTags: unit-testing, nestjs, nestjs-testing\nSource: Stack Overflow\n\nQuestion:\nI see two ways of mocking services in NestJS for unit testing, the first one is the same as we define providers in real modules like:\n\n```\nconst module = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(User),\n useValue: mockUsersRepository,\n }\n ],\n}).compile();\n```\n\nAnd the other way with `overrideProvider` method. As following:\n\n```\nconst module = await Test.createTestingModule({\n imports: [UserModule]\n})\n.overrideProvider(getRepositoryToken(User))\n.useValue(mockUsersRepository)\n.compile();\n```\n\nWhat is the difference?\n\n========================================\n\nTop Answer:\nSo let me try to explain it this way:\n`overrideProvider` is useful when you've imported an entire module and need to override something it has as a provider. A use case, like the answer mentioned, would be overriding a logger. So say you have\n\n```\nconst modRef = await Test.createTestingModule({\n import: [AuthModule]\n}).compile();\n```\n\nAnd assume that `AuthModule` has `imports: [ LoggerModule ]`. In our test, we don't really want to see all the logs created, but we can't provide a custom provider for the `LoggerService` because it's being imported and used via the `LoggerModule` (overriding an injection token isn't really a common practice). So to provide our own implementation for`LoggerService` (let's say we just need a noop `log` method) we can do the following\n\n```\nconst modRef = await Test.createTestingModule({\n import: [AuthModule]\n})\n .overrideProvider(LoggerService)\n .useValue({ log: () => { /* noop */ } })\n .compile();\n```\n\nAnd now when our `AuthService` calls `this.logger.log()` it will just call this `noop` and be done with it.\n\nOn the flip side, if we're doing unit testing, usually you don't need to `overrideProvider` because you just set up the `provider` and the custom provider directly in the testing module's metadata and use that.\n\nThe `overrideProvider` is really useful when you *have* to use `imports` (like integration and e2e tests), otherwise, generally, it's better to use a custom provider\n\n========================================\n\nCode:\n```js\nconst module = await Test.createTestingModule({\n  providers: [\n    UserService,\n    {\n      provide: getRepositoryToken(User),\n      useValue: mockUsersRepository,\n    }\n  ],\n}).compile();\n```\n\n```js\nconst module = await Test.createTestingModule({\n  imports: [UserModule]\n})\n.overrideProvider(getRepositoryToken(User))\n.useValue(mockUsersRepository)\n.compile();\n```\n\n```text\noverrideProvider\n```\n\n```js\n@Module({providers: [LoggerService], exports: [LoggerService]})\nexport class LoggerModule {}\n\n@Module({imports: [LoggerModule], providers: [FooService]})\nexport class FooModule {}\n\n@Module({imports: [LoggerModule], providers: [BarService]})\nexport class BarModule {}\n\n@Module({imports: [FooModule, BarModule]}\nexport class AppModule {}\n\n// TEST\nconst testModule = await Test.createTestingModule({\n  import: [AppModule]\n})\n  .overrideProvider(LoggerService)\n  .useValue(/* your logger mock will be provided in both FooService and BarService and you can easily test all related to logs then */)\n  .compile();\n```\n\n```text\nUserService\n```\n\n```text\nUserService\n```\n\n```text\nLogger\n```\n\n```text\n.overrideProvider\n```\n\n```text\nLogger\n```\n\n```text\nloggerMock\n```\n\n```js\nconst modRef = await Test.createTestingModule({\n  import: [AuthModule]\n}).compile();\n```\n\n```js\nconst modRef = await Test.createTestingModule({\n  import: [AuthModule]\n})\n  .overrideProvider(LoggerService)\n  .useValue({ log: () => { /* noop */ } })\n  .compile();\n```\n\n```text\noverrideProvider\n```\n\n```text\nAuthModule\n```\n\n```text\nimports: [ LoggerModule ]\n```\n\n```text\nLoggerService\n```\n\n```text\nLoggerModule\n```\n\n```text\nLoggerService\n```\n\n```text\nlog\n```\n\n```text\nAuthService\n```\n\n```text\nthis.logger.log()\n```\n\n```text\nnoop\n```\n\n```text\noverrideProvider\n```\n\n```text\nprovider\n```\n\n```text\noverrideProvider\n```\n\n```text\nimports\n```\n\n========================================\n\nComments:\n- Thank you. That helped a lot. I just didn't realize the last part. (Logger module). Can you please provide an example?\n- Provided more explanation, but unfortunately, I see you already accepted another answer...\n- Thank you so much. And one question, what would've happened if I'd used provider instead of overrideProvider in your example?\n- Not sure what you mean?\n- I mean, in your example, what happens if we use `provider` in `createTestingModule` instead of using `overrideProvider`?\n- It will not be overridden inside the modules then.\n- So, you mean `LoggerService` will be a part of AppModule, and in other modules, they're going to use their own `LoggerService`, Is it right?\n- I guess your explanations and examples make more sense. Therefore, I accepted your answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":217,"estimatedTokens":1221}}351{"id":"stack-69263677","source":"stackoverflow","questionId":69263677,"title":"NestJs Swagger: How to define Api Property for dynamic classes","tags":["typescript","swagger","nestjs","openapi","nestjs-swagger"],"text":"Title: NestJs Swagger: How to define Api Property for dynamic classes\nTags: typescript, swagger, nestjs, openapi, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI have below class\n\n```\nexport class DocumentsSteps {\n @ApiProperty({type: ???})\n [type: string]: DocumentStep;\n}\n```\n\nHow should I define ApiProperty type?\n\n========================================\n\nTop Answer:\nYou can wrap it with a function\n\n```\nexport type Constructor = new (...args: any[]) => I\n\nfunction ErrorDto(statusCode: number, message: string): Constructor{\n class Error implements Error{\n @ApiProperty({ example: statusCode })\n readonly statusCode: number\n\n @ApiProperty({ example: message })\n readonly message: string\n\n }\n return Error\n}\nexport class UnauthorizedErrorDto extends ErrorDto(401, 'Unauthorized'){}\nexport class BadRequestErrorDto extends ErrorDto(400, 'Bad Request'){}\n```\n\n========================================\n\nCode:\n```text\nexport class DocumentsSteps {\n    @ApiProperty({type: ???})\n    [type: string]: DocumentStep;\n}\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nexport function CustomApiProperty(type: string) {\n  return applyDecorators(\n    ApiProperty({type, ...}),\n  );\n}\n```\n\n```text\nexport type Constructor<I> = new (...args: any[]) => I\n\nfunction ErrorDto(statusCode: number, message: string): Constructor<Error>{\n  class Error implements Error{\n    @ApiProperty({ example: statusCode })\n    readonly statusCode: number\n\n    @ApiProperty({ example: message })\n    readonly message: string\n\n  }\n  return Error\n}\nexport class UnauthorizedErrorDto extends ErrorDto(401, 'Unauthorized'){}\nexport class BadRequestErrorDto extends ErrorDto(400, 'Bad Request'){}\n```\n\n```text\n@ApiExtraModels(DocumentStep)\nexport class DocumentsSteps {\n    @ApiProperty({\n        additionalProperties: { oneOf: [{ $ref: getSchemaPath(DocumentStep) }] },\n    })\n    [type: string]: DocumentStep;\n}\n```\n\n```text\n@ApiExtaModels()\n```\n\n========================================\n\nComments:\n- would you please add a small sample here about the changes manually, what should it look like","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":515}}352{"id":"stack-67367065","source":"stackoverflow","questionId":67367065,"title":"Dynamic kafka topic name in nestjs microservice","tags":["typescript","microservices","nestjs","nestjs-config"],"text":"Title: Dynamic kafka topic name in nestjs microservice\nTags: typescript, microservices, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nIn Nestjs I am using kafka as message broker and set topic name in like this:\n\n```\n@MessagePattern('topic-name')\nasync getNewRequest(@Payload() message: any): Promise {\n // my code goes here\n}\n```\n\nIs there any way to read kafka topic name from config service module?\n\n========================================\n\nTop Answer:\nYou can use `process.env.VAR_NAME`, like this:\n\n```\n@MessagePattern(process.env.MESSAGES_TOPIC)\n```\n\nOne important thing to notice is that `.env` file will not work, you'll need to set a environment variable prior to application start, that is because the ConfigService/dotenv loads too late for this case.\nThat can be achieved with this in you `packag.json`:\n\n```\n\"scripts\": {\n \"start\": \"export MESSAGES_TOPIC=topic_name || SET \\\"MESSAGES_TOPIC=topic_name \\\" && nest start\",\n},\n```\n\nAlthough Ali's answer may work, I think its too much for such a simple thing, It seems to me that is preferable do not use `ConfigService` for this specific case.\n\n========================================\n\nCode:\n```text\n@MessagePattern('topic-name')\nasync getNewRequest(@Payload() message: any): Promise<void> {\n  // my code goes here\n}\n```\n\n```text\nexport const KAFKA_TOPIC_METADATA = '__kafka-topic-candidate';\n\nexport function KafkaTopic(variable: string | keyof AppConfig): any {\n  return (\n    target: any,\n    key: string | symbol,\n    descriptor: PropertyDescriptor,\n  ) => {\n    Reflect.defineMetadata(\n      KAFKA_TOPIC_METADATA,\n      variable,\n      descriptor.value,\n    );\n    return descriptor;\n  };\n}\n```\n\n```text\nexport const KAFKA_TOPIC_METADATA = '__kafka-topic-candidate';\n\n@Injectable()\nexport class KafkaDecoratorProcessorService {\n  constructor(\n    private readonly LOG: Logger,\n    private readonly appConfig: AppConfig,\n  ) {\n  }\n\n  processKafkaDecorators(types: any[]) {\n    for (const type of types) {\n      const propNames = Object.getOwnPropertyNames(type.prototype);\n      for (const prop of propNames) {\n        const propValue = Reflect.getMetadata(\n          KAFKA_TOPIC_METADATA,\n          Reflect.get(type.prototype, prop),\n        );\n\n        if (propValue) {\n          const topic = this.appConfig[propValue];\n          this.LOG.log(`Setting topic ${topic} for ${type.name}#${prop}`);\n          Reflect.decorate(\n            [MessagePattern(topic)],\n            type.prototype,\n            prop,\n            Reflect.getOwnPropertyDescriptor(type.prototype, prop),\n          );\n        }\n      }\n    }\n  }\n}\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\n  app\n    .get(KafkaDecoratorProcessorService)\n    .processKafkaDecorators([AppController]);\n\n  app.connectMicroservice({\n    transport: Transport.KAFKA,\n    ...\n   })\n```\n\n```text\n@KafkaTopic('KAFKA_TOPIC_BOOK_UPDATE')\n  async processMessage(\n    @Payload() { value: payload }: { value: BookUpdateModel },\n  ) {\n    ...\n  }\n```\n\n```text\n@MessagePattern(process.env.MESSAGES_TOPIC)\n```\n\n```text\n\"scripts\": {\n  \"start\": \"export MESSAGES_TOPIC=topic_name || SET \\\"MESSAGES_TOPIC=topic_name \\\" && nest start\",\n},\n```\n\n```text\nprocess.env.VAR_NAME\n```\n\n```text\n.env\n```\n\n```text\npackag.json\n```\n\n```text\nConfigService\n```\n\n========================================\n\nComments:\n- Hi...I'm the same problem. Did you get it fixed?\n- In a mono-repo setup, if you place the .env in the root folder, then it will load correctly.\n- it works for me ! Thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":154,"estimatedTokens":875}}353{"id":"stack-61755735","source":"stackoverflow","questionId":61755735,"title":"How to make Dependency Injection work for global Exception Filter in NestJS?","tags":["dependency-injection","nestjs"],"text":"Title: How to make Dependency Injection work for global Exception Filter in NestJS?\nTags: dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to avoid using `app.useGlobalFilters(new AllExceptionsFilter(...));`, but I am struggling to make DI inject my custom LoggerService into AllExceptionsFilter.\n\nI have my app module with LoggerModule imported and filter defined like this:\n\n```\nimport { APP_FILTER } from '@nestjs/core';\n...\n\n@Module({\n imports: [LoggerModule],\n providers: [\n {\n provide: APP_FILTER,\n useClass: AllExceptionsFilter,\n },\n ],\n})\nexport default class AppModule {}\n```\n\nException Filter (pretty much the same code as in nest docs):\n\n```\nimport { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';\nimport LoggerService from '../modules/logger/logger.service';\n\n@Catch()\nexport default class AllExceptionsFilter implements ExceptionFilter {\n constructor(private readonly loggerService: LoggerService) {}\n\n catch(exception: Error, host: ArgumentsHost): void {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n\n console.log(this.loggerService);\n // this.loggerService.error(exception);\n\n const status =\n exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;\n\n response.status(status).json({\n statusCode: status,\n message: exception.message,\n path: request.url,\n });\n }\n}\n```\n\nLoggerModule:\n\n```\n@Global()\n@Module({\n providers: [LoggerService],\n exports: [LoggerService],\n})\nexport default class LoggerModule {}\n```\n\nCan you point out what is wrong, and why LoggerService is not injected into my ExceptionFilter?\n\nDocumentation reference.\n\n========================================\n\nTop Answer:\n**AllExceptionsFilter file everything good, only change the main.ts file**\n\n```\nconst loggerService = app.get(LoggerService);\napp.useGlobalFilters(new AllExceptionsFilter(loggerService));\n```\n\n========================================\n\nCode:\n```js\nimport { APP_FILTER } from '@nestjs/core';\n...\n\n@Module({\n  imports: [LoggerModule],\n  providers: [\n    {\n      provide: APP_FILTER,\n      useClass: AllExceptionsFilter,\n    },\n  ],\n})\nexport default class AppModule {}\n```\n\n```js\nimport { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';\nimport LoggerService from '../modules/logger/logger.service';\n\n@Catch()\nexport default class AllExceptionsFilter implements ExceptionFilter {\n  constructor(private readonly loggerService: LoggerService) {}\n\n  catch(exception: Error, host: ArgumentsHost): void {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse();\n    const request = ctx.getRequest();\n\n    console.log(this.loggerService);\n    // this.loggerService.error(exception);\n\n    const status =\n      exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    response.status(status).json({\n      statusCode: status,\n      message: exception.message,\n      path: request.url,\n    });\n  }\n}\n```\n\n```js\n@Global()\n@Module({\n  providers: [LoggerService],\n  exports: [LoggerService],\n})\nexport default class LoggerModule {}\n```\n\n```text\napp.useGlobalFilters(new AllExceptionsFilter(...));\n```\n\n```text\n@Injectable({ scope: Scope.REQUEST })\n```\n\n```text\n@Injectable({ scope: Scope.TRANSIENT })\n```\n\n```text\nconst loggerService = app.get<LoggerService>(LoggerService);\napp.useGlobalFilters(new AllExceptionsFilter(loggerService));\n```\n\n```text\n@Module({\n  imports: [LoggerModule],\n  providers: [\n    {\n      provide: APP_FILTER,\n      useClass: AllExceptionsFilter,\n      scope: Scope.REQUEST, // this new line\n    },\n  ],\n})\n```\n\n```js\n// global filter\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n  constructor(private readonly featureFlagsService: FeatureFlagsService) {}\n  ...\n}\n\n// app module\n@Module({\n  ...\n  providers: [\n    FeatureFlagsService,\n    {\n      provide: APP_FILTER,\n      useFactory: (featureFlagsService: FeatureFlagsService) => {\n        return new AllExceptionsFilter(featureFlagsService);\n      },\n      inject: [FeatureFlagsService],\n    },\n  ],\n})\nexport class AppModule implements NestModule {\n  ...\n}\n```\n\n```text\nuseFactory\n```\n\n```text\nFeatureFlagsService\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":200,"estimatedTokens":1070}}354{"id":"stack-49934901","source":"stackoverflow","questionId":49934901,"title":"NestJs - How to get url of handler?","tags":["nestjs"],"text":"Title: NestJs - How to get url of handler?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to redirect user to another url in my server, but I do not want to hardcode url like `res.redirect('/hello_world')`. Instead I want to just specify handler's url of specified controller like `res.redirect(HelloWorldController.handlerName.url)` where HelloWorldContoller is \n\n```\n@Controller()\nexport class HelloWorldController {\n @Get('hello_world')\n handlerName(): string {\n return 'Hello World!';\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Controller()\nexport class HelloWorldController {\n    @Get('hello_world')\n    handlerName(): string {\n        return 'Hello World!';\n    }\n}\n```\n\n```text\nres.redirect('/hello_world')\n```\n\n```text\nres.redirect(HelloWorldController.handlerName.url)\n```\n\n```text\nimport { PATH_METADATA } from '@nestjs/common/constants';\n\n@Controller('api')\nexport class ApiController {\n  @Get('hello')\n  root() {\n    let routePath = Reflect.getMetadata(PATH_METADATA, StaticController);\n    routePath += '/' + Reflect.getMetadata(PATH_METADATA, StaticController.prototype.serveStatic);\n    console.log(routePath); will return `api/hello`\n    return {\n      message: 'Hello World!',\n    };\n  }\n}\n```\n\n```text\nStaticController\n```\n\n```text\nReflect.getMetadata(PATH_METADATA, AnyOtherController);\n```\n\n========================================\n\nComments:\n- Thanks for an answer, but there are some misunderstandings: 1st - What is a PATH_METADATA? and 2nd - Why it returns `api&#47;hello` if I need a path not of self url, but other controller's url?\n- Ok. I understood. Instead of PATH_METADATA, we write 'path'. And we get url of specified controller's path and method's path. However, I thought that there will be NestJS's helper function that returns full path, instead of creating it by yourself. Thanks a lot\n- @NursultanZarlyk, you can also look at `NestJS` realization in source code: github.com/nestjs/nest/blob/&hellip;. There are some helper functions","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":69,"estimatedTokens":501}}355{"id":"stack-56208037","source":"stackoverflow","questionId":56208037,"title":"nestjs multer get list of new file names after multer storage","tags":["javascript","node.js","typescript","multer","nestjs"],"text":"Title: nestjs multer get list of new file names after multer storage\nTags: javascript, node.js, typescript, multer, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have this middleware that I use to upload files.\n\n```\n@Injectable()\nexport class FilesMiddleware implements NestMiddleware {\n\n private storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, path.join(__dirname, '../../uploads/'));\n },\n filename: (req, file, cb) => {\n let extArray = file.mimetype.split(\"/\");\n let extension = extArray[extArray.length - 1];\n cb(null, file.fieldname + '-' + Date.now() + '.' + extension)\n }\n});\n\n resolve(...args: any[]): MiddlewareFunction {\n return (req, res, next) => {\n console.log(req.files);\n const upload = multer({storage: this.storage});\n upload.any();\n return next();\n }\n }\n}\n```\n\nThe problem that in my request, when I use `req.files` it gives me the original file names instead of the new file names (with date, etc like I set in the multer storage options).\n\nIs there a way I can get the new file names multer just uploaded with the middleware?\n\n```\n@Post('upload')\n@UseInterceptors(FilesInterceptor('files[]', 20, {}))\npublic async onUpload(@Request() req, @Response() res, @UploadedFiles() files) {\n const mediaResponse = await this.media.saveMedias(0, files);\n res.json({status: true});\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class FilesMiddleware implements NestMiddleware {\n\n  private storage = multer.diskStorage({\n    destination: (req, file, cb) => {\n      cb(null, path.join(__dirname, '../../uploads/'));\n    },\n    filename: (req, file, cb) => {\n      let extArray = file.mimetype.split(\"/\");\n      let extension = extArray[extArray.length - 1];\n      cb(null, file.fieldname + '-' + Date.now() + '.' + extension)\n    }\n});\n\n  resolve(...args: any[]): MiddlewareFunction {\n    return (req, res, next) => {\n      console.log(req.files);\n      const upload = multer({storage: this.storage});\n      upload.any();\n      return next();\n    }\n  }\n}\n```\n\n```text\n@Post('upload')\n@UseInterceptors(FilesInterceptor('files[]', 20, {}))\npublic async onUpload(@Request() req, @Response() res, @UploadedFiles() files) {\n    const mediaResponse = await this.media.saveMedias(0, files);\n    res.json({status: true});\n}\n```\n\n```text\nreq.files\n```\n\n```text\nconst storage = {...};\n\n@Controller()\nexport class AppController {\n\n  @Post('upload')\n  @UseInterceptors(FilesInterceptor('files', 20, { storage }))\n  public async onUpload(@UploadedFiles() files) {\n    return files.map(file => file.filename);\n  }\n}\n```\n\n```text\nimports: [\n  MulterModule.register({\n    storage: {...},\n  })\n]\n```\n\n```text\nexport class FilesMiddleware implements NestMiddleware {\n  private storage = {...};\n\n  async use(req, res, next) {\n    const upload = multer({ storage: this.storage });\n    // wait until upload has finished\n    await new Promise((resolve, reject) => {\n      upload.array('files')(req, res, err => err ? reject(err) : resolve());\n    });\n    // Then you can access the new file names\n    console.log(req.files.map(file => file.filename));\n    return next();\n  }\n}\n```\n\n```text\n@Post('upload')\npublic async onUpload(@Request() req) {\n  return req.files.map(file => file.filename);\n}\n```\n\n```text\n[ { fieldname: 'files',\n    originalname: 'originalname.json',\n    encoding: '7bit',\n    mimetype: 'application/json',\n    destination: 'D:/myproject/src/uploads',\n    // This is what you are looking for\n    filename: 'files-1558459911159.json',\n    path:\n     'D:/myproject/src/uploads/files-1558459911159.json',\n    size: 2735 } ]\n```\n\n```text\nFilesInterceptor\n```\n\n```text\nFilesMiddleware\n```\n\n```text\nFilesInterceptor\n```\n\n```text\nFilesInterceptor\n```\n\n```text\nMulterModule\n```\n\n```text\nFilesInterceptor\n```\n\n```text\nFilesInterceptor\n```\n\n```text\nPromise\n```\n\n```text\nreq.files\n```\n\n```text\nrequest\n```\n\n```text\nreq.files\n```\n\n```text\n@UploadedFiles() files\n```\n\n========================================\n\nComments:\n- You might want to use `file.originalname` instead of `file.fieldname` in your `filename` function. Otherwise all your files will start with the same prefix *files*.","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":199,"estimatedTokens":1035}}356{"id":"stack-62268243","source":"stackoverflow","questionId":62268243,"title":"Passport Google Oauth2 not prompting select account when only 1 google account logged in","tags":["node.js","passport.js","nestjs","passport-google-oauth","passport-google-oauth2"],"text":"Title: Passport Google Oauth2 not prompting select account when only 1 google account logged in\nTags: node.js, passport.js, nestjs, passport-google-oauth, passport-google-oauth2\nSource: Stack Overflow\n\nQuestion:\nI'm trying to authenticate users in my node + nestjs api and want to prompt the user to select an account. \n\nThe prompt does not show up if you have only 1 account logged in and even when you are logged in with 2 accounts and you get prompted, the URL in the redirect still has &prompt=none in the parameters.\n\nI can in fact confirm that it makes no difference that prompt option.\n\nMy code simplified below: \n\n```\nimport { OAuth2Strategy } from \"passport-google-oauth\";\nimport { PassportStrategy } from \"@nestjs/passport\";\n@Injectable()\nexport class GoogleStrategy extends PassportStrategy(OAuth2Strategy, \"google\") {\n constructor(secretsService: SecretsService) {\n super({\n clientID: secretsService.get(\"google\", \"clientid\"),\n clientSecret: secretsService.get(\"google\", \"clientsecret\"),\n callbackURL: \"https://localhost:3000/auth/google/redirect\",\n scope: [\"email\", \"profile\", \"openid\"],\n passReqToCallback: true,\n prompt: \"select_account\",\n });\n }\n\n async validate(req: Request, accessToken, refreshToken, profile, done) {\n const { name, emails, photos } = profile;\n const user = {\n email: emails[0].value,\n firstName: name.givenName,\n lastName: name.familyName,\n picture: photos[0].value,\n accessToken,\n };\n return done(null, user);\n }\n}\n```\n\nHow can i possibly further debug this to see why/whats happening under the hood? \n\nThe actual endpoints: \n\n```\n@Controller(\"auth\")\nexport class AuthController {\n @Get(\"google\")\n @UseGuards(AuthGuard(\"google\"))\n private googleAuth() {}\n\n @Get(\"google/redirect\")\n @UseGuards(AuthGuard(\"google\"))\n googleAuthRedirect(@Req() req: Request, @Res() res: Response) {\n if (!req.user) {\n return res.send(\"No user from google\");\n }\n\n return res.send({\n message: \"User information from google\",\n user: req.user,\n });\n }\n}\n```\n\nI can't pass an options object with any of the guards or UseGuards decorator. \n\nI've also tried to pass an extra object parameter to the super call but that didn't work either.\n\n========================================\n\nTop Answer:\nFor anyone use nestjs and facing same issue, here is the solution\n\n```\nclass AuthGoogle extends AuthGuard('google') {\n constructor() {\n super({\n prompt: 'select_account'\n });\n } }\n }\n // using\n @UseGuards(AuthGoogle)\n private googleAuth() {}\n```\n\n========================================\n\nCode:\n```text\nimport { OAuth2Strategy } from \"passport-google-oauth\";\nimport { PassportStrategy } from \"@nestjs/passport\";\n@Injectable()\nexport class GoogleStrategy extends PassportStrategy(OAuth2Strategy, \"google\") {\n  constructor(secretsService: SecretsService) {\n    super({\n      clientID: secretsService.get(\"google\", \"clientid\"),\n      clientSecret: secretsService.get(\"google\", \"clientsecret\"),\n      callbackURL: \"https://localhost:3000/auth/google/redirect\",\n      scope: [\"email\", \"profile\", \"openid\"],\n      passReqToCallback: true,\n      prompt: \"select_account\",\n    });\n  }\n\n  async validate(req: Request, accessToken, refreshToken, profile, done) {\n    const { name, emails, photos } = profile;\n    const user = {\n      email: emails[0].value,\n      firstName: name.givenName,\n      lastName: name.familyName,\n      picture: photos[0].value,\n      accessToken,\n    };\n    return done(null, user);\n  }\n}\n```\n\n```text\n@Controller(\"auth\")\nexport class AuthController {\n  @Get(\"google\")\n  @UseGuards(AuthGuard(\"google\"))\n  private googleAuth() {}\n\n  @Get(\"google/redirect\")\n  @UseGuards(AuthGuard(\"google\"))\n  googleAuthRedirect(@Req() req: Request, @Res() res: Response) {\n    if (!req.user) {\n      return res.send(\"No user from google\");\n    }\n\n    return res.send({\n      message: \"User information from google\",\n      user: req.user,\n    });\n  }\n}\n```\n\n```text\nrouter.get(\n    '/auth/google',\n    passport.authenticate('google', {\n        accessType: 'offline',\n        callbackURL: callbackUrl,\n        includeGrantedScopes: true,\n        scope: ['profile', 'email'],\n        prompt: 'select_account', // <=== Add your prompt setting here\n    })\n);\n```\n\n```text\nOAuth2Strategy\n```\n\n```text\npassport.authenticate(passport, name, options, callback)\n```\n\n```text\npassport.authenticate(...)\n```\n\n```text\nprompt: 'select_account'\n```\n\n```text\npassport.authenticate()\n```\n\n```text\nclass AuthGoogle extends AuthGuard('google') {\n        constructor() {\n            super({\n                prompt: 'select_account'\n            });\n        } }\n    }\n     // using\n    @UseGuards(AuthGoogle)\n    private googleAuth() {}\n```\n\n========================================\n\nComments:\n- That's great, it's work, can you explain for me why I need to define a new class AuthGoogle, please\n- Post the code in your answer, don't just link to it :)\n- nice , adding authorizationParams does the job great","metadata":{"transformedAt":"2026-08-18T18:33:02.434Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":198,"estimatedTokens":1223}}357{"id":"stack-59337362","source":"stackoverflow","questionId":59337362,"title":"nestjs - how to use shared modules between nestjs applications","tags":["node-modules","nestjs"],"text":"Title: nestjs - how to use shared modules between nestjs applications\nTags: node-modules, nestjs\nSource: Stack Overflow\n\nQuestion:\nLet's say I have NestJs project, that consists of following parts, each with it's own git repository and deployed on different machines:\n\n- Api service\n\n- Message-queue processing workers service\n\nBoth of the services require part #3 - library for accessing RabbitMq.\nLet's say that #3 is some abstraction around the RabbitMq client that defines entities and services, that access MQ, so the modules #1. and #2. doesn't even know, they are working with RabbitMq. #3 is planned to be included / used as a library in #1 and #2, not as a microservice.\n\nHow should this be integrated together?\nLet's assume it from the perspective of API service:\n\n- It has the RabbitMq module inside the node_modules folder.\n\n- I want to use e.g. dependency injection in that RabbitMq library. Ideally, expose it as NestJs module, to be used in @Module imports of API module.\n\nShould I use NestJs as peerDependency in the RabbitMq module?\n\nI have like 3-4 shared-modules I need to between the modules #1 and #2. Not just MQ.\n\n========================================\n\nTop Answer:\nYou can use the workspace concept of nest js. I think monorepo mode will be the one that can help without having the complexity of making npm modules etc.\n\nhttps://docs.nestjs.com/cli/monorepo\n\n========================================\n\nComments:\n- I have been so looking for exactly that kind of article, thank You ;). I think this should be part of the documentation, I believe this is really basic problem every larger app needs to solve.","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":36,"estimatedTokens":408}}358{"id":"stack-55009830","source":"stackoverflow","questionId":55009830,"title":"NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined","tags":["typescript","jestjs","nestjs","typeorm"],"text":"Title: NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined\nTags: typescript, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nTrying to unit test.\nGot following error:\n\n TypeError: Cannot read property 'prototype' of undefined\n\n \n export class UserService {\n\n \n constructor(@InjectRepository(User) private readonly userRepository:\n Repository ) { } \n\n**spec.ts:**\n\n```\ndescribe('AuthController', () => {\nlet authController: AuthController;\nlet authService: AuthService;\nlet mockRepository = {\n\n};\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forFeature([User]),\n ],\n controllers: [AuthController],\n providers: [AuthService, {\n provide: getRepositoryToken(User),\n useValue: mockRepository\n }]\n }).compile()\n authService = module.get(AuthService);\n authController = module.get(AuthController)\n});\n```\n\nCan someone a solution please?\n\n**MORE INFO**:\n\nSo seems like its something wrong with `typeorm`\n\n```\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n\n }).compile()\n authService = module.get(AuthService);\n authController = module.get(AuthController)\n});\n```\n\nWith this code I'm getting exact the same error. So only problem is adding `typeorm` to this test Module.\n\nSo it fails because of dependency: **AuthController->AuthService->UserService->TypeORM**\n\nBtw just checked `UserService` using API with Postman and it works fine.\n\n**Still no result:**\n\n```\nmodule = await Test.createTestingModule({\n controllers: [AuthController],\n components: [\n {\n provide: AuthService,\n useValue: {}\n },\n {\n provide: UserService,\n useValue: {}\n },\n {\n provide: getRepositoryToken(User),\n useValue: {}\n }\n ],\n providers: [\n {\n provide: AuthService,\n useValue: {}\n },\n {\n provide: UserService,\n useValue: {}\n },\n {\n provide: getRepositoryToken(User),\n useValue: {}\n }\n ]\n }).compile()\n this.authController = module.get(AuthController)\n```\n\nAlso \n\n```\nclass AuthServiceMock {\n logIn(userName) {\n return { id:100, isDeleted:false, login:\"login\", password:\"password\"};\n }\n\n signUp() {\n return { expireIn: 3600, token:\"token\" };\n }\n}\n\ndescribe('AuthController', () => {\nlet module: TestingModule;\nlet authController: AuthController;\nlet authService: AuthService;\n\nbeforeEach(async () => {\n module = await Test.createTestingModule({\n controllers: [AuthController],\n components: [\n\n ],\n providers: [\n {\n provide: AuthService,\n useClass: AuthServiceMock\n },\n ]\n }).compile()\n this.authController = module.get(AuthController)\n});\n```\n\n========================================\n\nTop Answer:\nI just passed the User entity to Repository and it works.\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: Repository\n ) { }\n\n}\n```\n\nCheckout docs from here: https://docs.nestjs.com/techniques/database. They have pretty good docs.\n\n========================================\n\nCode:\n```text\ndescribe('AuthController', () => {\nlet authController: AuthController;\nlet authService: AuthService;\nlet mockRepository = {\n\n};\nbeforeEach(async () => {\n    const module = await Test.createTestingModule({\n        imports: [\n            TypeOrmModule.forFeature([User]),\n        ],\n        controllers: [AuthController],\n        providers: [AuthService, {\n            provide: getRepositoryToken(User),\n            useValue: mockRepository\n        }]\n    }).compile()\n    authService = module.get<AuthService>(AuthService);\n    authController = module.get<AuthController>(AuthController)\n});\n```\n\n```text\nbeforeEach(async () => {\n    const module = await Test.createTestingModule({\n\n    }).compile()\n    authService = module.get<AuthService>(AuthService);\n    authController = module.get<AuthController>(AuthController)\n});\n```\n\n```text\nmodule = await Test.createTestingModule({\n        controllers: [AuthController],\n        components: [\n            {\n                provide: AuthService,\n                useValue: {}\n            },\n            {\n                provide: UserService,\n                useValue: {}\n            },\n            {\n                provide: getRepositoryToken(User),\n                useValue: {}\n            }\n        ],\n        providers: [\n            {\n                provide: AuthService,\n                useValue: {}\n            },\n            {\n                provide: UserService,\n                useValue: {}\n            },\n            {\n                provide: getRepositoryToken(User),\n                useValue: {}\n            }\n        ]\n    }).compile()\n    this.authController = module.get<AuthController>(AuthController)\n```\n\n```text\nclass AuthServiceMock {\n    logIn(userName) {\n        return { id:100, isDeleted:false, login:\"login\", password:\"password\"};\n    }\n\n    signUp() {\n        return { expireIn: 3600, token:\"token\" };\n    }\n}\n\ndescribe('AuthController', () => {\nlet module: TestingModule;\nlet authController: AuthController;\nlet authService: AuthService;\n\nbeforeEach(async () => {\n    module = await Test.createTestingModule({\n        controllers: [AuthController],\n        components: [\n\n        ],\n        providers: [\n            {\n                provide: AuthService,\n                useClass: AuthServiceMock\n            },\n        ]\n    }).compile()\n    this.authController = module.get<AuthController>(AuthController)\n});\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n```text\nUserService\n```\n\n```js\nexport * from './user.module';\n```\n\n```text\nsrc/user/index.ts\n```\n\n```text\nUserModule\n```\n\n```text\nsrc/user/user.module.ts\n```\n\n```text\nUserModule\n```\n\n```text\nsrc/user/index.ts\n```\n\n```text\n@Injectable()\nexport class UserService {\n    constructor(\n        @InjectRepository(User)\n        private readonly userRepository: Repository<User>\n    ) { }\n\n}\n```\n\n```text\nconst module = await Test.createTestingModule({\n    controllers: [AuthController],\n    providers: [{\n        provide: AuthService,\n        useValue: authServiceMock\n    }]\n}).compile()\n```\n\n```text\nTypeOrmModule.forFeature(...)\n```\n\n```text\nTypeOrmModule.forRoot(...)\n```\n\n```text\nAuthService\n```\n\n```text\nAuthService\n```\n\n```text\nasync findAll() {\n    \n    return await this.userRepository.createCursor(this.userRepository.find()).toArray();\n  }\n```\n\n========================================\n\nComments:\n- Did you solve it somehow? I\"m having the same issue\n- @alex88 yes. I recreated project and copied all old files to new. Seems like it was some typeorm bug.\n- UserService injects repository and AuthService injects UserService. I tryed ur code but still getting same error.\n- Weird, `typeorm` is not involved at all in the controller test. What's the stacktrace of the error, where does it point to?\n- Have a look at this test for reference: github.com/kiwikern/shassi-nest/blob/master/src/auth/&hellip;\n- Its point to @InjectRepository(User) at at Object.getRepositoryToken\n- That's really weird. The actual `UserService` should *never* be instantiated when you unit test the `AuthController` or the `AuthService` with mocks.\n- Let us continue this discussion in chat.\n- In order to let more user benefit form your answer, could you provide more explanation please.\n- You saved me alive!","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":351,"estimatedTokens":1791}}359{"id":"stack-55480448","source":"stackoverflow","questionId":55480448,"title":"How to apply both ValidationPipe() and ParseIntPipe() to params?","tags":["javascript","node.js","typescript","validation","nestjs"],"text":"Title: How to apply both ValidationPipe() and ParseIntPipe() to params?\nTags: javascript, node.js, typescript, validation, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to apply both the `ValidationPipe()` and `ParseIntPipe()` to the params in my NestJs controller.\n\nThe intention is to apply `ParseIntPipe()` only on `@Param('id')` but `ValidationPipe()` for all params in `CreateDataParams` and Body DTO.\n\nHowever, I can't seem to apply both pipes the way I wanted. Here's what I have:\n\n```\n@Post(':id')\n@UsePipes(new ValidationPipe())\nasync create(\n @Param('id', new ParseIntPipe()) id: number, //this doesn't work\n @Param() params: CreateDataParams,\n @Body() createDto: CreateDto\n) {\n // params.id\n}\n```\n\nI have tried having another `@Param('id')` to apply the `ParseIntPipe()` transformer but this doesn't work.\n\nHow can I apply both `ValidationPipe()` and `ParseIntPipe()` to the params?\n\n========================================\n\nCode:\n```text\n@Post(':id')\n@UsePipes(new ValidationPipe())\nasync create(\n    @Param('id', new ParseIntPipe()) id: number,  //this doesn't work\n    @Param() params: CreateDataParams,\n    @Body() createDto: CreateDto\n) {\n    // params.id\n}\n```\n\n```text\nValidationPipe()\n```\n\n```text\nParseIntPipe()\n```\n\n```text\nParseIntPipe()\n```\n\n```text\n@Param('id')\n```\n\n```text\nValidationPipe()\n```\n\n```text\nCreateDataParams\n```\n\n```text\n@Param('id')\n```\n\n```text\nParseIntPipe()\n```\n\n```text\nValidationPipe()\n```\n\n```text\nParseIntPipe()\n```\n\n```text\nimport { Transform } from 'class-transformer';\nexport class CreateDataParams {\n  @Transform(id => parseInt(id), {toClassOnly: true})\n  id: number;\n}\n```\n\n```text\n@Post(':id')\n@UsePipes(new ValidationPipe({transform: true}))\nasync create(\n    @Param() params: CreateDataParams,\n    @Body() createDto: CreateDto\n) {\n    // params.id\n}\n```\n\n```text\nParseIntPipe\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nparams\n```\n\n```text\nstring\n```\n\n```text\nclass-transformer\n```\n\n```text\nnumber\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\nparseInt('5abc010')\n```\n\n```text\n5\n```\n\n========================================\n\nComments:\n- Oh thanks! I did not think of this. This worked very well!\n- I used @Transform(role => JSON.parse(id), {toClassOnly: true}) but its not working, any idea?\n- @KallolMedhi Did you set `transform: true` in your `ValidationPipe`?\n- Also, `id` is `undefined` in the function `role => JSON.parse(id)`. You have to change the name of the param.\n- @KimKern yea it worked now, i had to set transform: true in global validation pipe. Also can you tell me the difference between 'toClassOnly' and 'toPlainOnly' what should I do in my case?? i just have to parse a particular field in the body before it reaches DTO and validation\n- I think its best to refer the document in these cases, but anyway - 'toClassOnly' the transformation that you have done will be applied only when the plainJSON is transformed to a class (kind of when serialzed). 'toPlainOnly' is vice versa","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":158,"estimatedTokens":750}}360{"id":"stack-61795276","source":"stackoverflow","questionId":61795276,"title":"NestJS create a new instance with custom parameters staying in the dependency injection layer","tags":["node.js","typescript","nestjs"],"text":"Title: NestJS create a new instance with custom parameters staying in the dependency injection layer\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a new instance without breaking the DI layer, allowing my instance to have access to all injectable services it is using in its constructor\n\nn example of what I have currently which does not allow me using any injectable services:\n\n```\nconst camera: Camera = new Camera(id, options);\n```\n\nWith this approach, the camera class could not import any injectable singletons or classes.\n\nI have read here that you can use `moduleRef` to create a new instance, so I tried the following:\n\n```\nconst camera: Camera = await this.moduleRef.create(Camera);\n```\n\nBut the issue now is, I can't pass the `ID` and `Options` parameters, the only solution would be using a setter right after initializing it.\n\n**Question:**\n\nHow can you create a new instance (not singleton) of a class, have it created by nest's injector and pass custom parameters on creation in the latest version of NestJS?\n\n========================================\n\nTop Answer:\nWe had the same issue. The way we solved it is by using the useFactory, and instead of returning the value, we retuned a factory function that excepts the extra arguments and we use it to create new instances. Like so:\n\n```\nconst factory = {\n provide: PUPPETEER_FACTORY,\n useFactory: (configService): PuppeteerFactory => {\n return {\n create: function(config?: PuppeteerConfig) {\n return new Puppeteer(configService, config);\n }\n };\n },\n inject: [ConfigService]\n};\n```\n\nand than you simply use the create function that is returned, like so:\n\n```\nconstructor(@Inject(PUPPETEER_FACTORY) private puppeteerFactory: PuppeteerFactory) {}\nthis.puppeteerInstance = this.puppeteerFactory.create({\n timezone: \"UTC+8\",\n userAgent: \"BLA\"\n });\n```\n\nNotice that PUPPETEER_FACTORY is a const\n\n========================================\n\nCode:\n```text\nconst camera: Camera = new Camera(id, options);\n```\n\n```text\nconst camera: Camera = await this.moduleRef.create(Camera);\n```\n\n```text\nmoduleRef\n```\n\n```text\nID\n```\n\n```text\nOptions\n```\n\n```js\n@Module({\n   ...\n   providers: [\n      {\n         useFactory: (optProvider) => {\n           return new Camera(optProvider.id, optProvider.options);\n         }, \n         provide: Camera,\n         import: [OptProvider] // pay attention that OptProvider is a valid provider in this module\n      },\n      SomeService\n   ]\n})\nexport class SomeModule {}\n```\n\n```js\nexport class SomeService() {\n  constructor( protected readonly camera: Camera ) {}\n}\n```\n\n```text\nconst factory = {\n  provide: PUPPETEER_FACTORY,\n  useFactory: (configService): PuppeteerFactory => {\n    return {\n      create: function(config?: PuppeteerConfig) {\n        return new Puppeteer(configService, config);\n      }\n    };\n  },\n  inject: [ConfigService]\n};\n```\n\n```text\nconstructor(@Inject(PUPPETEER_FACTORY) private puppeteerFactory: PuppeteerFactory) {}\nthis.puppeteerInstance = this.puppeteerFactory.create({\n      timezone: \"UTC+8\",\n      userAgent: \"BLA\"\n    });\n```\n\n========================================\n\nComments:\n- Hey thank you for your time and answer. This still does not answer my question because with this way you can only inject existing injectables in the module but not a custom value passed via moduleRef!\n- so you can use this approach to build your own provider that you can inject using nest DI and transmit objects with it. Not sure that nest allows inject/remove something right it moduleRef because it could be more complex than just array with objects. It could have unobvious dependencies","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":131,"estimatedTokens":909}}361{"id":"stack-54648678","source":"stackoverflow","questionId":54648678,"title":"How to issue multiple commands from nestjs saga?","tags":["nestjs"],"text":"Title: How to issue multiple commands from nestjs saga?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI've created a saga to react on a given event. In that case, multiple commands need to be issued.\n\nMy Saga looks like this:\n\n```\n@Injectable()\nexport class SomeSagas {\n public constructor() {}\n\n onSomeEvent(events$: EventObservable): Observable {\n return events$.ofType(SomeEvent).pipe(\n map((event: SomeEvent) => {\n return of(new SomeCommand(uuid()), new SomeCommand(uuid()));\n }),\n );\n }\n}\n```\n\nWhen debugging I found that there is an error thrown 'CommandHandler not found exception!', which is kind of confusing because in case I return only one instance of `SomeCommand` the command handler is called correctly.\n\nDo I miss something or is the saga implementation just not supporting issuing multiple commands?\n\n========================================\n\nTop Answer:\nYou can use a `mergeMap()` to emit another observable. It will continue to emit that observable until it completes, but in your case that will happen all at once if you use an `of()` observable.\n\n```\nonSomeEvent(events$: EventObservable): Observable {\n return events$.ofType(SomeEvent).pipe(\n mergeMap((event: SomeEvent) => of(\n new SomeCommand(uuid()),\n new SomeCommand(uuid()),\n new SomeCommand(uuid()),\n ))\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class SomeSagas {\n    public constructor() {}\n\n    onSomeEvent(events$: EventObservable<any>): Observable<ICommand> {\n        return events$.ofType(SomeEvent).pipe(\n            map((event: SomeEvent) => {\n                return of(new SomeCommand(uuid()), new SomeCommand(uuid()));\n            }),\n        );\n    }\n}\n```\n\n```text\nSomeCommand\n```\n\n```text\n@Injectable()\nexport class SomeSagas {\n    public constructor() {}\n\n    onSomeEvent(events$: EventObservable<any>): Observable<ICommand> {\n        return events$.ofType(SomeEvent).pipe(\n            map((event: SomeEvent) => {\n                const commands: ICommand[] = [\n                  new SomeCommand(uuid()),\n                  new SomeCommand(uuid()),\n                  new SomeCommand(uuid()),\n                ];\n                return commands;\n            }),\n            flatMap(c => c), // piping to flatMap RxJS operator is solving the issue I had\n        );\n    }\n}\n```\n\n```text\nonSomeEvent(events$: EventObservable<any>): Observable<ICommand> {\n        return events$.ofType(SomeEvent).pipe(\n            mergeMap((event: SomeEvent) => of(\n                  new SomeCommand(uuid()),\n                  new SomeCommand(uuid()),\n                  new SomeCommand(uuid()),\n            ))\n        );\n    }\n}\n```\n\n```text\nmergeMap()\n```\n\n```text\nof()\n```\n\n```text\n@Injectable()\n    export class Saga {\n        public constructor() {}\n    \n        onSomeEvent(events$: EventObservable<any>): Observable<ICommand> {\n            return events$.ofType(SomeEvent).pipe(\n                map((event: SomeEvent) => {\n                    const commands: ICommand[] = [\n                      new FirstCommans(uuid()),\n                      new SecondCommand(uuid()),\n    \n                    ];\n                    return commands;\n                }),\n                mergeMap(c => c),\n            );\n        }\n    }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":130,"estimatedTokens":812}}362{"id":"stack-55092953","source":"stackoverflow","questionId":55092953,"title":"Defining Node environment in Nest.js","tags":["javascript","node.js","typescript","environment-variables","nestjs"],"text":"Title: Defining Node environment in Nest.js\nTags: javascript, node.js, typescript, environment-variables, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm in the process of setting up Nest.js project and I look for the efficient solution of defining Node environment which is used by the `ConfigService` for loading environment variables:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Module({\n providers: [\n {\n provide: ConfigService,\n useValue: new ConfigService(`environments/${process.env.NODE_ENV}.env`)\n }\n ],\n exports: [ConfigService]\n})\nexport class ConfigModule {}\n```\n\nRight now I'm defining it directly in the npm scripts (for example `\"start:dev\": \"NODE_ENV=development nodemon\"`), but I'm wondering if there is some better approach for handling different environments instead of appending it in every script?\n\n========================================\n\nTop Answer:\nwithout cross-env, you can use:\n\n```\n\"start:local\": \"NODE_ENV=test ts-node -r tsconfig-paths/register src/main.ts \"\n```\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Module({\n    providers: [\n        {\n            provide: ConfigService,\n            useValue: new ConfigService(`environments/${process.env.NODE_ENV}.env`)\n        }\n    ],\n    exports: [ConfigService]\n})\nexport class ConfigModule {}\n```\n\n```text\nConfigService\n```\n\n```text\n\"start:dev\": \"NODE_ENV=development nodemon\"\n```\n\n```text\n\"start\": \"cross-env NODE_ENV=development ts-node -r tsconfig-paths/register src/main.ts\",\n```\n\n```text\n\"globals\": {\n  \"NODE_ENV\": \"test\"\n}\n```\n\n```text\nlet previousNodeEnv;\nbeforeAll(() => {\n  previousNodeEnv = process.env.NODE_ENV;\n  process.env.NODE_ENV = 'test';\n});\n\nafterAll(() => process.env.NODE_ENV = previousNodeEnv);\n```\n\n```text\ndevelopment\n```\n\n```text\ncross-env\n```\n\n```text\njest-e2e.json\n```\n\n```text\n\"start:local\": \"NODE_ENV=test ts-node -r tsconfig-paths/register src/main.ts \"\n```\n\n```text\n\"start:dev\": \"set NODE_ENV=development && nest start --watch\"\n\"start:prod\": \"set NODE_ENV=production && node dist/main\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":101,"estimatedTokens":539}}363{"id":"stack-72803245","source":"stackoverflow","questionId":72803245,"title":"Nest js convert module from forRoot to forRootAsync","tags":["node.js","authentication","nestjs","node-modules","nest-dynamic-modules"],"text":"Title: Nest js convert module from forRoot to forRootAsync\nTags: node.js, authentication, nestjs, node-modules, nest-dynamic-modules\nSource: Stack Overflow\n\nQuestion:\n```\n@Module({\n imports: [],\n providers: [SupertokensService, AuthService],\n exports: [],\n controllers: [AuthController],\n})\nexport class AuthModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(AuthMiddleware).forRoutes('*');\n }\n static forRoot({\n connectionURI,\n apiKey,\n appInfo,\n }: AuthModuleConfig): DynamicModule {\n return {\n providers: [\n {\n useValue: {\n appInfo,\n connectionURI,\n apiKey,\n },\n provide: ConfigInjectionToken,\n },\n ],\n exports: [],\n imports: [],\n module: AuthModule,\n };\n }\n}\n```\n\nThe problem with this implementaion I can't use env variables, so I need **useFactory** to pass ConfigService. Can somebody do that, and give some explanation.\n\n========================================\n\nTop Answer:\nif you want to be compatible with v6 + and 9+ as well you can make a new provider.\n\n\r\n\r\n\n```\nimport { MySql2Database } from 'drizzle-orm/mysql2';\nimport { DRIZZLE_ORM } from './constants';\nimport { NestDrizzleService } from './nest-drizzle.service';\nimport { PostgresJsDatabase } from 'drizzle-orm/postgres-js';\nimport { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';\n\nexport const connectionFactory = {\n provide: DRIZZLE_ORM,\n useFactory: async (nestDrizzleService: {\n getDrizzle: () => Promise;\n }) => {\n return nestDrizzleService.getDrizzle();\n },\n inject: [NestDrizzleService],\n};\n```\n\n\r\n\r\n\r\n\nProvide is made to use a token (best practices):\n\n\r\n\r\n\n```\n@Inject(DRIZZLE_ORM) private readonly db: PostgresJsDb\n```\n\n\r\n\r\n\r\n\nAnd use it like:\n\n\r\n\r\n\n```\npublic static forRootAsync(options: NestDrizzleAsyncOptions): DynamicModule {\n return {\n module: NestDrizzleModule,\n providers: [...this.createProviders(options)],\n exports: [...this.createProviders(options)],\n };\n }\n\n private static createProviders(options: NestDrizzleAsyncOptions): Provider[] {\n if (options.useExisting || options.useFactory) {\n return [this.createOptionsProvider(options)];\n }\n\n return [\n this.createOptionsProvider(options),\n {\n provide: options.useClass,\n useClass: options.useClass,\n },\n ];\n }\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [],\n  providers: [SupertokensService, AuthService],\n  exports: [],\n  controllers: [AuthController],\n})\nexport class AuthModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(AuthMiddleware).forRoutes('*');\n  }\n  static forRoot({\n    connectionURI,\n    apiKey,\n    appInfo,\n  }: AuthModuleConfig): DynamicModule {\n    return {\n      providers: [\n        {\n          useValue: {\n            appInfo,\n            connectionURI,\n            apiKey,\n          },\n          provide: ConfigInjectionToken,\n        },\n      ],\n      exports: [],\n      imports: [],\n      module: AuthModule,\n    };\n  }\n}\n```\n\n```html\nimport { ConfigurableModuleBuilder } from '@nestjs/common';\nimport { AuthModuleConfig } from './config.interface';\n\nexport const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =\n  new ConfigurableModuleBuilder<AuthModuleConfig>()\n    .setClassMethodName('forRoot')\n    .build();\n```\n\n```html\nimport { MiddlewareConsumer, Module } from '@nestjs/common';\n\nimport { AuthMiddleware } from './auth.middleware';\nimport { SupertokensService } from './supertokens/supertokens.service';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { ConfigurableModuleClass } from './auth.module-definition';;\n\n@Module({\n  imports: [],\n  providers: [SupertokensService, AuthService],\n  controllers: [AuthController],\n  exports: [AuthService],\n})\nexport class AuthModule extends ConfigurableModuleClass {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(AuthMiddleware).forRoutes('*');\n  }\n}\n```\n\n```html\nimport { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';\nimport { AuthModule } from './auth/auth.module';\nimport { ConfigModule, ConfigType } from '@nestjs/config';\nimport authConfig from './auth/auth.config';\n\n@Module({\n  imports: [\n    AuthModule.forRootAsync({\n      inject: [authConfig.KEY],\n      imports: [ConfigModule.forFeature(authConfig)],\n      useFactory: (config: ConfigType<typeof authConfig>) => {\n        return {\n          connectionURI: config.CONNECTION_URI,\n          appInfo: {\n            appName: config.appInfo.APP_NAME,\n            apiDomain: config.appInfo.API_DOMAIN,\n            websiteDomain: config.appInfo.WEBSITE_DOMAIN,\n            apiBasePath: config.appInfo.API_BASE_PATH,\n            websiteBasePath: config.appInfo.WEBSITE_BASE_PATH,\n          },\n        };\n      },\n    })\n  ],\n  controllers: [],\n  providers: [\n  ],\n})\nexport class AppModule implements NestModule {\n}\n```\n\n```text\nauth.module-definition.ts\n```\n\n```text\nConfigurableModuleBuilder\n```\n\n```text\nsetClassMethodName('forRoot')\n```\n\n```text\nforRoot\n```\n\n```text\nforRoot\n```\n\n```text\nforRootAsync\n```\n\n```text\nConfigurableModuleClass\n```\n\n```text\nforRootAsync\n```\n\n```text\napp.module.ts\n```\n\n```text\nNest.js Config\n```\n\n```js\nimport { MySql2Database } from 'drizzle-orm/mysql2';\nimport { DRIZZLE_ORM } from './constants';\nimport { NestDrizzleService } from './nest-drizzle.service';\nimport { PostgresJsDatabase } from 'drizzle-orm/postgres-js';\nimport { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';\n\nexport const connectionFactory = {\n  provide: DRIZZLE_ORM,\n  useFactory: async (nestDrizzleService: {\n    getDrizzle: () => Promise<\n      MySql2Database | PostgresJsDatabase | BetterSQLite3Database\n    >;\n  }) => {\n    return nestDrizzleService.getDrizzle();\n  },\n  inject: [NestDrizzleService],\n};\n```\n\n```js\n@Inject(DRIZZLE_ORM) private readonly db: PostgresJsDb\n```\n\n```js\npublic static forRootAsync(options: NestDrizzleAsyncOptions): DynamicModule {\n    return {\n      module: NestDrizzleModule,\n      providers: [...this.createProviders(options)],\n      exports: [...this.createProviders(options)],\n    };\n  }\n\n  private static createProviders(options: NestDrizzleAsyncOptions): Provider[] {\n    if (options.useExisting || options.useFactory) {\n      return [this.createOptionsProvider(options)];\n    }\n\n    return [\n      this.createOptionsProvider(options),\n      {\n        provide: options.useClass,\n        useClass: options.useClass,\n      },\n    ];\n  }\n```\n\n========================================\n\nComments:\n- Did you figure it out? I am facing the same issue with Supertokens.\n- yes, I wrote the answer","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":310,"estimatedTokens":1634}}364{"id":"stack-60185547","source":"stackoverflow","questionId":60185547,"title":"How to jest mock nestjs imports?","tags":["node.js","typescript","unit-testing","jestjs","nestjs"],"text":"Title: How to jest mock nestjs imports?\nTags: node.js, typescript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to write a unit test for my nestjs 'Course' repository service (a service that has dependencies on Mongoose Model and Redis).\n\ncourses.repository.ts:\n\n```\nimport { Injectable, HttpException, NotFoundException } from \"@nestjs/common\";\n import { InjectModel } from \"@nestjs/mongoose\"\n import { Course } from \"../../../../shared/course\";\n import { Model } from \"mongoose\";\n import { RedisService } from 'nestjs-redis';\n\n @Injectable({}) \n export class CoursesRepository {\n\n private redisClient;\n constructor(\n @InjectModel('Course') private courseModel: Model,\n private readonly redisService: RedisService,\n ) {\n this.redisClient = this.redisService.getClient();\n\n }\n\n async findAll(): Promise {\n const courses = await this.redisClient.get('allCourses');\n if (!courses) {\n console.log('return from DB');\n const mongoCourses = await this.courseModel.find();\n await this.redisClient.set('allCourses', JSON.stringify(mongoCourses), 'EX', 20);\n return mongoCourses;\n }\n\n console.log('return from cache');\n return JSON.parse(courses);\n }\n}\n```\n\nThe test is initialized this way:\n\n```\nbeforeEach(async () => {\n const moduleRef = await Test.createTestingModule({\n imports: [\n MongooseModule.forRoot(MONGO_CONNECTION, { \n useNewUrlParser: true,\n useUnifiedTopology: true\n }),\n MongooseModule.forFeature([\n { name: \"Course\", schema: CoursesSchema },\n { name: \"Lesson\", schema: LessonsSchema }\n ]),\n RedisModule.register({})\n ],\n controllers: [CoursesController, LessonsController],\n providers: [\n CoursesRepository,\n LessonsRepository\n ],\n }).compile();\n\n coursesRepository = moduleRef.get(CoursesRepository);\n redisClient = moduleRef.get(RedisModule);\n\n});\n```\n\nMy Course repository service has 2 dependencies - Redis and Mongoose Model (Course).\nI would like to mock both of them.\n\nIf I was mocking a provider I would use that syntax:\n\n```\nproviders: [\n {provide: CoursesRepository, useFactory: mockCoursesRepository},\n LessonsRepository\n ],\n```\n\nCan I create a mock Redis service which will be used instead of the an actual Redis service during a test?\n\nHow ?\n\nThanks,\nYaron\n\n========================================\n\nTop Answer:\nNote that the accepted answer mocks a provider, which will satisfy the dependencies of your class under test IF it is also supplied from the `TestingModule` with a provider. However, it's not mocking `import`s as asked, which can be different. E.g. if you need to `import` some module which also depends on the mocked value, this will NOT work:\n\n```\n// DOES NOT WORK\nconst module = await Test.createTestingModule({\n imports: [\n ModuleThatNeedsConfig,\n ],\n providers: [\n { provide: ConfigService, useValue: mockConfig },\n ExampleService, // relies on something from ModuleThatNeedsConfig\n ]\n}).compile();\n```\n\nTo mock an `import`, you can use a `DynamicModule` that exports the mocked values:\n\n```\nconst module = await Test.createTestingModule({\n imports: [\n {\n module: class FakeModule {},\n providers: [{ provide: ConfigService, useValue: mockConfig }],\n exports: [ConfigService],\n },\n ModuleThatNeedsConfig,\n ],\n providers: [\n ClassUnderTest,\n ]\n}).compile();\n```\n\nAs that's a bit verbose, a utility function such as this can be helpful:\n\n```\nexport const createMockModule = (providers: Provider[]): DynamicModule => {\n const exports = providers.map((provider) => (provider as any).provide || provider);\n return {\n module: class MockModule {},\n providers,\n exports,\n global: true,\n };\n};\n```\n\nWhich can then be used like:\n\n```\nconst module = await Test.createTestingModule({\n imports: [\n createMockModule([{ provide: ConfigService, useValue: mockConfig }]),\n ModuleThatNeedsConfig,\n ],\n providers: [\n ClassUnderTest,\n ]\n}).compile();\n```\n\nThis often has the added benefit of letting you `import` the module for the class under test, rather than having the test bypass the module and `provide` the value directly.\n\n```\nconst module = await Test.createTestingModule({\n imports: [\n createMockModule([{ provide: ConfigService, useValue: mockConfig }]),\n ModuleThatNeedsConfig,\n ModuleUnderTest,\n ],\n}).compile();\n\nconst service = module.get(ClassUnderTest);\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, HttpException, NotFoundException } from \"@nestjs/common\";\n    import { InjectModel } from \"@nestjs/mongoose\"\n    import { Course } from \"../../../../shared/course\";\n    import { Model } from \"mongoose\";\n    import { RedisService } from 'nestjs-redis';\n\n\n    @Injectable({}) \n    export class CoursesRepository {\n\n      private redisClient;\n      constructor(\n        @InjectModel('Course') private courseModel: Model<Course>,\n        private readonly redisService: RedisService,\n      ) {\n        this.redisClient = this.redisService.getClient();\n\n      }\n\n\n      async findAll(): Promise<Course[]> {\n        const courses = await this.redisClient.get('allCourses');\n        if (!courses) {\n          console.log('return from DB');\n          const mongoCourses = await this.courseModel.find();\n          await this.redisClient.set('allCourses', JSON.stringify(mongoCourses), 'EX', 20);\n          return mongoCourses;\n        }\n\n        console.log('return from cache');\n        return JSON.parse(courses);\n      }\n}\n```\n\n```text\nbeforeEach(async () => {\n  const moduleRef = await Test.createTestingModule({\n    imports: [\n      MongooseModule.forRoot(MONGO_CONNECTION,  { \n        useNewUrlParser: true,\n        useUnifiedTopology: true\n      }),\n      MongooseModule.forFeature([\n        { name: \"Course\", schema: CoursesSchema },\n        { name: \"Lesson\", schema: LessonsSchema }\n      ]),\n      RedisModule.register({})\n    ],\n      controllers: [CoursesController, LessonsController],\n      providers: [\n         CoursesRepository,\n         LessonsRepository\n        ],\n    }).compile();\n\n  coursesRepository = moduleRef.get<CoursesRepository>(CoursesRepository);\n  redisClient = moduleRef.get<RedisModule>(RedisModule);\n\n});\n```\n\n```text\nproviders: [\n    {provide: CoursesRepository, useFactory: mockCoursesRepository},\n     LessonsRepository\n    ],\n```\n\n```text\nconst redisClientMockFactory = // ...\nconst redisServiceMock = {getClient: () => redisClientMockFactory()}\n\nproviders: [\n  { provide: RedisService, useValue: redisServiceMock },\n  { provide: getModelToken('Course'), useFactory: courseModelMockFactory },\n  CoursesRepository\n],\n```\n\n```text\nRedisService\n```\n\n```text\ngetModelToken\n```\n\n```js\n// DOES NOT WORK\nconst module = await Test.createTestingModule({\n  imports: [\n    ModuleThatNeedsConfig,\n  ],\n  providers: [\n    { provide: ConfigService, useValue: mockConfig },\n    ExampleService, // relies on something from ModuleThatNeedsConfig\n  ]\n}).compile();\n```\n\n```js\nconst module = await Test.createTestingModule({\n  imports: [\n    {\n      module: class FakeModule {},\n      providers: [{ provide: ConfigService, useValue: mockConfig }],\n      exports: [ConfigService],\n    },\n    ModuleThatNeedsConfig,\n  ],\n  providers: [\n    ClassUnderTest,\n  ]\n}).compile();\n```\n\n```js\nexport const createMockModule = (providers: Provider[]): DynamicModule => {\n  const exports = providers.map((provider) => (provider as any).provide || provider);\n  return {\n    module: class MockModule {},\n    providers,\n    exports,\n    global: true,\n  };\n};\n```\n\n```js\nconst module = await Test.createTestingModule({\n  imports: [\n    createMockModule([{ provide: ConfigService, useValue: mockConfig }]),\n    ModuleThatNeedsConfig,\n  ],\n  providers: [\n    ClassUnderTest,\n  ]\n}).compile();\n```\n\n```text\nconst module = await Test.createTestingModule({\n  imports: [\n    createMockModule([{ provide: ConfigService, useValue: mockConfig }]),\n    ModuleThatNeedsConfig,\n    ModuleUnderTest,\n  ],\n}).compile();\n\nconst service = module.get(ClassUnderTest);\n```\n\n```text\nTestingModule\n```\n\n```text\nimport\n```\n\n```text\nimport\n```\n\n```text\nimport\n```\n\n```text\nDynamicModule\n```\n\n```text\nimport\n```\n\n```text\nprovide\n```\n\n========================================\n\nComments:\n- Can you show the code of your `CoursesRepository`?\n- Thanks, great use of dynamic module here. I had a very complex module that had a forward ref dependency on a 3rd party dynamic module, AgendaModule, which needed a value that was not possible to provide in test cases. Your solution helped me nail it. I used dynamic module and bypassed Agenda module from its imports, keeping other imports intact. And, also provided mock custom provider for the associated service.","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":359,"estimatedTokens":2131}}365{"id":"stack-53679456","source":"stackoverflow","questionId":53679456,"title":"NestJS: How to register transient and per web request providers","tags":["node.js","typescript","nestjs"],"text":"Title: NestJS: How to register transient and per web request providers\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am working on a multi-tenant application using NestJS and offering my API through their GraphQL module. I would like to know how I could tell NestJS to instantiate my providers per web request. According to their documentation providers are singleton by default but I could not find a way to register transient or per request providers.\n\nLet me explain a specific use case for this. In my multi-tenant implementation, I have a database per customer and every time I receive a request in the backend I need to find out for which customer it is so I need to instantiate services with a connection to the right database.\n\nIs this even possible using NestJS?\n\n========================================\n\nTop Answer:\nI was struggling with similar issue, and one way to achieve this is to use `node-request-context` module as a global request register, that will give you the request context. So you will not have separate service instances, but you can ask this static register to give you request specific instance/connection.\n\nhttps://github.com/guyguyon/node-request-context\n\nCreate simple context helper:\n\n```\nimport { createNamespace, getNamespace } from 'node-request-context';\nimport * as uuid from 'uuid';\n\nexport class RequestContext {\n\n public static readonly NAMESPACE = 'some-namespace';\n public readonly id = uuid.v4();\n\n constructor(public readonly conn: Connection) { }\n\n static create(conn: Connection, next: Function) {\n const context = new RequestContext(conn);\n const namespace = getNamespace(RequestContext.NAMESPACE) || createNamespace(RequestContext.NAMESPACE);\n\n namespace.run(() => {\n namespace.set(RequestContext.name, context);\n next();\n });\n }\n\n static currentRequestContext(): RequestContext {\n const namespace = getNamespace(RequestContext.NAMESPACE);\n return namespace ? namespace.get(RequestContext.name) : null;\n }\n\n static getConnection(): Connection {\n const context = RequestContext.currentRequestContext();\n return context ? context.conn : null;\n }\n\n}\n```\n\nThe `conn` instance parameter is your connection, feel free to put there other request specific dependencies. Also the `id` there is just for debugging, no real need to use `uuid` module as I did.\n\nCreate middleware wrapper (this allows you to use DI here):\n\n```\n@Injectable()\nexport class ContextMiddleware implements NestMiddleware {\n\n constructor(private readonly connectionManager: ...) { }\n\n resolve(...args: any[]): MiddlewareFunction {\n return (req, res, next) => {\n // create the request specific connection here, probably based on some auth header...\n RequestContext.create(this.connectionManager.createConnection(), next);\n };\n }\n\n}\n```\n\nThen register new middleware in your nest application:\n\n```\nconst app = await NestFactory.create(AppModule, {});\napp.use(app.get(RequestLoggerMiddleware).resolve());\n```\n\nAnd finally the profit part - get the request specific connection anywhere in your application:\n\n```\nconst conn = RequestContext.getConnection();\n```\n\n========================================\n\nCode:\n```text\n@Injectable({ scope: Scope.REQUEST })\nexport class UsersService {}\n```\n\n```text\n{\n  provide: 'CACHE_MANAGER',\n  useClass: CacheManager,\n  scope: Scope.TRANSIENT,\n}\n```\n\n```text\n@Injectable()\n```\n\n```text\nimport { createNamespace, getNamespace } from 'node-request-context';\nimport * as uuid from 'uuid';\n\nexport class RequestContext {\n\n    public static readonly NAMESPACE = 'some-namespace';\n    public readonly id = uuid.v4();\n\n    constructor(public readonly conn: Connection) { }\n\n    static create(conn: Connection, next: Function) {\n        const context = new RequestContext(conn);\n        const namespace = getNamespace(RequestContext.NAMESPACE) || createNamespace(RequestContext.NAMESPACE);\n\n        namespace.run(() => {\n            namespace.set(RequestContext.name, context);\n            next();\n        });\n    }\n\n    static currentRequestContext(): RequestContext {\n        const namespace = getNamespace(RequestContext.NAMESPACE);\n        return namespace ? namespace.get(RequestContext.name) : null;\n    }\n\n    static getConnection(): Connection {\n        const context = RequestContext.currentRequestContext();\n        return context ? context.conn : null;\n    }\n\n}\n```\n\n```text\n@Injectable()\nexport class ContextMiddleware implements NestMiddleware {\n\n  constructor(private readonly connectionManager: ...) { }\n\n  resolve(...args: any[]): MiddlewareFunction {\n    return (req, res, next) => {\n      // create the request specific connection here, probably based on some auth header...\n      RequestContext.create(this.connectionManager.createConnection(), next);\n    };\n  }\n\n}\n```\n\n```text\nconst app = await NestFactory.create(AppModule, {});\napp.use(app.get(RequestLoggerMiddleware).resolve());\n```\n\n```text\nconst conn = RequestContext.getConnection();\n```\n\n```text\nnode-request-context\n```\n\n```text\nconn\n```\n\n```text\nid\n```\n\n```text\nuuid\n```\n\n```text\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\n    imports: [RequestScopeModule],\n})\n```\n\n```text\nimport { NJRS_REQUEST } from 'nj-request-scope';\n[...]\nconstructor(@Inject(NJRS_REQUEST) private readonly request: Request) {}\n```\n\n```text\nimport { RequestScope } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestScopeService {\n```\n\n========================================\n\nComments:\n- This is definitely in the right direction, thanks for sharing!\n- The node-request-context is not ready for production due to asynchronous api\n- Yes I have seen a lot of discussion about, in the meantime I had to swith to \"single database with tenant identifier\" in order to keep using NestJS which I think is great but it is still missing this which in my opinion is key","metadata":{"transformedAt":"2026-08-18T18:33:02.435Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":210,"estimatedTokens":1457}}366{"id":"stack-68796174","source":"stackoverflow","questionId":68796174,"title":"nest.js build throwing a lot of errors","tags":["node.js","typescript","nestjs"],"text":"Title: nest.js build throwing a lot of errors\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have this Nest.js app running and setup for a while and, out of a sudden, it started reporting this when I run **npm run build**.\n\n```\nnode_modules/@nestjs/config/dist/config.service.d.ts:1:23 - error TS2305: Module '\"./types\"' has no exported member 'Path'.\n\n1 import { NoInferType, Path, PathValue } from './types';\n ~~~~\nnode_modules/@nestjs/config/dist/config.service.d.ts:1:29 - error TS2305: Module '\"./types\"' has no exported member 'PathValue'.\n\n1 import { NoInferType, Path, PathValue } from './types';\n ~~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:114 - error TS1005: '?' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:117 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:124 - error TS2693: 'PathImpl' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:133 - error TS2304: Cannot find name 'T'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:135 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:155 - error TS2304: Cannot find name 'T'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:157 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:177 - error TS1005: '(' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:179 - error TS2693: 'string' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:185 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:191 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:191 - error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:192 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:193 - error TS18004: No value exists in scope for the shorthand property 'Key'. Either declare one or provide an initializer.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:198 - error TS2339: Property '$' does not exist on type '{ Key: any; }'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:199 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:199 - error TS2349: This expression is not callable.\n Type '{ [x: number]: any; Exclude(): any; keyof: any; any: any; }' has no call signatures.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:214 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:215 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:216 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:220 - error TS1005: ':' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:222 - error TS18004: No value exists in scope for the shorthand property 'keyof'. Either declare one or provide an initializer.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:228 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:228 - error TS2693: 'any' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:231 - error TS1005: ',' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:232 - error TS1109: Expression expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:233 - error TS1005: ':' expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:233 - error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:235 - error TS1109: Expression expected.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:237 - error TS2693: 'string' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl = Key extends string ? T[Key] extends Record ? `${Key}.${PathImpl> & string}` | `${Key}.${Exclude & string}` : never : never;\n ~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:66 - error TS1005: ',' expected.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:66 - error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:67 - error TS1005: ',' expected.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:68 - error TS18004: No value exists in scope for the shorthand property 'infer'. Either declare one or provide an initializer.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:74 - error TS1005: ',' expected.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:74 - error TS18004: No value exists in scope for the shorthand property 'Key'. Either declare one or provide an initializer.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:79 - error TS2339: Property '$' does not exist on type '{ infer: any; Key: any; }'.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:80 - error TS1005: ',' expected.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:80 - error TS2349: This expression is not callable.\n Type '{ infer: any; Rest: any; }' has no call signatures.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~~~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:81 - error TS18004: No value exists in scope for the shorthand property 'infer'. Either declare one or provide an initializer.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:87 - error TS1005: ',' expected.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:87 - error TS18004: No value exists in scope for the shorthand property 'Rest'. Either declare one or provide an initializer.\n\n4 export declare type PathValue> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path ? PathValue : never : never : P extends keyof T ? T[P] : never;\n ~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:5:1 - error TS1160: Unterminated template literal.\n```\n\nAnyone knows how to make this go away?\n\nAll I remember doing was trying to update the nest cli on the terminal. Now, it throws these exceptions every time I ran my application.\n\n========================================\n\nTop Answer:\nUpdating to NestJS 8 fixed all errors!\n\n========================================\n\nCode:\n```text\nnode_modules/@nestjs/config/dist/config.service.d.ts:1:23 - error TS2305: Module '\"./types\"' has no exported member 'Path'.\n\n1 import { NoInferType, Path, PathValue } from './types';\n                        ~~~~\nnode_modules/@nestjs/config/dist/config.service.d.ts:1:29 - error TS2305: Module '\"./types\"' has no exported member 'PathValue'.\n\n1 import { NoInferType, Path, PathValue } from './types';\n                              ~~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:114 - error TS1005: '?' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                   ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:117 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                      ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:124 - error TS2693: 'PathImpl' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                             ~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:133 - error TS2304: Cannot find name 'T'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                      ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:135 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                        ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:155 - error TS2304: Cannot find name 'T'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                            ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:157 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                              ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:177 - error TS1005: '(' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                  ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:179 - error TS2693: 'string' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                    ~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:185 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                          ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:191 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:191 - error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:192 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                 ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:193 - error TS18004: No value exists in scope for the shorthand property 'Key'. Either declare one or provide an initializer.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                  ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:198 - error TS2339: Property '$' does not exist on type '{ Key: any; }'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                       ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:199 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                        ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:199 - error TS2349: This expression is not callable.\n  Type '{ [x: number]: any; Exclude<keyof, T>(): any; keyof: any; any: any; }' has no call signatures.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:214 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                       ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:215 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                        ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:216 - error TS2304: Cannot find name 'Key'.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                         ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:220 - error TS1005: ':' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                             ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:222 - error TS18004: No value exists in scope for the shorthand property 'keyof'. Either declare one or provide an initializer.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                               ~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:228 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                     ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:228 - error TS2693: 'any' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                     ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:231 - error TS1005: ',' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                        ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:232 - error TS1109: Expression expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                         ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:233 - error TS1005: ':' expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                          ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:233 - error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                          ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:235 - error TS1109: Expression expected.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                            ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:1:237 - error TS2693: 'string' only refers to a type, but is being used as a value here.\n\n1 export declare type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;\n                                                                                                                                                                                                                                              ~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:66 - error TS1005: ',' expected.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                   ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:66 - error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                   ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:67 - error TS1005: ',' expected.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                    ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:68 - error TS18004: No value exists in scope for the shorthand property 'infer'. Either declare one or provide an initializer.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                     ~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:74 - error TS1005: ',' expected.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                           ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:74 - error TS18004: No value exists in scope for the shorthand property 'Key'. Either declare one or provide an initializer.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                           ~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:79 - error TS2339: Property '$' does not exist on type '{ infer: any; Key: any; }'.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                                ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:80 - error TS1005: ',' expected.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                                 ~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:80 - error TS2349: This expression is not callable.\n  Type '{ infer: any; Rest: any; }' has no call signatures.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                                 ~~~~~~~~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:81 - error TS18004: No value exists in scope for the shorthand property 'infer'. Either declare one or provide an initializer.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                                  ~~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:87 - error TS1005: ',' expected.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                                        ~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:4:87 - error TS18004: No value exists in scope for the shorthand property 'Rest'. Either declare one or provide an initializer.\n\n4 export declare type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;\n                                                                                        ~~~~\nnode_modules/@nestjs/config/dist/types/path-value.type.d.ts:5:1 - error TS1160: Unterminated template literal.\n```\n\n========================================\n\nComments:\n- Have you upgraded any of your project dependency? Or your local Node.js version?","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":387,"estimatedTokens":9327}}367{"id":"stack-53353623","source":"stackoverflow","questionId":53353623,"title":"In nest.js while using passport module do we have to use PassportModule.register() inside each modules?","tags":["typescript","passport.js","nestjs"],"text":"Title: In nest.js while using passport module do we have to use PassportModule.register() inside each modules?\nTags: typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nIf we don't import them inside each modules using @AuthGuard decorator then it's showing the following warning in logs.\n\n In order to use \"defaultStrategy\", please, ensure to import\n PassportModule in each place where AuthGuard() is being used.\n Otherwise, passport won't work correctly\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n secretOrPrivateKey: 'secretKey',\n signOptions: {\n expiresIn: 3600,\n },\n }),\n UsersModule,\n ],\n providers: [AuthService, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\nIs there any other way besides importing \"PassportModule.register({ defaultStrategy: 'jwt' })\" inside each modules.\n\n========================================\n\nTop Answer:\n### Simple solution\n\nThe `PassportModule.register({ โ€ฆ })` stuff is only needed *if* you want to use the AuthGuard syntax with an implied default strategy: `@UseGuards(AuthGuard)`.\n\nIt is not needed when mentioning the strategy explicitly every time:\n\n```\nimport { AuthGuard } from '@nestjs/passport';\n\n@UseGuards(AuthGuard('jwt'))\n// [...]\n```\n\n### Solution with a default strategy\n\nTo avoid the above syntax that mentions the strategy in every decorator call, you can define your own guard that does nothing but provide an alias for `AuthGuard` with your default strategy of choice:\n\n```\n// file jwt.guard.ts\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') { }\n```\n\nThen to use it, you don't have to do any `PassportModule.register({ โ€ฆ })` stuff in your module anymore. Just write this in your files:\n\n```\nimport { JwtAuthGuard } from '../path/to/module/auth/guards/jwt.guard';\n\n@UseGuards(JwtAuthGuard)\n// [...]\n```\n\n**Caveat:** The above custom guard, as shown, does not allow you to specify several alternative strategies at once: `@UseGuards(JwtAuthGuard(['jwt', 'anonymous']))`. None of your strategies would be applied this way. Instead, you would have to use: `@UseGuard(AuthGuard('jwt', 'anonymous'))`. Feel free to improve.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.register({\n      secretOrPrivateKey: 'secretKey',\n      signOptions: {\n        expiresIn: 3600,\n      },\n    }),\n    UsersModule,\n  ],\n  providers: [AuthService, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\n```text\nconst passportModule = PassportModule.register({ defaultStrategy: 'jwt' });\n\n@Module({\n  imports: [\n    passportModule,\n    JwtModule.register({\n      secretOrPrivateKey: 'secretKey',\n      signOptions: {\n        expiresIn: 3600,\n      },\n    }),\n    UsersModule,\n  ],\n  providers: [AuthService, JwtStrategy],\n  exports: [passportModule]\n})\nexport class AuthModule {}\n```\n\n```text\nAuthModule\n```\n\n```text\nAuthService\n```\n\n```text\nPassportModule\n```\n\n```text\nimport { AuthGuard } from '@nestjs/passport';\n\n@UseGuards(AuthGuard('jwt'))\n// [...]\n```\n\n```text\n// file jwt.guard.ts\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') { }\n```\n\n```text\nimport { JwtAuthGuard } from '../path/to/module/auth/guards/jwt.guard';\n\n@UseGuards(JwtAuthGuard)\n// [...]\n```\n\n```text\nPassportModule.register({ โ€ฆ })\n```\n\n```text\n@UseGuards(AuthGuard)\n```\n\n```text\nAuthGuard\n```\n\n```text\nPassportModule.register({ โ€ฆ })\n```\n\n```text\n@UseGuards(JwtAuthGuard(['jwt', 'anonymous']))\n```\n\n```text\n@UseGuard(AuthGuard('jwt', 'anonymous'))\n```\n\n========================================\n\nComments:\n- To be clear, from that point on, other modules would just be importing the `AuthModule` class, yes?\n- it might be better to import a module once and use it on all children modules","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":174,"estimatedTokens":996}}368{"id":"stack-60255641","source":"stackoverflow","questionId":60255641,"title":"NestJS - can't resolve ConfigService","tags":["nestjs"],"text":"Title: NestJS - can't resolve ConfigService\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS jwt passport to auth user. I the doc, here is my app module: \n\n```\nimport { Module } from '@nestjs/common';\nimport { UserModule } from './user/user.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AuthModule } from './auth/auth.module';\nimport { ConfigModule } from '@nestjs/config';\nimport configuration from '../config/configuration';\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n load: [configuration],\n }),\n TypeOrmModule.forRoot(),\n UserModule,\n AuthModule,\n ],\n})\nexport class AppModule {}\n```\n\nAnd here is my auth module:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { PassportModule } from '@nestjs/passport';\nimport { UserModule } from '../user/user.module';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtStrategy } from './jwt.strategy';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { JwtModule } from '@nestjs/jwt';\nimport { AuthController } from './auth.controller';\n\n@Module({\n imports: [\n UserModule,\n PassportModule,\n JwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n secret: configService.get('jwt.secret'),\n signOptions: {\n expiresIn: configService.get('jwt.expiresIn'),\n },\n }),\n inject: [ConfigService],\n }),\n ],\n providers: [AuthService, LocalStrategy, JwtStrategy],\n exports: [AuthService],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\nEvery time I run `npm run start`, I got this error message:\n\n```\nNest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.\n```\n\nI have searched this problem, but still can't fix this. Someone can help me? Thanks.\n\n========================================\n\nTop Answer:\nI fought with this same issue for hours but according to Chau Tran, after making `ConfigModule` global with `ConfigModule.forRoot({ isGlobal: true })` all my problems were gone. ๐Ÿ˜\n\n========================================\n\nCode:\n```js\nimport { Module } from '@nestjs/common';\nimport { UserModule } from './user/user.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AuthModule } from './auth/auth.module';\nimport { ConfigModule } from '@nestjs/config';\nimport configuration from '../config/configuration';\n\n@Module({\n  imports: [\n      ConfigModule.forRoot({\n          load: [configuration],\n      }),\n      TypeOrmModule.forRoot(),\n      UserModule,\n      AuthModule,\n  ],\n})\nexport class AppModule {}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { PassportModule } from '@nestjs/passport';\nimport { UserModule } from '../user/user.module';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtStrategy } from './jwt.strategy';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { JwtModule } from '@nestjs/jwt';\nimport { AuthController } from './auth.controller';\n\n@Module({\n    imports: [\n        UserModule,\n        PassportModule,\n        JwtModule.registerAsync({\n            imports: [ConfigModule],\n            useFactory: async (configService: ConfigService) => ({\n                secret:  configService.get('jwt.secret'),\n                signOptions: {\n                    expiresIn: configService.get('jwt.expiresIn'),\n                },\n            }),\n            inject: [ConfigService],\n        }),\n    ],\n    providers: [AuthService, LocalStrategy, JwtStrategy],\n    exports: [AuthService],\n    controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n```text\nNest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.\n```\n\n```text\nnpm run start\n```\n\n```text\nConfigModule\n```\n\n```text\nisGlobal: true\n```\n\n```text\n@nestjs/config@0.2.3\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigModule.forRoot({ isGlobal: true })\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ConfigModule as ConfigModuleSource } from '@nestjs/config';\nimport { validate } from './env.validation';\nimport { ConfigService } from './config.service';\n\n@Module({\n  imports: [\n    ConfigModuleSource.forRoot({ validate, isGlobal: true, cache: true }),\n  ],\n  providers: [ConfigService],\n  exports: [ConfigService],\n})\nexport class ConfigModule {}\n```\n\n```text\nConfigService\n```\n\n```text\n@nestjs/config\n```\n\n========================================\n\nComments:\n- Make `ConfigModule` global with `ConfigModule.forRoot({ isGlobal: true })`\n- Hi, I answered this question at stackoverflow.com/questions/60182039/&hellip; @ChauTran answer is correct as well.\n- To let everyone know, this is a logged issue on the ConfigModule repository. Waiting Kamil's reposnse","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":191,"estimatedTokens":1226}}369{"id":"stack-69549136","source":"stackoverflow","questionId":69549136,"title":"NestJS : TypeError: Cannot read property 'get' of undefined","tags":["nestjs"],"text":"Title: NestJS : TypeError: Cannot read property 'get' of undefined\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to pass the connection parameters to mongodb by enviroment file and I am getting the following error\n\n```\n[Nest] 1176 - 12/10/2021 23:34:35 ERROR [ExceptionHandler] Cannot read property 'get' of undefined\nTypeError: Cannot read property 'get' of undefined\n at MongoService.createMongooseOptions (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/src/common/mongo/mongo.service.ts:20:41)\n at Function. (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:135:120)\n at Generator.next ()\n at /Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:20:71\n at new Promise ()\n at __awaiter (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:16:12)\n at InstanceWrapper.useFactory [as metatype] (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:135:45)\n at Injector.instantiateClass (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:294:55)\n at callback (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:43:41)\n at Injector.resolveConstructorParams (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:119:24)\n```\n\nThis is the service mongo.service.ts\n\n```\nimport { MongooseModuleOptions, MongooseOptionsFactory } from '@nestjs/mongoose';\nimport { Configuration } from '../../config/config.keys';\nimport { ConfigService } from '../../config/config.service';\n\nexport class MongoService implements MongooseOptionsFactory {\n constructor( private configService: ConfigService ) {}\n\n createMongooseOptions(): MongooseModuleOptions {\n\n const user = this.configService.get(Configuration.DB_MONGO_USER);\n const password = this.configService.get(Configuration.DB_MONGO_PASSWORD);\n const server = this.configService.get(Configuration.DB_MONGO_HOST);\n const database = this.configService.get(Configuration.DB_MONGO_DATABASE);\n\n return {\n uri: `mongodb://${user}:${password}@${server}/${database}?retryWrites=true&w=majority`,\n };\n }\n}\n```\n\nAnd this I import it in the app.module.ts\n\n```\n@Module({\n imports: [\n MongooseModule.forRootAsync({\n useClass: MongoService,\n }),\n```\n\nAny suggestion,\nthanks,\nJM\n\n========================================\n\nTop Answer:\n```\n@Module({ \n imports: [ \n MongooseModule.forRootAsync({ \n imports: [ ConfigModule ], \n inject: [ConfigService],\n useClass: MongoService\n })\n})\n```\n\n========================================\n\nCode:\n```text\n[Nest] 1176  - 12/10/2021 23:34:35   ERROR [ExceptionHandler] Cannot read property 'get' of undefined\nTypeError: Cannot read property 'get' of undefined\n    at MongoService.createMongooseOptions (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/src/common/mongo/mongo.service.ts:20:41)\n    at Function.<anonymous> (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:135:120)\n    at Generator.next (<anonymous>)\n    at /Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:20:71\n    at new Promise (<anonymous>)\n    at __awaiter (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:16:12)\n    at InstanceWrapper.useFactory [as metatype] (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/mongoose/dist/mongoose-core.module.js:135:45)\n    at Injector.instantiateClass (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:294:55)\n    at callback (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:43:41)\n    at Injector.resolveConstructorParams (/Users/Desarrollos/NestJS/nestjs-ventas-negocios/node_modules/@nestjs/core/injector/injector.js:119:24)\n```\n\n```text\nimport { MongooseModuleOptions, MongooseOptionsFactory } from '@nestjs/mongoose';\nimport { Configuration } from '../../config/config.keys';\nimport { ConfigService } from '../../config/config.service';\n\nexport class MongoService implements MongooseOptionsFactory {\n    constructor( private configService: ConfigService ) {}\n\n    createMongooseOptions(): MongooseModuleOptions {\n\n        const user     = this.configService.get(Configuration.DB_MONGO_USER);\n        const password = this.configService.get(Configuration.DB_MONGO_PASSWORD);\n        const server   = this.configService.get(Configuration.DB_MONGO_HOST);\n        const database = this.configService.get(Configuration.DB_MONGO_DATABASE);\n\n        return {\n            uri: `mongodb://${user}:${password}@${server}/${database}?retryWrites=true&w=majority`,\n        };\n    }\n}\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forRootAsync({\n      useClass: MongoService,\n    }),\n```\n\n```text\nMongoService\n```\n\n```text\n@Injectable()\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigService\n```\n\n```text\nMongooseModule.forRootAsync()\n```\n\n```text\nuseClass\n```\n\n```text\nimports: [ConfigModule]\n```\n\n```text\nConfigService\n```\n\n```html\n@Module({ \n  imports: [ \n    MongooseModule.forRootAsync({ \n      imports: [ ConfigModule ], \n      inject: [ConfigService],\n      useClass: MongoService\n  })\n})\n```\n\n```js\n@Module({\n  imports: [\n    UsersModule,\n    JwtModule.registerAsync({\n      useFactory: async (configService: ConfigService) => ({\n        secretOrPrivateKey: \n        signOptions: {\n      }),\n      inject: [ConfigService], // i think u add line this\n    }),\n\n  ],\n  controllers: [AuthController],\n  providers: [AuthService],\n})\nexport class AuthModule { }\n```\n\n```text\ninject\n```\n\n========================================\n\nComments:\n- Did you search this site for *cannot get property of undefined*? There have been literally hundreds (if not thousands) of previous questions related to the same error asked (and answered) here before. Surely one of them can point out a way for you to solve this problem.\n- Maybe you forgot to add `@Injectable()` above `MongoService`\n- adding @Injectable I get the following error : Error: Nest can't resolve dependencies of the MongoService (?). Please make sure that the argument ConfigService at index [0] is available in the MongooseCoreModule context.\n- Thanks Jay, I'm obviously connecting something wrong and I can't see it. With @Injectable() , I get the following error : ERROR [ExceptionHandler] Nest can't resolve dependencies of the MongoService (?). Please make sure that the argument ConfigService at index [0] is available in the MongooseCoreModule context.\n- Did you add the `ConfigModule` to the `MongooseModule.forRootAsync()` options, like I mentioned in point 2?\n- The same error : @Module({ imports: [ MongooseModule.forRootAsync({ imports: [ ConfigService ], useClass: MongoService, inject: [ConfigService], }), VentaNegociosModule, ConfigModule ],\n- You have `imports: [ConfigService]`, not `imports: [ConfigModule]`. You also don't need `inject`","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":198,"estimatedTokens":1785}}370{"id":"stack-66070860","source":"stackoverflow","questionId":66070860,"title":"Puppeteer Error: error while loading shared libraries: libgobject-2.0.so.0","tags":["docker","puppeteer","nestjs","google-cloud-run"],"text":"Title: Puppeteer Error: error while loading shared libraries: libgobject-2.0.so.0\nTags: docker, puppeteer, nestjs, google-cloud-run\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS App deployed on Google Cloud Run which is using puppeteer (V7.0.1) to generate a PDF. Locally, everything is working absolutely fine, but on my Cloud Run Service I keep getting the following error:\n`/usr/app/node_modules/puppeteer/.local-chromium/linux-848005/chrome-linux/chrome: error while loading shared libraries: libgobject-2.0.so.0: cannot open shared object file: No such file or directory`\n\nThe directory does exist in the Docker container (checked with `RUN ls node_modules/.....`).\nUsing the Docker code from the puppeteer troubleshooting doc or any other snippet I found on similar issues on the web result in the same error for me.\n\n### Dockerfile:\n\n```\nFROM node:12-slim AS base\nWORKDIR /usr/app\n\nFROM base AS build\nRUN apt-get update \\\n && apt-get install -y wget gnupg \\\n && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \\\n && sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list' \\\n && apt-get update \\\n && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \\\n --no-install-recommends \\\n && rm -rf /var/lib/apt/lists/*\n\nCOPY package.json yarn.lock ./\nRUN yarn --prod\nCOPY . ./\nRUN yarn add @nestjs/cli\nRUN yarn sass && yarn build && yarn copy-pdf-assets\n\nFROM base\nCOPY --from=build /usr/app ./\nENV PATH /usr/app/node_modules/.bin:$PATH\nCMD yarn start:prod\n```\n\n### Generate PDF Function:\n\n```\n//also tried headless: true or false and many other flags that deemed to fix it for others\nconst browser = await puppeteer.launch({ args: ['--no-sandbox'] }); \n\ntry {\n const page = await browser.newPage();\n\n await page.setViewport({ height: 792, width: 1039 })\n await page.setContent(this.getTemplate(template, data), {\n waitUntil: ['load', 'domcontentloaded', 'networkidle0']\n });\n await page.addStyleTag({ path: this.resolvePath(`/templates/${template}/styles.css`) })\n\n await new Promise(resolve => setTimeout(resolve, 500));\n\n return await page.pdf({ format: 'a4', landscape: true, printBackground: true });\n} finally {\n await browser.close();\n}\n```\n\nLet me know if you need any other information.\nThanks in advance.\n\n========================================\n\nCode:\n```text\nFROM node:12-slim AS base\nWORKDIR /usr/app\n\nFROM base AS build\nRUN apt-get update \\\n    && apt-get install -y wget gnupg \\\n    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \\\n    && sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list' \\\n    && apt-get update \\\n    && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \\\n      --no-install-recommends \\\n    && rm -rf /var/lib/apt/lists/*\n\nCOPY package.json yarn.lock ./\nRUN yarn --prod\nCOPY . ./\nRUN yarn add @nestjs/cli\nRUN yarn sass && yarn build && yarn copy-pdf-assets\n\nFROM base\nCOPY --from=build /usr/app ./\nENV PATH /usr/app/node_modules/.bin:$PATH\nCMD yarn start:prod\n```\n\n```text\n//also tried headless: true or false and many other flags that deemed to fix it for others\nconst browser = await puppeteer.launch({ args: ['--no-sandbox'] }); \n\ntry {\n    const page = await browser.newPage();\n\n    await page.setViewport({ height: 792, width: 1039 })\n    await page.setContent(this.getTemplate(template, data), {\n        waitUntil: ['load', 'domcontentloaded', 'networkidle0']\n    });\n    await page.addStyleTag({ path: this.resolvePath(`/templates/${template}/styles.css`) })\n\n    await new Promise(resolve => setTimeout(resolve, 500));\n\n    return await page.pdf({ format: 'a4', landscape: true, printBackground: true });\n} finally {\n    await browser.close();\n}\n```\n\n```text\n/usr/app/node_modules/puppeteer/.local-chromium/linux-848005/chrome-linux/chrome: error while loading shared libraries: libgobject-2.0.so.0: cannot open shared object file: No such file or directory\n```\n\n```text\nRUN ls node_modules/.....\n```\n\n```text\nFROM node:12-slim AS base\nWORKDIR /usr/app\n\nFROM base AS build\nCOPY package.json yarn.lock ./\nRUN yarn --prod\nCOPY . ./\nRUN yarn add @nestjs/cli\nRUN yarn sass && yarn build && yarn copy-pdf-assets\n\nFROM base\nRUN apt-get update \\\n    && apt-get install -y wget gnupg \\\n    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \\\n    && sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list' \\\n    && apt-get update \\\n    && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \\\n      --no-install-recommends \\\n    && rm -rf /var/lib/apt/lists/*\nCOPY --from=build /usr/app ./\nENV PATH /usr/app/node_modules/.bin:$PATH\nCMD yarn start:prod\n```\n\n========================================\n\nComments:\n- Can you add the final version of your docker file?\n- @gandalf I added the code, as stated in the answer: Just had to move the chromium install to the last step\n- Chiming in in 2024, I can confirm that having these install steps as your last RUN command works! Also fwiw here is the official 'troubleshooting' doc from the puppeteer team on how to install chromium for puppeteer within a Dockerfile: github.com/puppeteer/puppeteer/blob/main/docs/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":154,"estimatedTokens":1391}}371{"id":"stack-50593140","source":"stackoverflow","questionId":50593140,"title":"How to use a route specific middleware of express in Nestjs?","tags":["nestjs"],"text":"Title: How to use a route specific middleware of express in Nestjs?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use this library (keycloak-connect) for authentication and authorization. It has a global middleware that can be directly used by `app.use()` method or by wrapping a nestjs middlewareclass around it. But how to use the route specific express middleware which is used to protect individual routes?.\n\nExample usage in plain express app\n\n```\napp.get( '/protected', keycloak.protect('adminRole'), handler );\n```\n\nThe protect method returns a plain express middleware with signature `function(req, res, next)`\n\n========================================\n\nTop Answer:\nIn case you only want your middleware to be applied on the routes in a controller, you may -\n\n```\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(LoggerMiddleware)\n .forRoutes(CatsController);\n }\n}\n```\n\n========================================\n\nCode:\n```text\napp.get( '/protected', keycloak.protect('adminRole'), handler );\n```\n\n```text\napp.use()\n```\n\n```text\nfunction(req, res, next)\n```\n\n```text\n@Module({\n  controllers: [YourController],\n})\nexport class YourModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(keyCloack.protect('adminRole'))\n      .forRoutes('/protected');\n  }\n}\n```\n\n```text\nGET\n```\n\n```text\nPOST\n```\n\n```text\n@Controller\n```\n\n```text\nYourController\n```\n\n```text\nNestModule\n```\n\n```text\nconfigure\n```\n\n```text\nconsumer\n```\n\n```text\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n  .apply(LoggerMiddleware)\n  .forRoutes(CatsController);\n }\n}\n```\n\n========================================\n\nComments:\n- If you want keycloack for auth, maybe consider using Guards instead. You can easily attach guard to method, controller or globally.\n- But how can I use that express middleware in guard?\n- Check accepted answer on this question: stackoverflow.com/questions/27117337/&hellip;\n- Where do you get the keyCloack instance from? Shoudn't it be possible to integrate it into an @AuthGuard? A link to an example keycaloak + naestjs setup would be much appreciated.\n- I don't know this library, sorry, I reused `keyCloack` because it was provided \"as is\" in the OP's code. However, I assume that you can create a custom provider for it, and register/export it in a custom/dedicated `@Module`. See \"Dependency Injection\" in the NestJS documentation. Modules and Guards can inject providers too. Thus, the example of `YourModule` I gave could have a constructor like `constructor(@Inject(KEYCLOACK) private keyCloack: SomeType) {}` and use `this.keyCloack` in its method. The same is true for a Guard.\n- This saved my day, for some reason path was not getting applied by controller directly it started working","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":105,"estimatedTokens":718}}372{"id":"stack-60182039","source":"stackoverflow","questionId":60182039,"title":"Nest.js can't resolve dependencies","tags":["typescript","nestjs","nestjs-config"],"text":"Title: Nest.js can't resolve dependencies\nTags: typescript, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI am trying to use `ConfigService` in my `users.module.ts` but I am getting an\n\n Error: Nest can't resolve dependencies of the UsersService (UserRepository, HttpService, ?). Please make sure that the argument ConfigService at index [2] is available in the UsersModule context.\n\nPotential solutions:\n\nIf ConfigService is a provider, is it part of the current\nUsersModule? \nIf ConfigService is exported from a separate @Module, is\nthat module imported within UsersModule?\n\nI have imported the ConfigModule in my UsersModule but still its not working :(\n\n**app.module.ts**\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({\n expandVariables: true,\n }),\n TypeOrmModule.forRoot(),\n UsersModule,\n AuthModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n\nexport class AppModule {}\n```\n\n**users.module.ts**\n\n```\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [UsersService],\n exports: [UsersService],\n})\n\nexport class UsersModule {}\n```\n\n**users.service.ts**\n\n```\nexport class UsersService {\n\n constructor(\n @InjectRepository(User)\n private readonly userRepository: Repository,\n private readonly httpService: HttpService,\n private readonly configService: ConfigService,\n ) {}\n\n}\n```\n\n========================================\n\nTop Answer:\nYou got things kinda crossed (I went through the same pain starting out too).\nBest practice would be to create a custom repository to handle the database logic.\n\nFirst declare a `UserRepository`:\n\n```\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n\n // add your custom db related method here later..\n\n}\n```\n\nThen in your `AppModule` you need to declare your entities like so:\n\n```\n@Module({\n\n imports: [\n\n TypeOrmModule.forRoot({\n\n type: 'mysql',\n host: process.env.DB_HOSTNAME || 'localhost',\n port: Number.parseInt(process.env.DB_PORT) || 3306,\n username: process.env.DB_USERNAME || 'root',\n password: process.env.DB_PASSWORD || 'mysql',\n database: process.env.DB_NAME || 'nestjs',\n synchronize: process.env.DB_SYNCHRONIZE === 'true' || true,\n keepConnectionAlive: true,\n entities: [\n\n User\n\n ]\n\n })\n\n...\n```\n\nAnd then in your `UsersModule` declare your repository:\n\n```\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([UserRepository])],\n controllers: [UsersController],\n providers: [UsersService],\n exports: [UsersService],\n})\n\nexport class UsersModule {}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      expandVariables: true,\n    }),\n    TypeOrmModule.forRoot(),\n    UsersModule,\n    AuthModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n\nexport class AppModule {}\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([User])],\n  controllers: [UsersController],\n  providers: [UsersService],\n  exports: [UsersService],\n})\n\nexport class UsersModule {}\n```\n\n```text\nexport class UsersService {\n\n constructor(\n    @InjectRepository(User)\n    private readonly userRepository: Repository<User>,\n    private readonly httpService: HttpService,\n    private readonly configService: ConfigService,\n  ) {}\n\n}\n```\n\n```text\nConfigService\n```\n\n```text\nusers.module.ts\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      expandVariables: true,\n    }),\n    TypeOrmModule.forRoot(),\n    UsersModule,\n    AuthModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n\nexport class AppModule {}\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([UserRepository])],\n  controllers: [UsersController],\n  providers: [UsersService, ConfigService],\n  exports: [UsersService],\n})\n\nexport class UsersModule {}\n```\n\n```text\nusers.module.ts\n```\n\n```text\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n\n    // add your custom db related method here later..\n\n}\n```\n\n```text\n@Module({\n\n    imports: [\n\n        TypeOrmModule.forRoot({\n\n            type: 'mysql',\n            host: process.env.DB_HOSTNAME || 'localhost',\n            port: Number.parseInt(process.env.DB_PORT) || 3306,\n            username: process.env.DB_USERNAME || 'root',\n            password: process.env.DB_PASSWORD || 'mysql',\n            database: process.env.DB_NAME || 'nestjs',\n            synchronize: process.env.DB_SYNCHRONIZE === 'true' || true,\n            keepConnectionAlive: true,\n            entities: [\n\n                User\n\n            ]\n\n        })\n\n...\n```\n\n```text\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([UserRepository])],\n  controllers: [UsersController],\n  providers: [UsersService],\n  exports: [UsersService],\n})\n\nexport class UsersModule {}\n```\n\n```text\nUserRepository\n```\n\n```text\nAppModule\n```\n\n```text\nUsersModule\n```\n\n========================================\n\nComments:\n- Setting it to Global does work but what I wanted is to explicitly import it wherever required. You answer is indeed correct but the reason why I posted this question is because I wanted to know what it is not working even though everything is correct\n- Hi @IstiyakTailor, In order to make it work, aside from import it. you still have to declare it as providers in that module itself. Refer to the example I edit above.\n- It was a bug. They fixed it.\n- This answer could be improved by including only code that has changed, and some text calling out what changed. As it stands it may be hard for users to see what you did that answers op's question.","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":282,"estimatedTokens":1473}}373{"id":"stack-61500218","source":"stackoverflow","questionId":61500218,"title":"How to unit test NestJs http request with full coverage?","tags":["typescript","unit-testing","jestjs","nestjs"],"text":"Title: How to unit test NestJs http request with full coverage?\nTags: typescript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am having trouble to test my NestJs Service. I wrote a method, which does a GET http request:\n\n```\ngetEntries(): Observable {\n Logger.log(`requesting GET: ${this.apiHost}${HREF.entries}`);\n return this.http.get(`${this.apiHost}${HREF.entries}`).pipe(\n catchError((error) => {\n return throwError(error);\n }),\n map(response => response.data)\n );\n }\n```\n\nI want to write a unit test for this method. This unit test should cover all lines of this method.\nI tried to use \"nock\" package to mock this http request, but no matter how i try the coverage result is always the same.\n\n```\nreturn throwError(error);\n\nmap(response => response.data);\n```\n\nThis two lines were uncovered.\n\nHere my test file:\n\n```\ndescribe('getEntries method', () => {\n it('should do get request and return entries', () => {\n nock('http://localhost:3000')\n .get('/v1/entries')\n .reply(200, {\n data: require('../mocks/entries.json')\n });\n try {\n const result = service.getEntries();\n result.subscribe(res => {\n expect(res).toEqual(require('../mocks/entries.json'));\n });\n } catch (e) {\n expect(e).toBeUndefined();\n }\n });\n it('should return error if request failed', () => {\n nock('http://localhost:3000')\n .get('/v1/entries')\n .replyWithError('request failed');\n service.getEntries().subscribe(res => {\n expect(res).toBeUndefined();\n }, err => {\n expect(err).toBe('request failed');\n })\n });\n });\n```\n\n========================================\n\nTop Answer:\nThank you for your reply. The code works fundamentally. I had to make a few changes for the test to work. Here are my changes:\n\n```\ndescribe('getEntries method', () => {\n it('should do get request and return entries', (done) => {\n jest.spyOn(service['http'], 'get').mockReturnValue(of({data: require('../mocks/entries.json'), status: 200, statusText: 'OK', headers: {}, config: {}}));\n let data = {};\n\n service.getEntries().subscribe({\n next: (val) => {data = val},\n error: (err) => { throw err; },\n complete: () => {\n expect(data).toEqual(require('../mocks/entries.json'))\n done();\n }\n });\n });\n it('should return error if request failed', (done) => {\n jest.spyOn(service['http'], 'get').mockReturnValue(throwError('request failed'));\n let data = {};\n\n service.getEntries().subscribe({\n next: (val) => {data = val},\n error: (err) => {\n expect(err).toBe('request failed');\n done();\n },\n complete: () => {\n expect(data).toBeUndefined();\n done();\n }\n });\n });\n });\n```\n\nYou have to mock AxiosReponse on httpSpy mockReturnValue, so i added 'status', 'statusText', 'header', 'config'. Otherwise you will get a type error.\n\nAnd second part. I was spying on httpService like this:\n\n```\nlet httpService: HttpService;\nhttpService = module.get(HttpService)\n```\n\nThis doesn't work. I have to spy on the HttpService injection of my Service.\n\n```\nconstructor(private readonly http: HttpService) {}\n```\n\nThat' why my spy looks like: service['http'].\n\nNow i have full coverage on this http request :)\n\nThank you so much ;)\nHave a nice day!\n\n========================================\n\nCode:\n```text\ngetEntries(): Observable<Entries[]> {\n    Logger.log(`requesting GET: ${this.apiHost}${HREF.entries}`);\n    return this.http.get(`${this.apiHost}${HREF.entries}`).pipe(\n      catchError((error) => {\n        return throwError(error);\n      }),\n      map(response => response.data)\n    );\n  }\n```\n\n```text\nreturn throwError(error);\n\nmap(response => response.data);\n```\n\n```text\ndescribe('getEntries method', () => {\n    it('should do get request and return entries', () => {\n      nock('http://localhost:3000')\n        .get('/v1/entries')\n        .reply(200, {\n          data: require('../mocks/entries.json')\n        });\n      try {\n        const result = service.getEntries();\n        result.subscribe(res => {\n          expect(res).toEqual(require('../mocks/entries.json'));\n        });\n      } catch (e) {\n        expect(e).toBeUndefined();\n      }\n    });\n    it('should return error if request failed', () => {\n      nock('http://localhost:3000')\n        .get('/v1/entries')\n        .replyWithError('request failed');\n      service.getEntries().subscribe(res => {\n        expect(res).toBeUndefined();\n      }, err => {\n        expect(err).toBe('request failed');\n      })\n    });\n  });\n```\n\n```js\nit('should do the request and get the entries', (done) => {\n  const httpSpy = jest.spyOn(httpService, 'get')\n    .mockReturnValue(of({data: require('../mocks/entries.json')}))\n  let data = {};\n  service.getEntires().subscribe({\n    next: (val) => {data = val},\n    error: (err) => { throw error; }\n    complete: () => {\n      expect(data).toEqual(require('../mocks/entries.json'))\n      done();\n    }\n});\n```\n\n```text\nnock\n```\n\n```text\nHttpService\n```\n\n```text\njest.spyOn\n```\n\n```text\nthrowError()\n```\n\n```text\nof\n```\n\n```text\nthrowError\n```\n\n```text\nrxjs\n```\n\n```text\nHttpService\n```\n\n```text\ndescribe('getEntries method', () => {\n    it('should do get request and return entries', (done) => {\n      jest.spyOn(service['http'], 'get').mockReturnValue(of({data: require('../mocks/entries.json'), status: 200, statusText: 'OK', headers: {}, config: {}}));\n      let data = {};\n\n      service.getEntries().subscribe({\n        next: (val) => {data = val},\n        error: (err) => { throw err; },\n        complete: () => {\n          expect(data).toEqual(require('../mocks/entries.json'))\n          done();\n        }\n      });\n    });\n    it('should return error if request failed', (done) => {\n      jest.spyOn(service['http'], 'get').mockReturnValue(throwError('request failed'));\n      let data = {};\n\n      service.getEntries().subscribe({\n        next: (val) => {data = val},\n        error: (err) => {\n          expect(err).toBe('request failed');\n          done();\n        },\n        complete: () => {\n          expect(data).toBeUndefined();\n          done();\n        }\n      });\n    });\n  });\n```\n\n```text\nlet httpService: HttpService;\nhttpService = module.get(HttpService)\n```\n\n```text\nconstructor(private readonly http: HttpService) {}\n```\n\n========================================\n\nComments:\n- Thank your, i posted a few Changes.\n- Any way to do so for `post`?\n- `jest.spyOn(httpService, 'post')...` most of it follows as you'd expect. It's just another method on the `HttpService`","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":270,"estimatedTokens":1585}}374{"id":"stack-65485069","source":"stackoverflow","questionId":65485069,"title":"Nestjs catch 500 error and return the error","tags":["nestjs"],"text":"Title: Nestjs catch 500 error and return the error\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen an unhandled error occurs, the front side gets a 500 error without any information about the error. It just receives this:\n\n```\n{\n \"statusCode\": 500,\n \"message\": \"Internal server error\"\n}\n```\n\nBut when I check the console, I see what happened and what the error message is. It's ok in the development environment but it's hard to figure out in production. How can I return a complete error message in production instead of just a simple message like `\"Internal server error\"`?\n\n========================================\n\nTop Answer:\nNestJS has the `NotFoundException` you can use.\n\nYou can implement your own custom Exception filters and add it to your controllers to capture a `NotFoundException` or whatever communication protocol, but this is assuming that you have an **HTTP** communication protocol.\n\nSo if http is the only communication protocol you are dealing with then you can just write this into one of your methods inside your service:\n\n```\nif (!user) {\n throw new NotFoundException('user not found');\n}\n```\n\nAnd you would import that from:\n\n```\nimport { Injectable, NotFoundException } from '@nestjs/common';\n```\n\n========================================\n\nCode:\n```text\n{\n  \"statusCode\": 500,\n  \"message\": \"Internal server error\"\n}\n```\n\n```text\n\"Internal server error\"\n```\n\n```text\nif (!user) {\n  throw new NotFoundException('user not found');\n}\n```\n\n```text\nimport { Injectable, NotFoundException } from '@nestjs/common';\n```\n\n```text\nNotFoundException\n```\n\n```text\nNotFoundException\n```\n\n```text\nasync getUsers(){\n    let response = doSomething();\n    if (response.status !== 200) {\n      throw new HttpException(\n        `Error getting users: ${response.status} ${response.statusText}`,\n        response.status,\n      )\n    } else {\n      return response.data\n    }\n  }\n```\n\n```text\nHttpException\n```\n\n```text\nError\n```\n\n```text\n//InternalServerError.filter.ts\nimport {\n    InternalServerErrorException,\n    Catch,\n    ArgumentsHost,\n    ExceptionFilter,\n    HttpStatus,\n    HttpException\n} from \"@nestjs/common\";\n// catch all error\n@Catch()\nexport default class InternalServerErrorExceptionFilter implements ExceptionFilter {\n    catch(exception: Error, host: ArgumentsHost) {\n      \n        let { message: errMsg, stack: errStack, name: errName } = exception;\n        // let errRes = exception.getResponse();\n        // let errCode = exception.getStatus();\n        let ctx = host.switchToHttp();\n        let req = ctx.getRequest();\n        let res = ctx.getResponse();\n        const statusName = \"็ณป็ปŸๅ†…้ƒจ้”™่ฏฏ\";\n        res.statusCode = HttpStatus.INTERNAL_SERVER_ERROR;\n        // HttpException Error\n        if (exception instanceof HttpException) {\n            // set httpException res to res\n            res.status(exception.getStatus()).json(exception.getResponse());\n            return;\n        }\n        // other error to rewirte InternalServerErrorException response\n        res.render(\"Error.ejs\", {\n            exception,\n            errMsg,\n            errStack,\n            errName,\n            statusCode: res.statusCode,\n            statusName,\n            req\n        });\n    }\n}\n```\n\n```text\n// app.module.ts\n@Module({\nproviders:[{\n        provide: APP_FILTER,\n        useClass: InternalServerErrorExceptionFilter\n    }])\n```\n\n```text\n@Post('register');\nregister(@Body() user: UserInterface): any { // UserInterface call 500 exception\n  Logger.error('user', user)\n```\n\n========================================\n\nComments:\n- Thank you. I just read this but didn't get my answer.\n- I mean, generally all errors in JavaScript have a `message` property, so you could `res.send(exception.message)` (general code, make sure you tailor it to your needs) and it should send back what happened instead of \"Internal Server Error\"","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":154,"estimatedTokens":962}}375{"id":"stack-62105763","source":"stackoverflow","questionId":62105763,"title":"NestJS passing Authorization header to HttpService","tags":["http","http-headers","nestjs"],"text":"Title: NestJS passing Authorization header to HttpService\nTags: http, http-headers, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS application which acts as a proxy between a front-end and multiple other back-ends.\n\nI basically want to be able to pass a specific header (Authorization) from incoming @Req (requests) in the controller to the HttpService that then talks to the other back-ends.\n\nuser controller (has access to request) -> \nuser service (injects httpService that somehow already picks the Authorization header) -> External backends.\n\nRight now I need to extract the token from @Headers and then pass token to service which has to paste it to all HttpService calls. \n\nThanks in advance!\n\n========================================\n\nTop Answer:\nI'm not sure if this will help you, but maybe if you get the header from the controller and put it in your services function...\n\n// Controller:\n\n```\n@Get()\ngetAll(@Request() req){\n const header = req.headers;\n return this._zoneService.sendToHttp(header);\n}\n```\n\nMaybe microservices can be better ?\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class HttpServiceInterceptor implements NestInterceptor {\n  constructor(private httpService: HttpService) {}\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n  \n    // ** if you use normal HTTP module **\n    const ctx = context.switchToHttp();\n    const token = ctx.getRequest().headers['authorization'];\n\n    // ** if you use GraphQL module **\n    const ctx = GqlExecutionContext.create(context);\n    const token = ctx.getContext().token;\n\n    if (ctx.token) {\n      this.httpService.axiosRef.defaults.headers.common['authorization'] =\n        token;\n    }\n    return next.handle().pipe();\n  }\n}\n```\n\n```js\nGraphQLModule.forRoot({\n  debug: true,\n  playground: true,\n  autoSchemaFile: 'schema.gql',\n  context: ({ req }) => {\n    return { token: req.headers.authorization };\n  },\n}),\n```\n\n```js\n@UseInterceptors(HttpServiceInterceptor)\nexport class CatsController {}\n```\n\n```js\n@Module({\n  providers: [\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: HttpServiceInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nmiddleware\n```\n\n```text\ninterceptor\n```\n\n```text\nGraphQLModule\n```\n\n```text\n@Get()\ngetAll(@Request() req){\n    const header = req.headers;\n    return this._zoneService.sendToHttp(header);\n}\n```\n\n```js\n@Injectable()\nexport class BearerMiddleware implements NestMiddleware {\n  constructor(private readonly httpService: HttpService) {}\n  use(req: Request, res: Response, next: Function) {\n    this.httpService.axiosRef.interceptors.request.use(request => {\n      request.headers = {\n        ...request.headers,\n        Authorization: req.headers.Authorization || '',\n      };\n      return request;\n    });\n    next();\n  }\n}\n```\n\n```js\nimport { HttpModule } from '@nestjs/axios';\n@Module({\n  providers: [],\n  controllers: [YourController],\n  imports: [\n    HttpModule,\n  ],\n  exports: [],\n})\nexport class YourModule {}\n```\n\n```js\nimport { HttpService } from '@nestjs/axios';\nimport { Controller, HttpStatus, Res, BadRequestException } from '@nestjs/common';\n\n@Controller('your-controller')\nexport class YourController {\n  constructor(\n    private httpService: HttpService,\n  ) {}\n\n  async fetchApi(@Res() res) {\n    const urlAPI = 'https://xxx.vn';\n    try {\n      const source = await this.httpService.get(urlAPI,\n        {\n          headers: { Authorization: 'Basic XXX-TOKEN' },\n        },\n      );\n      return res.status(HttpStatus.OK).json({ ...source });\n    } catch (error) {\n      throw new BadRequestException(error.response?.statusText);\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- Did you find a solution? Can you with me? I am facing the same challenge. Thanks\n- @hksfho I posted the solution below. The caveat is that you change the Axios instance in the background so if your modules modify headers post-controller layer you lose the changes.\n- The problem is that I don't want to do this for every method. I want my HttpService instance to be told ONCE (Middleware:esque) to add said header\n- No.. a new interceptor will be created each time when use() is called. the data not correct .\n- @hksfho which could be a better way?\n- could you update the type of observable, TS doesn't like any.\n- I need to send x-app-token. Can I do it using the above method?","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":173,"estimatedTokens":1099}}376{"id":"stack-68334376","source":"stackoverflow","questionId":68334376,"title":"MODULE_NOT_FOUND Nestjs and Swagger","tags":["typescript","swagger","nestjs","swagger-ui"],"text":"Title: MODULE_NOT_FOUND Nestjs and Swagger\nTags: typescript, swagger, nestjs, swagger-ui\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add Swagger to my Nestjs app. Module not found error is thrown when I'm trying to compile it.\nI use the same code from Nestjs documentation.\nThis is my main.ts:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n const config = new DocumentBuilder()\n .setTitle('Cats example')\n .setDescription('The cats API description')\n .setVersion('1.0')\n .addTag('cats')\n .build();\n const document = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup('api', app, document);\n\n await app.listen(3000);\n}\nbootstrap();\n```\n\nThis is the error:\n\n```\ninternal/modules/cjs/loader.js:883\n throw err;\n ^\n\nError: Cannot find module '@nestjs/core/router/route-path-factory'\nRequire stack:\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\swagger-explorer.js\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\swagger-scanner.js \n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\swagger-module.js \n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\index.js\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\index.js\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\dist\\main.js\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)\n at Function.Module._load (internal/modules/cjs/loader.js:725:27)\n```\n\nI'm using Node 14.15.1, @nestjs/swagger 5.0.0, swagger-ui-express: 4.1.6\n\n========================================\n\nTop Answer:\nSwagger v5 is compatible with Nest v8 (@nestjs/core@^8.0.0, @nestjs/common@^8.0.0 etc)\nSwagger v4 is compatible with Nest v7\n\nSource from https://github.com/nestjs/nest/issues/7499\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const config = new DocumentBuilder()\n    .setTitle('Cats example')\n    .setDescription('The cats API description')\n    .setVersion('1.0')\n    .addTag('cats')\n    .build();\n  const document = SwaggerModule.createDocument(app, config);\n  SwaggerModule.setup('api', app, document);\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\ninternal/modules/cjs/loader.js:883\n  throw err;\n  ^\n\nError: Cannot find module '@nestjs/core/router/route-path-factory'\nRequire stack:\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\swagger-explorer.js\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\swagger-scanner.js \n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\swagger-module.js  \n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\dist\\index.js\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\node_modules\\@nestjs\\swagger\\index.js\n- D:\\BK\\solidity\\MVPApp\\blockchain\\back-end-student-wallet-v2\\dist\\main.js\n    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)\n    at Function.Module._load (internal/modules/cjs/loader.js:725:27)\n```\n\n```text\n{\n\"@nestjs/common\": \"^8.0.0\",\n\"@nestjs/config\": \"^1.1.5\",\n\"@nestjs/core\": \"^8.0.0\",\n\"@nestjs/platform-express\": \"^8.0.0\",\n}\n```\n\n```text\n{\n        \"@nestjs/cli\": \"^8.0.0\",\n        \"@nestjs/schematics\": \"^8.0.0\",\n        \"@nestjs/testing\": \"^8.0.0\",\n    }\n```\n\n========================================\n\nComments:\n- update latest version of @nestjs/platform-express, @nestjs/common,@nestjs/core solve my problem\n- Post your comment as an answer and accept it, so your question will appear as solved.","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":958}}377{"id":"stack-51932562","source":"stackoverflow","questionId":51932562,"title":"NestJS: Adding verification options to AuthGuard with JWT","tags":["javascript","node.js","nestjs"],"text":"Title: NestJS: Adding verification options to AuthGuard with JWT\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to make use of the `AuthGuard` decorator, and the passport JWT strategy, following the documentation.\n\nEverything in the documentation works great. But I now want to protect a route with a scope contained in the JWT. So here is a basic jwt payload generated by my application:\n\n```\n{\n \"user\": {\n \"id\": \"20189c4f-1183-4216-8b48-333ddb825de8\",\n \"username\": \"user.test@gmail.com\"\n },\n \"scope\": [\n \"manage_server\"\n ],\n \"iat\": 1534766258,\n \"exp\": 1534771258,\n \"iss\": \"15f2463d-8810-44f9-a908-801872ded159\",\n \"sub\": \"20189c4f-1183-4216-8b48-333ddb825de8\",\n \"jti\": \"078047bc-fc1f-4c35-8abe-72834f7bcc44\"\n}\n```\n\nHere is the basic protected route being guarded by the `AuthGuard` decorator:\n\n```\n@Get('protected')\n@UseGuards(AuthGuard('jwt'))\nasync protected(): Promise {\n return 'Hello Protected World';\n}\n```\n\nI would like to add options and restrict the access of that route to the people having the `manager_server` scope into their JWT. So after reading a little bit of the `AuthGuard` code, I thought that I was able to write something like:\n\n```\n@Get('protected')\n@UseGuards(AuthGuard('jwt', {\n scope: 'manage_server'\n}))\nasync protected(): Promise {\n return 'Hello Protected World';\n}\n```\n\n**However, I can't see in the documentation where I could make use of this option.** \n\nI thought that adding an option argument to the `validate` function of the `JWTStrategy` could make the trick, but it does not. Here is my `validate` function (contained in the `jwt.strategy.ts` file):\n\n```\nasync validate(payload: JwtPayload, done: ((err: any, value: any) => void)) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n return done(new UnauthorizedException(), false);\n }\n done(null, user);\n}\n```\n\nThank you very much for your help and don't hesitate to ask me for more informations in the comments if you need so.\n\n========================================\n\nTop Answer:\nI tried a slightly different approach, by extending the AuthGuard guard. I wanted to maintain the ability to use different Passport Strategies, so I included a mixin. Feedback is appreciated.\n\nIn your Jwt strategy you could simply return the JwtPaylozd so that the user has a scopes attribute. Then the custom AuthGuard looks like this:\n\n```\nimport { UnauthorizedException, mixin } from \"@nestjs/common\";\nimport { AuthGuard } from \"@nestjs/passport\";\n\nexport function AuthScopes(scopes: string[], type?: string | string[]) {\n return mixin(class ScopesAuth extends AuthGuard(type) {\n protected readonly scopes = scopes;\n handleRequest(err, user, info, context) {\n if (err || !user) {\n throw err || new UnauthorizedException();\n }\n\n if(!this.scopes.some(s => user.scopes.split(' ').includes(s)))\n {\n throw new UnauthorizedException(`JWT does not possess one of the required scopes (${this.scopes.join(',')})`);\n }\n return user;\n }\n });\n }\n```\n\nYou can then use this guard like so:\n\n```\n@Get('protected')\n@UseGuards(AuthScopes(['secret:read'], 'jwt'))\nasync protected(): Promise {\n return 'Hello Protected World';\n}\n```\n\n'jwt' represents the strategy.\n\n========================================\n\nCode:\n```js\n{\n  \"user\": {\n    \"id\": \"20189c4f-1183-4216-8b48-333ddb825de8\",\n    \"username\": \"user.test@gmail.com\"\n  },\n  \"scope\": [\n    \"manage_server\"\n  ],\n  \"iat\": 1534766258,\n  \"exp\": 1534771258,\n  \"iss\": \"15f2463d-8810-44f9-a908-801872ded159\",\n  \"sub\": \"20189c4f-1183-4216-8b48-333ddb825de8\",\n  \"jti\": \"078047bc-fc1f-4c35-8abe-72834f7bcc44\"\n}\n```\n\n```js\n@Get('protected')\n@UseGuards(AuthGuard('jwt'))\nasync protected(): Promise<string> {\n    return 'Hello Protected World';\n}\n```\n\n```js\n@Get('protected')\n@UseGuards(AuthGuard('jwt', {\n    scope: 'manage_server'\n}))\nasync protected(): Promise<string> {\n    return 'Hello Protected World';\n}\n```\n\n```js\nasync validate(payload: JwtPayload, done: ((err: any, value: any) => void)) {\n    const user = await this.authService.validateUser(payload);\n    if (!user) {\n        return done(new UnauthorizedException(), false);\n    }\n    done(null, user);\n}\n```\n\n```text\nAuthGuard\n```\n\n```text\nAuthGuard\n```\n\n```text\nmanager_server\n```\n\n```text\nAuthGuard\n```\n\n```text\nvalidate\n```\n\n```text\nJWTStrategy\n```\n\n```text\nvalidate\n```\n\n```text\njwt.strategy.ts\n```\n\n```text\nexport const Scopes = (...scopes: string[]) => SetMetadata('scopes', scopes);\n```\n\n```text\n@Injectable()\nexport class ScopesGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const scopes = this.reflector.get<string[]>('scopes', context.getHandler());\n    if (!scopes) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const user = request.user;\n    const hasScope = () => user.scopes.some((scope) => scopes.includes(scope));\n    return user && user.scopes && hasScope();\n  }\n}\n```\n\n```text\n@Module({\n  providers: [\n    {\n      provide: APP_GUARD,\n      useClass: ScopesGuard,\n    },\n  ],\n})\nexport class ApplicationModule {}\n```\n\n```text\n@Get('protected')\n@UseGuards(AuthGuard('jwt'))\n@Scopes('manage_server')\nasync protected(): Promise<string> {\n    return 'Hello Protected World';\n}\n```\n\n```text\noptions.callback\n```\n\n```text\nAuthGuard\n```\n\n```text\nScopesGuard\n```\n\n```text\nRolesGuard\n```\n\n```text\n@Scopes('manage_server')\n```\n\n```text\nRolesGuard\n```\n\n```text\nuser\n```\n\n```text\n@Scopes()\n```\n\n```text\nScopesGuard\n```\n\n```text\nimport { UnauthorizedException, mixin } from \"@nestjs/common\";\nimport { AuthGuard } from \"@nestjs/passport\";\n\nexport function AuthScopes(scopes: string[], type?: string | string[]) {\n    return mixin(class ScopesAuth extends AuthGuard(type) {\n        protected readonly scopes = scopes;\n        handleRequest(err, user, info, context) {\n        if (err || !user) {\n            throw err || new UnauthorizedException();\n        }\n\n        if(!this.scopes.some(s => user.scopes.split(' ').includes(s)))\n        {\n            throw new UnauthorizedException(`JWT does not possess one of the required scopes (${this.scopes.join(',')})`);\n        }\n        return user;\n        }\n    });\n  }\n```\n\n```text\n@Get('protected')\n@UseGuards(AuthScopes(['secret:read'], 'jwt'))\nasync protected(): Promise<string> {\n    return 'Hello Protected World';\n}\n```\n\n========================================\n\nComments:\n- Great, thank you very much, using a custom guard was the solution I came with since I posted the question, but your solution of using a custom decorator is something I really like. Thank you for your time!\n- Nice class for checking scopes Kim! I did find several minor typos with the class: 1. You're spreading the scopes parameter so `@Scopes(['manage_server'])` will raise a compile time warning. I changed `(...scopes: string[])` to `(scopes: string[])` 2. make sure scope includes the variable \"scope\", not \"scopes\". `(scope => scopes.includes(scope));` Thanks again!\n- @leokwanbt14 Thanks! :-) I have updated the answer with your input. I've left in the spread though because then you can use the decorator as `@Scopes('manage_server')` instead of `@Scopes(['manage_server'])` which feels more natural to me.\n- I did exactly the same but context.switchToHttp().getRequest(); is always undefined for me @KimKern\n- @YashwanthKata context.switchToHttp().getRequest(); is undefned for me too\n- It gives the following error `TypeError: Cannot read property 'split' of undefined`\n- @MohamedSaleh I am guessing you are not including any scopes in your JWT token?\n- Yes, I think it was the problem :)","metadata":{"transformedAt":"2026-08-18T18:33:02.436Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":305,"estimatedTokens":1897}}378{"id":"stack-69653359","source":"stackoverflow","questionId":69653359,"title":"Is NestJs a right choice for a node.js beginner or should I do something with Express first?","tags":["node.js","typescript","express","sails.js","nestjs"],"text":"Title: Is NestJs a right choice for a node.js beginner or should I do something with Express first?\nTags: node.js, typescript, express, sails.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI know `Nest.js` is on top of Express JS and can be on fastify, I have completed the express JS library project in the Mozilla (MDN) training site but for many reasons like the architecture of the app and discussions that I saw on web about problematic situations with express and modern JS like async-await, etcโ€ฆ\n\nI searched for a more reliable choice: sails-js, nest and feathers came up, feathers were awesome but `Nest.js` had very good documentation and I avoided typescript for a while, but as for now it seems to be everywhere, and I hope with nest I could get to know it better and the practical use of it, at frontend I honestly could not find a good reason for using it besides it's a trend, except for angular 2 plus. Don't get me wrong angular is one of the reasons I hope to come around TS.\n\n### Short Version\n\nSo this is my current situation as a frontend developer (vue & svelte mostly) a few months in NodeJS atmosphere (express and hapi) my question is: *should I stick to hapi & express or go with NestJs & alternatives like feathers and sails?*\n\nPlease forgive my lack of experience for writing in English.\n\n========================================\n\nTop Answer:\nContrary to popular opinion, I'll suggest to get to know express a bit, make a plain simple server with JS and express (no fancy framweorks), convert it to TS. Get to know express library and how it works. NestJS abstracts a lot of the express'y' stuff. Its always good to know how it works under the hood.\n\nI came from plain old JS + express to NestJS, and it feels good to know how it works under the hood.\n\nIt need not be a big app, just create a TODO with Auth,Validation and DB.\n\nThere is nothing wrong starting with NestJS though.\n\n========================================\n\nCode:\n```text\nNest.js\n```\n\n```text\nNest.js\n```\n\n```text\ncontoller\n```\n\n```text\nservice\n```\n\n```text\nmodule\n```\n\n```text\nforRoot\n```\n\n```text\nforRootAsync\n```\n\n========================================\n\nComments:\n- i would stick to express/hapi. I work in hapi and nestjs both, on daily basis in my projects at work. I found nestjs more abstract than hapi. Somehow i find that hapi suits me better, in terms of syntax, simplicity and understanding, at this moment. If you just do simple projects for yourself for sake of practice, i would stick to simple solutions. Doing it for real apps, is another story. Experts will decide on that.\n- Please provide enough code so others can better understand or reproduce the problem.\n- Welcome to the StackOverflow community! Take a look at How to ask a good question and please don't forget to mark answers as accepted and upvote useful comments or posts.\n- @StefanZivkovic on my last job as a frontend dev I was working with people who had great experience in java,and there and then I saw how much of a programmer they truly are and not a programmer I am,I can't go start with somthing like java so I tought the OO framworks of js can help me become better and soon TS is in the way to that\n- None! Use Fastify+Nuxt and Ecmascript (for types there are good alternatives to clumsy typescript)\n- @CodeGust Acctually I ended up with nuxt 3 + adonis 5 on back-end, honestly I'm considering trying monolithic with edge templates or something like inertia to bring vue to adonis , Im a little disappointed on the issues that SSR meant to address on SEO, but overall coding with vue 3 vite is a joy to say the least and adonis 5 documents really helped me, it's unbelievable how great people are in these comunities\n- @w3bsite good choice! you might also like WebComponents with Stenciljs - that might be the future. And those things can also be used with Vue for some scenarios.\n- yes it's true nestjs can be used without TS and its practical not just an advertising claim,thank you for taking the time to answer my question\n- about TS and the future I heard the same reasoning from other senior programmers,thank you for the answer\n- this is true , I had a pretty smooth journey getting in back-end side and avoided confusion because I started with vercel serverless functions and in that environment the only focus was logic I used deta for database , it's a simple no-sql key value db, then went to express / fastify finally adonis 5 and PostgreSQL and vue/nuxt on front, of course I'm just using these tools and not saying I know them just learning by using them.","metadata":{"transformedAt":"2026-08-18T18:33:02.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":1138}}379{"id":"stack-58966110","source":"stackoverflow","questionId":58966110,"title":"TypeScript add custom Request header in Express","tags":["node.js","typescript","express","http-headers","nestjs"],"text":"Title: TypeScript add custom Request header in Express\nTags: node.js, typescript, express, http-headers, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to add a **custom header** to my request, but it must be modified/implemented in the interface. \n\nThe default `Request` interface references `IncomingHttpHeaders`. So I am attempting to extend this interface with my own custom token header. \n\n```\nimport { IncomingHttpHeaders } from 'http';\n\ndeclare module 'express-serve-static-core' {\n interface IncomingHttpHeaders {\n \"XYZ-Token\"?: string\n }\n}\n```\n\nI have updated my `.tsconfig` file to read the `./types` folder. The name of my file is `index.d.ts`\n\nI can successfully compile the code if I do not use my custom header, but when I try to reference the token header in the code I get the following compilation error: \n\n**Error**\n\n```\nerror TS2538: Type 'string[]' cannot be used as an index type.\n\n req.headers['XYZ-Token']\n```\n\nIf I use any of the values of the original interface everything works fine.\n\n**Example:**\n\n```\nreq.headers['user-agent']\n```\n\n**Additional information**: I am using NestJS, which uses Fastify/Express under the hood. I can confirm that the Request interface being used is from Express. Fastify is backwards compatible with all Express modules. Mainly using Fastify because it's faster.\n\n========================================\n\nTop Answer:\nFor whatever reason, it thinks the string you are passing in is an array, but besides that point, if you need to set a custom header (and it is not a dynamic value) you can use the `@Header()` decorator. If it is dynamic then you can use an interceptor to grab the response pre-flight and set the header there with something like\n\n```\n@Injectable()\nexport class CustomHeaderInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n return next\n .handle()\n .pipe(\n tap(() => context.switchToHttp().getResponse().header('XYZ-Token', customValue),\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { IncomingHttpHeaders } from 'http';\n\ndeclare module 'express-serve-static-core' {\n    interface IncomingHttpHeaders {\n        \"XYZ-Token\"?: string\n    }\n}\n```\n\n```text\nerror TS2538: Type 'string[]' cannot be used as an index type.\n\n    req.headers['XYZ-Token']\n```\n\n```text\nreq.headers['user-agent']\n```\n\n```text\nRequest\n```\n\n```text\nIncomingHttpHeaders\n```\n\n```text\n.tsconfig\n```\n\n```text\n./types\n```\n\n```text\nindex.d.ts\n```\n\n```text\nimport { IncomingHttpHeaders } from 'http';\n\ndeclare module 'http' {\n    interface IncomingHttpHeaders {\n        \"XYZ-Token\"?: string\n    }\n}\n```\n\n```text\nIncomingHttpHeaders\n```\n\n```text\nRequest\n```\n\n```text\nexpress-serve-static-core\n```\n\n```text\nIncomingHttpHeaders\n```\n\n```text\nhttp\n```\n\n```js\n@Injectable()\nexport class CustomHeaderInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next\n      .handle()\n      .pipe(\n        tap(() => context.switchToHttp().getResponse().header('XYZ-Token', customValue),\n      );\n  }\n}\n```\n\n```text\n@Header()\n```\n\n```text\nimport { IncomingHttpHeaders } from \"http2\";\n\ninterface MyCustomsHearders {\n    foo: \"bar\";\n}\n\ntype IncomingCustomHeaders = IncomingHttpHeaders & MyCustomsHearders;\nconst { foo } = req.headers as IncomingCustomHeaders;\n```\n\n```text\nIncomingHttpHeaders\n```\n\n========================================\n\nComments:\n- Thanks for the information on the @Headers. I was able to get my code working with the new header by extending the IncomingHttpHeaders interface. I needed this change globally throughout my API. Looks like when I was declaring the new type, I was still specifying the express-serve-static-sore, where it needed to be http module.","metadata":{"transformedAt":"2026-08-18T18:33:02.437Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":168,"estimatedTokens":943}}380{"id":"stack-66346501","source":"stackoverflow","questionId":66346501,"title":"How to set HTTP only cookie in NestJS","tags":["typescript","express","cookies","jwt","nestjs"],"text":"Title: How to set HTTP only cookie in NestJS\nTags: typescript, express, cookies, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement JWT authorization with accessToken and refreshToken. Both the accessToken and refresh token need to be set in HTTP only cookie.\n\nI tried this code but it is not setting cookies. I am using NestJS framework here.\n\n```\nimport { Controller, Request, Post, Body, Response } from '@nestjs/common';\n@Controller()\nexport class UserController {\n constructor() {}\n\n @Post('users/login')\n async login(\n @Request() req,\n @Body() credentials: { username: string; password: string },\n @Response() res,\n ) {\n try {\n // Login with username and password\n const accessToken = 'something';\n const refreshToken = 'something';\n const user = { username: credentials.username };\n\n res.cookie('accessToken', accessToken, {\n expires: new Date(new Date().getTime() + 30 * 1000),\n sameSite: 'strict',\n httpOnly: true,\n });\n return res.send(user);\n } catch (error) {\n throw error;\n }\n }\n}\n```\n\nThe res.send() method is working fine i am getting data in response .How can i set cookie here ?\n\nThis is my main.ts file: -\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Logger } from '@nestjs/common';\nimport { AuthenticatedSocketIoAdapter } from './chat/authchat.adapter';\nimport * as cookieParser from 'cookie-parser';\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.enableCors();\n app.use(cookieParser());\n app.useWebSocketAdapter(new AuthenticatedSocketIoAdapter(app));\n await app.listen(3000);\n Logger.log('User microservice running');\n}\nbootstrap();\n```\n\nAnd to get the cookie I am using:-\n\n```\nrequest.cookies\n```\n\n========================================\n\nTop Answer:\nI encountered almost the same issue as you. Axios could not save the cookies.\nThe Chrome required to set up SameSite: 'none', secure: true.\nStill did not work thou. It did saved the cookie using fetch method, but only in browsers running with Chromium... So mozilla did not received it. My axios was:\n\n```\nconst response = await axios.post(url+'/login', loginState, {withCredentials: true});\n```\n\nThe backend Nestjs: Main.ts:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.setGlobalPrefix('v1/api');\n app.use(cookieParser());\n app.useGlobalPipes(new ValidationPipe());\n app.enableCors({\n credentials: true,\n origin: process.env.FRONTEND_URL,\n })\n await app.listen(3000);\n}\n```\n\nMy AuthService Login function (remember about passthrought: true in Res)\n\n```\n@Post('login')\nasync login(\n @Body()body: LoginUserDTO,\n @Res({passthrough: true}) response: Response\n ): Promise {\n const user = await this.userService.getOne({where: {\"user_email\": body.email}});\n if(!user) {\n throw new NotFoundException('User not found')\n }\n if(!await bcrypt.compare(body.password, user.user_password)) {\n throw new BadRequestException('Password incorrect');\n }\n const frontendDomain = this.configService.get('FRONTEND_DOMAIN');\n const jwtToken = await this.jwtService.signAsync({id: user.user_id});\n response.cookie('jwt', jwtToken, {httpOnly: true, domain: frontendDomain,});\n\n return {'jwt': jwtToken}\n}\n```\n\nWeirdly enough what solved my issue was to add the domain into the response.cookie.\n\nAlso my dev env variables used for CORS and cookie domain:\n\n```\nFRONTEND_URL = http://localhost:3333\nFRONTEND_DOMAIN = localhost\n```\n\nHope my code can help\n\n========================================\n\nCode:\n```text\nimport { Controller, Request, Post, Body, Response } from '@nestjs/common';\n@Controller()\nexport class UserController {\n  constructor() {}\n\n  @Post('users/login')\n  async login(\n    @Request() req,\n    @Body() credentials: { username: string; password: string },\n    @Response() res,\n  ) {\n    try {\n      // Login with username and password\n      const accessToken = 'something';\n      const refreshToken = 'something';\n      const user = { username: credentials.username };\n\n      res.cookie('accessToken', accessToken, {\n        expires: new Date(new Date().getTime() + 30 * 1000),\n        sameSite: 'strict',\n        httpOnly: true,\n      });\n      return res.send(user);\n    } catch (error) {\n      throw error;\n    }\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Logger } from '@nestjs/common';\nimport { AuthenticatedSocketIoAdapter } from './chat/authchat.adapter';\nimport * as cookieParser from 'cookie-parser';\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.enableCors();\n  app.use(cookieParser());\n  app.useWebSocketAdapter(new AuthenticatedSocketIoAdapter(app));\n  await app.listen(3000);\n  Logger.log('User microservice running');\n}\nbootstrap();\n```\n\n```text\nrequest.cookies\n```\n\n```text\nwithCredentials\n```\n\n```text\ntrue\n```\n\n```text\nconst response = await axios.post(url+'/login', loginState, {withCredentials: true});\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.setGlobalPrefix('v1/api');\n  app.use(cookieParser());\n  app.useGlobalPipes(new ValidationPipe());\n  app.enableCors({\n    credentials: true,\n    origin: process.env.FRONTEND_URL,\n  })\n  await app.listen(3000);\n}\n```\n\n```text\n@Post('login')\nasync login(\n        @Body()body: LoginUserDTO,\n        @Res({passthrough: true}) response: Response\n    ): Promise<any> {\n    const user = await this.userService.getOne({where: {\"user_email\": body.email}});\n    if(!user) {\n        throw new NotFoundException('User not found')\n    }\n    if(!await bcrypt.compare(body.password, user.user_password)) {\n        throw new BadRequestException('Password incorrect');\n    }\n    const frontendDomain = this.configService.get<string>('FRONTEND_DOMAIN');\n    const jwtToken = await this.jwtService.signAsync({id: user.user_id});\n    response.cookie('jwt', jwtToken, {httpOnly: true, domain: frontendDomain,});\n\n    return {'jwt': jwtToken}\n}\n```\n\n```text\nFRONTEND_URL = http://localhost:3333\nFRONTEND_DOMAIN = localhost\n```\n\n```text\nasync refresh(@Res({ passthrough: true }) res: FastifyReply): Promise<void> {\n    const [cookieName, cookieToken] = ['refreshToken', 'someSecretToken'];\n    \n    // 1. with special method (depends on engine)\n    res.setCookie(cookieName, cookieToken, { httpOnly: true, maxAge: 60_000 });\n\n    // 2. common way\n    res.header('Set-Cookie', [`${cookieName}=${cookieToken}; HttpOnly; Secure; SameSite=None; Max-Age=60; Path=/;`, 'otherCookieAndParams...']);\n}\n```\n\n========================================\n\nComments:\n- How are you checking for the cookie? That code looks fine to me\n- I am using cookie parser and then trying to get cookies with this: - request.cookies\n- Are you setting the domain for the cookie? It looks like you aren't so it's probably defaulting to that route and only that route. How are you trying to check the cookie **on the client/caller side**?\n- I am setting domain for cookie and on the client side i don't want to access cookies. Now that i updated my Nest cli and their package this code is working fine, i can see cookie in network tab response but now I am not able to get the cookie in backend on next API calls\n- The request.cookies gives me empty object every time.\n- How are you sending the request from the client side? It sounds like the server side is doing it's job with setting the cookies, it's now an issue of *sending* the cookies from the client (browser)\n- I am using Axios in react for all the API calls, I am not sending the cookie form the front-end, I am little confused here do i need to enable flag or pass option to Axios to be able to send cookie ?\n- I just want to send whatever cookie the server is setting on client's browser back to the server so that I can use the token which is inside the cookie for Authorization in JwtAuthGuard\n- I believe Axios requires you to add `withCredentials` to add cookies to the request. If you can show the client code t would be helpful\n- Yes that exactly what I was forgetting.\n- Btw, I'd suggest returning access token and keeping it in memory on frontend while keeping refresh token in cookies.\n- Have the same issue, but this did not work for me","metadata":{"transformedAt":"2026-08-18T18:33:02.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":262,"estimatedTokens":2052}}381{"id":"stack-57909126","source":"stackoverflow","questionId":57909126,"title":"Expose normal http endpoint in NestJS Microservices","tags":["javascript","node.js","typescript","microservices","nestjs"],"text":"Title: Expose normal http endpoint in NestJS Microservices\nTags: javascript, node.js, typescript, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have this microservice written with NestJs:\n\n```\nasync function bootstrap() {\n const port = parseInt(process.env.PORT || '5000', 10);\n\n const app = await NestFactory.createMicroservice(ApplicationModule, {\n transport: Transport.TCP,\n options: { host: '0.0.0.0', port }\n });\n app.listen(() => console.log(`Microservice is listening on port ${port}`));\n}\nbootstrap();\n```\n\nBut now I need to implement an endpoint `/metrics` for Prometheus. So the question is how do I do this with NestJs microservice\n\nFrom this issue I get the impression that it is not possible. Is this true and if so, is there a workaround I can use?\n\nI tried to apply middleware as follows\n\n```\nModule({\n imports: [],\n controllers: [AppController],\n providers: [AppService, DBService],\n})\nexport class ApplicationModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(MetricsMiddleware)\n .forRoutes('/metrics') // Also tried '*'\n }\n}\n```\n\nBut when I do `curl http://localhost:5000/metrics` nothing happens, the middleware is not called\n\n```\n@Injectable()\nexport class MetricsMiddleware implements NestMiddleware {\n constructor() {}\n\n use(req, res, next) {\n console.log('yes');\n next();\n }\n}\n```\n\nUpdate: This issue will also not help :(\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const port = parseInt(process.env.PORT || '5000', 10);\n\n  const app = await NestFactory.createMicroservice(ApplicationModule, {\n    transport: Transport.TCP,\n    options: { host: '0.0.0.0', port }\n  });\n  app.listen(() => console.log(`Microservice is listening on port ${port}`));\n}\nbootstrap();\n```\n\n```text\nModule({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService, DBService],\n})\nexport class ApplicationModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(MetricsMiddleware)\n      .forRoutes('/metrics') // Also tried '*'\n  }\n}\n```\n\n```text\n@Injectable()\nexport class MetricsMiddleware implements NestMiddleware {\n    constructor() {}\n\n    use(req, res, next) {\n        console.log('yes');\n        next();\n    }\n}\n```\n\n```text\n/metrics\n```\n\n```text\ncurl http://localhost:5000/metrics\n```\n\n```text\n// Create your regular nest application.\nconst app = await NestFactory.create(ApplicationModule);\n\n// Then combine it with your microservice\nconst microservice = app.connectMicroservice({\n  transport: Transport.TCP,\n  options: { host: '0.0.0.0', port: 5000 }\n});\n\nawait app.startAllMicroservices();\nawait app.listen(3001);\n```\n\n========================================\n\nComments:\n- What if I want all my microservices to be able to support http requests, but also be able to communicate with each other. Is this possible?\n- @Shirohige Have a look at this thread: stackoverflow.com/a/53996635/4694994\n- Wait, this already is a hybrid application... What do you mean? They can all communicate with each other either via the \"microservice protocol\" or http.\n- So I'm trying to expose endpoints to my web application from multiple microservices. For example, if I do a GET request on /users, it will hit an endpoint from the Users service, and if I do a GET requests on /notifications, it will hit an endpoint from the Notifications service. With the hybrid application, it seems to me that only the 'main' app that connects all microservices is able to expose endpoints and connect to the other microservices, or should all other microservices also be instantiated with the hybrid approach?\n- @Shirohige But are you using any other transport protocol besides your http requests? If not, simply create all your microservices as regular applications. Only if you want to use an additional transport protocol besides http you need to create a hybrid application.\n- It's rather hard to understand your requirements in the limited space of a comment. Maybe consider opening a new question.\n- I'm new to NestJS and microservices overall. I will go with your suggestion and just create multiple regular applications, thanks very much!\n- `startAllMicroservicesAsync()` is now **deprecated**. you can use the alternative similarly: `await app.startAllMicroservices();`","metadata":{"transformedAt":"2026-08-18T18:33:02.438Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":133,"estimatedTokens":1068}}382{"id":"stack-61143316","source":"stackoverflow","questionId":61143316,"title":"NestJS/swagger: what model is the ApiExtraModel expecting as a parameter?","tags":["javascript","swagger","nestjs","openapi"],"text":"Title: NestJS/swagger: what model is the ApiExtraModel expecting as a parameter?\nTags: javascript, swagger, nestjs, openapi\nSource: Stack Overflow\n\nQuestion:\nThe `@nestjs/swagger` doc describes here that defining an extra model should be done this way:\n\n```\n@ApiExtraModels(ExtraModel)\nexport class CreateCatDto {}\n```\n\nBut what is `ExtraModel` here ? The doc is not very clear about this.\n\n========================================\n\nTop Answer:\nWorked for me, when I've set @ApiExtraModels(MyModelClass) on the top of controller.\n\nThanks for this topic and also to this comment in GitHub issue.\n\nI don't want to list all models in extraModels array in SwaggerModule.createDocument, so this is a great solution for me.\n\n========================================\n\nCode:\n```js\n@ApiExtraModels(ExtraModel)\nexport class CreateCatDto {}\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nExtraModel\n```\n\n```text\nimport { ExtraModel } from '<filename>'\n```\n\n```text\nApiExtraModels\n```\n\n```text\n@ApiExtraModels(ExtraModel)\nexport class CreateCatDto {\n\n@ApiProperty({\n  type: 'array',\n  items: {\n    oneOf: [\n      { $ref: getSchemaPath(Cat) },\n      { $ref: getSchemaPath(Dog) },\n    ],\n  },\n})\npets: Pet[];\n}\n```\n\n```text\n@ApiExtraModels(Cat)\n@ApiExtraModels(Dog)\nexport class CreateCatDto {\n\n@ApiProperty({\n  type: 'array',\n  items: {\n    oneOf: [\n      { $ref: getSchemaPath(Cat) },\n      { $ref: getSchemaPath(Dog) },\n    ],\n  },\n})\npets: Pet[];\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":360}}383{"id":"stack-52797727","source":"stackoverflow","questionId":52797727,"title":"Process of testing with TypeORM and Nestjs, and jest using mocks?","tags":["testing","tdd","nestjs","typeorm"],"text":"Title: Process of testing with TypeORM and Nestjs, and jest using mocks?\nTags: testing, tdd, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n**This question can likely be generalized to stubbing repositories in a service and how to properly test and provide coverage in the context of this question.**\n\nI am in the process of learning more about testing, but am stuck with how to properly perform testing that involves the DB. \n\nI have a User entity that defines the columns and some initial validation logic.\n\n```\nimport { IsAlphanumeric, IsEmail, MinLength } from 'class-validator';\n import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n @Entity()\n export class User {\n @PrimaryGeneratedColumn()\n public id!: number;\n\n @Column()\n public name!: string;\n\n @IsEmail()\n @Column()\n public email!: string;\n\n @MinLength(8)\n @Column()\n public password!: string;\n }\n```\n\nAnd I have a UserService that injects the Repository for the entity.\n\n```\nimport { Injectable } from '@nestjs/common';\n import { InjectRepository } from '@nestjs/typeorm';\n import { validateOrReject } from 'class-validator';\n import { Repository } from 'typeorm';\n import { CreateUserDTO } from './dto/create-user.dto';\n import { User } from './user.entity';\n\n @Injectable()\n export class UserService {\n constructor(\n @InjectRepository(User) private readonly userRepository: Repository\n ) {}\n\n public async create(dto: CreateUserDTO) {\n const user = this.userRepository.create(dto);\n await validateOrReject(user);\n await this.userRepository.save(user);\n }\n\n public async findAll(): Promise {\n return await this.userRepository.find();\n }\n\n public async findByEmail(email: string): Promise {\n return await this.userRepository.findOne({\n where: {\n email,\n },\n });\n }\n }\n```\n\nAnd here is my preliminary test so you can my train of thought...\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\n import { getRepositoryToken } from '@nestjs/typeorm';\n import { User } from './user.entity';\n import { UserService } from './user.service';\n\n const createMock = jest.fn((dto: any) => {\n return dto;\n });\n\n const saveMock = jest.fn((dto: any) => {\n return dto;\n });\n\n const MockRepository = jest.fn().mockImplementation(() => {\n return {\n create: createMock,\n save: saveMock,\n };\n });\n const mockRepository = new MockRepository();\n\n describe('UserService', () => {\n let service: UserService;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(User),\n useValue: mockRepository,\n },\n ],\n }).compile();\n service = module.get(UserService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n it('should not create invalid user', async () => {\n // ??\n });\n });\n```\n\nSo while I can make the test run and everything, I am not sure what I am actually supposed to be testing. I can obviously test that it validates on create, and for other things like findAll, I feel like I am just mocking the database? For me to properly test this, would it need to be connected to a database so I can check that the right data is returned?\n\nThe nest documents say \"we usually want to avoid any database connection\", but doesn't doing that defeat the purpose since we aren't *really* testing the functionality? Because while I can mock that the save returns a value, I am not testing for any errors that can occur with unique columns, nullable data, incrementing values to be set, etc... right?\n\n========================================\n\nTop Answer:\nWhat @AyKarsi suggest is better than nothing, but it's still a bad practice.\n\nUnit testing should mock databases and third party API calls.\n\nIntegration testing should test what has been mocked with the real database, and that part only.\n\nEnd-to-end testing is there to check that the whole app is well connected altogether.\n\nFor more details, you can read : https://martinfowler.com/articles/practical-test-pyramid.html\n\n========================================\n\nCode:\n```js\nimport { IsAlphanumeric, IsEmail, MinLength } from 'class-validator';\n    import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n    @Entity()\n    export class User {\n      @PrimaryGeneratedColumn()\n      public id!: number;\n\n      @Column()\n      public name!: string;\n\n      @IsEmail()\n      @Column()\n      public email!: string;\n\n      @MinLength(8)\n      @Column()\n      public password!: string;\n    }\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\n    import { InjectRepository } from '@nestjs/typeorm';\n    import { validateOrReject } from 'class-validator';\n    import { Repository } from 'typeorm';\n    import { CreateUserDTO } from './dto/create-user.dto';\n    import { User } from './user.entity';\n\n    @Injectable()\n    export class UserService {\n      constructor(\n        @InjectRepository(User) private readonly userRepository: Repository<User>\n      ) {}\n\n      public async create(dto: CreateUserDTO) {\n        const user = this.userRepository.create(dto);\n        await validateOrReject(user);\n        await this.userRepository.save(user);\n      }\n\n      public async findAll(): Promise<User[]> {\n        return await this.userRepository.find();\n      }\n\n      public async findByEmail(email: string): Promise<User | undefined> {\n        return await this.userRepository.findOne({\n          where: {\n            email,\n          },\n        });\n      }\n    }\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\n    import { getRepositoryToken } from '@nestjs/typeorm';\n    import { User } from './user.entity';\n    import { UserService } from './user.service';\n\n    const createMock = jest.fn((dto: any) => {\n      return dto;\n    });\n\n    const saveMock = jest.fn((dto: any) => {\n      return dto;\n    });\n\n    const MockRepository = jest.fn().mockImplementation(() => {\n      return {\n        create: createMock,\n        save: saveMock,\n      };\n    });\n    const mockRepository = new MockRepository();\n\n    describe('UserService', () => {\n      let service: UserService;\n\n      beforeAll(async () => {\n        const module: TestingModule = await Test.createTestingModule({\n          providers: [\n            UserService,\n            {\n              provide: getRepositoryToken(User),\n              useValue: mockRepository,\n            },\n          ],\n        }).compile();\n        service = module.get<UserService>(UserService);\n      });\n\n      it('should be defined', () => {\n        expect(service).toBeDefined();\n      });\n\n      it('should not create invalid user', async () => {\n        // ??\n      });\n    });\n```\n\n========================================\n\nComments:\n- \"I am not sure what I am actually supposed to be testing\", exactly, because you basically have nothing to test in your service. The only thing you could test is if your service properly call the repository methods you want it to call and with the proper parameters and for that you will use a \"spyOn\" or \"toHaveBeenCalledWith\". TypeORM is already a tested library, so you don't want to test TypeORM. Testing against a database is a functional test, not a unit test, in that case, I would reorganize your test in a End-to-End fashion, calling your API endpoint and testing the database after the call.\n- Okay thank you I really appreciate the feedback. I ended up doing something really similar. I decided to use sqljs for the test database and have TypeORM setup to drop the DB after each test and to synchronize at the start of each test. It is still really fast, and like you said simplifies things greatly. Thanks!\n- In general, there is nothing bad about testing against the database, as long it not part of the unit test. And it's actually impossible to make e2e test without hitting the database. So, all depends of the use-case, the only important part is to not mix-up all your tests together.\n- @AyKarsi How can I import real database repository into my Test module?\n- I think it's OK to test with an one-off database such as SQLite `:memory:`, demo: stackoverflow.com/a/59483875/5172890\n- @kenberkeley your development database should match your production database though","metadata":{"transformedAt":"2026-08-18T18:33:02.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":250,"estimatedTokens":2030}}384{"id":"stack-66193796","source":"stackoverflow","questionId":66193796,"title":"Using test database when e2e-testing NestJS","tags":["javascript","nestjs","e2e-testing","typeorm"],"text":"Title: Using test database when e2e-testing NestJS\nTags: javascript, nestjs, e2e-testing, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn this project, it uses NestJS along with TypeORM. For real API requests, CRUD operation is being operated on MySQL(which is using AWS RDS).\n\nNow I am trying to use SQLite(In-Memory) to test API results.\n\nI successfully implemented this in Unit Test, as the code below.\n\nFirst, below is `create-memory-db.ts`, which returns a connection to in-memory SQLite database.\n\n```\ntype Entity = Function | string | EntitySchema;\n\nexport async function createMemoryDB(entities: Entity[]) {\n return createConnection({\n type: 'sqlite',\n database: ':memory:',\n entities,\n logging: false,\n synchronize: true,\n });\n}\n```\n\n- And by using the exported function above, I successfully ran Unit test, like below.\n\n```\ndescribe('UserService Logic Test', () => {\n let userService: UserService;\n let connection: Connection;\n let userRepository: Repository;\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n\n // testing codes.\n});\n```\n\nI am trying to do the same thing on e2e tests. I tried below code.\n\n```\n// user.e2e-spec.ts\n\ndescribe('UserController (e2e)', () => {\n let userController: UserController;\n let userService: UserService;\n let userRepository: Repository;\n let connection: Connection;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n userController = new UserController(userService);\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [],\n controllers: [UserController],\n providers: [UserService],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n // await userRepository.query('DELETE FROM users');\n });\n\n it('[POST] /user : Response is OK if conditions are right', () => {\n const dto = new UserCreateDto();\n dto.name = NAME;\n dto.email = EMAIL;\n dto.password = PASSWORD;\n\n return request(app.getHttpServer())\n .post('/user')\n .send(JSON.stringify(dto))\n .expect(HttpStatus.CREATED);\n });\n});\n```\n\nI cannot create `UserModule` since it doesn't have a constructor with `Connection` parameter.\nThe code itself has no compile error, but gets results below when e2e test is executed.\n\n```\nNest can't resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index[0] is available in the RootTestModule context.\n\nPotential solutions:\n- If UserRepository is a provider, is it part of the current RootTestModule?\n- If UserRepository is exported from a seperate @Module, is that module imported within RootTestModule?\n @Module({\n imports: [/* The module containing UserRepository */]\n })\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\nAny help would be greatly appreciated. Thanks :)\n\n- UPDATE : New error occured after trying below.\n\n```\ndescribe('UserController (e2e)', () => {\n let userService: UserService;\n let userRepository: Repository;\n let connection: Connection;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [UserModule],\n })\n .overrideProvider(UserService)\n .useClass(userService)\n .compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n\n it('[POST] /user : Response is OK if conditions are right', async () => {\n const dto = new UserCreateDto();\n dto.name = NAME;\n dto.email = EMAIL;\n dto.password = PASSWORD;\n\n const result = await request(app.getHttpServer())\n .post('/user')\n .send(JSON.stringify(dto))\n .expect({ status: HttpStatus.CREATED });\n });\n});\n```\n\n- I checked if query is working, and was able to see that it is using SQLite database as I wanted. But new error appeared in console.\n\n```\nTypeError: metatype is not a constructor.\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\n========================================\n\nTop Answer:\nFor those looking for setup e2e tests that hit endpoints and assert the response body, you can do something like this:\n\n```\n// app.module.ts\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: async (configService: ConfigService) => {\n if (process.env.APPLICATION_ENV === 'test') {\n return {\n type: 'sqlite',\n database: ':memory:',\n entities: [Entity],\n synchronize: true,\n }\n }\n return {\n // your default options\n };\n },\n }),\n ]\n})\n```\n\n========================================\n\nCode:\n```text\ntype Entity = Function | string | EntitySchema<any>;\n\nexport async function createMemoryDB(entities: Entity[]) {\n  return createConnection({\n    type: 'sqlite',\n    database: ':memory:',\n    entities,\n    logging: false,\n    synchronize: true,\n  });\n}\n```\n\n```text\ndescribe('UserService Logic Test', () => {\n  let userService: UserService;\n  let connection: Connection;\n  let userRepository: Repository<User>;\n\n  beforeAll(async () => {\n    connection = await createMemoryDB([User]);\n    userRepository = await connection.getRepository(User);\n    userService = new UserService(userRepository);\n  });\n\n  afterAll(async () => {\n    await connection.close();\n  });\n\n  afterEach(async () => {\n    await userRepository.query('DELETE FROM users');\n  });\n\n  // testing codes.\n});\n```\n\n```text\n// user.e2e-spec.ts\n\ndescribe('UserController (e2e)', () => {\n  let userController: UserController;\n  let userService: UserService;\n  let userRepository: Repository<User>;\n  let connection: Connection;\n  let app: INestApplication;\n  const NAME = 'NAME';\n  const EMAIL = 'test@test.com';\n  const PASSWORD = '12345asbcd';\n\n  beforeAll(async () => {\n    connection = await createMemoryDB([User]);\n    userRepository = await connection.getRepository(User);\n    userService = new UserService(userRepository);\n    userController = new UserController(userService);\n\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [],\n      controllers: [UserController],\n      providers: [UserService],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  afterAll(async () => {\n    await connection.close();\n  });\n\n  afterEach(async () => {\n    // await userRepository.query('DELETE FROM users');\n  });\n\n  it('[POST] /user : Response is OK if conditions are right', () => {\n    const dto = new UserCreateDto();\n    dto.name = NAME;\n    dto.email = EMAIL;\n    dto.password = PASSWORD;\n\n    return request(app.getHttpServer())\n      .post('/user')\n      .send(JSON.stringify(dto))\n      .expect(HttpStatus.CREATED);\n  });\n});\n```\n\n```text\nNest can't resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index[0] is available in the RootTestModule context.\n\nPotential solutions:\n- If UserRepository is a provider, is it part of the current RootTestModule?\n- If UserRepository is exported from a seperate @Module, is that module imported within RootTestModule?\n  @Module({\n    imports: [/* The module containing UserRepository */]\n  })\n\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\n```text\ndescribe('UserController (e2e)', () => {\n  let userService: UserService;\n  let userRepository: Repository<User>;\n  let connection: Connection;\n  let app: INestApplication;\n  const NAME = 'NAME';\n  const EMAIL = 'test@test.com';\n  const PASSWORD = '12345asbcd';\n\n  beforeAll(async () => {\n    connection = await createMemoryDB([User]);\n    userRepository = await connection.getRepository(User);\n    userService = new UserService(userRepository);\n\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [UserModule],\n    })\n      .overrideProvider(UserService)\n      .useClass(userService)\n      .compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  afterAll(async () => {\n    await connection.close();\n  });\n\n  afterEach(async () => {\n    await userRepository.query('DELETE FROM users');\n  });\n\n  it('[POST] /user : Response is OK if conditions are right', async () => {\n    const dto = new UserCreateDto();\n    dto.name = NAME;\n    dto.email = EMAIL;\n    dto.password = PASSWORD;\n\n    const result = await request(app.getHttpServer())\n      .post('/user')\n      .send(JSON.stringify(dto))\n      .expect({ status: HttpStatus.CREATED });\n  });\n});\n```\n\n```text\nTypeError: metatype is not a constructor.\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\n```text\ncreate-memory-db.ts\n```\n\n```text\nUserModule\n```\n\n```text\nConnection\n```\n\n```text\ndescribe('UserController (e2e)', () => {\n  let userService: UserService;\n  let userRepository: Repository<User>;\n  let app: INestApplication;\n  const NAME = 'NAME';\n  const EMAIL = 'test@test.com';\n  const PASSWORD = '12345asbcd';\n\n  beforeAll(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [\n        UserModule,\n        TypeOrmModule.forRoot({\n          type: 'sqlite',\n          database: ':memory:',\n          entities: [User],\n          logging: true,\n          synchronize: true,\n        }),\n      ],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n    userRepository = moduleFixture.get('UserRepository');\n    userService = new UserService(userRepository);\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n\n  afterEach(async () => {\n    await userRepository.query('DELETE FROM users');\n  });\n});\n```\n\n```text\nTypeOrm.forRoot()\n```\n\n```text\nTest.createTestingModule\n```\n\n```text\n// app.module.ts\n@Module({\n  imports: [\n    TypeOrmModule.forRootAsync({\n      useFactory: async (configService: ConfigService) => {\n        if (process.env.APPLICATION_ENV === 'test') {\n          return {\n            type: 'sqlite',\n            database: ':memory:',\n            entities: [Entity],\n            synchronize: true,\n          }\n        }\n        return {\n          // your default options\n        };\n      },\n    }),\n  ]\n})\n```\n\n========================================\n\nComments:\n- This is really helpful to me! Thanks for your own answer.\n- @CasimirCrystal My pleasure :)","metadata":{"transformedAt":"2026-08-18T18:33:02.438Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":457,"estimatedTokens":2733}}385{"id":"stack-60530110","source":"stackoverflow","questionId":60530110,"title":"How to implement Passport.js Azure AD Bearer Strategy ( OpenID ) in NestJS","tags":["azure-active-directory","passport.js","nestjs"],"text":"Title: How to implement Passport.js Azure AD Bearer Strategy ( OpenID ) in NestJS\nTags: azure-active-directory, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nFollowing the documentation for nestjs and passport I have the following implementation.\n\nI started with the default nest cli setup, nest new auth-test I then added an auth folder under the src folder where the aad-auth.gaurd, aad.strategy and auth.module below sit.\n\nI then added the new guard to the default route in the app.controller.ts\n\nI confirmed the Azure App Registration setup by using it successfully as a C# Web API, so the Azure side is setup correctly.\n\nI don't need to issue a JWT as that is issues in the front end by Azure AD, that bearer token is passed to the API in the header. There are no helpful errors, simply a 500 Internal Error. I notice a lot of Github requests for documentation on implementing Azure AD with nest, along with any OAuth flow provider (facebook, google) but as yet that request is still open.\n\nNot sure what is implemented wrong, any guidance or suggestions would be appreciated on fixing the below code.\n\nDocumentation:\nNestJS : https://docs.nestjs.com/techniques/authentication\nPassport : http://www.passportjs.org/packages/passport-azure-ad/\n\n//auth/aad.strategy.ts\n\n```\nimport { BearerStrategy } from 'passport-azure-ad';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, ValidationPipe } from '@nestjs/common';\n\n@Injectable() \nexport class AADStrategy extends PassportStrategy(BearerStrategy) {\n constructor () {\n super({\n identityMetadata: \"https://login.microsoftonline.com/.onmicrosoft.com/v2.0/.well-known/openid-configuration\",\n clientID: \"\",\n issuer: null,\n audience: null,\n loggingLevel: \"info\",\n passReqToCallback: false\n })\n }\n\n async validate(payload: any){\n console.log(payload);\n return(payload); \n }\n}\n```\n\n//auth/aad-auth.gaurd\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class AADAuthGaurd extends AuthGuard('aad') {}\n```\n\n//auth/auth.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { AADStrategy } from './aad.strategy'\n\n@Module({\n imports: [\n AADStrategy,\n ],\n providers: [\n AADStrategy,\n ]\n})\nexport class AuthModule {}\n```\n\n//app.controller.ts\n\n```\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { AADAuthGaurd } from './auth/aad-auth.gaurd';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @UseGuards(AADAuthGaurd)\n @Get()\n getHello(): string {\n return this.appService.getHello();\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { BearerStrategy } from 'passport-azure-ad';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, ValidationPipe } from '@nestjs/common';\n\n@Injectable() \nexport class AADStrategy extends PassportStrategy(BearerStrategy) {\n    constructor () {\n        super({\n            identityMetadata: \"https://login.microsoftonline.com/<tenant>.onmicrosoft.com/v2.0/.well-known/openid-configuration\",\n            clientID: \"<clientid>\",\n            issuer: null,\n            audience: null,\n            loggingLevel: \"info\",\n            passReqToCallback: false\n        })\n    }\n\n    async validate(payload: any){\n        console.log(payload);\n        return(payload);    \n    }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class AADAuthGaurd extends AuthGuard('aad') {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AADStrategy } from './aad.strategy'\n\n@Module({\n    imports: [\n        AADStrategy,\n    ],\n    providers: [\n        AADStrategy,\n    ]\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { AADAuthGaurd } from './auth/aad-auth.gaurd';\n\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @UseGuards(AADAuthGaurd)\n  @Get()\n  getHello(): string {\n    return this.appService.getHello();\n  }\n}\n```\n\n```text\n//app.controller.ts\n```\n\n```text\nimport { Controller, Get, Injectable, UseGuards } from '@nestjs/common';\n    import { AppService } from './app.service';\n    import { AuthGuard, PassportStrategy } from \"@nestjs/passport\";\n    import { BearerStrategy } from 'passport-azure-ad'\n    \n    @Injectable()\n    export class AzureADStrategy extends PassportStrategy(BearerStrategy, 'oauth-bearer')\n    {\n      constructor()\n      {\n        super({\n          identityMetadata: `https://login.microsoftonline.com/<tenant>.onmicrosoft.com/.well-known/openid-configuration`,\n          clientID: 'client id from azure app',\n        })\n      }\n    \n      async validate(response: any)\n      {\n        const { unique_name }: {unique_name: string} = response;\n        if (unique_name) return unique_name;\n        else return null;\n      }\n    }\n    \n    @Controller()\n    export class AppController {\n      constructor() {}\n    \n      @Get('unprotected')\n      unprotected() : string {\n        return 'Unprotected';\n      }\n    \n      @UseGuards(AuthGuard('oauth-bearer'))\n      @Get('protected')\n      protected() : string {\n        return 'Protected';\n      }\n    }\n```\n\n========================================\n\nComments:\n- Hi, I have a similar issue but I can't make it work, Do you have a simple stater project with the minimum config to make it work properly? I'm trying to implement B2C which makes it more complex. Any kind of help will be really appreciated !\n- If you are using Azure AD B2C you need to do a different input such as: super({ identityMetadata: `https:&#47;&#47;login.microsoftonline.com&#47;{tenantName}.onmicrosoft.c&zwnj;&#8203;om&#47;B2C_1_SIGNIN&#47;v2.0&zwnj;&#8203;&#47;.well-known&#47;openid-&zwnj;&#8203;configuration`, clientID: 'your b2c apps clientid goes here', isB2C: true, policyName: 'B2C_1_SIGNIN', //Replace with your user_flow or custom_policy name validateIssuer: false //Don't do this for production :) }) Was extra painful to get to work until I discovered this for my situation.","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":214,"estimatedTokens":1554}}386{"id":"stack-56193832","source":"stackoverflow","questionId":56193832,"title":"Expecting specific error when writing unit tests in jest","tags":["unit-testing","exception","jestjs","nestjs"],"text":"Title: Expecting specific error when writing unit tests in jest\nTags: unit-testing, exception, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use nestjs (6.5.0) and jest (24.8) and have a method that throws an error:\n\n```\npublic async doSomething(): Promise {\n throw new BadRequestException({ data: '', error: 'foo' });\n }\n```\n\nHow can I write a unit test that checks that we get the expected exception with the expected data? The obvious solution is:\n\n```\nit('test', async () => {\n expect(await userController.doSomething())\n .rejects.toThrowError(new BadRequestException({ data: '', error: 'foo'});\n});\n```\n\nbut that doesn't work because `new BadRequestException()` creates an object with a different call stack. How can I test this?\n\n========================================\n\nTop Answer:\nCompared to examples in jest documentation, you may have 2 problems here.\n\n- `await` should be outside the `expect` argument\n\n- `rejects` implies an error was thrown, so you test for equality\n\nSomething like:\n\n```\nit('test', async () => {\n await expect(userController.doSomething())\n .rejects.toEqual(new BadRequestException({ data: '', error: 'foo'});\n});\n```\n\n========================================\n\nCode:\n```js\npublic async doSomething(): Promise<{ data: string, error?: string }> {\n    throw new BadRequestException({ data: '', error: 'foo' });\n  }\n```\n\n```js\nit('test', async () => {\n  expect(await userController.doSomething())\n    .rejects.toThrowError(new BadRequestException({ data: '', error: 'foo'});\n});\n```\n\n```text\nnew BadRequestException()\n```\n\n```js\nit('test', async () => {\n  await expect(userController.doSomething()).rejects.toContainException(\n    new BadRequestException({ data: '', error: 'foo' }),\n  );\n});\n```\n\n```js\nimport { HttpException } from '@nestjs/common';\n\n// ensure this is parsed as a module.\nexport {};\n\n// https://stackoverflow.com/questions/43667085/extending-third-party-module-that-is-globally-exposed\n\ndeclare global {\n  namespace jest {\n    interface Matchers<R> {\n      toContainException: (expected: R | any) => {};\n    }\n  }\n}\n\n// this will extend the expect with a custom matcher\nexpect.extend({\n  toContainException<T extends HttpException>(received: T, expected: T) {\n    const success =\n      this.equals(received.message, expected.message) &&\n      this.equals(received.getStatus(), expected.getStatus());\n\n    const not = success ? ' not' : '';\n    return {\n      message: () =>\n        `expected Exception ${received.name}${not} to be ${expected.name}` +\n        '\\n\\n' +\n        `Expected: ${this.utils.printExpected(expected.message)}, ` +\n        `status: ${this.utils.printExpected(expected.getStatus())} \\n` +\n        `Received: ${this.utils.printReceived(received.message)}, ` +\n        `status: ${this.utils.printReceived(received.getStatus())}`,\n      pass: success,\n    };\n  },\n});\n```\n\n```js\nit('test', async () => {\n  await expect(userController.doSomething())\n    .rejects.toEqual(new BadRequestException({ data: '', error: 'foo'});\n});\n```\n\n```text\nawait\n```\n\n```text\nexpect\n```\n\n```text\nrejects\n```\n\n```text\nawait expect(something).resolves.toThrowError(\n      new Error('No message for signing.'),\n    );\n```\n\n```text\nit('test', async () => {\n  await expect(userController.doSomething())\n    .rejects.toThrow(new BadRequestException({ data: '', error: 'foo'});\n});\n```\n\n========================================\n\nComments:\n- Not being familiar with javascript, this may be a stupid question, but: Ignoring for a moment that you are writing tests - where would, in the production code, the exception be caught?\n- In production code exceptions are all handled by nestjs and eventually the browser.\n- Did you found solution?\n- @nilesh-suryavanshi Yes, see the accepted answer below.\n- ah, yes, you're right that `await` should be outside and I should test for equality with `rejects`. However, that doesn't solve the main problem: `new BadRequestException` creates a new object with a different call stack than the one in `doSomething`.\n- If you want to test the exact error message, then you should use `message` instead of `error` for BadRequestException object.\n- Why did this answer got downvoted? Why is it not useful? At least it works. There might be a better solution, but I don't see any other answers or comments that would show them.","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":150,"estimatedTokens":1076}}387{"id":"stack-77804479","source":"stackoverflow","questionId":77804479,"title":"Decorators are not valid here, biome(parse)","tags":["typescript","nestjs","biomejs"],"text":"Title: Decorators are not valid here, biome(parse)\nTags: typescript, nestjs, biomejs\nSource: Stack Overflow\n\nQuestion:\nThe default biomejs configuration (or linting rule) raises an error on every decorator defined in NestJS resolvers:\n\n```\nDecorators are not valid here. biome(parse)\n```\n\nHow to ignore this rule globally?\n\n========================================\n\nTop Answer:\nSetting the rule `unsafeParameterDecoratorsEnabled` to true works to prevent the errors when running biome through the CLI, but they still show up when using the plugin. I haven't found a solution for that.\n\n```\n\"javascript\": {\n \"parser\": {\n \"unsafeParameterDecoratorsEnabled\": true\n }\n},\n```\n\n========================================\n\nCode:\n```text\nDecorators are not valid here. biome(parse)\n```\n\n```json\n\"javascript\": {\n        \"parser\": {\n            \"unsafeParameterDecoratorsEnabled\": true\n        }\n    },\n```\n\n```text\n\"javascript\": {\n    \"parser\": {\n        \"unsafeParameterDecoratorsEnabled\": true\n    }\n},\n```\n\n```text\nunsafeParameterDecoratorsEnabled\n```\n\n========================================\n\nComments:\n- In the VS Code extension, I have found that setting `\"biome.requireConfiguration\": true` will force the plugin to respect the workspace biome.json. Otherwise it does seem to always use some default config. Of course, this means that in locations without a valid biome.json, the linting will be disabled completely.","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":57,"estimatedTokens":354}}388{"id":"stack-59107360","source":"stackoverflow","questionId":59107360,"title":"Is there a way to auto create a databse in typeORM?","tags":["node.js","nestjs","typeorm"],"text":"Title: Is there a way to auto create a databse in typeORM?\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am migrating from sequelizeORM to typeORM. In sequelize-cli there are nice commands to drop database and create a new one for example:\n\n```\nnode_modules/.bin/sequelize db:drop\nnode_modules/.bin/sequelize db:create\nnode_modules/.bin/sequelize db:migrate\n```\n\nOk, for typeORM I know how to run migration but I can't find anywhere how to automatically create or drop a database. Tnx in advance.\n\n========================================\n\nTop Answer:\nyou can use the CLI tool `typeorm schema:drop` or if you want to drop and recreate the database on each startup, you can use\n\n```\n{\n...\n dropSchema: true,\n... \n \"migrations\": [\n \"dist/migrations/**/*.js\"\n ]\n}\n```\n\nwhere you do your connection options and set migrations path, and so forth.\n\n========================================\n\nCode:\n```text\nnode_modules/.bin/sequelize db:drop\nnode_modules/.bin/sequelize db:create\nnode_modules/.bin/sequelize db:migrate\n```\n\n```js\nimport {createDatabase} from \"typeorm-extension\";\n\n(async () => {\n    await createDatabase({ifNotExist: true});\n   \n    await dropDatabase({ifExist: true});\n\n    process.exit(0);\n})();\n```\n\n```js\ncreateDatabase({ifNotExist: true, characterSet: \"UTF8\"});\n```\n\n```js\ncreateDatabase({ifNotExist: true, charset: \"utf8mb4_general_ci\", characterSet: \"utf8mb4\"});\n```\n\n```text\ncreate\n```\n\n```text\ndrop\n```\n\n```text\ncharset\n```\n\n```text\ncharacterSet\n```\n\n```text\ncharset\n```\n\n```text\ncharacterSet\n```\n\n```text\ncreateDatabase()\n```\n\n```text\n{\n...\n  dropSchema: true,\n...  \n  \"migrations\": [\n    \"dist/migrations/**/*.js\"\n  ]\n}\n```\n\n```text\ntypeorm schema:drop\n```\n\n========================================\n\nComments:\n- Be careful not to use it on the production environment!!!\n- Production environments should always be handled with care ๐Ÿ™ˆ๐Ÿ™†โ€โ™‚๏ธ Although if you have seeds and โ€œrunMigrations: trueโ€ you might be able to get away with it, depending on circumstances\n- does it really answer the question? What is the way to create database?\n- @ะ ะพะผะฐะฝะกะพะปัะฝะธะบ Setting 'dropSchema: true' drops the database when the application is started, after which the database specified with entities and migrations (given that runMigrations is set to true) is created. So in effect it's a sort of \"drop and recreate\".\n- Be careful about using this library on production, any unwanted changes in the library can wipe out your database!","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":113,"estimatedTokens":613}}389{"id":"stack-65655181","source":"stackoverflow","questionId":65655181,"title":"Extends the Request interface to add a fixed user property and extend any other class","tags":["nestjs","nestjs-passport"],"text":"Title: Extends the Request interface to add a fixed user property and extend any other class\nTags: nestjs, nestjs-passport\nSource: Stack Overflow\n\nQuestion:\nI'm doing a server-side application with NestJS and TypeScript in combination with the implementation of Passport JWT.\n\n**A little bit of context first:**\n\nMy JwtStrategy *(no issues here)*:\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private userService: UserService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: 'hi',\n });\n }\n\n async validate(payload: IJwtClaims): Promise {\n const { sub: id } = payload;\n\n // Find the user's database record by its \"id\" and return it.\n const user = await this.userService.findById(id);\n\n if (!user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\nAccording to the documentation about the `validate()` method:\n\nPassport will build a user object based on the return value of our\nvalidate() method, and attach it as a property on the Request object.\n\nThanks to this behavior, I can access the `user` object in my handler like this:\n\n```\n@Get('hi')\n example(@Req() request: Request) {\n const userId = (request.user as UserEntity).id;\n }\n```\n\nDid you notice that I have used a Type Assertion (tells the compiler to consider the user object as UserEntity) ? Without it, I won't have auto-completion about my entity's properties.\n\nAs a quick solution, I have created a class that extends the `Request` interface and include my own property of type `UserEntity`.\n\n```\nimport { Request } from 'express';\nimport { UserEntity } from 'entities/user.entity';\n\nexport class WithUserEntityRequestDto extends Request {\n user: UserEntity;\n}\n```\n\nNow, my handler will be:\n\n```\n@Get('hi')\n example(@Req() request: WithUserEntityRequestDto) {\n const userId = request.user.id; // Nicer\n }\n```\n\n**The real issue now:**\n\nI have (and will have more) a handler that will receive a payload, let's call it for this example `PasswordResetRequestDto`.\n\n```\nexport class PasswordResetRequestDto {\n currentPassword: string;\n newPassword: string;\n}\n```\n\nThe handler will be:\n\n```\n@Get('password-reset')\n resetPassword(@Body() request: PasswordResetRequestDto) {\n }\n```\n\nNow, I don't have access to the user's object. I would like to access it to know who is the user that is making this request.\n\n**What I have tried:**\n\nUse TypeScript Generics and add a new property to my previous `WithUserEntityRequestDto` class like this:\n\n```\nexport class WithUserEntityRequestDto extends Request {\n user: UserEntity;\n newProp: T;\n}\n```\n\nAnd the handler will be:\n\n```\n@Get('password-reset')\n resetPassword(@Req() request: WithUserEntityRequestDto) {\n }\n```\n\nBut now the `PasswordResetRequestDto` will be under `newProp`, making it not a scalable solution. Any type that I pass as the generic will be under `newProp`. Also, I cannot extends `T` because a class cannot extends two classes. I don't see myself doing classes like this all the time.\n\n**What I expect to accomplish:**\n\nPass a type to my `WithUserEntityRequestDto` class to include the passed type properties and also the user object by default. A way that I can do for example:\n\n```\nrequest: WithUserEntityRequestDto\nrequest: WithUserEntityRequestDto\n```\n\nAnd the value will be something like:\n\n```\n{\n user: UserEntity, // As default, always present\n // all the properties of the passed type (T),\n // all the properties of the Request interface\n}\n```\n\nMy goal is to find an easy and scalable way to extends the `Request` interface and include any type/class on it, while having the user object (`UserEntity`) always present.\n\nThanks for the time and any help/advice/approach will be appreciated.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private userService: UserService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: 'hi',\n    });\n  }\n\n  async validate(payload: IJwtClaims): Promise<UserEntity> {\n    const { sub: id } = payload;\n\n    // Find the user's database record by its \"id\" and return it.\n    const user = await this.userService.findById(id);\n\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n\n    return user;\n  }\n}\n```\n\n```text\n@Get('hi')\n  example(@Req() request: Request) {\n    const userId = (request.user as UserEntity).id;\n  }\n```\n\n```text\nimport { Request } from 'express';\nimport { UserEntity } from 'entities/user.entity';\n\nexport class WithUserEntityRequestDto extends Request {\n  user: UserEntity;\n}\n```\n\n```text\n@Get('hi')\n  example(@Req() request: WithUserEntityRequestDto) {\n    const userId = request.user.id; // Nicer\n  }\n```\n\n```text\nexport class PasswordResetRequestDto {\n  currentPassword: string;\n  newPassword: string;\n}\n```\n\n```text\n@Get('password-reset')\n  resetPassword(@Body() request: PasswordResetRequestDto) {\n  }\n```\n\n```text\nexport class WithUserEntityRequestDto<T> extends Request {\n  user: UserEntity;\n  newProp: T;\n}\n```\n\n```text\n@Get('password-reset')\n  resetPassword(@Req() request: WithUserEntityRequestDto<PasswordResetRequestDto>) {\n  }\n```\n\n```text\nrequest: WithUserEntityRequestDto<AwesomeRequestDto>\nrequest: WithUserEntityRequestDto<BankRequestDto>\n```\n\n```text\n{\n   user: UserEntity, // As default, always present\n   // all the properties of the passed type (T),\n   // all the properties of the Request interface\n}\n```\n\n```text\nvalidate()\n```\n\n```text\nuser\n```\n\n```text\nRequest\n```\n\n```text\nUserEntity\n```\n\n```text\nPasswordResetRequestDto\n```\n\n```text\nWithUserEntityRequestDto\n```\n\n```text\nPasswordResetRequestDto\n```\n\n```text\nnewProp\n```\n\n```text\nnewProp\n```\n\n```text\nT\n```\n\n```text\nWithUserEntityRequestDto\n```\n\n```text\nRequest\n```\n\n```text\nUserEntity\n```\n\n```js\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n    \n    export const User = createParamDecorator(\n      (data: unknown, ctx: ExecutionContext) => {\n        const request = ctx.switchToHttp().getRequest();\n        return request.user;\n      },\n    );\n```\n\n```js\n@Get('hi')\n      example(@Req() request: Request,@User() user: UserEntity) {\n        const userId = user.id; \n      }\n```\n\n========================================\n\nComments:\n- Totally forgot about that possibility, thanks a lot, it's working nicely.","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":301,"estimatedTokens":1586}}390{"id":"stack-63978639","source":"stackoverflow","questionId":63978639,"title":"NestJs/swagger: Define ref schemas without DTO classes","tags":["nestjs","nestjs-swagger"],"text":"Title: NestJs/swagger: Define ref schemas without DTO classes\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI have an app where I define the API response schemas as plain javascript objects according to the open-api spec. Currently I am passing that to the `ApiResponse` decorator in @nestjs/swagger as follows:\n\n```\nclass CatsController {\n\n @Get()\n @ApiResponse({\n status: 200,\n schema: catSchema // plain js object imported from another file\n })\n getAll() {}\n}\n```\n\nThis is working great. However, the output open-api spec contains the verbose schema for every endpoint which uses the `catSchema`. **Instead, I want the output swagger file to have the catSchema under the `components` section, and have a corresponding `$ref` in the paths section.**\n\n```\ncomponents:\n schemas:\n Cat:\n properties:\n name:\n type: string\npaths:\n /cats/{id}:\n get:\n responses:\n '200':\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/Cat'\n```\n\nSo far, it seems the only way to do that would be to define the schema as a DTO class and use the `ApiProperty` decorator for each class property. In my case, that means I have to refactor all the plain object schemas in open-api spec to be DTO classes.\n\nIs there a way to feed the raw schema to the library and get the expected outcome?\n\n```\n// instead of this:\nclass CatDto {\n @ApiProperty()\n name: string;\n}\n\n// I want to do:\nconst catSchema = {\n type: 'object',\n properties: {\n name: { type: 'string' }\n }\n}\n```\n\n========================================\n\nTop Answer:\nI guess this can also be achieved with using `getSchemaPath` and `ApiExtraModels`:\n\n```\nimport { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';\n\n@ApiExtraModels(CatDto) // for CatDto to be found by getSchemaPath()\n@ApiResponse({\n schema: {\n '$ref': getSchemaPath(CatDto)\n }\n})\n```\n\nMore on extra models: https://docs.nestjs.com/openapi/types-and-parameters#extra-models\n\nIn my case, that means I have to refactor all the plain object schemas in open-api spec to be DTO classes.\n\nYou don't need to manually annotate objects, you can also use this plugin, which is opt-in: https://docs.nestjs.com/openapi/cli-plugin\n\n========================================\n\nCode:\n```js\nclass CatsController {\n\n  @Get()\n  @ApiResponse({\n    status: 200,\n    schema: catSchema // plain js object imported from another file\n  })\n  getAll() {}\n}\n```\n\n```yaml\ncomponents:\n  schemas:\n    Cat:\n      properties:\n        name:\n          type: string\npaths:\n  /cats/{id}:\n    get:\n      responses:\n        '200':\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Cat'\n```\n\n```js\n// instead of this:\nclass CatDto {\n  @ApiProperty()\n  name: string;\n}\n\n// I want to do:\nconst catSchema = {\n  type: 'object',\n  properties: {\n    name: { type: 'string' }\n  }\n}\n```\n\n```text\nApiResponse\n```\n\n```text\ncatSchema\n```\n\n```text\ncomponents\n```\n\n```text\n$ref\n```\n\n```text\nApiProperty\n```\n\n```js\nconst dynamicName = 'foo'; // passed as a parameter to the decorator\n\nclass IntermediateDTO {\n  @ApiProperty(schema) // schema as a plain object\n  data: any;\n}\n\nconst proxyObject = {\n  [dynamicName] = class extends IntermediateDTO {}\n}\n```\n\n```text\nclass extends IntermediateDTO {}\n```\n\n```text\nApiResponse\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\n@ApiResponse({\n    status: 200,\n    schema: {\n      example: // write the response you want here\n      [    \n        {\n          userId: 1,\n          name: 'name',\n          \n        },\n      ],\n    },\n  })\n```\n\n```js\nimport { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';\n\n@ApiExtraModels(CatDto) // for CatDto to be found by getSchemaPath()\n@ApiResponse({\n  schema: {\n    '$ref': getSchemaPath(CatDto)\n  }\n})\n```\n\n```text\ngetSchemaPath\n```\n\n```text\nApiExtraModels\n```\n\n========================================\n\nComments:\n- In short, No The reason behind this is: `@ApiProperty` is the tag by which swagger in NestJs understands the schema and it is not supported in inline schema design. Can you explain a bit more in detail on how do you want to pass the schema?\n- Thanks for the response @TanmoyBhattacharjee. I want to pass the inline schema to `@ApiResponse` directly. It works well, except it doesn't do `$ref` schemas. The output contains the schema directly under the responses section. Does that make sense?\n- Does this still work? Can you please clarify the usage in `@ApiResponse()`?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Thanks for the answer. My question is more about sticking with the plain schema json, rather than converting them to be DTO classes.","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":218,"estimatedTokens":1214}}391{"id":"stack-55598213","source":"stackoverflow","questionId":55598213,"title":"Enums not working with nestjs and graphql","tags":["typescript","enums","graphql","nestjs","typeorm"],"text":"Title: Enums not working with nestjs and graphql\nTags: typescript, enums, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have recently moved from using typegraphql and typeorm directly to using them with nestjs. Mostly this has been a straightforward experience. I however have one issue with respect to enums.\n\nI have a set of custom decorators that I have combined together so that I can easily decorate up my models without having both typeorm, typegraphql and class validator decorators. This worked great before and works fine now in all cases other than enums.\n\nAs an example here is an @OptionalDecimal decorator:\n\n```\nimport { IsNumber } from 'class-validator'\nimport { Field, Float } from 'type-graphql'\nimport { Column } from 'typeorm'\n\nexport function OptionalDecimal() {\n const typeDecorator = IsNumber()\n const fieldDecorator = Field(type => Float, { nullable: true })\n const columnDecorator = Column('decimal', { nullable: true })\n\n return (target: any, key: string) => {\n typeDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\nMy @Enum decorator is as so:\n\n```\nimport { IsEnum } from 'class-validator'\nimport { Field } from 'type-graphql'\nimport { Column } from 'typeorm'\nimport { IEnumOptions } from './IEnumOptions'\n\nexport function Enum(\n typeFunction: (type?: any) => object,\n options: IEnumOptions = {}\n) {\n const isEnumDecorator = IsEnum(typeFunction())\n const fieldDecorator = Field(typeFunction)\n const columnDecorator = Column({\n default: options.default,\n enum: typeFunction(),\n type: 'enum',\n })\n\n return (target: any, key: string) => {\n isEnumDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\nI define my enums in separate files like so:\n\n```\nimport { registerEnumType } from 'type-graphql'\n\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\nregisterEnumType(AccountState, { name: 'AccountState' })\n```\n\nAnd is used thusly:\n\n```\n@EntityType()\nexport class Member extends VersionedEntity {\n @IdentifierNewGuid()\n public readonly id: string\n\n @Enum(type => AccountState, { default: AccountState.ACTIVE })\n public accountState: AccountState\n...\n```\n\nMy database is returning numeric ids for the enumerations and the field type in the database (mysql) is `enum`. As an example where my database is returning 1 for accountState which should be SUSPENDED I receive a graphql error:\n\n```\n\"errors\": [\n {\n \"message\": \"Expected a value of type \\\"AccountState\\\" but received: 1\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"searchMembers\",\n 0,\n \"accountState\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Expected a value of type \\\"AccountState\\\" but received: 1\",\n \" at completeLeafValue\n```\n\nSo to recap this approach worked fine with typeorm and typegraphql directly but sadly fails to work now. All the other decorators I have appear to work fine (50+) so it's just something that's up specifically with enums.\n\nThis is a major blocker for me and any help would be greatly appreciated as I am currently out of ideas.\n\nEdit - In response to Shusson, when I add the decorators manually it also does not work actually:\n\n```\n@Column({\n default: AccountState.ACTIVE,\n enum: AccountState,\n type: 'enum',\n })\n@Field(type => AccountState)\npublic accountState: AccountState\n```\n\nCheers,\nMark\n\n========================================\n\nTop Answer:\nSince this is still an issue in 2022, here is a solution I came up with that does not require you to change your integer enums to string ones with the keys exactly matching the values. You can use the `@Transform` decorator from the `class-transformer` package.\n\n```\n@ArgsType()\nexport class SomeArgs {\n @Field(() => SomeEnum, {\n nullable: true,\n defaultValue: SomeEnum.SOME_KEY,\n })\n @Transform(({ value }) => \n typeof value === 'string' ? SomeEnum[value] : value\n )\n someEnumProp?: SomeEnum = SomeEnum.SOME_KEY;\n}\n```\n\nWhere SomeEnum is like:\n\n```\nexport enum SomeEnum {\n SOME_KEY = 1, \n SOME_OTHER_KEY = 2, \n}\n\nregisterEnumType(SomeEnum, {name: 'SomeEnum'})\n```\n\n========================================\n\nCode:\n```text\nimport { IsNumber } from 'class-validator'\nimport { Field, Float } from 'type-graphql'\nimport { Column } from 'typeorm'\n\nexport function OptionalDecimal() {\n    const typeDecorator = IsNumber()\n    const fieldDecorator = Field(type => Float, { nullable: true })\n    const columnDecorator = Column('decimal', { nullable: true })\n\n    return (target: any, key: string) => {\n        typeDecorator(target, key)\n        fieldDecorator(target, key)\n        columnDecorator(target, key)\n    }\n}\n```\n\n```text\nimport { IsEnum } from 'class-validator'\nimport { Field } from 'type-graphql'\nimport { Column } from 'typeorm'\nimport { IEnumOptions } from './IEnumOptions'\n\nexport function Enum(\n    typeFunction: (type?: any) => object,\n    options: IEnumOptions = {}\n) {\n    const isEnumDecorator = IsEnum(typeFunction())\n    const fieldDecorator = Field(typeFunction)\n    const columnDecorator = Column({\n        default: options.default,\n        enum: typeFunction(),\n        type: 'enum',\n    })\n\n    return (target: any, key: string) => {\n        isEnumDecorator(target, key)\n        fieldDecorator(target, key)\n        columnDecorator(target, key)\n    }\n}\n```\n\n```text\nimport { registerEnumType } from 'type-graphql'\n\nexport enum AccountState {\n  ACTIVE,\n  SUSPENDED,\n  CLOSED,\n}\n\nregisterEnumType(AccountState, { name: 'AccountState' })\n```\n\n```text\n@EntityType()\nexport class Member extends VersionedEntity {\n  @IdentifierNewGuid()\n  public readonly id: string\n\n  @Enum(type => AccountState, { default: AccountState.ACTIVE })\n  public accountState: AccountState\n...\n```\n\n```text\n\"errors\": [\n    {\n      \"message\": \"Expected a value of type \\\"AccountState\\\" but received: 1\",\n      \"locations\": [\n        {\n          \"line\": 3,\n          \"column\": 5\n        }\n      ],\n      \"path\": [\n        \"searchMembers\",\n        0,\n        \"accountState\"\n      ],\n      \"extensions\": {\n        \"code\": \"INTERNAL_SERVER_ERROR\",\n        \"exception\": {\n          \"stacktrace\": [\n            \"Error: Expected a value of type \\\"AccountState\\\" but received: 1\",\n            \"    at completeLeafValue\n```\n\n```text\n@Column({\n    default: AccountState.ACTIVE,\n    enum: AccountState,\n    type: 'enum',\n  })\n@Field(type => AccountState)\npublic accountState: AccountState\n```\n\n```text\nenum\n```\n\n```text\nexport enum AccountState {\n  ACTIVE='ACTIVE',\n  SUSPENDED='SUSPENDED',\n  CLOSED='CLOSED',\n}\n```\n\n```text\n@ArgsType()\nexport class SomeArgs {\n  @Field(() => SomeEnum, {\n    nullable: true,\n    defaultValue: SomeEnum.SOME_KEY,\n  })\n  @Transform(({ value }) => \n    typeof value === 'string' ? SomeEnum[value] : value\n  )\n  someEnumProp?: SomeEnum = SomeEnum.SOME_KEY;\n}\n```\n\n```text\nexport enum SomeEnum {\n  SOME_KEY = 1, \n  SOME_OTHER_KEY = 2, \n}\n\nregisterEnumType(SomeEnum, {name: 'SomeEnum'})\n```\n\n```text\n@Transform\n```\n\n```text\nclass-transformer\n```\n\n```text\nexport enum AccountState {\n  ACTIVE,\n  SUSPENDED,\n  CLOSED,\n}\n\n// Make to register before creating resolver\nregisterEnumType(AccountState, { name: 'AccountState' })\n\nexport const accountStateResolver: Record<keyof typeof AccountState, any> = {\n  ACTIVE: 0,\n  SUSPENDED: 1,\n  CLOSED: 2\n};\n```\n\n```text\n@Module({\n  ...\n  imports:[\n    ...\n    GraphQLModule.forRoot({\n      ...\n      resolvers: {\n        AccountState: accountStateResolver,\n      }\n    }),\n    ...\n  ]\n  ...\n})\n```\n\n```text\nexport function createGQLEnumType<T>(enumType: T): { [key: string]: string } {\n  const result = {} as { [key: string]: string }\n  for (const key in enumType) {\n    if (Object.prototype.hasOwnProperty.call(enumType, key)) {\n      const value = enumType[key as keyof T] as string\n      result[value] = value\n    }\n  }\n  return result\n}\n```\n\n```text\nconst AccountStateGQLEnum = createGQLEnumType(AccountState)\nregisterEnumType(AccountStateGQLEnum, { name: 'AccountState' })\n\n@InputType({ description: 'Sample input type' })\nexport class SampleInput {\n\n  @Field(() => AccountStateGQLEnum!)\n  accountState: AccountState\n}\n```\n\n========================================\n\nComments:\n- Have you tried replacing the custom enum decorator with the standard typeorm declaration?\n- I have updated my question, thanks for your response @shusson\n- You're awesome man.. I just missed the registerEnumType(), I was using the string Enums, however it was not working, I saw your code and BAM.... I got the hint... In my case enum with Numeric value also working.. Just declare mongoose document using interface with int enum.\n- Thanks, glad I could be of help :)\n- i'm using the @Field decorator in nestjs/graphql pkg. Tried setting the defaultValue as an array containing an enum member...graphql playground threw an error stating `\"each value in ... must be a valid enum value\"`. It was only after setting the enum member to equal its string equivalent was there no longer an error... Your solution helped solve my problem. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":371,"estimatedTokens":2250}}392{"id":"stack-60347894","source":"stackoverflow","questionId":60347894,"title":"How do you inject a service in NestJS into a typeorm repository?","tags":["typescript","nestjs","typeorm"],"text":"Title: How do you inject a service in NestJS into a typeorm repository?\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a `UserRepository` which handles creating/authenticating users infront of the database. I want to perform hashing & validation for the user's password, so I created a seperate service for that purpose, trying to single repsonsibility principle, which is declared like this:\n\n```\n@Injectable()\nexport default class HashService\n```\n\nAnd I import it in my module:\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([UserRepository])],\n controllers: [AuthController],\n providers: [AuthService, HashService],\n})\nexport class AuthModule {}\n```\n\nI wish to inject it into `UserRepository`, I tried passing in it as a constructor parameter but it didn't work because it's base class already accepts 2 parameters there, so I tried injecting my service after them like so:\n\n```\n@EntityRepository(User)\nexport default class UserRepository extends Repository {\n constructor(\n entityManager: EntityManager,\n entityMetadata: EntityMetadata,\n @Inject() private readonly hashService: HashService,\n ) {\n super();\n }\n\n // Logic...\n}\n```\n\nBut `hashService` was undefined, I also tried without the `@Inject()` decorator.\nWhat would be the best way to inject `HashService` into my repository? Do I have to create a new instance of it?\n\n========================================\n\nTop Answer:\nYou can add it manually from the module service like this:\n\naskers.service.ts:\n\n```\nconstructor(\n @InjectRepository(AskersRepository)\n private repository: AskersRepository,\n private logger: LoggingService,\n) {\n this.repository.logger = logger;\n}\n```\n\naskers.repository.ts:\n\n```\nlogger: LoggingService;\n```\n\nAnd then the logger service will be available in the repository like it has been injected.\n\nHere is an article I wrote about the hacking of injecting a service with request scope into TypeORM (ยฉ to me.. - ๐Ÿ˜‰)\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport default class HashService\n```\n\n```text\n@Module({\n    imports: [TypeOrmModule.forFeature([UserRepository])],\n    controllers: [AuthController],\n    providers: [AuthService, HashService],\n})\nexport class AuthModule {}\n```\n\n```text\n@EntityRepository(User)\nexport default class UserRepository extends Repository<User> {\n    constructor(\n        entityManager: EntityManager,\n        entityMetadata: EntityMetadata,\n        @Inject() private readonly hashService: HashService,\n    ) {\n        super();\n    }\n\n    // Logic...\n}\n```\n\n```text\nUserRepository\n```\n\n```text\nUserRepository\n```\n\n```text\nhashService\n```\n\n```text\n@Inject()\n```\n\n```text\nHashService\n```\n\n```text\nRepository\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\nCustomRepository\n```\n\n```text\n@Injectable()\nexport class CatalogService {\n    constructor (\n        private readonly cacheService: CacheService,\n        public readonly catalogRepository: CatalogRepository\n    ) {\n        this.catalogRepository.cacheService = this.cacheService;\n    }\n}\n```\n\n```text\n@EntityRepository(CatalogEntity)\nexport class CatalogRepository extends Repository<CatalogEntity> {\n    cacheService: CacheService;\n    cacheExpirySeconds = 60*60;\n}\n```\n\n```text\nconstructor(\n    @InjectRepository(AskersRepository)\n    private repository: AskersRepository,\n    private logger: LoggingService,\n) {\n    this.repository.logger = logger;\n}\n```\n\n```text\nlogger: LoggingService;\n```\n\n========================================\n\nComments:\n- This implementation does the trick like DI would have thanks.\n- See the article here - medium.com/@israellev770/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.439Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":173,"estimatedTokens":901}}393{"id":"stack-49096068","source":"stackoverflow","questionId":49096068,"title":"Upload file using nestjs and multer","tags":["nestjs"],"text":"Title: Upload file using nestjs and multer\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nSince nestjs is an express app, it's possible to use any library to handle upload using nest, and since it provides Midlewares, it's also possible to use multer. My question is: What's the best way to handle file uploads using nestjs?\n\n========================================\n\nTop Answer:\nA cleaner way would be to extract the configurations to a separate file and then call it inside the interceptor method\n\n```\nimport { extname } from 'path';\nimport { existsSync, mkdirSync } from 'fs';\nimport { diskStorage } from 'multer';\nimport { v4 as uuid } from 'uuid';\nimport { HttpException, HttpStatus } from '@nestjs/common';\n\n// Multer configuration\nexport const multerConfig = {\n dest: process.env.UPLOAD_LOCATION,\n};\n\n// Multer upload options\nexport const multerOptions = {\n // Enable file size limits\n limits: {\n fileSize: +process.env.MAX_FILE_SIZE,\n },\n // Check the mimetypes to allow for upload\n fileFilter: (req: any, file: any, cb: any) => {\n if (file.mimetype.match(/\\/(jpg|jpeg|png|gif)$/)) {\n // Allow storage of file\n cb(null, true);\n } else {\n // Reject file\n cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);\n }\n },\n // Storage properties\n storage: diskStorage({\n // Destination storage path details\n destination: (req: any, file: any, cb: any) => {\n const uploadPath = multerConfig.dest;\n // Create folder if doesn't exist\n if (!existsSync(uploadPath)) {\n mkdirSync(uploadPath);\n }\n cb(null, uploadPath);\n },\n // File modification details\n filename: (req: any, file: any, cb: any) => {\n // Calling the callback passing the random name generated with the original extension name\n cb(null, `${uuid()}${extname(file.originalname)}`);\n },\n }),\n};\n```\n\nand then call it under the interceptor like so\n\n```\nimport { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'\nimport { diskStorage } from 'multer'\nimport { extname } from 'path'\nimport { multerOptions } from 'src/config/multer.config';\n...\n\n@Post('/action/upload')\n@UseInterceptors(FileInterceptor('file', multerOptions))\nasync upload( @UploadedFile() file) {\n console.log(file)\n}\n```\n\n========================================\n\nCode:\n```js\nimport { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'\n\n... \n \n@UseInterceptors(FileInterceptor('file'))\nasync upload( @UploadedFile() file) {\n  console.log(file)\n}\n```\n\n```js\nimport { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'\nimport { diskStorage } from 'multer'\nimport { extname } from 'path'\n\n...\n\n@UseInterceptors(FileInterceptor('file', {\n  storage: diskStorage({\n    destination: './uploads'\n    , filename: (req, file, cb) => {\n      // Generating a 32 random chars long string\n      const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')\n      //Calling the callback passing the random name generated with the original extension name\n      cb(null, `${randomName}${extname(file.originalname)}`)\n    }\n  })\n}))\nasync upload( @UploadedFile() file) {\n  console.log(file)\n}\n```\n\n```text\nv4.6.0\n```\n\n```text\nfile\n```\n\n```text\nbuffer\n```\n\n```text\nfile\n```\n\n```text\nfilename\n```\n\n```text\ndestination\n```\n\n```text\npath\n```\n\n```text\ndestination\n```\n\n```text\ndiskStorage\n```\n\n```text\nfilename\n```\n\n```text\ndiskStorage\n```\n\n```text\n@UploadedFiles\n```\n\n```text\nFilesInterceptor\n```\n\n```js\nimport { extname } from 'path';\nimport { existsSync, mkdirSync } from 'fs';\nimport { diskStorage } from 'multer';\nimport { v4 as uuid } from 'uuid';\nimport { HttpException, HttpStatus } from '@nestjs/common';\n\n// Multer configuration\nexport const multerConfig = {\n    dest: process.env.UPLOAD_LOCATION,\n};\n\n// Multer upload options\nexport const multerOptions = {\n    // Enable file size limits\n    limits: {\n        fileSize: +process.env.MAX_FILE_SIZE,\n    },\n    // Check the mimetypes to allow for upload\n    fileFilter: (req: any, file: any, cb: any) => {\n        if (file.mimetype.match(/\\/(jpg|jpeg|png|gif)$/)) {\n            // Allow storage of file\n            cb(null, true);\n        } else {\n            // Reject file\n            cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);\n        }\n    },\n    // Storage properties\n    storage: diskStorage({\n        // Destination storage path details\n        destination: (req: any, file: any, cb: any) => {\n            const uploadPath = multerConfig.dest;\n            // Create folder if doesn't exist\n            if (!existsSync(uploadPath)) {\n                mkdirSync(uploadPath);\n            }\n            cb(null, uploadPath);\n        },\n        // File modification details\n        filename: (req: any, file: any, cb: any) => {\n            // Calling the callback passing the random name generated with the original extension name\n            cb(null, `${uuid()}${extname(file.originalname)}`);\n        },\n    }),\n};\n```\n\n```js\nimport { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'\nimport { diskStorage } from 'multer'\nimport { extname } from 'path'\nimport { multerOptions } from 'src/config/multer.config';\n...\n\n@Post('/action/upload')\n@UseInterceptors(FileInterceptor('file', multerOptions))\nasync upload( @UploadedFile() file) {\n  console.log(file)\n}\n```\n\n```text\n@Controller()\nexport class Uploader {\n  @Post('sampleName')\n  @UseInterceptors(FileInterceptor('file'))\n  uploadFile(@UploadedFile() file) {\n  // file name selection \n    const path = `desired path`;\n    const writeStream = fs.createWriteStream(path);  \n    writeStream.write(file.buffer);\n    writeStream.end();\n    return {\n      result: [res],\n    };\n  }\n}\n```\n\n```text\nfetch('controller address', {\n          method: 'POST',\n          body: data,\n        })\n          .then((response) => response.json())\n          .then((success) => {\n            // What to do when succeed \n});\n          })\n          .catch((error) => console.log('Error in uploading file: ', error));\n```\n\n```text\nexport const storage = diskStorage({\n  destination: \"./uploads\",\n  filename: (req, file, callback) => {\n    callback(null, generateFilename(file));\n  }\n});\n\nfunction generateFilename(file) {\n  return `${Date.now()}.${extname(file.originalname)}`;\n}\n```\n\n```text\nimport {\n  Controller,\n  Post,\n  UseInterceptors,\n  UploadedFile\n} from \"@nestjs/common\";\nimport { FileInterceptor } from \"@nestjs/platform-express\";\n\nimport { diskStorage } from \"multer\";\nimport { extname } from \"path\";\nimport { storage } from \"./storage.config\"\n\n\n@Controller()\nexport class YourController {\n  @Post(\"upload\") // API path\n  @UseInterceptors(\n    FileInterceptor(\n      \"file\", // name of the field being passed\n      { storage }\n    )\n  )\n  async upload(@UploadedFile() file) {\n    return file;\n  }\n}\n```\n\n```text\nFileInterceptor\n```\n\n```text\n@nestjs/common\n```\n\n```text\n@Post(\"/blackBoardUpload\")\n  @UseInterceptors(\n    FileInterceptor('image', {\n      storage: memoryStorage(),\n\n\n\n      fileFilter: zipFileFilter,\n\n    }),\n  )\n  async uploadedFile(@UploadedFile() file) {\n    console.log(file)\n    const response = {\n      originalname: file.originalname,\n      filename: file.filename,\n    };\n    var AdmZip = require('adm-zip');\n    var zip = new AdmZip(file.buffer);\n\n    var zipEntries = zip.getEntries();\n    console.log(zipEntries.length);\n    \n    return {\n      status: HttpStatus.OK,\n      message: 'Received Zip file successfully!',\n      data: response,\n    };\n  }\n```\n\n```text\nimport { FileInterceptor } from '@nestjs/platform-express';\n```\n\n```text\nCreate a helper.ts file that rename your file and contains path\n        \n    export class Helper {\n            static customFileName(req, file, cb) {\n              const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);\n              let fileExtension = \"\";\n              if(file.mimetype.indexOf(\"jpeg\") > -1){\n                  fileExtension = \"jpg\"\n              }else if(file.mimetype.indexOf(\"png\") > -1){\n                  fileExtension = \"png\";\n              }\n              const originalName = file.originalname.split(\".\")[0];\n              cb(null, originalName + '-' + uniqueSuffix+\".\"+fileExtension);\n            }\n           \n            static destinationPath(req, file, cb) {\n              cb(null, 'uploads/')\n            }\n          }\n\ncode for controller\n\nimport { Helper } from '../service/Helper';\nimport { diskStorage } from 'multer';\nimport {FileInterceptor} from '@nestjs/platform-express'\nimport {Controller, Post, Body, UseInterceptors, UploadedFile} from '@nestjs/common'\n\n    @Post('upload')\n    @UseInterceptors(\n        FileInterceptor('picture', {\n            storage: diskStorage({\n                destination: Helper.destinationPath,\n                filename: Helper.customFileName,\n            }),\n        }),\n    )\n\n    uploadFile(@UploadedFile() file: Express.Multer.File) {\n    console.log(file);\n    }\n```\n\n```text\nimport { Controller, Post, UploadedFiles, UploadedFile, UseInterceptors } from '@nestjs/common';\nimport { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';\nimport { AppService } from './app.service';\nimport { Express } from 'express';\n\n\n@Controller('api/portal/file')\n\n\nexport class AppController {\n  constructor(private appService: AppService) {}\n\n\n  @Post('/multiple')\n  @UseInterceptors(FilesInterceptor('files'))\n  async uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>) {\n    const req = {\n      files,\n      prospectId: 1234,\n    };\n    return await this.appService.getUrls(req);\n  }\n\n\n  @Post('/single')\n  @UseInterceptors(FileInterceptor('file'))\n  async uploadFile(@UploadedFile() file: Express.Multer.File) {\n    const req = {\n      files: [file],\n      prospectId: 1234,\n    };\n    return await this.appService.getUrls(req);\n  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { FileDataReq, FileDataRes } from './dto/app.dto';\n\n@Injectable()\nexport class AppService {\n\n  async getUrls(uploadData: FileDataReq): Promise<FileDataRes> {\n    const { prospectId } = uploadData;\n    const response = { urls: [], prospectId };\n    const { files } = uploadData;\n    for (const file of files) {\n      const { originalname } = file;\n      let url = `/${prospectId}/${new Date().getTime()}_${originalname.trim().split(' ').join('_')}`;\n      response.urls.push(url);\n    }\n    return response;\n  }\n}\n```\n\n```text\nexport class FileDataReq {\n  files: any[];\n  prospectId: number;\n}\n\nexport class FileDataRes {\n  urls: string[];\n  prospectId: number;\n}\n```\n\n```text\nimport { createParamDecorator, ExecutionContext, InternalServerErrorException } from '@nestjs/common';\nimport Busboy from 'busboy';\nimport { Request } from 'express';\n\nexport const FileUpload = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext): Promise<Express.Multer.File> => {\n    const req = ctx.switchToHttp().getRequest<Request>();\n\n    return new Promise((resolve, reject) => {\n      const fileContent: any[] = [];\n      const bb = Busboy({ headers: req.headers as any });\n      let multerFile: Partial<Express.Multer.File> = {};\n\n      bb.on('file', (fieldname, file, info) => {\n        const { filename, encoding, mimeType } = info;\n\n        file.on('data', (data) => {\n          fileContent.push(data);\n        });\n\n        file.on('end', () => {\n          const buffer = Buffer.concat(fileContent);\n\n          // Simular el objeto Express.Multer.File\n          multerFile = {\n            fieldname,\n            originalname: filename,\n            encoding,\n            mimetype: mimeType,\n            buffer,\n            size: buffer.length,\n            destination: '',\n            filename,\n            path: '',\n          };\n        });\n      });\n\n      bb.on('finish', () => {\n        resolve(multerFile as Express.Multer.File);\n      });\n\n      bb.on('error', (error: any) => {\n        reject(new InternalServerErrorException('Failed to process file upload', error.message));\n      });\n\n      bb.end(req.body);\n    });\n  },\n);\n```\n\n========================================\n\nComments:\n- What is `const randomName` doing?\n- A crazy way to generate a randomic 32 charaters. You'd better use npmjs.com/package/uuid\n- @VictorIvens can you please show how to change the file name with the latest packages.. Thanks\n- how to rename the image dynamically? assume when we create a new user and we need to upload the profile image and rename the image with userId or something?\n- great solution! I liked you put all the pieces together\n- `multerConfig.dest` is undefined because `env` hasn't been loaded at the first time.\n- @DucTrungMai make sure you are loading your env files before your application boots up. To check this add this import in the beginning of your `main.ts` file `import * as dotenv from 'dotenv';` This ensures that the env is available for use before the app context is loaded.\n- Fileinterceptor(multeroptions) saves the file in the disk storage, whenever we call that request. What if there is issue in insert or update method. In that case I don't want to store the file in the disk storage. The file should be saved to disk storage only when the db insert or update method is success. How can it be done?\n- I have a problem with your solution. ``` @UseInterceptors( FileInterceptor( 'file', { storage }, ), ) ``` throw me error: `Argument type Type is not assignable to parameter type NestInterceptor | Function`\n- This methods in AWS lambda throws this Error: Invalid CEN header (bad signature)\n- If getting the error \"Namespace 'global.Express' has no exported member 'Multer'\" then replace \"Array\" with \"any\" or try to remove the error by installing Express/multer","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":524,"estimatedTokens":3432}}394{"id":"stack-54544920","source":"stackoverflow","questionId":54544920,"title":"NestJS Authentication with Auth0 via `passport-jwt`","tags":["typescript","jwt","passport.js","auth0","nestjs"],"text":"Title: NestJS Authentication with Auth0 via `passport-jwt`\nTags: typescript, jwt, passport.js, auth0, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a NestJS project that uses Auth0 for authentication, with the `passport-jwt` library (in conjunction with `@nestjs/passport`), though I am unable to get it to work. I'm not sure where I'm going wrong. I've read the docs over and over again but still can't find the problem.\n\n### Code\n\n### /src/auth/jwt.strategy.ts\n\n```\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { passportJwtSecret } from 'jwks-rsa';\nimport { xor } from 'lodash';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n secretOrKeyProvider: passportJwtSecret({\n cache: true,\n rateLimit: true,\n jwksRequestsPerMinute: 5,\n jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,\n }),\n\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n audience: 'http://localhost:3000',\n issuer: `https://${process.env.AUTH0_DOMAIN}/`,\n });\n }\n\n validate(payload: JwtPayload) {\n if (\n xor(payload.scope.split(' '), ['openid', 'profile', 'email']).length > 0\n ) {\n throw new UnauthorizedException(\n 'JWT does not possess the requires scope (`openid profile email`).',\n );\n }\n }\n}\n```\n\n### /src/auth/interfaces/jwt-payload.interface\n\n```\n/* Doesn't do much, not really relevant */\nimport { JsonObject } from '../../common/interfaces/json-object.interface';\n\nexport interface JwtPayload extends JsonObject {\n /** Issuer (who created and signed this token) */\n iss?: string;\n /** Subject (whom the token refers to) */\n sub?: string;\n /** Audience (who or what the token is intended for) */\n aud?: string[];\n /** Issued at (seconds since Unix epoch) */\n iat?: number;\n /** Expiration time (seconds since Unix epoch) */\n exp?: number;\n /** Authorization party (the party to which this token was issued) */\n azp?: string;\n /** Token scope (what the token has access to) */\n scope?: string;\n}\n```\n\n### /src/auth/auth.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { JwtStrategy } from './jwt.strategy';\nimport { PassportModule } from '@nestjs/passport';\n\n@Module({\n imports: [PassportModule.register({ defaultStrategy: 'jwt' })],\n providers: [JwtStrategy],\n exports: [JwtStrategy],\n})\nexport class AuthModule {}\n```\n\n### /src/app.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { AuthModule } from './auth/auth.module';\n\n@Module({\n imports: [AuthModule],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n### /src/app.controller.ts\n\n```\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get()\n getHello(): string {\n return this.appService.getHello();\n }\n\n @Get('protected')\n @UseGuards(AuthGuard())\n getProtected(): string {\n return 'This route is protected';\n }\n}\n```\n\nA get request to `localhost:3000/protected` **WITH** a valid bearer token results in the error `{\"statusCode\":401,\"error\":\"Unauthorized\"}`.\n\nFull source can be found at https://github.com/jajaperson/nest-auth0\n\nThanks in advance;\n\nJames Jensen\n\n========================================\n\nCode:\n```text\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { passportJwtSecret } from 'jwks-rsa';\nimport { xor } from 'lodash';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      secretOrKeyProvider: passportJwtSecret({\n        cache: true,\n        rateLimit: true,\n        jwksRequestsPerMinute: 5,\n        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,\n      }),\n\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      audience: 'http://localhost:3000',\n      issuer: `https://${process.env.AUTH0_DOMAIN}/`,\n    });\n  }\n\n  validate(payload: JwtPayload) {\n    if (\n      xor(payload.scope.split(' '), ['openid', 'profile', 'email']).length > 0\n    ) {\n      throw new UnauthorizedException(\n        'JWT does not possess the requires scope (`openid profile email`).',\n      );\n    }\n  }\n}\n```\n\n```text\n/* Doesn't do much, not really relevant */\nimport { JsonObject } from '../../common/interfaces/json-object.interface';\n\nexport interface JwtPayload extends JsonObject {\n  /** Issuer (who created and signed this token) */\n  iss?: string;\n  /** Subject (whom the token refers to) */\n  sub?: string;\n  /** Audience (who or what the token is intended for) */\n  aud?: string[];\n  /** Issued at (seconds since Unix epoch) */\n  iat?: number;\n  /** Expiration time (seconds since Unix epoch) */\n  exp?: number;\n  /** Authorization party (the party to which this token was issued) */\n  azp?: string;\n  /** Token scope (what the token has access to) */\n  scope?: string;\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { JwtStrategy } from './jwt.strategy';\nimport { PassportModule } from '@nestjs/passport';\n\n@Module({\n  imports: [PassportModule.register({ defaultStrategy: 'jwt' })],\n  providers: [JwtStrategy],\n  exports: [JwtStrategy],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { AuthModule } from './auth/auth.module';\n\n@Module({\n  imports: [AuthModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getHello(): string {\n    return this.appService.getHello();\n  }\n\n  @Get('protected')\n  @UseGuards(AuthGuard())\n  getProtected(): string {\n    return 'This route is protected';\n  }\n}\n```\n\n```text\npassport-jwt\n```\n\n```text\n@nestjs/passport\n```\n\n```text\nlocalhost:3000/protected\n```\n\n```text\n{\"statusCode\":401,\"error\":\"Unauthorized\"}\n```\n\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      secretOrKeyProvider: passportJwtSecret({\n        cache: true,\n        rateLimit: true,\n        jwksRequestsPerMinute: 5,\n        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,\n      }),\n\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      audience: 'http://localhost:3000',\n      issuer: `https://${process.env.AUTH0_DOMAIN}/`,\n    });\n  }\n\n  validate(payload: JwtPayload): JwtPayload {\n    if (\n      xor(payload.scope.split(' '), ['openid', 'profile', 'email']).length > 0\n    ) {\n      throw new UnauthorizedException(\n        'JWT does not possess the requires scope (`openid profile email`).',\n      );\n    }\n    return payload;\n  }\n}\n```\n\n```text\nUNABLE_TO_VERIFY_LEAF_SIGNATURE\n```\n\n```text\npayload\n```\n\n========================================\n\nComments:\n- Are you sure your `validate` function is getting called with the `payload`?\n- @ChauTran How would I go about doing that??? The documentation about this isn't really clear (or at least it isn't to me :) ).\n- well you put console.log in the validate method :)\n- I'll go do that, and get back to you :))\n- @ChauTran nope, it would appear not.","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":309,"estimatedTokens":1972}}395{"id":"stack-65847961","source":"stackoverflow","questionId":65847961,"title":"Is there a way to use static method with dependency injection in NestJS?","tags":["javascript","node.js","dependency-injection","nestjs"],"text":"Title: Is there a way to use static method with dependency injection in NestJS?\nTags: javascript, node.js, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nAn example is better than a long explanation:\n\n```\n// Backery.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { Backery } from './Backery.entity';\n\n@Injectable()\nexport class BackeryService {\n constructor(\n @InjectRepository(Backery)\n private readonly backeryRepository: Repository,\n ) {}\n\n static myStaticMethodToGetPrice() {\n return 1;\n }\n\n otherMethod() {\n this.backeryRepository.find();\n /* ... */\n }\n}\n```\n\n```\n// Backery.resolver.ts\nimport { Bakery } from './Bakery.entity';\nimport { BakeryService } from './Bakery.service';\n\n@Resolver(() => Bakery)\nexport class BakeryResolver {\n constructor() {}\n\n @ResolveField('price', () => Number)\n async getPrice(): Promise {\n return BakeryService.myStaticMethodToGetPrice(); // No dependency injection here :(\n }\n}\n```\n\nHow can I replace `BakeryService.myStaticMethodToGetPrice()` to use dependency injection, so I can test things easily for example?\n\n========================================\n\nTop Answer:\nThere is a very easy way to create static functions that use services from your NestJs DI.\n\nOne good example is the use for Domain Events and avoiding polluting your entities' constructors with technical services.\n\nIn your main.ts\n\n```\nlet app: INestApplication;\n\nasync function bootstrap() {\n app = await NestFactory.create(AppModule);\n\n install();\n ...\n ...\n}\n\nbootstrap();\n\nexport const getInstance = () => {\n return app;\n};\n```\n\nFrom any static context within your app:\n\n```\nimport { getInstance } from '@/main';\n\nstatic async emmitEvent() {\n let eventEmitter = await getInstance().resolve(EventEmitter2);\n eventEmitter.emit(JSON.stringify(nodeCreateEvent));\n}\n```\n\n========================================\n\nCode:\n```text\n// Backery.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { Backery } from './Backery.entity';\n\n@Injectable()\nexport class BackeryService {\n  constructor(\n    @InjectRepository(Backery)\n    private readonly backeryRepository: Repository<Backery>,\n  ) {}\n\n  static myStaticMethodToGetPrice() {\n    return 1;\n  }\n\n  otherMethod() {\n    this.backeryRepository.find();\n    /* ... */\n  }\n}\n```\n\n```text\n// Backery.resolver.ts\nimport { Bakery } from './Bakery.entity';\nimport { BakeryService } from './Bakery.service';\n\n@Resolver(() => Bakery)\nexport class BakeryResolver {\n  constructor() {}\n\n  @ResolveField('price', () => Number)\n  async getPrice(): Promise<number> {\n    return BakeryService.myStaticMethodToGetPrice(); // No dependency injection here :(\n  }\n}\n```\n\n```text\nBakeryService.myStaticMethodToGetPrice()\n```\n\n```text\n1\n```\n\n```text\nlet app: INestApplication;\n\nasync function bootstrap() {\n  app = await NestFactory.create(AppModule);\n\n  install();\n  ...\n  ...\n}\n\nbootstrap();\n\nexport const getInstance = () => {\n  return app;\n};\n```\n\n```text\nimport { getInstance } from '@/main';\n\nstatic async emmitEvent() {\n    let eventEmitter = await getInstance().resolve(EventEmitter2);\n    eventEmitter.emit(JSON.stringify(nodeCreateEvent));\n}\n```\n\n```text\nimport { GeoService } from '../geoservice/geoservice.service';\nimport { Inject } from '@nestjs/common';\n\nexport class myClass {\n    @Inject(GeoService)\n    private static geoService: GeoService;\n\n    someMethod() {\n        this.geoService...\n    }\n}\n```\n\n```text\n@Inject()\n```\n\n```text\n// app-context.ts\nimport { INestApplication, Type } from '@nestjs/common';\n\nexport class AppContext {\n  static instance: INestApplication;\n\n  // eslint-disable-next-line @typescript-eslint/ban-types\n  static tryGet<TInput = any, TResult = TInput>(typeOrToken: Type<TInput> | Function | string | symbol): TResult | null {\n    if (!AppContext.instance) return null;\n    try {\n      return AppContext.instance.get(typeOrToken);\n    } catch (err) {\n      return null;\n    }\n  }\n}\n```\n\n```text\nconst app = AppContext.instance = await NestFactory.create(AppModule, {\n  // ...\n});\n```\n\n```text\n// decorators.ts\nexport const DEPENDENCY_INJECTION_METADATA = 'self:dependency_injection';\n\nexport function StaticInject<T>(type: T): ParameterDecorator {\n  return (target: object, _key: string | symbol | undefined, index: number) => {\n    let dependencies = Reflect.getMetadata(DEPENDENCY_INJECTION_METADATA, target) || [];\n    dependencies = [...dependencies, { index, key, type }];\n    Reflect.defineMetadata(DEPENDENCY_INJECTION_METADATA, dependencies, target);\n  };\n}\n\nexport const StaticInjection: MethodDecorator = (target: object, key: string | symbol, descriptor: PropertyDescriptor) => {\n  const dependencies = Reflect.getMetadata(DEPENDENCY_INJECTION_METADATA, target) || [];\n  const originalMethod = descriptor.value;\n  descriptor.value = function(...args: unknown[]) { // do to use arrow function here! we need to keep function context\n    if (!AppContext.instance) throw new Error('AppContext is not initialized');\n    for (const { index, type } of dependencies) {\n      args[index] = AppContext.tryGet(type);\n      if (!args[index]) throw new Error(`Dependency injection failed for ${type}`);\n    }\n    return originalMethod.apply(this, args);\n  };\n};\n```\n\n```text\n@StaticInjection\n  static myMethod(otherParams: any, @StaticInject(SomeService) someService?: SomeService) {\n    return someService.something(otherParams);\n  }\n```\n\n========================================\n\nComments:\n- Is there a particular reason why you want this to be a static method? In other words why can't you just inject `BakeryService` in your `BakeryResolver` and call the price method on an instance of the service?\n- @eol the method does not use `this`, so it feels more natural to make it static as it does not depend on the object instance.\n- This code is valid, but is it the official recommandation? Or it's better to avoid static method entirely in order to use DI and ease the tesing?\n- I like to avoid static **except for ** when it comes to dynamic modules.\n- static methods can use DI if you get a reference to your nest app object. It has a \"resolve\" method that allows you to get any object by type from its DI context\n- You haven't really made Dependency injection work with static methods, you've just made the static method reference something that *can* use dependency injection. And if you were to run this static method from outside the main application, you'll get a runtime error due to the bootstrap method possibly not finishing yet. Along with that, your `main.ts` is now used for more than just starting the server, which starts to violate the single responsibility principle Nest tries to endorse.\n- It is not very clear on what exactly the OP wants to accomplish but my answer clearly allows you to access the app context from static method. And yes it may fail if you call it ,for whatever reason, outside the app running context. As for the single responsibility - we prefer having our entities clean instead of injecting, bunch of things through constructor etc.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":254,"estimatedTokens":1854}}396{"id":"stack-58239364","source":"stackoverflow","questionId":58239364,"title":"Integrate nestjs with sentry","tags":["javascript","nestjs"],"text":"Title: Integrate nestjs with sentry\nTags: javascript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to integrate sentry with nest.js + express but I just found raven version but that is deprecated.\nI the sentry docs for integrate with express but dont know how to handle the 'All controllers should live here' part.\n\n```\nconst express = require('express');\nconst app = express();\nconst Sentry = require('@sentry/node');\n\nSentry.init({ dsn: 'https://5265e36cb9104baf9b3109bb5da9423e@sentry.io/1768434' });\n\n// The request handler must be the first middleware on the app\napp.use(Sentry.Handlers.requestHandler());\n\n**// All controllers should live here\napp.get('/', function rootHandler(req, res) {\n res.end('Hello world!');\n});**\n\n// The error handler must be before any other error middleware and after all controllers\napp.use(Sentry.Handlers.errorHandler());\n\n// Optional fallthrough error handler\napp.use(function onError(err, req, res, next) {\n // The error id is attached to `res.sentry` to be returned\n // and optionally displayed to the user for support.\n res.statusCode = 500;\n res.end(res.sentry + \"\\n\");\n});\n\napp.listen(3000);\n```\n\n========================================\n\nTop Answer:\n**Deprecated**: My answer is now deprecated as Sentry evolved their SDK (since v8) and now provide a Nest.js documentation. You can still check the repository below for a complete example, or if you use a version \nI just created a Sample Project on Github to answer this question:\n\nhttps://github.com/ericjeker/nestjs-sentry-example\n\nBelow is a partial copy of the README file. Let me know if you have any questions.\n\n### Create the needed elements\n\nCreate Sentry module, service, and interceptor\n\n```\n$ nest g module sentry\n$ nest g service sentry\n$ nest g interceptor sentry/sentry\n```\n\n### SentryModule\n\nCreate the `SentryModule.forRoot()` method and add the `Sentry.init(options)` in it.\n\nCall the `SentryModule.forRoot({...})` in the `AppModule` and integrate with your preferred configuration (I use `ConfigModule` and a `.env` file).\n\nAdd the call to the Express requestHandler middleware in the `AppModule.configure()`.\n\n```\nconfigure(consumer: MiddlewareConsumer): void {\n consumer.apply(Sentry.Handlers.requestHandler()).forRoutes({\n path: '*',\n method: RequestMethod.ALL,\n });\n }\n```\n\nIt is important to use that middleware otherwise the current Hub will be global and\nyou will run into conflicts as Sentry creates a Hub by thread and Node.js is not multi-threaded.\n\n### SentryService\n\nWe want to initialize the transaction in the constructor of the service. You can\ncustomize your main transaction there.\n\nNote that because I inject the Express request, the service must be request scoped. You\ncan read more about that here.\n\n```\n@Injectable({ scope: Scope.REQUEST })\nexport class SentryService {\n constructor(@Inject(REQUEST) private request: Request) {\n // ... etc ...\n }\n}\n```\n\n### SentryInterceptor\n\nThe `SentryInterceptor` will capture the exception and finish the transaction. Please also\nnote that it must be request scoped as we inject the `SentryService`:\n\n```\n@Injectable({ scope: Scope.REQUEST })\nexport class SentryInterceptor implements NestInterceptor {\n constructor(private sentryService: SentryService) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n // ... etc ...\n }\n}\n```\n\nAs an example, I added a span. This is not necessary, but it will just make the trace nicer in the performance viewer of Sentry.\n\nYou can add more spans anywhere in your application simply by injecting the `SentryService` and calling `startChild` or by simply calling the `startChild` method of the current span.\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst app = express();\nconst Sentry = require('@sentry/node');\n\nSentry.init({ dsn: 'https://5265e36cb9104baf9b3109bb5da9423e@sentry.io/1768434' });\n\n// The request handler must be the first middleware on the app\napp.use(Sentry.Handlers.requestHandler());\n\n**// All controllers should live here\napp.get('/', function rootHandler(req, res) {\n  res.end('Hello world!');\n});**\n\n// The error handler must be before any other error middleware and after all controllers\napp.use(Sentry.Handlers.errorHandler());\n\n// Optional fallthrough error handler\napp.use(function onError(err, req, res, next) {\n  // The error id is attached to `res.sentry` to be returned\n  // and optionally displayed to the user for support.\n  res.statusCode = 500;\n  res.end(res.sentry + \"\\n\");\n});\n\napp.listen(3000);\n```\n\n```text\nasync function bootstrap() {\n  Sentry.init({ dsn: 'https://5265e36cb9104baf9b3109bb5da9423e@sentry.io/1768434' });\n  const app = await NestFactory.create(AppModule);\n  // middlewares\n  await app.listen(3000);\n}\n```\n\n```text\n@Module({\n  imports: [\n    RavenModule,...\n  ],\n  controllers: [],\n  providers: [{\n    provide: APP_INTERCEPTOR,\n    useValue: new RavenInterceptor({\n      filters: [\n        // Filter exceptions of type HttpException. Ignore those that\n        // have status code of less than 500\n        { type: HttpException, filter: (exception: HttpException) => 500 > exception.getStatus() },\n      ],\n    }),\n  }],\n})\n```\n\n```bash\n$ nest g module sentry\n$ nest g service sentry\n$ nest g interceptor sentry/sentry\n```\n\n```js\nconfigure(consumer: MiddlewareConsumer): void {\n    consumer.apply(Sentry.Handlers.requestHandler()).forRoutes({\n      path: '*',\n      method: RequestMethod.ALL,\n    });\n  }\n```\n\n```js\n@Injectable({ scope: Scope.REQUEST })\nexport class SentryService {\n  constructor(@Inject(REQUEST) private request: Request) {\n    // ... etc ...\n  }\n}\n```\n\n```js\n@Injectable({ scope: Scope.REQUEST })\nexport class SentryInterceptor implements NestInterceptor {\n  constructor(private sentryService: SentryService) {}\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    // ... etc ...\n  }\n}\n```\n\n```text\nSentryModule.forRoot()\n```\n\n```text\nSentry.init(options)\n```\n\n```text\nSentryModule.forRoot({...})\n```\n\n```text\nAppModule\n```\n\n```text\nConfigModule\n```\n\n```text\n.env\n```\n\n```text\nAppModule.configure()\n```\n\n```text\nSentryInterceptor\n```\n\n```text\nSentryService\n```\n\n```text\nSentryService\n```\n\n```text\nstartChild\n```\n\n```text\nstartChild\n```\n\n========================================\n\nComments:\n- It's not clear in your question, but for the code you've provided, does it have any problems other than not being integrated with nest.js?\n- all is fine just this part of the code is the problem app.get('/', function rootHandler(req, res) { res.end('Hello world!'); });\n- This was an incredible answer. This is the way to go with Nest 8.\n- Great work! This line is giving me problems... `return Sentry.getCurrentHub().getScope().getSpan()` Seems like the span created in the constructer just isn't available when we pull it from the service...\n- up: Updated sentry SDK broke your example. Seems like the `createTransaction` method does not return the transaction anymore... downgrading to version 6.11 fixed the issue.\n- Hey @crice1988, thanks for pointing this out. For everyone else, it's a bug on Sentry's side, Sentry already merged a fix for it, but there is a workaround documented here: github.com/getsentry/sentry-javascript/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":266,"estimatedTokens":1807}}397{"id":"stack-71489564","source":"stackoverflow","questionId":71489564,"title":"Module '\"@nestjs/config\"' has no exported member 'ConfigModule'","tags":["node.js","typescript","nestjs","backend","config"],"text":"Title: Module '\"@nestjs/config\"' has no exported member 'ConfigModule'\nTags: node.js, typescript, nestjs, backend, config\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS,I installed @nestjs/config module using the command :\n\n```\nnpm i --save @nestjs/config\n```\n\nI got this error : **Module '\"@nestjs/config\"' has no exported member 'ConfigModule'**\n\nthis is my code in app.module file :\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { AuthModule } from './auth/auth.module';\nimport { UserModule } from './user/user.module';\nimport { BookmarkModule } from './bookmark/bookmark.module';\nimport { PrismaModule } from './prisma/prisma.module';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n imports: [ConfigModule, AuthModule, UserModule, BookmarkModule, PrismaModule],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nPS : Node version : 17.6.0 / OS : Manjaro Linux\n\n========================================\n\nTop Answer:\nIf the problem persist after applying @Wahรฉb answer, try:\n\n- **on Windows**: `Shift + Ctrl + p` -> Restart TS server\n\n- **on Mac**: `Cmd + Shift + p` -> Restart TS server\n\nAfter this, you should have `ConfigModule` imported correctly.\n\n========================================\n\nCode:\n```text\nnpm i --save @nestjs/config\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { AuthModule } from './auth/auth.module';\nimport { UserModule } from './user/user.module';\nimport { BookmarkModule } from './bookmark/bookmark.module';\nimport { PrismaModule } from './prisma/prisma.module';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule, AuthModule, UserModule, BookmarkModule, PrismaModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nnpm uninstall @nestjs/config && npm install @nestjs/config\n```\n\n```text\nShift + Ctrl + p\n```\n\n```text\nCmd + Shift + p\n```\n\n```text\nConfigModule\n```\n\n========================================\n\nComments:\n- did you got that error when running `npm run build` or what?\n- I answered the quetion, you can check my answer\n- worked on fedora 39 workstation Linux\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":94,"estimatedTokens":658}}398{"id":"stack-67695710","source":"stackoverflow","questionId":67695710,"title":"Nestjs how to make extend partialtype(createDto) make nested properties of dtos inside createDto also optional","tags":["nestjs"],"text":"Title: Nestjs how to make extend partialtype(createDto) make nested properties of dtos inside createDto also optional\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have UpdateUserDto:\n\n```\nexport class UpdateUserDto extends PartialType(CreateUserDto) {\n\n}\n```\n\nCreateUserDto:\n\n```\nexport class CreateUserDto {\n @ValidateNested({ each: true })\n @IsOptional()\n Point: CreateUserPointDto;\n}\n```\n\nCreateUserPointDto:\n\n```\nexport class CreateUserPointDto{\n @IsString()\n name: string\n @IsString()\n color: string\n \n}\n```\n\nNow partial type makes all properties of CreateUserDto optional, the problem is, it doesn't create all properties of Point that is inside CreateUserDto optional.\n\nHow do I go about solving this issue?\n\nAlso another unrelated problem, any validation to Point in UpdateUser only works with `{ PartialType } from '@nestjs/mapped-types'`\n\nIf I use `import { PartialType } from '@nestjs/swagger'`, For the same code it says Point.property name/color should not exist.\n\n========================================\n\nTop Answer:\nYou can create a partial type for `CreateUserPointDto`:\n\n```\nexport class UpdateCreateUserPointDto extends PartialType(CreateUserPointDto) {}\n```\n\nAnd `UpdateUserDto` will be then:\n\n```\nexport class UpdateUserDto extends PartialType(CreateUserDto) {\n @ValidateNested({ each: true })\n @IsOptional()\n @Type(() => UpdateCreateUserPointDto)\n Point?: CreateUserPointDto;\n}\n```\n\n========================================\n\nCode:\n```text\nexport class UpdateUserDto extends PartialType(CreateUserDto) {\n\n}\n```\n\n```text\nexport class CreateUserDto {\n  @ValidateNested({ each: true })\n  @IsOptional()\n  Point: CreateUserPointDto;\n}\n```\n\n```text\nexport class CreateUserPointDto{\n  @IsString()\n  name: string\n  @IsString()\n  color: string\n  \n}\n```\n\n```text\n{ PartialType } from '@nestjs/mapped-types'\n```\n\n```text\nimport { PartialType } from '@nestjs/swagger'\n```\n\n```js\nimport { Type } from 'class-transformer';\n\nexport class CreateUserDto {\n  @ValidateNested({ each: true })\n  @IsOptional()\n\n  @Type(() => CreateUserPointDto) // -> this line\n  Point: CreateUserPointDto;\n}\n```\n\n```text\n@Type\n```\n\n```text\nclass-transformers\n```\n\n```text\nPoint\n```\n\n```text\nexport class UpdateCreateUserPointDto extends PartialType(CreateUserPointDto) {}\n```\n\n```text\nexport class UpdateUserDto extends PartialType(CreateUserDto) {\n  @ValidateNested({ each: true })\n  @IsOptional()\n  @Type(() => UpdateCreateUserPointDto)\n  Point?: CreateUserPointDto;\n}\n```\n\n```text\nCreateUserPointDto\n```\n\n```text\nUpdateUserDto\n```\n\n========================================\n\nComments:\n- Haven't coded in NestJS in a while but If I remember correctly what you said is correct, so thanks hopefully that will help others!\n- This does not work for nested Property as it still check for all the property of CreateUserPointDto","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":148,"estimatedTokens":703}}399{"id":"stack-76465393","source":"stackoverflow","questionId":76465393,"title":"Passing undefined value in WHERE condition behaves as true/matching condition in typeorm","tags":["typescript","nestjs","typeorm"],"text":"Title: Passing undefined value in WHERE condition behaves as true/matching condition in typeorm\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI discovered this strange behaviour of typeorm, which is that if the property in the condition of WHERE clause of the FIND query (find, findOne, findBy etc) is undefined, then it behaves like a true condition and returns records (first record for findOne and all records for find).\n\nI know this can be prevented using validators or an IF statement to check against undefined property, but I want to know a direct way with typeorm itself to handle it, apart from this.\n\nHere is what I am doing:\n\n```\nconst client = await this.clientRepository.findOne({\n where: {\n id: payload.clientId //undefined\n }\n });\n```\n\nI got the first record of the client table, even though the clientId was undefined.\n\n========================================\n\nCode:\n```text\nconst client = await this.clientRepository.findOne({\n        where: {\n          id: payload.clientId //undefined\n        }\n      });\n```\n\n```text\nconst client = await this.clientRepository.findOne({\n        where: {\n          id: Equal(payload.clientId)\n        }\n});\n```\n\n```text\nEqual()\n```\n\n========================================\n\nComments:\n- I think this is intended behaviour and you should not work with an id that's obligatory in first place when it's undefined or not an ID.\n- I know it can be prevented by pre-hand validation, but my question was if it can be done without any validations using Typeorm. @mechaadi answered my question.","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":49,"estimatedTokens":390}}400{"id":"stack-64678506","source":"stackoverflow","questionId":64678506,"title":"Why am I unable to connect to MongoDB using NestJS and Mongoose?","tags":["node.js","mongodb","mongoose","nestjs"],"text":"Title: Why am I unable to connect to MongoDB using NestJS and Mongoose?\nTags: node.js, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a nest.js node server and I am trying to connect mongoDB data base in the app.module, when the connection string doesn't contains the DB name - the connection to default DB \"test\" success, but when I specify the DB name- always getting \"Authentication failed\" error.\n\n[Nest] 53087 - 11/08/2023, 6:30:46 PM ERROR [MongooseModule] Unable to connect to the database. Retrying (1)...\n\n`app.module.ts`:\n\nThis works:\n\n```\nimports: [\n MongooseModule.forRoot('mongodb://admin:admin@localhost:30000'),\n ]\n```\n\nBut this specifying the DB name failed with Authentication error:\n\n```\nimports: [\n MongooseModule.forRoot('mongodb://admin:admin@localhost:30000/test'),\n ]\n```\n\nor:\n\n```\nimports: [\n MongooseModule.forRoot('mongodb://admin:admin@localhost:30000/data'),\n ]\n```\n\nUsing MongoClient directly (without nestjs) connecting successfully:\n\n```\nconst client = new MongoClient('mongodb://admin:admin@localhost:30000');\nawait client.connect();\ndb = client.db('data');\n```\n\nWhat is the issue?\n\n========================================\n\nTop Answer:\nAccording to NestJS official document, `forRoot()` method accepts the same configuration object as `mongoose.connect()` from the Mongoose package.\n\nYou can see on the documentation of mongoose.connect(), all the options that you can apply.\n\nYou may define the db name this way:\n\n```\nimports: [\n MongooseModule.forRoot('mongodb://admin:admin@localhost:30000', {\n dbName: 'custom_db_name',\n })\n]\n```\n\n========================================\n\nCode:\n```js\nimports: [\n    MongooseModule.forRoot('mongodb://admin:admin@localhost:30000'),\n  ]\n```\n\n```js\nimports: [\n    MongooseModule.forRoot('mongodb://admin:admin@localhost:30000/test'),\n  ]\n```\n\n```text\nimports: [\n    MongooseModule.forRoot('mongodb://admin:admin@localhost:30000/data'),\n  ]\n```\n\n```js\nconst client = new MongoClient('mongodb://admin:admin@localhost:30000');\nawait client.connect();\ndb = client.db('data');\n```\n\n```text\napp.module.ts\n```\n\n```text\nimports: [\n    MongooseModule.forRoot({\n       uri: 'mongodb://admin:admin@localhost:30000',\n       dbName: 'data'\n    }),\n  ]\n```\n\n```text\nimports: [\n      MongooseModule.forRoot(\n      'mongodb://user:password@localhost:27017/nestjs-tutorial?authSource=admin&readPreference=primary',\n    ),\n    customModule,\n   ],\n```\n\n```text\nimports: [\n  MongooseModule.forRoot('mongodb://admin:admin@localhost:30000', {\n    dbName: 'custom_db_name',\n  })\n]\n```\n\n```text\nforRoot()\n```\n\n```text\nmongoose.connect()\n```\n\n```js\nMongooseModule.forRoot('mongodb://127.0.0.1:27017', { dbName: 'myapp' })\n```\n\n```js\nimports: [\n    MongooseModule.forRoot('mongodb://127.0.0.1:27017', {\n      dbName: 'some_database',\n    }),\n  ],\n```\n\n```js\nMongooseModule.forRoot('mongodb://127.0.0.1:27017/some_database')\n```\n\n```text\nmongoose.connect()\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nMongooseModule.forRoot('mongodb://localhost:27017/some_database')\n```\n\n```text\nMongooseModule.forRoot('mongodb://127.0.0.1:27017/some_database')\n```\n\n```text\n127.0.0.1\n```\n\n```text\nlocalhost\n```\n\n```text\n> mongodb://root:example@localhost:27017?appName=&directConnection=true...\n```\n\n```text\nmongodb://root:example@localhost:27017?appName=xxx&directConnection=true...\n```\n\n```text\nMongooseModule\n```\n\n```text\nappName\n```\n\n========================================\n\nComments:\n- Have a look at stackoverflow.com/questions/63754742/&hellip;\n- Changing 'localhost' to '127.0.0.1' worked for me. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.440Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":192,"estimatedTokens":894}}401{"id":"stack-61830890","source":"stackoverflow","questionId":61830890,"title":"facebook-passport with NestJS","tags":["node.js","passport.js","nestjs","passport-facebook","passport-facebook-token"],"text":"Title: facebook-passport with NestJS\nTags: node.js, passport.js, nestjs, passport-facebook, passport-facebook-token\nSource: Stack Overflow\n\nQuestion:\nI have looked into both `passport-facebook` and `passport-facebook-token` integration with NestJS. The problem is that NestJS abstracts passport implementation with its own utilities such as AuthGuard.\n\nBecause of this, `ExpressJS` style implementation that's documented will not work with NestJS. This for instance is not compliant with the `@nestjs/passport` package:\n\n```\nvar FacebookTokenStrategy = require('passport-facebook-token');\n\npassport.use(new FacebookTokenStrategy({\n clientID: FACEBOOK_APP_ID,\n clientSecret: FACEBOOK_APP_SECRET\n }, function(accessToken, refreshToken, profile, done) {\n User.findOrCreate({facebookId: profile.id}, function (error, user) {\n return done(error, user);\n });\n }\n));\n```\n\nThis blog post shows one strategy for implementing `passport-facebook-token` using an unfamiliar interface that isn't compliant with `AuthGuard`. \n\n```\n@Injectable()\nexport class FacebookStrategy {\n constructor(\n private readonly userService: UserService,\n ) {\n this.init();\n }\n init() {\n use(\n new FacebookTokenStrategy(\n {\n clientID: ,\n clientSecret: ,\n fbGraphVersion: 'v3.0',\n },\n async (\n accessToken: string,\n refreshToken: string,\n profile: any,\n done: any,\n ) => {\n const user = await this.userService.findOrCreate(\n profile,\n );\n return done(null, user);\n },\n ),\n );\n }\n}\n```\n\nThe problem here is that this seems to be completely unconventional to how NestJS expects you to handle a passport strategy. It is hacked together. It could break in future NestJS updates as well. There's also no exception handling here; I have no way to capture exceptions such as `InternalOAuthError` which gets thrown by `passport-facebook-token` because of the callback nature that's being utilized. \n\nIs there a clean way to implement either one of `passport-facebook` or `passport-facebook-token` so that it'll use `@nestjs/passport`'s `validate()` method? From the documentation: For each strategy, Passport will call the verify function (implemented with the validate() method in @nestjs/passport). There should be a way to pass a `clientId`, `clientSecret` in the constructor and then put the rest of the logic into the `validate()` method.\n\nI would imagine the final result to look something similar to the following (this does not work):\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport FacebookTokenStrategy from \"passport-facebook-token\";\n\n@Injectable()\nexport class FacebookStrategy extends PassportStrategy(FacebookTokenStrategy, 'facebook')\n{\n\n constructor()\n {\n super({\n clientID : 'anid', // In my particular case, I am not interested in `callbackURL`. I am just validating an access token that the client has forwarded to the server. I just put the above to be explicit.\n\nAlso if you are curious, the code above produces an `InternalOAuthError` but I have no way of capturing the exception in the strategy to see what the real problem is because it isn't implemented correctly. I know that in this particular case the `access_token` I am passing is invalid, if I pass a valid one, the code works. With a proper implementation though I would be able to capture the exception, inspect the error, and be able to bubble up a proper exception to the user, in this case an HTTP 401.\n\n```\nInternalOAuthError: Failed to fetch user profile\n```\n\nIt seems clear that the exception is being thrown outside of the `validate()` method, and that's why our try/catch block is not capturing the `InternalOAuthError`. Handling this exception is critical for normal user experience and I am not sure what the NestJS way of handling it is in this implementation or how error handling should be done.\n\n========================================\n\nTop Answer:\nIn my case, I used to use the `passport-facebook-token` with older version of nest. To upgrade, the adjustment of the strategy was needed. I am also not interested in the callback url.\n\nThis is a working version with `passport-facebook-token` that uses nest conventions and benefits from dependency injection:\n\n```\nimport { Injectable } from '@nestjs/common'\n\nimport { PassportStrategy } from '@nestjs/passport'\nimport * as FacebookTokenStrategy from 'passport-facebook-token'\n\nimport { UserService } from '../user/user.service'\nimport { FacebookUser } from './types'\n\n@Injectable()\nexport class FacebookStrategy extends PassportStrategy(FacebookTokenStrategy, 'facebook-token') {\n constructor(private userService: UserService) {\n super({\n clientID: process.env.FB_CLIENT_ID,\n clientSecret: process.env.FB_CLIENT_SECRET,\n })\n }\n\n async validate(\n accessToken: string,\n refreshToken: string,\n profile: FacebookTokenStrategy.Profile,\n done: (err: any, user: any, info?: any) => void,\n ): Promise {\n const userToInsert: FacebookUser = {\n ...\n }\n\n try {\n const user = await this.userService.findOrCreateWithFacebook(userToInsert)\n\n return done(null, user.id) // whatever should get to your controller\n } catch (e) {\n return done('error', null)\n }\n }\n}\n```\n\nThis creates the `facebook-token` that can be used in the controller.\n\n========================================\n\nCode:\n```text\nvar FacebookTokenStrategy = require('passport-facebook-token');\n\npassport.use(new FacebookTokenStrategy({\n    clientID: FACEBOOK_APP_ID,\n    clientSecret: FACEBOOK_APP_SECRET\n  }, function(accessToken, refreshToken, profile, done) {\n    User.findOrCreate({facebookId: profile.id}, function (error, user) {\n      return done(error, user);\n    });\n  }\n));\n```\n\n```text\n@Injectable()\nexport class FacebookStrategy {\n  constructor(\n    private readonly userService: UserService,\n  ) {\n    this.init();\n  }\n  init() {\n    use(\n      new FacebookTokenStrategy(\n        {\n          clientID: <YOUR_APP_CLIENT_ID>,\n          clientSecret: <YOUR_APP_CLIENT_SECRET>,\n          fbGraphVersion: 'v3.0',\n        },\n        async (\n          accessToken: string,\n          refreshToken: string,\n          profile: any,\n          done: any,\n        ) => {\n          const user = await this.userService.findOrCreate(\n            profile,\n          );\n          return done(null, user);\n        },\n      ),\n    );\n  }\n}\n```\n\n```text\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport FacebookTokenStrategy from \"passport-facebook-token\";\n\n\n@Injectable()\nexport class FacebookStrategy extends PassportStrategy(FacebookTokenStrategy, 'facebook')\n{\n\n    constructor()\n    {\n        super({\n            clientID    : 'anid',     // <- Replace this with your client id\n            clientSecret: 'secret', // <- Replace this with your client secret\n        })\n    }\n\n\n    async validate(request: any, accessToken: string, refreshToken: string, profile: any, done: Function)\n    {\n        try\n        {\n            console.log(`hey we got a profile: `, profile);\n\n            const jwt: string = 'placeholderJWT'\n            const user = \n            {\n                jwt\n            }\n\n            done(null, user);\n        }\n        catch(err)\n        {\n            console.log(`got an error: `, err)\n            done(err, false);\n        }\n    }\n\n}\n```\n\n```text\nInternalOAuthError: Failed to fetch user profile\n```\n\n```text\npassport-facebook\n```\n\n```text\npassport-facebook-token\n```\n\n```text\nExpressJS\n```\n\n```text\n@nestjs/passport\n```\n\n```text\npassport-facebook-token\n```\n\n```text\nAuthGuard\n```\n\n```text\nInternalOAuthError\n```\n\n```text\npassport-facebook-token\n```\n\n```text\npassport-facebook\n```\n\n```text\npassport-facebook-token\n```\n\n```text\n@nestjs/passport\n```\n\n```text\nvalidate()\n```\n\n```text\nclientId\n```\n\n```text\nclientSecret\n```\n\n```text\nvalidate()\n```\n\n```text\ncallbackURL\n```\n\n```text\nInternalOAuthError\n```\n\n```text\naccess_token\n```\n\n```text\nvalidate()\n```\n\n```text\nInternalOAuthError\n```\n\n```js\nimport {\n  ExecutionContext,\n  Injectable,\n  UnauthorizedException,\n} from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  canActivate(context: ExecutionContext) {\n    // Add your custom authentication logic here\n    // for example, call super.logIn(request) to establish a session.\n    return super.canActivate(context);\n  }\n\n  handleRequest(err, user, info) {\n    // You can throw an exception based on either \"info\" or \"err\" arguments\n    if (err || !user) {\n      throw err || new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\n```text\nStrategy\n```\n\n```text\nextends PassportStrategy()\n```\n\n```text\nAuthGuard('facebook')\n```\n\n```text\nhandleRequest()\n```\n\n```text\nimport { Injectable } from '@nestjs/common'\n\nimport { PassportStrategy } from '@nestjs/passport'\nimport * as FacebookTokenStrategy from 'passport-facebook-token'\n\nimport { UserService } from '../user/user.service'\nimport { FacebookUser } from './types'\n\n@Injectable()\nexport class FacebookStrategy extends PassportStrategy(FacebookTokenStrategy, 'facebook-token') {\n  constructor(private userService: UserService) {\n    super({\n      clientID: process.env.FB_CLIENT_ID,\n      clientSecret: process.env.FB_CLIENT_SECRET,\n    })\n  }\n\n  async validate(\n    accessToken: string,\n    refreshToken: string,\n    profile: FacebookTokenStrategy.Profile,\n    done: (err: any, user: any, info?: any) => void,\n  ): Promise<any> {\n    const userToInsert: FacebookUser = {\n      ...\n    }\n\n    try {\n      const user = await this.userService.findOrCreateWithFacebook(userToInsert)\n\n      return done(null, user.id) // whatever should get to your controller\n    } catch (e) {\n      return done('error', null)\n    }\n  }\n}\n```\n\n```text\npassport-facebook-token\n```\n\n```text\npassport-facebook-token\n```\n\n```text\nfacebook-token\n```\n\n========================================\n\nComments:\n- thanks so much Jay, I am not sure how I overlooked this. it is exactly what I need.\n- Do you have any idea what type of object `err` is? it seems to be a string which is difficult to parse\n- Nope. One of the problems is passport is not a typed package, so who knows what error it is returning.\n- This answer also saved me a lot of time.. Maybe they should write it better at the documentation, i also like @randombits was like 'How did i overlook this!'\n- How would you propose it written better? It's already linkable, which means it has a header on the page. And every passport strategy is usable with Nest by creating a `Strategy` class and using the built in `AuthGuard()`.","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":412,"estimatedTokens":2624}}402{"id":"stack-60616994","source":"stackoverflow","questionId":60616994,"title":"Nestjs testing module not found","tags":["jestjs","nestjs"],"text":"Title: Nestjs testing module not found\nTags: jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI created a simple REST API using Mongdoose with Nestjs. I have in total 2 tests and they are failing.\nThe test output:\n\n FAIL src/app/auth/auth.service.spec.ts\n โ— Test suite failed to run\n\n```\nCannot find module '@shared/errors' from 'auth.service.ts'\n\n 5 | \n 6 | import { AppLogger } from '../logger/logger';\n> 7 | import { Errors } from '@shared/errors';\n | ^\n 8 | import { ILoginDto } from './dto/login.dto';\n 9 | import { ITokenDto } from './dto/auth.dto';\n 10 | import { IUser } from '@user/document/user.doc';\n\n at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)\n at Object. (auth/auth.service.ts:7:1)\n```\n\nFAIL src/app/user/user.service.spec.ts\n โ— Test suite failed to run\n\n```\nCannot find module '@shared/errors' from 'user.service.ts'\n\n 1 | import { BadRequestException, Injectable } from '@nestjs/common';\n 2 | import { InjectModel } from '@nestjs/mongoose';\n> 3 | import { Errors } from '@shared/errors';\n | ^\n 4 | import { createMultipleRandom } from '@shared/utils';\n 5 | import { Model } from 'mongoose';\n 6 | import { AppLogger } from '../logger/logger';\n\n at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)\n at Object. (user/user.service.ts:3:1)\n```\n\nTest Suites: 2 failed, 2 total\nTests: 0 total\nSnapshots: 0 total\nTime: 2.751s\nRan all test suites.\n\ntsconfig.json:\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"paths\": {\n \"@app/*\": [\"src/app/*\"],\n \"@auth/*\": [\"src/app/auth/*\"],\n \"@config/*\": [\"config/*\"],\n \"@logger/*\": [\"src/app/logger/*\"],\n \"@shared/*\": [\"src/app/shared/*\"],\n \"@user/*\": [\"src/app/user/*\"],\n }\n },\n \"include\": [\n \"src/**/*\"\n ],\n\n \"exclude\": [\"node_modules\", \"dist\"]\n}\n```\n\nauth.service.spec.ts:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AuthService } from './auth.service';\ndescribe('AuthService', () => {\n let service: AuthService;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [AuthService],\n }).compile();\n\n service = module.get(AuthService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n});\n```\n\nIn @shared/errors.ts I just export a constant variable. Since it is not a module, how should I import this in a test ? How can I solve this problem ?\n\n========================================\n\nTop Answer:\nIf you're coming from google then this can also happen if VSCode autocompletes your imports as `src/xyz/abc/service.ts` instead of `../xyz/abc/service.ts`.\n\nWhen running tests the test code won't be able to locate the correct service(s) at run-time. It needs fully relative paths without an absolute `'src/'` at the beginning.\n\n========================================\n\nCode:\n```text\nCannot find module '@shared/errors' from 'auth.service.ts'\n\n   5 | \n   6 | import { AppLogger } from '../logger/logger';\n>  7 | import { Errors } from '@shared/errors';\n     | ^\n   8 | import { ILoginDto } from './dto/login.dto';\n   9 | import { ITokenDto } from './dto/auth.dto';\n  10 | import { IUser } from '@user/document/user.doc';\n\n  at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)\n  at Object.<anonymous> (auth/auth.service.ts:7:1)\n```\n\n```text\nCannot find module '@shared/errors' from 'user.service.ts'\n\n  1 | import { BadRequestException, Injectable } from '@nestjs/common';\n  2 | import { InjectModel } from '@nestjs/mongoose';\n> 3 | import { Errors } from '@shared/errors';\n    | ^\n  4 | import { createMultipleRandom } from '@shared/utils';\n  5 | import { Model } from 'mongoose';\n  6 | import { AppLogger } from '../logger/logger';\n\n  at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)\n  at Object.<anonymous> (user/user.service.ts:3:1)\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"paths\": {\n      \"@app/*\": [\"src/app/*\"],\n      \"@auth/*\": [\"src/app/auth/*\"],\n      \"@config/*\": [\"config/*\"],\n      \"@logger/*\": [\"src/app/logger/*\"],\n      \"@shared/*\": [\"src/app/shared/*\"],\n      \"@user/*\": [\"src/app/user/*\"],\n    }\n  },\n  \"include\": [\n    \"src/**/*\"\n  ],\n\n  \"exclude\": [\"node_modules\", \"dist\"]\n}\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AuthService } from './auth.service';\ndescribe('AuthService', () => {\n  let service: AuthService;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [AuthService],\n    }).compile();\n\n    service = module.get<AuthService>(AuthService);\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n});\n```\n\n```js\n{\n  ...\n  \"moduleNameMapper\": {\n    \"^@Shared/(.)*$\": \"<rootDir>/src/app/shared/$1\"\n  }\n}\n```\n\n```text\n<rootDir>\n```\n\n```text\n.\n```\n\n```text\n./src\n```\n\n```text\n\"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"moduleNameMapper\": {\n      \"@resources\": \"<rootDir>/resources\",\n      \"@shared\": \"<rootDir>/shared\",\n      \"@email\": \"<rootDir>/email\",\n      \"@auth\": \"<rootDir>/auth\",\n      \"@config\": \"<rootDir>/config\",\n      \"@database\": \"<rootDir>/database\"\n    },\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"collectCoverageFrom\": [\n      \"**/*.(t|j)s\"\n    ],\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  }\n```\n\n```text\n\"paths\": {\n      \"@resources/*\": [\"src/resources/*\"],\n      \"@resources\": [\"src/resources\"],\n      \"@shared/*\": [\"src/shared/*\"],\n      \"@shared\": [\"src/shared\"],\n      \"@email/*\": [\"src/email/*\"],\n      \"@email\": [\"src/email\"]\n    }\n```\n\n```text\nsrc/xyz/abc/service.ts\n```\n\n```text\n../xyz/abc/service.ts\n```\n\n```text\n'src/'\n```\n\n========================================\n\nComments:\n- Thank you, that worked for me :) I am trying now to test services, which use Mongoose model, do you also have some tips for this ? I think that this docs.nestjs.com/techniques/mongodb#testing will help me\n- You'll need a mock model to manage that. You can see some examples here\n- I mocked the model like in the examples, but I have now another problem. It says, that 'DatabaseConnection' is not available in the MongooseModule context. Since I do mock, why should I need a connection though ?\n- That would lead me to believe that you still have a database connection in use in your code somewhere. Without seeing what's happening, it can't easily be answered. Sounds like some model it's fully mocked, but again, can't say for sure\n- I found the problem. Inside \"AuthService\" I injected \"UserService\", which uses the MongooseModule.forFeature(...). So the MongooseModule was missing in the test file. After I imported the module, where the MondooseModule.forRoot(..) was imported, it worked. Thanks again.\n- Link no longer works. new link here\n- In cases where the is set to \"rootDir\": \"src\", you can use this; \"^@Shared/(.*)$\": \"/src/app/shared/$1\"\n- Thanks! any way to change this behaviour in VSCode?\n- I don't use VSCode unfortunately it's far inferior to webstorm and as such I have never had this issue in webstorm. I filed this answer on behalf of a coworker who uses VSCode and had this issue.\n- I managed to change these settings: `JavaScript โ€บ Preferences: Import Module Specifier` and `TypeScript โ€บ Preferences: Import Module Specifier` to `relative`","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":281,"estimatedTokens":1960}}403{"id":"stack-52904724","source":"stackoverflow","questionId":52904724,"title":"Nest can't resolve dependencies of the USERRepository","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of the USERRepository\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThis is really an unexpected problem.\n\nWhen I type in the terminal \"npm run start\", there's an error.\n\n```\n[Nest] 40671 - 2018-10-20 17:46:37 [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms\nError: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.\n at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)\n at \n at process._tickCallback (internal/process/next_tick.js:160:7)\n at Function.Module.runMain (module.js:703:11)\n at Object. (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)\n at Module._compile (module.js:660:30)\n at Object.Module._extensions..js (module.js:671:10)\n at Module.load (module.js:573:32)\n at tryModuleLoad (module.js:513:12)\n at Function.Module._load (module.js:505:3)\n 1: node::Abort() [/usr/local/bin/node]\n 2: node::Chdir(v8::FunctionCallbackInfo const&) [/usr/local/bin/node]\n 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo const&)) [/usr/local/bin/node]\n 4: v8::internal::MaybeHandle v8::internal::(anonymous namespace)::HandleApiCallHelper(v8::internal::Isolate*, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::BuiltinArguments) [/usr/local/bin/node]\n 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]\n 6: 0x909046042fd\nAbort trap: 6\n```\n\nI tried everything I can do, but I couldn't solve it. My codes are as below:\n\n**below is [app.module.ts]**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\nimport {TypeOrmModule} from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forRoot(\n{\n \"type\":\"postgres\",\n \"name\":\"pm_main\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"test\",\n \"database\": \"test\",\n \"synchronize\":true\n }\n ),UserModule],\n controllers: [AppController],\n providers: [AppService]\n})\nexport class AppModule {}\n```\n\n**Below is [user.service.ts]**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\nimport { Repository } from 'typeorm';\n\n@Injectable()\nexport class UserService {\n\n constructor(\n @InjectRepository(USER)\n private readonly userRepository: Repository\n ){}\n\n async findAllUser(): Promise {\n return await this.userRepository.find();\n }\n}\n```\n\n**Below is [user.module.ts]**\n\n```\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\nimport { PROJECT } from 'project/models/project.model';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\n\n@Module({\n imports: [TypeOrmModule.forFeature([USER])],\n providers: [UserService],\n controllers: [UserController],\n exports: [UserService]\n})\nexport class UserModule {}\n```\n\nI 100% followed the sample of the document, but it seems not right.\n\nFor more information, the dependencies in package.json are as below:\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^5.3.9\" \n \"@nestjs/core\": \"^5.3.10\", \n \"@nestjs/typeorm\": \"^5.2.0\",\n \"ajv\": \"^6.5.4\",\n \"class-validator\": \"^0.9.1\",\n \"fastify-formbody\": \"^2.0.0\",\n \"jsonwebtoken\": \"^8.3.0\",\n \"passport\": \"^0.4.0\",\n \"passport-jwt\": \"^4.0.0\",\n \"pg\": \"^7.4.3\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rxjs\": \"^6.0.0\",\n \"typeorm\": \"^0.2.7\",\n \"typescript\": \"^2.6.2\"\n```\n\n**Also [user.model.ts] as USER is shown below**\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from \"typeorm\";\nimport { IsNotEmpty, IsDate, IsEmail, IsArray, IsEnum, IsJSON } from 'class-validator'\nimport { user_Gender, user_Status } from \"./user.enum\";\nimport { PROJECT } from 'project/models/project.model';\n\n@Entity()\nexport class USER {\n @PrimaryGeneratedColumn('uuid')\n id:string;\n\n @Column({unique:true})\n @IsNotEmpty()\n username:string;\n\n @Column()\n password:string;\n\n @Column()\n @IsEnum({user_Gender})\n gender:string;\n\n @Column(\"jsonb\")\n @IsJSON()\n realname?:{\n firstName:string;\n lastName:string;\n middleName:string;\n };\n\n @Column()\n @IsDate()\n birthday?:Date;\n\n @CreateDateColumn()\n createAt:Date;\n\n @UpdateDateColumn()\n updateAt:Date;\n\n @Column()\n @IsArray()\n industry?:string[];\n\n @Column()\n @IsEmail()\n email?:string;\n\n @Column()\n @IsArray()\n org?:string[];\n\n @Column()\n current_org?:string;\n\n @Column(\"jsonb\")\n @IsJSON()\n user_location?:{\n country:string;\n province_or_state:string;\n city:string;\n district:string;\n address:string;\n };\n\n @Column(\"jsonb\")\n @IsJSON()\n mobilephone?:{code:string,number:string};\n\n @Column(\"text\")\n avater:string;\n\n @Column()\n @IsArray()\n receive_account?:[{\n name:string,\n number:string,\n bank:string,\n swiftCode?:string,\n address?:string}]\n\n @Column()\n @IsDate()\n last_loginAt?:Date;\n\n @Column()\n @IsEnum(user_Status)\n status:string;\n\n @Column()\n projectsId:[];\n\n @ManyToMany(type => PROJECT, project => project.members)\n @JoinTable()\n projects:PROJECT[];\n\n}\n```\n\n========================================\n\nTop Answer:\nKim's solution doesn't completely solve the problem when there are multiple databases in use.\n\nfinally solve it when check out this issue. https://github.com/nestjs/typeorm/issues/105\n\nThat is, also need to specify the connection name when @InjectRepositry(Model, connectionName)\n\n========================================\n\nCode:\n```text\n[Nest] 40671   - 2018-10-20 17:46:37   [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms\nError: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.\n    at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)\n    at <anonymous>\n    at process._tickCallback (internal/process/next_tick.js:160:7)\n    at Function.Module.runMain (module.js:703:11)\n    at Object.<anonymous> (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)\n    at Module._compile (module.js:660:30)\n    at Object.Module._extensions..js (module.js:671:10)\n    at Module.load (module.js:573:32)\n    at tryModuleLoad (module.js:513:12)\n    at Function.Module._load (module.js:505:3)\n 1: node::Abort() [/usr/local/bin/node]\n 2: node::Chdir(v8::FunctionCallbackInfo<v8::Value> const&) [/usr/local/bin/node]\n 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/usr/local/bin/node]\n 4: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/usr/local/bin/node]\n 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]\n 6: 0x909046042fd\nAbort trap: 6\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\nimport {TypeOrmModule} from '@nestjs/typeorm';\n\n@Module({\n  imports: [TypeOrmModule.forRoot(\n{\n      \"type\":\"postgres\",\n      \"name\":\"pm_main\",\n      \"host\": \"localhost\",\n      \"port\": 5432,\n      \"username\": \"postgres\",\n      \"password\": \"test\",\n      \"database\": \"test\",\n      \"synchronize\":true\n  }\n  ),UserModule],\n  controllers: [AppController],\n  providers: [AppService]\n})\nexport class AppModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\nimport { Repository } from 'typeorm';\n\n@Injectable()\nexport class UserService {\n\n    constructor(\n        @InjectRepository(USER)\n        private readonly userRepository: Repository<USER>\n    ){}\n\n    async findAllUser(): Promise<USER[]> {\n        return await this.userRepository.find();\n    }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\nimport { PROJECT } from 'project/models/project.model';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([USER])],\n  providers: [UserService],\n  controllers: [UserController],\n  exports: [UserService]\n})\nexport class UserModule {}\n```\n\n```text\n\"dependencies\": {\n    \"@nestjs/common\": \"^5.3.9\" \n    \"@nestjs/core\": \"^5.3.10\", \n    \"@nestjs/typeorm\": \"^5.2.0\",\n    \"ajv\": \"^6.5.4\",\n    \"class-validator\": \"^0.9.1\",\n    \"fastify-formbody\": \"^2.0.0\",\n    \"jsonwebtoken\": \"^8.3.0\",\n    \"passport\": \"^0.4.0\",\n    \"passport-jwt\": \"^4.0.0\",\n    \"pg\": \"^7.4.3\",\n    \"reflect-metadata\": \"^0.1.12\",\n    \"rxjs\": \"^6.0.0\",\n    \"typeorm\": \"^0.2.7\",\n    \"typescript\": \"^2.6.2\"\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from \"typeorm\";\nimport { IsNotEmpty, IsDate, IsEmail, IsArray, IsEnum, IsJSON } from 'class-validator'\nimport { user_Gender, user_Status } from \"./user.enum\";\nimport { PROJECT } from 'project/models/project.model';\n\n@Entity()\nexport class USER {\n    @PrimaryGeneratedColumn('uuid')\n    id:string;\n\n    @Column({unique:true})\n    @IsNotEmpty()\n    username:string;\n\n    @Column()\n    password:string;\n\n    @Column()\n    @IsEnum({user_Gender})\n    gender:string;\n\n    @Column(\"jsonb\")\n    @IsJSON()\n    realname?:{\n        firstName:string;\n        lastName:string;\n        middleName:string;\n    };\n\n    @Column()\n    @IsDate()\n    birthday?:Date;\n\n    @CreateDateColumn()\n    createAt:Date;\n\n    @UpdateDateColumn()\n    updateAt:Date;\n\n    @Column()\n    @IsArray()\n    industry?:string[];\n\n    @Column()\n    @IsEmail()\n    email?:string;\n\n    @Column()\n    @IsArray()\n    org?:string[];\n\n    @Column()\n    current_org?:string;\n\n    @Column(\"jsonb\")\n    @IsJSON()\n    user_location?:{\n        country:string;\n        province_or_state:string;\n        city:string;\n        district:string;\n        address:string;\n    };\n\n    @Column(\"jsonb\")\n    @IsJSON()\n    mobilephone?:{code:string,number:string};\n\n    @Column(\"text\")\n    avater:string;\n\n    @Column()\n    @IsArray()\n    receive_account?:[{\n        name:string,\n        number:string,\n        bank:string,\n        swiftCode?:string,\n        address?:string}]\n\n    @Column()\n    @IsDate()\n    last_loginAt?:Date;\n\n    @Column()\n    @IsEnum(user_Status)\n    status:string;\n\n    @Column()\n    projectsId:[];\n\n    @ManyToMany(type => PROJECT, project => project.members)\n    @JoinTable()\n    projects:PROJECT[];\n\n}\n```\n\n```text\nimports: [TypeOrmModule.forRoot({\n      \"type\":\"postgres\",\n      \"name\":\"pm_main\",\n      ^^^^^^^^^^^^^^^^^\n      \"host\": \"localhost\",\n      \"port\": 5432,\n      \"username\": \"postgres\",\n      \"password\": \"test\",\n      \"database\": \"test\",\n      \"synchronize\":true\n  }\n```\n\n```text\nimports: [TypeOrmModule.forFeature([USER])],\n```\n\n```text\nTypeOrmModule.forFeature([USER], 'pm_main')\n```\n\n```text\nforFeature\n```\n\n```text\nforFeature\n```\n\n```text\n\"name\":\"pm_main\",\n```\n\n```text\nforRoot\n```\n\n```text\nimport { UserEntity } from './user.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nconst module = await Test.createTestingModule({\n    controllers: [UsersController],\n    providers: [UsersService],\n    imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line\n}).compile();\n```\n\n========================================\n\nComments:\n- I couldn't spot an error on first glance. Can you include your `USER` model from /models/user.model?\n- @KimKern Thanks for your reply. I have included the USER model.\n- Thanks ! Was stuck for hours because I had the same issue.\n- I am facing this issue.I have two databases, already adding the name in forFeature but still the same.\n- Solved my issue with Sequelize.\n- It would be helpful if you could explain what the code in your answer changes to solve the OP's problem.Code without comments has very little value t oothers\n- Thanks, even though this doesn't answer the original question, but it gave me the clue to my problem, where i'm getting this error in my test script","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":497,"estimatedTokens":3234}}404{"id":"stack-69159038","source":"stackoverflow","questionId":69159038,"title":"how to I get a user's IP address when separate client and server apps, in Node with Nest.js","tags":["node.js","reactjs","express","nestjs"],"text":"Title: how to I get a user's IP address when separate client and server apps, in Node with Nest.js\nTags: node.js, reactjs, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have two apps, one front end (react.js) and one a REST API back-end(nest.js based on express.js). How do I get the IP address of the user accessing the back-end when the front-end client makes a request to the back-end?\n\nI checked this question and try the solutions\n\nWith separate client and server apps, how do I get a user's IP address, in Node with Koa?\n\nExpress.js: how to get remote client address\n\nbut I get server IP of front-end not client IP.\n\nIs there a way without any change in front-end app, I get real client IP in nest.js?\n\n========================================\n\nTop Answer:\nAccording to the NestJS docs, there's a decorator available to get the request Ip Address. It's used like this:\n\n```\nimport {Get, Ip} from \"@nestjs/common\"\n\n@Get('myEndpoint')\nasync myEndpointFunc(@Ip() ip){\n console.log(ip)\n}\n```\n\nHere's a complete list of decorators that can be used:\nhttps://docs.nestjs.com/custom-decorators\n\n========================================\n\nCode:\n```text\nnpm i --save request-ip\nnpm i --save-dev @types/request-ip\n```\n\n```text\napp.use(requestIp.mw());\n```\n\n```text\nreq.clientIp\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\nimport * as requestIp from 'request-ip';\n\nexport const IpAddress = createParamDecorator((data, req) => {\n    if (req.clientIp) return req.clientIp;\n    return requestIp.getClientIp(req);\n});\n```\n\n```text\n@Get('/users')\nasync users(@IpAddress() ipAddress){\n}\n```\n\n```text\nrequest-ip\n```\n\n```text\nmain.ts\n```\n\n```js\nimport { Injectable, Logger, NestMiddleware } from \"@nestjs/common\";\nimport { NextFunction, Request, Response } from \"express\";\n\n@Injectable()\nexport class HttpLoggerMiddleware implements NestMiddleware {\n    private logger = new Logger();\n\n    use(request: Request, response: Response, next: NextFunction): void {\n        const { ip, method, originalUrl } = request;\n\n        response.on(\"finish\", () => {\n            const msg = `${ip} ${method} ${originalUrl}`;\n            this.logger.log(msg);\n        });\n\n        next();\n    }\n}\n```\n\n```text\nRequest\n```\n\n```js\nimport {Get, Ip} from \"@nestjs/common\"\n\n@Get('myEndpoint')\nasync myEndpointFunc(@Ip() ip){\n  console.log(ip)\n}\n```\n\n```text\nconst ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;\n```\n\n```text\n@Post(\"/mypath\")\n  @HttpCode(HttpStatus.OK)\n  async intention(\n      @Body() body: MyRequest,\n      @Req() requestToReadIp: Request\n  ): Promise<PurchaseIntentionResponse>  {\n      const ips = requestToReadIp.headers['x-forwarded-for'] as string\n      const userIp = ips.split(\",\")[0]\n      ...\n  }\n```\n\n```text\nnpm i --save request-ip\nnpm i --save-dev @types/request-ip\n```\n\n```js\nimport { ExecutionContext, createParamDecorator } from '@nestjs/common';\nimport { Request } from 'express';\nimport * as requestIp from 'request-ip';\n\nexport const Ip = createParamDecorator((data, ctx: ExecutionContext) => {\n  const ip = requestIp.getClientIp(ctx.switchToHttp().getRequest() as Request);\n\n  return ip.slice(0, 7) === '::ffff:' ? ip.slice(7) : ip;\n});\n```\n\n```js\nimport { Ip } from './helpers'\n\n@Get('/users')\nasync users(@Ip() ip: string){\nconsole.log({ ip })\n}\n```\n\n========================================\n\nComments:\n- For me, req was of type ExecutionContext. So instead of calling it req, call it ctx and do: `const request = ctx.switchToHttp().getRequest();`\n- `request-ip` hasn't been properly maintained for ~3 years now. The IP address it picks for header can be forged.\n- Not worked. I got the IP: ::ffff:127.0.0.1\n- If you're working on your local host that's the response you'll get @Henry","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":158,"estimatedTokens":935}}405{"id":"stack-65097317","source":"stackoverflow","questionId":65097317,"title":"Errors while initializing MongoDB with Nestjs/Angular","tags":["angular","mongodb","nestjs"],"text":"Title: Errors while initializing MongoDB with Nestjs/Angular\nTags: angular, mongodb, nestjs\nSource: Stack Overflow\n\nQuestion:\nI finally came here after putting lot of efforts but no success. I learn Nestjs/Angular/MongoDB. So far I got success running both Angular server & Nestjs server simaltaneously. But I get huge list of errors 147 (mostly related to schema) when I initialize mongoDB with them.\n\nIt doesn't seem that errors are related to my codes, but install dependencies. In any case I copy hereunder my codes as well. I try this app both ubuntu & windows. but same error persist.\n\napp.controller.ts:\n\n```\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\n export class AppController {\n constructor(private readonly appService: AppService) {}\n\n@Get()\n healthCheck(): string {\n return this.appService.appStatus();\n }\n}\n```\n\nApp.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { config } from './config';\n\n@Module({\n imports: [\n MongooseModule.forRoot(config.mongoUri, {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n useCreateIndex: true,\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\napp.service.ts\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectConnection } from '@nestjs/mongoose';\nimport { Connection } from 'mongoose';\nimport { config } from './config';\n\n@Injectable()\nexport class AppService {\n constructor(@InjectConnection() private connection: Connection) {}\n appStatus(): string {\n return `${config.appName} is running in port ${config.port}. Connected to \n ${this.connection.name}`;\n }\n}\n```\n\nconfig.ts\n\n```\nimport * as dotenv from 'dotenv';\n\nconst result = dotenv.config();\n\n if (result?.error) {\n throw new Error('Add .env file');\n}\n\nexport const config = {\n env: process.env.SZ_ENV,\n appName: process.env.SZ_APP,\n port: process.env.SZ_PORT,\n mongoUri: \n `mongodb+srv://${process.env.SZ_MONGO_USER}:${process.env.SZ_MONGO_PASS}@\n ${process.env.SZ_MONGO_HOST}/${process.env.SZ_MONGO_DB} \n authSource=admin&replicaSet=${process.env.SZ_MONGO_REPLICA}&\n readPreference=primary&ssl=true`,\n };\n```\n\nmain.ts\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { config } from './config';\n\n async function bootstrap() {\n const { appName, port } = config;\n const app = await NestFactory.create(AppModule);\n await app.listen(port, () => {\n console.info(`${appName} is running in http://localhost:${port}`);\n });\n }\nbootstrap();\n```\n\nERROR: while yarn start:server\n\n```\n[8:16:58 PM] Starting compilation in watch mode...\n\nnode_modules/@nestjs/mongoose/dist/factories/schema.factory.d.ts:4:60 - error TS2315: Type \n'Schema' is not generic.\n\n4 static createForClass(target: Type): mongoose.Schema;\n ~~~~~~~~~~~~~~~~~~\nnode_modules/@types/mongoose/index.d.ts:79:1 - error TS6200: Definitions of the following \nidentifiers conflict with those in another file: DocumentDefinition, FilterQuery, \nUpdateQuery, NativeError, Mongoose, CastError, Collection, Connection, Error, QueryCursor, \nVirtualType, Schema, Subdocument, Array, DocumentArray, Buffer, ObjectId, Decimal128, Map, \nAggregate, SchemaType, Document\n\n79 declare module \"mongoose\" {\n```\n\n```\nnode_modules/mongoose/index.d.ts:1:1\n 1 declare module \"mongoose\" {\n ~~~~~~~\n Conflicts are in this file.\n\n node_modules/@types/mongoose/index.d.ts:226:14 - error TS2403: Subsequent variable \n declarations must have the same type. Variable 'SchemaTypes' must be of type 'typeof \n Types', but here has type 'typeof Types'.\n\n 226 export var SchemaTypes: typeof Schema.Types;\n ~~~~~~~~~~~\n\n node_modules/mongoose/index.d.ts:45:14\n 45 export var SchemaTypes: typeof Schema.Types;\n ~~~~~~~~~~~\n 'SchemaTypes' was also declared here.\n\n node_modules/@types/mongoose/index.d.ts:822:24 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 822 constructor(query: Query, options: any);\n ~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1013:19 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 1013 pre = Query>(\n ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1013:32 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 1013 pre = Query>(\n ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1036:48 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 1036 pre | Query | Aggregate>(\n ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1048:19 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 1048 pre = Query>(\n ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1048:32 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 1048 pre = Query>(\n ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1074:48 - error TS2314: Generic type \n 'Query' requires 3 type argument(s).\n\n 1074 pre | Query | Aggregate>(\n ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1264:5 - error TS2374: Duplicate string index \n signature.\n\n 1264 [path: string]: SchemaTypeOpts | Schema | SchemaType;\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1627:76 - error TS2314: Generic type \n'Query' requires 3 type argument(s).\n\n 1627 replaceOne(replacement: any, callback?: (err: any, raw: any) => void): Query;\n```\n\n========================================\n\nTop Answer:\nNew mongoose **v5.11.x** released its own types definition, so you shouldn't use **@types/mongoose** anymore\nhttps://github.com/Automattic/mongoose/issues/9606#issuecomment-736710621\n\n========================================\n\nCode:\n```text\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\n export class AppController {\n constructor(private readonly appService: AppService) {}\n\n@Get()\n healthCheck(): string {\n  return this.appService.appStatus();\n  }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { config } from './config';\n\n@Module({\n  imports: [\n    MongooseModule.forRoot(config.mongoUri, {\n      useNewUrlParser: true,\n      useUnifiedTopology: true,\n      useCreateIndex: true,\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectConnection } from '@nestjs/mongoose';\nimport { Connection } from 'mongoose';\nimport { config } from './config';\n\n@Injectable()\nexport class AppService {\n  constructor(@InjectConnection() private connection: Connection) {}\n   appStatus(): string {\n   return `${config.appName} is running in port ${config.port}. Connected to \n    ${this.connection.name}`;\n  }\n}\n```\n\n```text\nimport * as dotenv from 'dotenv';\n\nconst result = dotenv.config();\n\n if (result?.error) {\n throw new Error('Add .env file');\n}\n\nexport const config = {\n  env: process.env.SZ_ENV,\n  appName: process.env.SZ_APP,\n  port: process.env.SZ_PORT,\n  mongoUri:  \n `mongodb+srv://${process.env.SZ_MONGO_USER}:${process.env.SZ_MONGO_PASS}@\n  ${process.env.SZ_MONGO_HOST}/${process.env.SZ_MONGO_DB} \n  authSource=admin&replicaSet=${process.env.SZ_MONGO_REPLICA}&\n  readPreference=primary&ssl=true`,\n  };\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { config } from './config';\n\n async function bootstrap() {\n  const { appName, port } = config;\n  const app = await NestFactory.create(AppModule);\n  await app.listen(port, () => {\n    console.info(`${appName} is running in http://localhost:${port}`);\n  });\n }\nbootstrap();\n```\n\n```text\n[8:16:58 PM] Starting compilation in watch mode...\n\nnode_modules/@nestjs/mongoose/dist/factories/schema.factory.d.ts:4:60 - error TS2315: Type \n'Schema' is not generic.\n\n4     static createForClass<T = any>(target: Type<unknown>): mongoose.Schema<T>;\n                                                         ~~~~~~~~~~~~~~~~~~\nnode_modules/@types/mongoose/index.d.ts:79:1 - error TS6200: Definitions of the following \nidentifiers conflict with those in another file: DocumentDefinition, FilterQuery, \nUpdateQuery, NativeError, Mongoose, CastError, Collection, Connection, Error, QueryCursor, \nVirtualType, Schema, Subdocument, Array, DocumentArray, Buffer, ObjectId, Decimal128, Map, \nAggregate, SchemaType, Document\n\n79     declare module \"mongoose\" {\n```\n\n```text\nnode_modules/mongoose/index.d.ts:1:1\n 1 declare module \"mongoose\" {\n   ~~~~~~~\n Conflicts are in this file.\n\n node_modules/@types/mongoose/index.d.ts:226:14 - error TS2403: Subsequent variable \n declarations must have the same type.  Variable 'SchemaTypes' must be of type 'typeof \n Types', but here has type 'typeof Types'.\n\n 226   export var SchemaTypes: typeof Schema.Types;\n              ~~~~~~~~~~~\n\n node_modules/mongoose/index.d.ts:45:14\n 45   export var SchemaTypes: typeof Schema.Types;\n                 ~~~~~~~~~~~\n 'SchemaTypes' was also declared here.\n\n node_modules/@types/mongoose/index.d.ts:822:24 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 822     constructor(query: Query<T>, options: any);\n                        ~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1013:19 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 1013     pre<T extends Query<any> = Query<any>>(\n                    ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1013:32 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 1013     pre<T extends Query<any> = Query<any>>(\n                                 ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1036:48 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 1036     pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(\n                                                 ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1048:19 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 1048     pre<T extends Query<any> = Query<any>>(\n                    ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1048:32 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 1048     pre<T extends Query<any> = Query<any>>(\n                                 ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1074:48 - error TS2314: Generic type \n 'Query<ResultType, DocType, T>' requires 3 type argument(s).\n\n 1074     pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(\n                                                 ~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1264:5 - error TS2374: Duplicate string index \n signature.\n\n 1264     [path: string]: SchemaTypeOpts<any> | Schema | SchemaType;\n      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n node_modules/@types/mongoose/index.d.ts:1627:76 - error TS2314: Generic type \n'Query<ResultType, \n   DocType, T>' requires 3 type argument(s).\n\n 1627     replaceOne(replacement: any, callback?: (err: any, raw: any) => void): Query<any>;\n```\n\n```text\n\"version\": \"5.11.2\"\n```\n\n```text\n\"mongoose\": \"^5.10.11\"\n```\n\n```text\n\"mongoose\": \"~5.10.11\"\n```\n\n```text\n\"version\": \"5.10.19\"\n```\n\n```text\n\"skipLibCheck\": true\n```\n\n========================================\n\nComments:\n- I don't think I'm using higher version. These are mongoose dependencies from pck.json. \"dependencies\": \"mongoose\": \"^5.9.23\", \"@nestjs/mongoose\": \"^7.0.2\", \"devDependencies\": \"@types/mongoose\": \"^5.7.31\",\n- You can check the version by running `npm ls --depth=0 | grep mongoose` or `yarn list --depth=0 | grep mongoose`. Using `^5.9.23` means it will use `5.x.x` so long as it is above 5.9, because the `^` means this version or minor version above\n- Tks, still getting: MongooseModule] Unable to connect to the database. Retrying (3)... +3006ms, although I downgraded to 5.10.2. any help further ?\n- You can let it count to nine (9) and it will print out the problem. Looking at your config, it looks like you may be missing the `?` for the query parameters.\n- To prevent updating Mongoose to `> 5.11.x` you can change in package.json` `\"mongoose\": \"^5.10.x\"` to `\"mongoose\": \"~5.10.x\"`.\n- after update package.json what did you do next ? make any command related to yarn / npm update or something ? because index.d.ts can't be created itself, at least not in my case\n- @TheKash I installed dependecies again. ran command npm install after removing node_modules and package-lock","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":415,"estimatedTokens":3198}}406{"id":"stack-64982545","source":"stackoverflow","questionId":64982545,"title":"How to get FullURL with NestJS?","tags":["nestjs"],"text":"Title: How to get FullURL with NestJS?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nHow do I get the full URL of the page that NestJS is processing?\n(e.g. http://localhost:3000/hoge)\n\n```\n// \n// If you implement it with express, it looks like this.\n// e.g. http://localhost:3000/hoge\n// \nfunction getFullUrl(req: express.Request) {\n return `${req.protocol}://${req.get('Host')}${req.originalUrl}`;\n}\n```\n\n========================================\n\nCode:\n```text\n// \n// If you implement it with express, it looks like this.\n// e.g. http://localhost:3000/hoge\n// \nfunction getFullUrl(req: express.Request) {\n  return `${req.protocol}://${req.get('Host')}${req.originalUrl}`;\n}\n```\n\n```text\nimport {Controller, Get, Req} from '@nestjs/common';\nimport {Request} from 'express';\n\n@Controller()\nexport class AppController {    \n    @Get()\n    getHello(@Req() req: Request): void {\n        console.log(`${req.protocol}://${req.get('Host')}${req.originalUrl}`);\n    }\n}\n```\n\n```text\nReq()\n```\n\n========================================\n\nComments:\n- **This answer has been very helpful to me.** Thank you very much. It was also understood that it was based on the premise of using the Express HTTP adapter.","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":300}}407{"id":"stack-60578332","source":"stackoverflow","questionId":60578332,"title":"Use global nest module in decorator","tags":["nestjs"],"text":"Title: Use global nest module in decorator\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a global logger module in nest, that logs to a cloud logging service. I am trying to create a class method decorator that adds logging functionality. But I am struggling how to inject the service of a global nest module inside a decorator, since all dependency injection mechanisms I found in the docs depend are class or class property based injection.\n\n```\nexport function logDecorator() {\n\n // I would like to inject a LoggerService that is a provider of a global logger module\n let logger = ???\n\n return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {\n //get original method\n const originalMethod = propertyDescriptor.value;\n\n //redefine descriptor value within own function block\n propertyDescriptor.value = function(...args: any[]) {\n logger.log(`${propertyKey} method called with args.`);\n \n //attach original method implementation\n const result = originalMethod.apply(this, args);\n\n //log result of method\n logger.log(`${propertyKey} method return value`);\n };\n };\n}\n```\n\n**UPDATE: Per reqest a simple example**\nBasic example would be to log calls to a service method using my custom logger (which in my case logs to a cloud service):\n\n```\nclass MyService {\n @logDecorator()\n someMethod(name: string) {\n // calls to this method as well as method return values would be logged to CloudWatch\n return `Hello ${name}`\n }\n}\n```\n\nAnother extended use case would be to catch some errors, then log them. I have a lot of this kind of logic that get reused across all my services.\n\n========================================\n\nTop Answer:\nIn my case I wanted to transform a request param into an entity, only decorator approach seemed hard, a mix of a decorator and a pipe proved easy.\n\nTake the example of a decorator from https://docs.nestjs.com/custom-decorators\n\n```\n// user.decorator.js\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n (data: unknown, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n return request.user;\n },\n);\n\n//user-entity-from-req.pipe.ts\nimport { BadRequestException, Injectable, NotFoundException, PipeTransform } from '@nestjs/common';\nimport { EntityManager } from 'typeorm';\nimport { UserEntity } from 'modules/users/lib/entities/user.entity';\nimport { UserToken } from 'auth/models/user-token';\nimport { isString, isUUID } from 'class-validator';\n\n@Injectable()\nexport class UserEntityByReq implements PipeTransform {\n constructor(readonly em: EntityManager) {}\n\n async transform(value: UserToken): Promise {\n if (!isString(value.accessKey) || !isUUID(value.accessKey)) {\n throw new BadRequestException('Access key does not match any known user');\n }\n\n const entity = await this.em.findOne(UserEntity, { where: { uuid: value.accessKey } });\n\n if (!entity || !entity.uuid || entity.uuid !== value) {\n throw new NotFoundException(`Cannot find user from access key [${value.accessKey}]`);\n }\n\n return entity;\n }\n}\n\n// controller\n@Get()\n// the secret is to use the pipe in the decorator\nasync findOne(@User(UserEntityByReq) user: UserEntity) {\n console.log(user);\n}\n```\n\nWill allow you to have a pipe with dependency injection and a decorator for easy use.\n\n========================================\n\nCode:\n```ts\nexport function logDecorator() {\n\n  // I would like to inject a LoggerService that is a provider of a global logger module\n  let logger = ???\n\n  return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {\n    //get original method\n    const originalMethod = propertyDescriptor.value;\n\n    //redefine descriptor value within own function block\n    propertyDescriptor.value = function(...args: any[]) {\n      logger.log(`${propertyKey} method called with args.`);\n      \n      //attach original method implementation\n      const result = originalMethod.apply(this, args);\n\n      //log result of method\n      logger.log(`${propertyKey} method return value`);\n    };\n  };\n}\n```\n\n```ts\nclass MyService {\n    @logDecorator()\n    someMethod(name: string) {\n        // calls to this method as well as method return values would be logged to CloudWatch\n        return `Hello ${name}`\n    }\n}\n```\n\n```ts\nimport { Inject } from '@nestjs/common';\nimport { LoggerService } from '../../logger/logger.service';\n\nexport function logErrorDecorator(bubble = true) {\n  const injectLogger = Inject(LoggerService);\n\n  return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {\n    injectLogger(target, 'logger'); // this is the same as using constructor(private readonly logger: LoggerService) in a class\n\n    //get original method\n    const originalMethod = propertyDescriptor.value;\n\n    //redefine descriptor value within own function block\n    propertyDescriptor.value = async function(...args: any[]) {\n      try {\n        return await originalMethod.apply(this, args);\n      } catch (error) {\n        const logger: LoggerService = this.logger;\n\n        logger.setContext(target.constructor.name);\n        logger.error(error.message, error.stack);\n\n        // rethrow error, so it can bubble up\n        if (bubble) {\n          throw error;\n        }\n      }\n    };\n  };\n}\n```\n\n```ts\nexport class FoobarService implements OnModuleInit {\n  onModuleInit() {\n    this.test();\n  }\n\n  @logErrorDecorator()\n  test() {\n    throw new Error('Oh my');\n  }\n}\n```\n\n```js\n// user.decorator.js\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return request.user;\n  },\n);\n\n\n//user-entity-from-req.pipe.ts\nimport { BadRequestException, Injectable, NotFoundException, PipeTransform } from '@nestjs/common';\nimport { EntityManager } from 'typeorm';\nimport { UserEntity } from 'modules/users/lib/entities/user.entity';\nimport { UserToken } from 'auth/models/user-token';\nimport { isString, isUUID } from 'class-validator';\n\n@Injectable()\nexport class UserEntityByReq implements PipeTransform {\n    constructor(readonly em: EntityManager) {}\n\n    async transform(value: UserToken): Promise<StoreEntity> {\n        if (!isString(value.accessKey) || !isUUID(value.accessKey)) {\n            throw new BadRequestException('Access key does not match any known user');\n        }\n\n        const entity = await this.em.findOne(UserEntity, { where: { uuid: value.accessKey } });\n\n        if (!entity || !entity.uuid || entity.uuid !== value) {\n            throw new NotFoundException(`Cannot find user from access key [${value.accessKey}]`);\n        }\n\n        return entity;\n    }\n}\n\n// controller\n@Get()\n// the secret is to use the pipe in the decorator\nasync findOne(@User(UserEntityByReq) user: UserEntity) {\n  console.log(user);\n}\n```\n\n========================================\n\nComments:\n- Can you possibly show an example of how you'd like to use this decorator? I think I get the idea of what you're wanting to do, but not 100% sure on it.\n- @JayMcDoniel: Sure, I updated the questions with a simple example\n- When I use this approach the service ends up being undefined in the descriptions value function. In my case the service Iโ€™m using also depends on two other services, so that may have an impact. Can this solution be used for services that inject other ones?\n- @vinnymac Oi, have you found out what was causing your service to come undefined? Seems like I'm having the same problem here. Even though it works nicely when I use this decorator in a service class, the injected service turns undefined when I use it in a different class, in a factory, to be precise. I tried making it injectable but it didn't help.\n- Hey @Albert, Have you found out what was causing your service to be undefined?\n- @hikvineh Hi, yes I have but I don't remember already what it was exactly but it was just some minor thing, after I fixed it, everything worked as expected, so yeah I confirm that the solution described in the answer works! And this service I was injecting into my decorator also injects a bunch of other dependencies, so it does not really matter if your service has other services injected into it, everything works as expected.\n- My guess that it could be circular dependency problem.\n- This is awesome, thank you. I'm trying to use this for a logger as well and my problem is some providers have the logger as part of the constructor and some don't. Would it be possible to do the injection conditionally?\n- @valerii15298 it very well may have been a circular dependency issue. I will have to look back at my notes and see what I did. If I recall, I ended up foregoing this solution entirely as I couldn't get it working, but your theory makes sense as the cause to me.\n- When I use this approach, compiler complains that logger does not exist, how did you overcome this?\n- anyone figured out this issue with undefined service?\n- @GoranJakovljevic my service was undefined because I forgot to return `propertyDescriptor` after I redefined `propertyDescriptor.value`","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":244,"estimatedTokens":2281}}408{"id":"stack-64494797","source":"stackoverflow","questionId":64494797,"title":"Class transformer not converting to array of numbers","tags":["typescript","nestjs","class-validator","class-transformer"],"text":"Title: Class transformer not converting to array of numbers\nTags: typescript, nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have a DTO in which I have a field which is an array of numbers. These ids are coming via API query parameters. I am using Class Transformer to transform these ids into an array of numbers. But I am getting an array of strings only. My DTO class is as below.\n\n```\nexport class EvseGetQueryDto {\n ...\n ...\n\n @IsOptional()\n @IsArray()\n @IsNumber({}, {each: true})\n @ApiProperty({ type: [Number] })\n @Type(() => Number)\n locations?: number[];\n\n ...\n ...\n}\n```\n\nMy Controller code looks like this.\n\n```\nasync GetAll(@Query() query: EvseGetQueryDto): Promise {\n return await this.evseService.GetAll(query);\n}\n```\n\nIf I call my controller like this below, I am still getting `['1', '2']` in my locations field.\n\n```\nhttp://localhost:3000/evses?locations[]=1&locations[]=2\n```\n\nCan anyone please guide me?\n\n========================================\n\nTop Answer:\nif you don't like your search queries to look like\n\n```\n/evses?locations[]=1&locations[]=2\n```\n\nand want something like passing an entire list\n\n```\n/evses?locations=1,1\n```\n\nuse inside your class\n\n```\nexport class yourclass {\n\n @Transform(({ value }) => value.toString().split(',').map(Number))\n locations:Number[];\n\n}\n```\n\n========================================\n\nCode:\n```text\nexport class EvseGetQueryDto {\n  ...\n  ...\n\n  @IsOptional()\n  @IsArray()\n  @IsNumber({}, {each: true})\n  @ApiProperty({ type: [Number] })\n  @Type(() => Number)\n  locations?: number[];\n\n  ...\n  ...\n}\n```\n\n```text\nasync GetAll(@Query() query: EvseGetQueryDto): Promise<EvseDto[]> {\n    return await this.evseService.GetAll(query);\n}\n```\n\n```text\nhttp://localhost:3000/evses?locations[]=1&locations[]=2\n```\n\n```text\n['1', '2']\n```\n\n```js\nimport {  Type } from 'class-transformer';\nimport { IsArray, IsNumber } from 'class-validator';\n\nexport class NumbersQuery {\n  @Type(() => Number)\n  @IsArray()\n  @IsNumber({}, {each: true})\n  numbers: number[];\n}\n```\n\n```js\nimport { Controller, Get, Query, UsePipes, ValidationPipe } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { NumbersQuery } from './numbers';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getHello(@Query() query: Record<string, unknown>): string {\n    return this.appService.getHello(query);\n  }\n\n  @UsePipes(new ValidationPipe({ transform: true }))\n  @Get('numbers')\n  getNumbers(@Query() numbers: NumbersQuery) {\n    console.log(numbers);\n    return numbers.numbers;\n  }\n}\n```\n\n```text\nโ–ถ curl http://localhost:3000/numbers/\\?numbers\\[\\]\\=1\\&numbers\\[\\]\\=2\n[1,2]%\n```\n\n```text\n[Nest] 76497   - 10/23/2020, 10:40:47 AM   [NestFactory] Starting Nest application...\n[Nest] 76497   - 10/23/2020, 10:40:47 AM   [InstanceLoader] AppModule dependencies initialized +11ms\n[Nest] 76497   - 10/23/2020, 10:40:47 AM   [RoutesResolver] AppController {}: +5ms\n[Nest] 76497   - 10/23/2020, 10:40:47 AM   [RouterExplorer] Mapped {, GET} route +2ms\n[Nest] 76497   - 10/23/2020, 10:40:47 AM   [RouterExplorer] Mapped {/numbers, GET} route +1ms\n[Nest] 76497   - 10/23/2020, 10:40:47 AM   [NestApplication] Nest application successfully started +1ms\nNumbersQuery { numbers: [ 1, 2 ] }\n```\n\n```text\n@Type(() => Number)\n```\n\n```text\ntransform: true\n```\n\n```text\nValidationPipe\n```\n\n```text\n/evses?locations[]=1&locations[]=2\n```\n\n```text\n/evses?locations=1,1\n```\n\n```text\nexport class yourclass {\n\n\n    @Transform(({ value }) => value.toString().split(',').map(Number))\n    locations:Number[];\n\n}\n```\n\n========================================\n\nComments:\n- Thanks a lot Jay! I found the issue after you explained this stuff. I was missing a validation Pipe in my controller.","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":184,"estimatedTokens":950}}409{"id":"stack-67937648","source":"stackoverflow","questionId":67937648,"title":"How to group endpoints in Nest js with Swagger","tags":["javascript","swagger","nestjs"],"text":"Title: How to group endpoints in Nest js with Swagger\nTags: javascript, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to group API endpoints based on tags in Nest.js such that all employee endpoints under Employee tag, all site endpoints under Site tag etc. Currently, all my endpoints are under default tag. I am using Swagger in Nest.js.\n\nHow can I implement it?\n\n========================================\n\nCode:\n```js\n@ApiTags('cats')\n@Controller('cats')\nexport class CatsController {}\n```\n\n```text\n@ApiTags(...tags)\n```\n\n========================================\n\nComments:\n- This is interesting, it used to work, but now I get `Module '\"@nestjs&#47;swagger\"' has no exported member 'ApiQuery'`\n- @jesse-carter What if we want to put multiple category under one higher category? For example: panel/articles, panel/posts, panel/users. I think you get the idea.\n- @KasirBarati if swagger doesn't support it, I don't think NestJS will do github.com/OAI/OpenAPI-Specification/issues/1367\n- I can confirm it works now, with nestjs project","metadata":{"transformedAt":"2026-08-18T18:33:02.441Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":29,"estimatedTokens":262}}410{"id":"stack-56790991","source":"stackoverflow","questionId":56790991,"title":"npm run build > not creating dist folder in NestJs project","tags":["json","nestjs"],"text":"Title: npm run build > not creating dist folder in NestJs project\nTags: json, nestjs\nSource: Stack Overflow\n\nQuestion:\nI tried to start my project with `npm run start:prod` command but got \n\n**`Error: Cannot find module {path to my project}\\dist\\main.js'`.**\n\nI have tried to rename the path to all my files in the project from src/myController to ../myController .\n\n**My package.json (scripts)**\n\n```\n\"scripts\": {\n \"build\": \"tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n \"start:dev\": \"concurrently \\\"wait-on dist/main.js && nodemon\\\" \\\"tsc -w -p tsconfig.json\\\" \",\n \"start:debug\": \"nodemon --config nodemon-debug.json\",\n \"prestart:prod\": \"rimraf dist && npm run build\",\n \"start:prod\": \"node dist/main.js\"\n```\n\n**My tsconfig.json**\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"noImplicitAny\": false,\n \"removeComments\": true,\n \"allowSyntheticDefaultImports\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es6\",\n \"sourceMap\": true,\n \"rootDir\": \".\",\n \"outDir\": \"../dist\",\n \"baseUrl\": \"./src\"\n },\n \"include\": [ \"./src/**/*.ts\", ],\n \"exclude\": [\"node_modules\", \"dist\", \"src/**/*.spec.ts\", \"src/**/__test__/*\"]\n}\n```\n\n**The actual output:**\n\n nest-typescript-starter@1.0.0 prestart:prod \n {path to my project}\n rimraf dist && npm run build\n\n \n nest-typescript-starter@1.0.0 build \n {path to my project}\n tsc -p tsconfig.build.json\n\n \n nest-typescript-starter@1.0.0 start:prod \n {path to my project}\n node dist/main.js\n\ninternal/modules/cjs/loader.js:584\n throw err;\n ^\n\n Error: Cannot find module\n {path to my project}\\dist\\main.js'\n\n========================================\n\nTop Answer:\nyou can just add a new command:\nunder the scripts in package.json :\n\n```\n\"start:live\": \"rimraf dist && nest build && node dist/src/main\",\n```\n\nthen you can run:\n\n```\nnpm run start:live\n```\n\n========================================\n\nCode:\n```text\n\"scripts\": {\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n    \"start:dev\": \"concurrently \\\"wait-on dist/main.js && nodemon\\\" \\\"tsc -w -p tsconfig.json\\\" \",\n    \"start:debug\": \"nodemon --config nodemon-debug.json\",\n    \"prestart:prod\": \"rimraf dist && npm run build\",\n    \"start:prod\": \"node dist/main.js\"\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"noImplicitAny\": false,\n    \"removeComments\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es6\",\n    \"sourceMap\": true,\n    \"rootDir\": \".\",\n    \"outDir\": \"../dist\",\n    \"baseUrl\": \"./src\"\n  },\n  \"include\": [ \"./src/**/*.ts\", ],\n  \"exclude\": [\"node_modules\", \"dist\", \"src/**/*.spec.ts\", \"src/**/__test__/*\"]\n}\n```\n\n```text\nnpm run start:prod\n```\n\n```text\nError: Cannot find module {path to my project}\\dist\\main.js'\n```\n\n```text\n\"start:prod\": \"node dist/main.js\"\n```\n\n```text\n\"start:prod\": \"node dist/src/main.js\"\n```\n\n```text\n\"outDir\": \"../dist\"\n```\n\n```text\n\"outDir\": \"./dist\"\n```\n\n```text\n\"start:live\": \"rimraf dist && nest build && node dist/src/main\",\n```\n\n```text\nnpm run start:live\n```\n\n========================================\n\nComments:\n- You can accept your own answer as the correct solution, by the way, to help others in the future know what response to look at.\n- This helped me as well. I believe in my case its due to a fact I'm generating typings from schema outside of the `src`. Still I don't like much seeing `dist&#47;src` at all yet that's another story...\n- I had the same problem, it looks like NestJs ships with the following in the package.json `\"start:prod\": \"node dist&#47;main\"` updating to `\"start:prod\": \"node dist&#47;src&#47;main\"` solved my issue","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":159,"estimatedTokens":975}}411{"id":"stack-67202527","source":"stackoverflow","questionId":67202527,"title":"Can we use server sent events in nestjs without using interval?","tags":["microservices","mqtt","nestjs","server-sent-events","nestjs-gateways"],"text":"Title: Can we use server sent events in nestjs without using interval?\nTags: microservices, mqtt, nestjs, server-sent-events, nestjs-gateways\nSource: Stack Overflow\n\nQuestion:\nI'm creating few **microservices** using **nestjs**.\n\nFor instance I have **x**, **y** & **z** services all interconnected by **grpc** but I want **service x to send updates to a webapp** on a particular entity change so I have **considered server-sent-events** *[open to any other better solution]*.\n\nFollowing the **nestjs documentation**, they have a function running at n interval for sse route, seems to be resource exhaustive. Is there a way to actually sent events when there's a update.\n\nLets say I have another api call in the same service that is **triggered by a button click** on another webapp, how do I trigger the **event to fire only when the button is clicked** and not continuously keep sending events. Also if you know any **idiomatic way** to achieve this which getting hacky would be appreciated, want it to be last resort.\n\n### [BONUS Question]\n\nI also considered **MQTT** to send events. But I get a feeling that it isn't possible for a single service to have **MQTT and gRPC**. I'm skeptical of using MQTT because of its **latency and how it will affect internal message passing**. If I could limit to external clients it would be great (i.e, x service to use gRPC for internal connections and MQTT for webapp just need one route to be exposed by mqtt).\n(PS **I'm new to microservices** so please be comprehensive about your solutions :p)\n\n### Thanks in advance for reading till end!\n\n========================================\n\nTop Answer:\nYou can. The important thing is that in NestJS `SSE` is implemented with Observables, so as long as you have an observable you can add to, you can use it to send back SSE events. The easiest way to work with this is with `Subject`s. I used to have an example of this somewhere, but generally, it would look something like this\n\n```\n@Controller()\nexport class SseController {\n constructor(private readonly sseService: SseService) {}\n\n @SSE()\n doTheSse() {\n return this.sseService.sendEvents();\n }\n}\n```\n\n```\n@Injectable()\nexport class SseService {\n private events = new Subject();\n\n addEvent(event) {\n this.events.next(event);\n }\n\n sendEvents() {\n return this.events.asObservable();\n }\n}\n```\n\n```\n@Injectable()\nexport class ButtonTriggeredService {\n constructor(private readonly sseService: SseService) {}\n\n buttonClickedOrSomething() {\n this.sseService.addEvent(buttonClickedEvent);\n }\n}\n```\n\nPardon the pseudo-code nature of the above, but in general it does show how you can use Subjects to create observables for SSE events. So long as the `@SSE()` endpoint returns an observable with the proper shape, you're golden.\n\n========================================\n\nCode:\n```text\nimport {Injectable} from '@nestjs/common';\nimport {fromEvent} from \"rxjs\";\nimport {EventEmitter} from \"events\";\n\n@Injectable()\nexport class EventsService {\n\n    private readonly emitter = new EventEmitter();\n\n    subscribe(channel: string) {\n        return fromEvent(this.emitter, channel);\n    }\n\n    emit(channel: string, data?: object) {\n        this.emitter.emit(channel, {data});\n    }\n\n}\n```\n\n```js\n@Controller()\nexport class SseController {\n  constructor(private readonly sseService: SseService) {}\n\n  @SSE()\n  doTheSse() {\n    return this.sseService.sendEvents();\n  }\n}\n```\n\n```js\n@Injectable()\nexport class SseService {\n  private events = new Subject();\n\n  addEvent(event) {\n    this.events.next(event);\n  }\n\n  sendEvents() {\n    return this.events.asObservable();\n  }\n}\n```\n\n```js\n@Injectable()\nexport class ButtonTriggeredService {\n  constructor(private readonly sseService: SseService) {}\n\n  buttonClickedOrSomething() {\n    this.sseService.addEvent(buttonClickedEvent);\n  }\n}\n```\n\n```text\nSSE\n```\n\n```text\nSubject\n```\n\n```text\n@SSE()\n```\n\n```text\n@Sse('sse-endpoint')\n  sse(): Observable<any> {\n    //data have to strem\n    const arr = ['d1','d2', 'd3']; \n    return new Observable((subscriber) => {\n        while(arr.len){\n            subscriber.next(arr.pop()); // data have to return in every chunk\n        }\n        if(arr.len == 0) subscriber.complete(); // complete the subscription\n    });\n  }\n```\n\n```text\nimport { Public } from 'src/decorators';\nimport { Observable } from 'rxjs';\nimport { FastifyReply } from 'fastify';\nimport { NotificationService } from './notification.service';\n\nimport { Sse, Controller, Res } from '@nestjs/common';\n\n@Public()\n@Controller()\nexport class NotificationController {\n  constructor(private notificationService: NotificationService) {}\n  @Sse('notifications')\n  async sendNotification(@Res() reply: FastifyReply): Promise<Observable<any>> {\n    return await this.notificationService.handleConnection();\n  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Subject } from 'rxjs';\n\n@Injectable()\nexport class NotificationService {\n  notificationEvent: Subject<any> = new Subject();\n  async handleConnection() {\n    setInterval(() => {\n      this.notificationEvent.next({ data: { message: 'Hello World' } });\n    }, 1000);\n    return this.notificationEvent.asObservable();\n  }\n}\n```\n\n```text\n...\n    import { Observable, fromEvent, map } from 'rxjs';\n    import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; \n    import { Sse, MessageEvent } from '@nestjs/common';\n    ...\n\n    @Controller('users')\n    export class UsersController {\n      constructor(\n        private readonly usersService: UsersService,\n        private eventEmitter: EventEmitter2,\n      ) { }\n    \n      @Post()\n      @ApiOkResponse({ type: UserEntity })\n      async create(@Body() createUserDto: CreateUserDto) {\n        const user = await this.usersService.create(createUserDto);\n        this.eventEmitter.emit('user-create', user);\n        return user;\n      }\n    \n      @OnEvent('user-create')\n      @Sse('create-user')\n      sse(): Observable<MessageEvent> {\n        try {\n          return fromEvent(this.eventEmitter, 'employee-create').pipe(\n            map((data) => {\n              return new MessageEvent('employee-create', { data: data } as MessageEvent);\n            }),\n          );\n        } catch (e) {\n          console.log('error', e);\n        }\n      }\n    }\n```\n\n```html\n<script type=\"text/javascript\">\n    const eventSource = new EventSource('http://localhost:3000/users/create-user');\n    eventSource.onmessage = ({ data }) => {\n        const message = document.createElement('li');\n        message.innerText = 'New message: ' + data;\n        document.body.appendChild(message);\n    };\n</script>\n```\n\n========================================\n\nComments:\n- is there any way to isolate that event subject to a particular user? For SSE in controller I'm doing something like @Sse('/status/update/:userId'). Thinking I should use a map. Any better solutions?\n- The map doesn't sound like a terrible idea to me. I don't know much else about sse filtering, so it might be something to look into\n- @Nikhil.Nixel have you found any solution to isolate for a particular user? Currently in the same situation as you are\n- I did something like this, @Sse('/status/update/:userId') then I could store subjects in map with key as userId, if you have large number of users its not ideal for the RAM since it will keep hogging those spaces if you have too many subjects because of too many users\n- @Mohaimin look the above comment\n- I don't think SSE is ideal for these cases for isolating to specific entity. You could have better luck with using plain old sockets @Mohaimin\n- How did you send back data for that specific key(userId)? And about the socket implementation, yeah thinking that too but at this point I'm just curious :P\n- it returns the ids for me, but I don't use ids in my code. I want to know, how to create custom observables.\n- @BennisonJ Observables are just another construct, like Promises, to handle Async code. There are several creation operators like `of`, `from`, and `timer` depending on your needs.\n- Actually, I am new to observable, can you explain to me how to create custom observables in nest js sse?\n- @BennisonJ by using a creation operator\n- @JayMcDoniel I have been facing an problem nests when using observable in sse, I asked that as a question on this platform, kindly check that and if know solution let me know stackoverflow.com/questions/75607348/&hellip;\n- what's the known bug?\n- @wopolow Don't inject any service inside EventsService because it will stop to work.\n- @NingaCodingTRV It doesn't seem to trigger this error now\n- What did you return from the controller file?\n- @BennisonJ Please see the repo with code example: github.com/ningacoding/nest-sse-bug/tree/main/src\n- @NingaCodingTRV did it fixed? I cloned and run it and it is working\n- Answers should include an explanation of why a code snippet is a solution, please edit this answer to add some context","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":259,"estimatedTokens":2222}}412{"id":"stack-55825937","source":"stackoverflow","questionId":55825937,"title":"How to validate optional parameters in Nest.js?","tags":["validation","nestjs"],"text":"Title: How to validate optional parameters in Nest.js?\nTags: validation, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to validate parameters of my `PUT` `users/` endpoint but I'd like that all parameters are optional but once the api consumer fill these parameters I'd like to validate them.\n\nI tried to combined `@ApiModelProperty` **required false** with validation pipes decorator but validation pipe took over `ApiModelProperty`\n(pretty normal for sending **400 bad request** `HttpException`)\n\nHere is my DTO - `usersUpdate.dto.ts`:\n\n```\nimport { IsEmail, IsEnum, IsPhoneNumber, IsEmpty } from 'class-validator';\nimport { ApiModelProperty } from '@nestjs/swagger';\nimport { RoleType } from './role-type.enum';\n\nclass UserInfo {\n @ApiModelProperty({ description: 'User firstname', required: false })\n readonly firstname: string;\n\n @ApiModelProperty({ description: 'User lastname', required: false })\n readonly lastname: string;\n\n @ApiModelProperty({description: 'User postal address', required: false })\n readonly address: string;\n\n @ApiModelProperty({ description: 'User phone number', required: false })\n @IsPhoneNumber('FR')\n readonly phone: string;\n\n @ApiModelProperty({ description: 'User siret number', required: false })\n readonly siret: string;\n}\n\nexport class UpdateUserDTO {\n @ApiModelProperty({ description: 'User email address', required: false })\n readonly email: string;\n\n @ApiModelProperty({ description: 'User password', required: false })\n readonly password: string;\n\n @ApiModelProperty({ description: 'User informations', required: false })\n readonly user_info: UserInfo;\n\n @ApiModelProperty({ enum: ['Admin', 'Runner', 'Dispatcher'], description:'User role', required: false })\n readonly role: RoleType;\n\n @ApiModelProperty({ description: 'User activation token', required: false })\n readonly activationToken: string;\n}\n```\n\nI would like to use and `@IsEmail()` decorator on email parameter and a `@Enum()` decorator in role but once I use these decorator the parameter is mandatory.\n\nAnybody know how to skip this validator if parameters are empty?\n\n========================================\n\nCode:\n```text\nimport { IsEmail, IsEnum, IsPhoneNumber, IsEmpty } from 'class-validator';\nimport { ApiModelProperty } from '@nestjs/swagger';\nimport { RoleType } from './role-type.enum';\n\nclass UserInfo {\n    @ApiModelProperty({ description: 'User firstname', required: false  })\n    readonly firstname: string;\n\n    @ApiModelProperty({ description: 'User lastname', required: false  })\n    readonly lastname: string;\n\n    @ApiModelProperty({description: 'User postal address', required: false })\n    readonly address: string;\n\n    @ApiModelProperty({ description: 'User phone number', required: false  })\n    @IsPhoneNumber('FR')\n    readonly phone: string;\n\n    @ApiModelProperty({ description: 'User siret number', required: false  })\n    readonly siret: string;\n}\n\nexport class UpdateUserDTO {\n    @ApiModelProperty({ description: 'User email address', required: false })\n    readonly email: string;\n\n    @ApiModelProperty({ description: 'User password', required: false })\n    readonly password: string;\n\n    @ApiModelProperty({ description: 'User informations', required: false })\n    readonly user_info: UserInfo;\n\n    @ApiModelProperty({ enum: ['Admin', 'Runner', 'Dispatcher'], description:'User role',  required: false })\n    readonly role: RoleType;\n\n    @ApiModelProperty({ description: 'User activation token', required: false })\n    readonly activationToken: string;\n}\n```\n\n```text\nPUT\n```\n\n```text\nusers/\n```\n\n```text\n@ApiModelProperty\n```\n\n```text\nApiModelProperty\n```\n\n```text\nHttpException\n```\n\n```text\nusersUpdate.dto.ts\n```\n\n```text\n@IsEmail()\n```\n\n```text\n@Enum()\n```\n\n```js\nimport { IsEmail, IsEnum, IsPhoneNumber, IsEmpty, IsOptional } from 'class-validator';\n    import { ApiModelPropertyOptional } from '@nestjs/swagger';\n    import { RoleType } from './role-type.enum';\n\n    class UserInfo {\n        @ApiModelPropertyOptional({ description: 'User firstname' })\n        @IsOptional()\n        readonly firstname: string;\n\n        @ApiModelPropertyOptional({ description: 'User lastname' })\n        @IsOptional()\n        readonly lastname: string;\n\n        @ApiModelPropertyOptional({description: 'User postal address' })\n        @IsOptional()\n        readonly address: string;\n\n        @ApiModelPropertyOptional({ description: 'User phone number'  })\n        @IsOptional()\n        @IsPhoneNumber('FR')\n        readonly phone: string;\n\n        @ApiModelPropertyOptional({ description: 'User siret number'  })\n        @IsOptional()\n        readonly siret: string;\n    }\n\n    export class UpdateUserDTO {\n        @ApiModelPropertyOptional({ description: 'User email address' })\n        @IsEmail()\n        @IsOptional()\n        readonly email: string;\n\n        @ApiModelPropertyOptional({ description: 'User password' })\n        @IsOptional()\n        readonly password: string;\n\n        @ApiModelPropertyOptional({ description: 'User informations' })\n        @IsOptional()\n        readonly user_info: UserInfo;\n\n        @ApiModelPropertyOptional({ enum: ['Admin', 'Runner', 'Dispatcher'], description:'User role' })\n        @IsEnum(RoleType)\n        @IsOptional()\n        readonly role: RoleType;\n\n        @ApiModelPropertyOptional({ description: 'User activation token' })\n        @IsOptional()\n        readonly activationToken: string;\n    }\n```\n\n```text\n@IsOptional\n```\n\n```text\n@ApiModelProperty({ description: 'User activation token', required: false })\n```\n\n```text\n@ApiModelPropertyOptional\n```\n\n```text\n@IsEmail()\n```\n\n```text\n@IsNotEmpty()\n```\n\n```text\n@IsOptional()\n```\n\n========================================\n\nComments:\n- Please accept the answer if it solved your question :)","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":214,"estimatedTokens":1433}}413{"id":"stack-65478137","source":"stackoverflow","questionId":65478137,"title":"Mock Injected Service In Unit Testing Nest.js","tags":["node.js","jestjs","nestjs"],"text":"Title: Mock Injected Service In Unit Testing Nest.js\nTags: node.js, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to test my service (Location Service). In this Location Service, I inject repository and other service called GeoLocationService, but got stuck when I am trying to mock this GeoLocationService.\n\nIt throws me an error\n\n```\nGeolocationService โ€บ should be defined\n\n Nest can't resolve dependencies of the GeolocationService (?). Please make sure that the argument HttpService at index [0] is available in the RootTestModule context.\n```\n\nHere is the provider's code\n\n```\n@Injectable()\nexport class LocationService {\n constructor(\n @Inject('LOCATION_REPOSITORY')\n private locationRepository: Repository,\n\n private geolocationService: GeolocationService, // this is actually what I ma trying to mock\n ) {}\n\n async getAllLocations(): Promise {\nreturn await this.locationRepository.find()\n }\n....\n}\n```\n\nHere is the test code\n\n```\ndescribe('LocationService', () => {\n let service: LocationService;\n let repo: Repository;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [GeolocationModule],\n providers: [\n LocationService,\n {\n provide: getRepositoryToken(Location),\n useClass: Repository,\n },\n ],\n }).compile();\n\n service = module.get(LocationService);\n repo = module.get>(getRepositoryToken(Location));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n});\n```\n\n========================================\n\nCode:\n```text\nGeolocationService โ€บ should be defined\n\n    Nest can't resolve dependencies of the GeolocationService (?). Please make sure that the argument HttpService at index [0] is available in the RootTestModule context.\n```\n\n```text\n@Injectable()\nexport class LocationService {\n  constructor(\n    @Inject('LOCATION_REPOSITORY')\n    private locationRepository: Repository<Location>,\n\n    private geolocationService: GeolocationService, // this is actually what I ma trying to mock\n  ) {}\n\n  async getAllLocations(): Promise<Object> {\nreturn await this.locationRepository.find()\n  }\n....\n}\n```\n\n```text\ndescribe('LocationService', () => {\n  let service: LocationService;\n  let repo: Repository<Location>;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports: [GeolocationModule],\n      providers: [\n        LocationService,\n        {\n          provide: getRepositoryToken(Location),\n          useClass: Repository,\n        },\n      ],\n    }).compile();\n\n    service = module.get<LocationService>(LocationService);\n    repo = module.get<Repository<Location>>(getRepositoryToken(Location));\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n});\n```\n\n```js\n{\n  provide: GeolocationService,\n  useValue: {\n    method1: jest.fn(),\n    method2: jest.fn(),\n  }\n}\n```\n\n```text\nimports: [GeolocationModule]\n```\n\n```text\nGeolocationService\n```\n\n```text\nGeolocationService\n```\n\n```text\njest.fn()\n```\n\n```text\njest.fn().mockResolved/ReturnedValue()\n```\n\n```text\nproviders\n```\n\n========================================\n\nComments:\n- why do we not import modules? isn't service part of the module?\n- When you add `imports: [SomeModule]`, then if `SomeModule` has other imports you need to take care to have those available in the test context as well, and then those import's imports and so on down the chain. By just adding the service, you know exactly what dependencies are needed to be provided, and can provide basic mocks without going further into dependency hell","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":155,"estimatedTokens":888}}414{"id":"stack-71383271","source":"stackoverflow","questionId":71383271,"title":"Nestjs import service or the whole module","tags":["nestjs"],"text":"Title: Nestjs import service or the whole module\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm new in Nestjs, and I don't understand when I need to import the whole module or only the service if I want to Inject in another module.\n\nFor example:\nI have my loggingModule\n\n```\nimport { Module } from \"@nestjs/common\";\nimport { LoggingService } from \"./logging.service\";\n\n@Module({\n providers: [LoggingService],\n exports: [LoggingService],\n})\nexport class LoggingModule {}\n```\n\nwith my logginService:\n\n```\nimport { Injectable } from \"@nestjs/common\";\n\n@Injectable()\nexport class LoggingService {\n\n logToConsole(logString: string) {\n console.log(logString)\n }\n}\n```\n\nI want to import it into another module, like BookModule\n\n```\nimport { Module } from \"@nestjs/common\";\nimport { LoggingModule } from \"src/logging/logging.module\";\nimport { BookController } from \"./book.controller\";\nimport { BooksService } from \"./books.service\";\n\n@Module({\n controllers: [BookController],\n providers: [BooksService],\n imports: [LoggingModule]\n})\nexport class BooksModule {\n\n}\n```\n\nand inside my controller I can do:\n\n```\n@Controller('books')\nexport class BookController {\n\n constructor(private booksService: BooksService, private loggingService: LoggingService) {}\n```\n\nthe question is:\nWhen I need to import the whole module instead of the single service (LogginService) in providers, like:\n\n```\n@Module({\n controllers: [BookController],\n providers: [BooksService,LoggingService],\n})\nexport class BooksModule {\n```\n\n========================================\n\nCode:\n```js\nimport { Module } from \"@nestjs/common\";\nimport { LoggingService } from \"./logging.service\";\n\n@Module({\n    providers: [LoggingService],\n    exports: [LoggingService],\n})\nexport class LoggingModule {}\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\n\n@Injectable()\nexport class LoggingService {\n\n    logToConsole(logString: string) {\n        console.log(logString)\n    }\n}\n```\n\n```js\nimport { Module } from \"@nestjs/common\";\nimport { LoggingModule } from \"src/logging/logging.module\";\nimport { BookController } from \"./book.controller\";\nimport { BooksService } from \"./books.service\";\n\n\n@Module({\n    controllers: [BookController],\n    providers: [BooksService],\n    imports: [LoggingModule]\n})\nexport class BooksModule {\n\n}\n```\n\n```js\n@Controller('books')\nexport class BookController {\n\n    constructor(private booksService: BooksService, private loggingService: LoggingService) {}\n```\n\n```js\n@Module({\n    controllers: [BookController],\n    providers: [BooksService,LoggingService],\n})\nexport class BooksModule {\n```\n\n```text\nprovider\n```\n\n```text\nproviders\n```\n\n```text\nthis.someClass.field\n```\n\n```text\nthis.someClass.field\n```\n\n========================================\n\nComments:\n- Is it documented in nest docs? I also had question if I import the same module in different places other places, will I get exported providers instantiated once or multiply times.\n- He is right about the instantiation. I tested it by adding a `console.log` in the service constructor using both approaches. I got 2 logs if when adding the service as provider and only 1 when importing the whole module.\n- This is a great answer. For smaller helper classes or simple one-off services, would you still recommend wrapping them with a module? Say you have a utility class, like `UrlBuilder`. Building a module around this (and possibly other such helpers) seems like it would lead to \"module bloat\", whereas injecting via `provider` seems viable. Maybe this is the 1% you're talking about?\n- @lux nothing says you have to have one module per provider. You could create a `UtilitiesModule` that holds the `UrlBuilder` provider (and others) and exports them. That is, if you want to ensure you only get one instance. If you aren't worried about memory or state then you could add a new provider each time\n- It's funny you say that about the `UtilitiesModule`, that thought just ran across my mind as well while looking at the IDE. It not only serves to reduce the memory footprint and ensure singletons, but also helps with code organization. Thanks very much for the input.","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":155,"estimatedTokens":1030}}415{"id":"stack-65421526","source":"stackoverflow","questionId":65421526,"title":"Nest.js - Create index in mongoose schema","tags":["node.js","mongoose","nestjs"],"text":"Title: Nest.js - Create index in mongoose schema\nTags: node.js, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow do I create an index of property in mongoose schema using Nest.js?\n\nI tried to add index as a property option, But the index hasn't been created:\n\n```\n@Schema()\nexport class Schema extends Document {\n\n @Prop()\n _id: string;\n\n @Prop({required: true, index: true})\n type: string;\n\n @Prop()\n creationDate: string;\n\n @Prop()\n name: string;\n}\n\nexport const MySchema = SchemaFactory.createForClass(Schema);\n```\n\nI tried this way too:\n\n```\nexport const MySchema = SchemaFactory.createForClass(Schema).index({ type: 1 });\n```\n\nBoth doesn't work as expected.\n\nWhat is the way to do that?\n\nThanks\n\n========================================\n\nTop Answer:\nThis works for me\n\n```\nexport const MySchema = SchemaFactory.createForClass(Schema);\nMySchema.index({ type: 1 }, { unique: true });\n```\n\nSame can be extended for compound index as well - ex:\n\n```\nMySchema.index({ type: 1, name: 1 }, { unique: true });\n```\n\n========================================\n\nCode:\n```text\n@Schema()\nexport class Schema extends Document {\n\n  @Prop()\n  _id: string;\n\n  @Prop({required: true, index: true})\n  type: string;\n\n  @Prop()\n  creationDate: string;\n\n  @Prop()\n  name: string;\n}\n\nexport const MySchema = SchemaFactory.createForClass(Schema);\n```\n\n```text\nexport const MySchema = SchemaFactory.createForClass(Schema).index({ type: 1 });\n```\n\n```text\n@Schema({useCreateIndex: true})\n    export class Schema extends Document {\n    \n      @Prop()\n      _id: string;\n    \n      @Prop({required: true, index: true})\n      type: string;\n    \n      @Prop()\n      creationDate: string;\n    \n      @Prop()\n      name: string;\n    }\n\nexport const MySchema = SchemaFactory.createForClass(Schema);\n```\n\n```text\n{\n  uri: `....`,\n  user: ,\n  pass: ,\n  //useNewUrlParser: true,\n  useCreateIndex: true,\n  //useUnifiedTopology: true,\n  //useFindAndModify: false,\n  retryAttempts: 3\n}\n```\n\n```text\nuseCreateIndex\n```\n\n```js\nexport const MySchema = SchemaFactory.createForClass(Schema);\nMySchema.index({ type: 1 }, { unique: true });\n```\n\n```js\nMySchema.index({ type: 1, name: 1 }, { unique: true });\n```\n\n```text\n@Prop({ index: \"2dsphere\" })\n```\n\n```text\nMongooseModule.forRootAsync({\n useFactory: async (config: ConfigService) => ({\n   uri: config.get('mongo_url'),\n   useNewUrlParser: true,\n   useCreateIndex: true,\n }),\n inject: [ConfigService],\n})\n```\n\n```text\nuseCreateIndex: true\n```\n\n========================================\n\nComments:\n- both solutions should work, is `Document` imported from mongoose?\n- Yes, Document is imported from 'mongoose'. when running the service i get this warning: DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead, so I guess, something happened with my index, but the only index in this collection is \"_id\"\n- do you need to tell to the schema that a field is an index if that already is set in the mongodb?","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":155,"estimatedTokens":738}}416{"id":"stack-63766390","source":"stackoverflow","questionId":63766390,"title":"Using Nest.js I would like to trim() all @body() input values","tags":["node.js","typescript","nestjs"],"text":"Title: Using Nest.js I would like to trim() all @body() input values\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to trim (empty white spaces at the beggining / end of a input field) of all body values. I don't want to have to loop all body elements\nfor each API request to clean the fields up.\n\nI was wondering if I can overwrite the @body() annotation, and put the code in there, or if there's a input formatter or pipe that does that.\n\nAt the moment, I'm doing this:\n\n```\ncreateAccount(@Body() body: any) {\n this.account.create(body.map(s => s.trim()))\n}\n```\n\nThanks\n\n========================================\n\nTop Answer:\nI made an interceptor just for that. I use it globally but you can use it wherever you want with `@UseInterceptors` decorator. Here is the base class that can be extended for other body transformations also:\n\n```\nimport { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common'\nimport { Observable } from 'rxjs'\n\nexport abstract class TransformRequest implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n this.cleanRequest(context.switchToHttp().getRequest())\n return next.handle()\n }\n\n cleanRequest(req: any): void {\n req.query = this.cleanObject(req.query)\n req.params = this.cleanObject(req.params)\n\n // If you use express adapter you will have\n // req.method\n // If you use fastify adapter you will have\n // req.raw.method\n\n if (req.raw.method !== 'GET') {\n req.body = this.cleanObject(req.body)\n }\n }\n\n cleanObject(obj: object | null | undefined) {\n if (!obj) {\n return obj\n }\n\n for (const key in obj) {\n // Prototype of obj is null\n // if (!obj.hasOwnProperty(key)) {\n // continue\n // }\n\n const value = obj[key]\n\n // If the value is another nested object we need to recursively\n // clean it too. This will work for both array and object.\n if (value instanceof Object) {\n this.cleanObject(value)\n } else {\n // If the value is not an object then it's a scalar\n // so we just let it be transformed.\n obj[key] = this.transform(key, value)\n }\n }\n\n return obj\n }\n\n abstract transform(key: string | number, value: boolean | number | string | null | undefined): any\n}\n```\n\nAnd here is the trim strings class:\n\n```\nimport { Injectable } from '@nestjs/common'\nimport { TransformRequest } from './transform.request'\n\n@Injectable()\nexport class TrimStrings extends TransformRequest {\n private except = ['password']\n\n transform(key: string | number, value: any) {\n if (this.isString(value) && this.isString(key) && !this.except.includes(key)) {\n return value.trim()\n }\n\n return value\n }\n\n isString(value: any): value is string {\n return typeof value === 'string' || value instanceof String\n }\n}\n```\n\nYou can also find it in this repository.\n\nI actually think it's a better idea to trim the body in the front-end side if that is an option.\n\n========================================\n\nCode:\n```text\ncreateAccount(@Body() body: any) {\n  this.account.create(body.map(s => s.trim()))\n}\n```\n\n```text\nimport { Injectable, PipeTransform, \nArgumentMetadata, BadRequestException } from '@nestjs/common'\n\n@Injectable()\nexport class TrimPipe implements PipeTransform {\n  private isObj(obj: any): boolean {\n    return typeof obj === 'object' && obj !== null\n  }\n\n  private trim(values) {\n    Object.keys(values).forEach(key => {\n      if (key !== 'password') {\n        if (this.isObj(values[key])) {\n          values[key] = this.trim(values[key])\n        } else {\n          if (typeof values[key] === 'string') {\n            values[key] = values[key].trim()\n          }\n        }\n      }\n    })\n    return values\n  }\n\n  transform(values: any, metadata: ArgumentMetadata) {\n    const { type } = metadata\n    if (this.isObj(values) && type === 'body') {\n      return this.trim(values)\n    }\n\n    throw new BadRequestException('Validation failed')\n  }\n}\n```\n\n```text\n@UsePipes(new TrimPipe())\n  createAccount(@Body() body: any) {\n    this.account.create(body)\n  }\n```\n\n```text\napp.useGlobalPipes(new TrimPipe());\n```\n\n```text\nimport { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common'\nimport { Observable } from 'rxjs'\n\nexport abstract class TransformRequest implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    this.cleanRequest(context.switchToHttp().getRequest())\n    return next.handle()\n  }\n\n  cleanRequest(req: any): void {\n    req.query = this.cleanObject(req.query)\n    req.params = this.cleanObject(req.params)\n\n    // If you use express adapter you will have\n    // req.method\n    // If you use fastify adapter you will have\n    // req.raw.method\n\n    if (req.raw.method !== 'GET') {\n      req.body = this.cleanObject(req.body)\n    }\n  }\n\n  cleanObject(obj: object | null | undefined) {\n    if (!obj) {\n      return obj\n    }\n\n    for (const key in obj) {\n      // Prototype of obj is null\n      // if (!obj.hasOwnProperty(key)) {\n      //   continue\n      // }\n\n      const value = obj[key]\n\n      // If the value is another nested object we need to recursively\n      // clean it too. This will work for both array and object.\n      if (value instanceof Object) {\n        this.cleanObject(value)\n      } else {\n        // If the value is not an object then it's a scalar\n        // so we just let it be transformed.\n        obj[key] = this.transform(key, value)\n      }\n    }\n\n    return obj\n  }\n\n  abstract transform(key: string | number, value: boolean | number | string | null | undefined): any\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common'\nimport { TransformRequest } from './transform.request'\n\n@Injectable()\nexport class TrimStrings extends TransformRequest {\n  private except = ['password']\n\n  transform(key: string | number, value: any) {\n    if (this.isString(value) && this.isString(key) && !this.except.includes(key)) {\n      return value.trim()\n    }\n\n    return value\n  }\n\n  isString(value: any): value is string {\n    return typeof value === 'string' || value instanceof String\n  }\n}\n```\n\n```text\n@UseInterceptors\n```\n\n```text\nimport { NestMiddleware } from '@nestjs/common';\nimport { Request, Response, NextFunction } from 'express';\n\nexport class TrimMiddleware implements NestMiddleware {\n  use(req: Request, _res: Response, next: NextFunction) {\n    const requestBody = req.body;\n    if (this.isObj(requestBody)) {\n      req.body = this.trim(requestBody);\n    }\n    next();\n  }\n  private isObj(obj: any): boolean {\n    return typeof obj === 'object' && obj !== null;\n  }\n\n  private trim(value: unknown) {\n    if (typeof value === 'string') {\n      return value.trim();\n    }\n\n    if (Array.isArray(value)) {\n      value.forEach((element, index) => {\n        value[index] = this.trim(element);\n      });\n      return value;\n    }\n\n    if (this.isObj(value)) {\n      Object.keys(value).forEach(key => {\n        value[key] = this.trim(value[key]);\n      });\n      return value;\n    }\n\n    return value;\n  }\n}\n```\n\n```text\nNestMiddleware\n```\n\n```text\nNestModule\n```\n\n```text\napply\n```\n\n```text\nforRoutes\n```\n\n========================================\n\nComments:\n- Thank you! oh! except \"password\" is a must have! And recursive checking... Awesome! I don't agree with you that it's a better idea to trim the body content in the front-end, because it could be manipulated.\n- Yeah it could be manipulated. If that is a concern, then back-end trim is better of course. And this could be adapted to be a pipe instead of an interceptor. A pipe would probably be a better option.\n- Yes! I'm reading that a transform pipe is a better option, than having an interceptor.\n- I used this solution and worked. Although I got one problem that if we use optional path param in controller routes, it throws error. For me the workaround was `if (this.isObj(values) && type === 'body') { return this.trim(values) } else { return values; }`. Because I didn't want to throw error when type is not body.","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":308,"estimatedTokens":1975}}417{"id":"stack-63967171","source":"stackoverflow","questionId":63967171,"title":"What is the --watch and --debug option in nest start","tags":["javascript","typescript","nestjs"],"text":"Title: What is the --watch and --debug option in nest start\nTags: javascript, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI read following documentation described `nest` command.\n\nhttps://docs.nestjs.com/cli/scripts\n\nAccording to the document, following must be added to `package.json`\n\n```\n\"build\": \"nest build\",\n\"start\": \"nest start\",\n\"start:dev\": \"nest start --watch\",\n\"start:debug\": \"nest start --debug --watch\",\n```\n\nWhat are the `--watch` and `--debug` options?\n\n========================================\n\nTop Answer:\nAccording to the nestjs start docs the actual uses are as follows;\n\n`--watch`\n\n```\nRun in watch mode (live-reload)\nAlias -w\n```\n\nSource files which are saved with changes are automatically compiled without the need to manually run `npm run start` to trigger webpack compilation after every change.\n\nFor example, typescript files with changes (on save, or when using git) in `src` will be compiled to javascript files in `dist` (depending on your setup)\n\n`--debug`\n\n```\nRun in debug mode (with --inspect flag)\nAlias -d\n```\n\nThe `--debug` flag actually runs the node process using the `--inspect` flag to allow native debugging using an IDE or otherwise. Once the node process is running, you can use an IDE to connect to to the node debug address and port (default 127.0.0.1:9229) and use breakpoints* to pause execution.\n\n*However, do note that the above at present isn't *completely* accurate. IDEs usually need the `--inspect-brk` flag (for breakpoints) and it seems there is still a problem with the nestjs implementation.\n\nSome IDEs (for example VS Code) can get around this with an auto-attach feature and it seems `--debug` is not even needed. Although very easy to set up, it is not as streamlined when developing multiple running node apps.\n\n========================================\n\nCode:\n```text\n\"build\": \"nest build\",\n\"start\": \"nest start\",\n\"start:dev\": \"nest start --watch\",\n\"start:debug\": \"nest start --debug --watch\",\n```\n\n```text\nnest\n```\n\n```text\npackage.json\n```\n\n```text\n--watch\n```\n\n```text\n--debug\n```\n\n```text\n--watch\n```\n\n```text\n--debug\n```\n\n```text\nRun in watch mode (live-reload)\nAlias -w\n```\n\n```text\nRun in debug mode (with --inspect flag)\nAlias -d\n```\n\n```text\n--watch\n```\n\n```text\nnpm run start\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\n--debug\n```\n\n```text\n--debug\n```\n\n```text\n--inspect\n```\n\n```text\n--inspect-brk\n```\n\n```text\n--debug\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":128,"estimatedTokens":602}}418{"id":"stack-77420116","source":"stackoverflow","questionId":77420116,"title":"Nestjs - Cannot find module dist\\main","tags":["typescript","nestjs"],"text":"Title: Nestjs - Cannot find module dist\\main\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using nestjs. I have a front application so I've decided to create a \"common\" folder for both front and back:\n\n```\nproject \n โ”‚\n โ””โ”€โ”€โ”€common\n โ”‚ โ”‚\n โ”‚ โ””โ”€โ”€โ”€dtos\n โ”‚ โ”‚ dto-a.ts\n โ”‚ โ”‚ dto-b.ts\n โ”‚ \n โ””โ”€โ”€โ”€api (==> nestjs)\n โ”‚ โ”‚\n โ”‚ โ””โ”€โ”€โ”€src\n โ”‚\n โ””โ”€โ”€โ”€front\n โ”‚\n โ””โ”€โ”€โ”€src\n```\n\nIn both front and back, I have added this to tsconfig:\n\n```\n{\n \"compilerOptions\": {\n \"paths\": {\n \"@common/*\": [\"../common/*\"]\n }\n }\n}\n```\n\nSo I can use my models like this:\n\n```\nimport { DtoA} from \"@common/dtos\";\n```\n\nHowever, since I made the change, the compilation is creating two folder under the `dist` folder:\n\n```\ndist\n โ”‚\n โ””โ”€โ”€โ”€common\n โ”‚ \n โ””โ”€โ”€โ”€api\n```\n\nNestjs tries to find something into `dist/main`, and fails:\n\nError: Cannot find module 'path\\to\\project\\api\\dist\\main'\nat Function.Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)\nat Function.Module._load (node:internal/modules/cjs/loader:885:27)\nat Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)\nat node:internal/main/run_main_module:23:47\n\nHow can I tell nestjs to look into `dist/api/main`, or how can I bundle the common folder inside the api build?\n\n========================================\n\nTop Answer:\nThe answer is quite straightforward, the only thing you'll need to do is to delete the \"tsconfig.build.tsbuildinfo\" file that get's auto-generated.\n\n========================================\n\nCode:\n```text\nproject  \n    โ”‚\n    โ””โ”€โ”€โ”€common\n    โ”‚   โ”‚\n    โ”‚   โ””โ”€โ”€โ”€dtos\n    โ”‚       โ”‚   dto-a.ts\n    โ”‚       โ”‚   dto-b.ts\n    โ”‚   \n    โ””โ”€โ”€โ”€api  (==> nestjs)\n    โ”‚   โ”‚\n    โ”‚   โ””โ”€โ”€โ”€src\n    โ”‚\n    โ””โ”€โ”€โ”€front\n        โ”‚\n        โ””โ”€โ”€โ”€src\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"@common/*\": [\"../common/*\"]\n    }\n  }\n}\n```\n\n```js\nimport { DtoA} from \"@common/dtos\";\n```\n\n```text\ndist\n    โ”‚\n    โ””โ”€โ”€โ”€common\n    โ”‚   \n    โ””โ”€โ”€โ”€api\n```\n\n```text\ndist\n```\n\n```text\ndist/main\n```\n\n```text\ndist/api/main\n```\n\n```text\ndist\n```\n\n```text\nnpm run start:dev\n```\n\n```text\ntsconfig.json\n\n\"incremental\": false // make it false\n```\n\n========================================\n\nComments:\n- it works! I set it to `api&#47;src&#47;main.js`\n- Add this entry to the file nest-cli.json\n- worked for me !\n- it worked for me, thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":144,"estimatedTokens":573}}419{"id":"stack-57565810","source":"stackoverflow","questionId":57565810,"title":"How to define varchar and enum in TypeORM?","tags":["postgresql","typescript","nestjs","typeorm"],"text":"Title: How to define varchar and enum in TypeORM?\nTags: postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have database structure need to declare the variable into `varchar`, `int`, and `enum` using TypeORM in TypeScript. But in TypeScript doesn't have data type varchar and int. How do I declare it?\n\nDatabase structure\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n account_id: varchar;\n\n @Column()\n email: varchar;\n\n @Column()\n phone_number: varchar;\n\n @Column()\n address: varchar;\n\n @Column()\n status: enum;\n\n @Column()\n current_id: varchar;\n}\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    account_id: varchar;\n\n    @Column()\n    email: varchar;\n\n    @Column()\n    phone_number: varchar;\n\n    @Column()\n    address: varchar;\n\n    @Column()\n    status: enum;\n\n    @Column()\n    current_id: varchar;\n}\n```\n\n```text\nvarchar\n```\n\n```text\nint\n```\n\n```text\nenum\n```\n\n```text\nimport {Entity, Column, PrimaryGeneratedColumn} from \"typeorm\";\n\n@Entity()\nexport class Photo {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column({\n        length: 100\n    })\n    name: string;\n\n    @Column(\"text\")\n    description: string;\n\n    @Column()\n    filename: string;\n\n    @Column(\"double\")\n    views: number;\n\n    @Column()\n    isPublished: boolean;\n}\n```\n\n========================================\n\nComments:\n- You can use `string` and `number` for varchar and int. Also check the official typescript docs for all available types.\n- Okay, thank you for your respond\n- I understand now. Thank you for your help\n- @firdaus Could you please approve the answer if it resolves your query.","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":115,"estimatedTokens":471}}420{"id":"stack-68214492","source":"stackoverflow","questionId":68214492,"title":"How can a Nest Bull queue be tested via Jest (DI via @InjectQueue)?","tags":["typescript","dependency-injection","jestjs","mocking","nestjs"],"text":"Title: How can a Nest Bull queue be tested via Jest (DI via @InjectQueue)?\nTags: typescript, dependency-injection, jestjs, mocking, nestjs\nSource: Stack Overflow\n\nQuestion:\nGiven an Injectable that uses a queue via the @InjectQueue decorator:\n\n```\n@Injectable()\nexport class EnqueuerService {\n constructor (\n @InjectQueue(QUEUE_NAME) private readonly queue: Queue\n ) {\n }\n\n async foo () {\n return this.queue.add('job')\n }\n}\n```\n\nHow can I test that this service calls the queue correctly? I can do the bsic scaffolding:\n\n```\ndescribe('EnqueuerService', () => {\n let module: TestingModule\n let enqueuerService: EnqueuerService\n\n beforeAll(async () => {\n module = await Test.createTestingModule({\n imports: [EnqueuerModule]\n }).compile()\n enqueuerService = module.get(EnqueuerService)\n\n // Here I'd usually pull in the dependency to test against:\n // queue = module.get(QUEUE_NAME)\n //\n // (but this doesn't work because queue is using the @InjectQueue decorator)\n })\n\n afterAll(async () => await module.close())\n\n describe('#foo', () => {\n it('adds a job', async () => {\n await enqueuerService.foo()\n\n // Something like this would be nice: \n // expect(queue.add).toBeCalledTimes(1)\n //\n // (but maybe there are alternative ways that are easier?)\n })\n })\n})\n```\n\nI'm quite lost in the Nest DI container setup but I suspect there's some clever way of doing this. But despite hours of attempts I can't make progress, and the documentation isn't helping me. Can anyone offer a solution? It doesn't **have** to be mocking, if it's easier to create a real queue to test against that's fine too I just want to verify my service enqueues as expected! Any help appreciated.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class EnqueuerService {\n  constructor (\n    @InjectQueue(QUEUE_NAME) private readonly queue: Queue\n  ) {\n  }\n\n  async foo () {\n    return this.queue.add('job')\n  }\n}\n```\n\n```text\ndescribe('EnqueuerService', () => {\n  let module: TestingModule\n  let enqueuerService: EnqueuerService\n\n  beforeAll(async () => {\n    module = await Test.createTestingModule({\n      imports: [EnqueuerModule]\n    }).compile()\n    enqueuerService = module.get(EnqueuerService)\n\n    // Here I'd usually pull in the dependency to test against:\n    // queue = module.get(QUEUE_NAME)\n    //\n    // (but this doesn't work because queue is using the @InjectQueue decorator)\n  })\n\n  afterAll(async () => await module.close())\n\n  describe('#foo', () => {\n    it('adds a job', async () => {\n      await enqueuerService.foo()\n\n      // Something like this would be nice: \n      // expect(queue.add).toBeCalledTimes(1)\n      //\n      // (but maybe there are alternative ways that are easier?)\n    })\n  })\n})\n```\n\n```text\nimport { getQueueToken } from '@nestjs/bull';\n\ndescribe('EnqueuerService', () => {\n  let module: TestingModule\n  let enqueuerService: EnqueuerService\n\n  beforeAll(async () => {\n    module = await Test.createTestingModule({\n      imports: [EnqueuerModule]\n    })\n      .overrideProvider(getQueueToken(QUEUE_NAME))\n      .useValue({ /* mocked queue */ })\n      .compile()\n\n    enqueuerService = module.get(EnqueuerService)\n    queue = module.get(QUEUE_NAME)\n  })\n\n  afterAll(async () => await module.close())\n\n  describe('#foo', () => {\n    it('adds a job', async () => {\n      await enqueuerService.foo()\n\n      expect(queue.add).toBeCalledTimes(1)\n    })\n  })\n})\n```\n\n```text\nlet module: TestingModule\nlet enqueuerService: EnqueuerService\nlet mockQueue;\n\n// Create a helper function to create the app.\nconst createApp = async () => {\n  module = await Test.createTestingModule({\n    imports: [EnqueuerModule]\n  })\n    .overrideProvider(getQueueToken(QUEUE_NAME))\n    .useValue(mockQueue)\n    .compile()\n\n  enqueuerService = module.get(EnqueuerService)\n}\n\ndescribe('EnqueuerService', () => {    \n  // Recreate app before each test to clean the mock.\n  beforeEach(async () => {\n    mockQueue = {\n      add: jest.fn(),\n    };\n    await createApp();\n  })\n\n  afterAll(async () => await module.close())\n\n  describe('#foo', () => {\n    it('adds a job', async () => {\n      await enqueuerService.foo()\n\n      // Check calls on the mock.\n      expect(mockQueue.add).toBeCalledTimes(1)\n    })\n  })\n\n  describe('#bar', () => {\n    // Override the mock for a specific test suite.\n    beforeEach(async () => {\n      mockQueue.add = jest.fn().mockImplementation(/** */);\n      // The mock has changed so we need to recreate the app to use the new value.\n      await createApp();\n    })\n\n    it('adds a job', async () => {\n      // ...\n    })\n  })\n})\n```\n\n```text\ngetQueueToken(name?: string)\n```\n\n========================================\n\nComments:\n- That looks promising! I get this error though: `Error: Nest could not find queue element`, it comes from the `module.get(QUEUE_NAME)` line. FWIW if I remove the \"queue\" references entirely the test runs (albeit with no assertions), so there is **something** here that works, it feels very close to working fully.\n- I added an example on how to mock the queue without relying on nest to retrieve the mock\n- Very nice, thanks. FWIW I ended up using jest-mock-extended to create the mock (`mockQueue = mock();`).","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":199,"estimatedTokens":1294}}421{"id":"stack-64939247","source":"stackoverflow","questionId":64939247,"title":"NestJs Swagger mixed types","tags":["typescript","swagger","nestjs","openapi"],"text":"Title: NestJs Swagger mixed types\nTags: typescript, swagger, nestjs, openapi\nSource: Stack Overflow\n\nQuestion:\nI have a class that one of the properties can be string or array of strings, not sure how should I define it in swagger\n\n```\n@ApiProperty({\n description: `to email address`,\n type: ???, ;\n```\n\nI tried\n\n```\n@ApiProperty({\n description: `to email address(es)`,\n additionalProperties: {\n oneOf: [\n { type: 'string' },\n { type: 'Array' },\n ],\n },\n required: true,\n })\n```\n\nand\n\n```\n@ApiProperty({\n description: `to email address(es)`,\n additionalProperties: {\n oneOf: [\n { type: 'string' },\n { type: 'string[]' },\n ],\n },\n required: true,\n })\n```\n\nand\n\n```\n@ApiProperty({\n description: `to email address(es)`,\n additionalProperties: {\n oneOf: [\n { type: 'string' },\n { type: '[string]' },\n ],\n },\n required: true,\n })\n```\n\nbut the result is like below image, which is not correct\n\nhttps://i.sstatic.net/NWyig.png\n\n========================================\n\nCode:\n```text\n@ApiProperty({\n        description: `to email address`,\n        type: ???, <- what should be here?\n        required: true,\n    })\n    to: string | Array<string>;\n```\n\n```text\n@ApiProperty({\n        description: `to email address(es)`,\n        additionalProperties: {\n            oneOf: [\n                { type: 'string' },\n                { type: 'Array<string>' },\n            ],\n        },\n        required: true,\n    })\n```\n\n```text\n@ApiProperty({\n        description: `to email address(es)`,\n        additionalProperties: {\n            oneOf: [\n                { type: 'string' },\n                { type: 'string[]' },\n            ],\n        },\n        required: true,\n    })\n```\n\n```text\n@ApiProperty({\n        description: `to email address(es)`,\n        additionalProperties: {\n            oneOf: [\n                { type: 'string' },\n                { type: '[string]' },\n            ],\n        },\n        required: true,\n    })\n```\n\n```text\n@ApiProperty({\n   oneOf: [\n      { type: 'string' },\n      { \n         type: 'array',\n         items: {\n            type: 'string'\n         }\n      }\n   ]\n})\n```\n\n```text\nArray<TItem>\n```\n\n```text\n{type: 'array', items: { type: TItem } }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":134,"estimatedTokens":543}}422{"id":"stack-50822301","source":"stackoverflow","questionId":50822301,"title":"NestJS Cannot resolve dependencies of the UsersModule","tags":["typescript","nestjs"],"text":"Title: NestJS Cannot resolve dependencies of the UsersModule\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nNestJS Cannot resolve dependencies of the UsersModule. Error:\n\nError: Nest can't resolve dependencies of the UsersModule (?). Please\nverify whether [0] argument is available in the current context.\n\napp.module.ts:\n\n```\n@Module({\n imports: [\n ConfigModule,\n DatabaseModule,\n GraphQLModule,\n UsersModule,\n ],\n providers: [\n ErrorService,\n ],\n exports: [\n DatabaseModule,\n ErrorService,\n ],\n})\nexport class AppModule implements NestModule {}\n```\n\nusers.module.ts:\n\n```\n@Module({\n imports: [\n DatabaseModule,\n ErrorService,\n ],\n providers: [\n UsersService,\n ...usersProviders,\n UserResolver,\n ],\n})\nexport class UsersModule {\n constructor(private readonly errorService: ErrorService) {}\n}\n```\n\nProblem is this ErrorService, but for instance Database module is used in similar way, and it works without any error. I'm little confused) Maybe somebody would help. Thank you.\n\n========================================\n\nTop Answer:\nIn my case it was a wrong used of the Inject function:\n\nI had this:\n\n```\nexport class UsersModule {\n constructor(\n @Inject()\n private readonly errorService: ErrorService\n ) {}\n\n}\n```\n\nInstead of this:\n\n```\nexport class UsersModule {\n constructor(private readonly errorService: ErrorService) {}\n}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    ConfigModule,\n    DatabaseModule,\n    GraphQLModule,\n    UsersModule,\n  ],\n  providers: [\n    ErrorService,\n  ],\n  exports: [\n    DatabaseModule,\n    ErrorService,\n  ],\n})\nexport class AppModule implements NestModule {}\n```\n\n```text\n@Module({\n    imports: [\n        DatabaseModule,\n        ErrorService,\n    ],\n    providers: [\n        UsersService,\n        ...usersProviders,\n        UserResolver,\n    ],\n})\nexport class UsersModule {\n    constructor(private readonly errorService: ErrorService) {}\n}\n```\n\n```text\n// errors.module.ts\n@Module({\n  providers: [ ErrorService ],\n  exports: [ ErrorService ],\n})\nexport class ErrorsModule {}\n\n// users.module.ts\n@Module({\n  imports: [ErrorsModule],\n})\nexport class UsersModule {\n  constructor(private readonly errorService: ErrorService) {}\n}\n```\n\n```text\n@Global()\n@Module({\n  providers: [LoggerService],\n  exports: [LoggerService],\n})\nexport class LoggerModule {\n  constructor(private readonly loggerService: LoggerService) { /* initialize logger, or whatever */ }\n}\n```\n\n```text\nErrorService\n```\n\n```text\nUsersModule\n```\n\n```text\nproviders\n```\n\n```text\nUsersModule\n```\n\n```text\nexports\n```\n\n```text\nimport\n```\n\n```text\nUsersModule\n```\n\n```text\nexports\n```\n\n```text\nAppModule\n```\n\n```text\nErrorService\n```\n\n```text\nproviders\n```\n\n```text\nUsersModule\n```\n\n```text\nErrorsModule\n```\n\n```text\nexports\n```\n\n```text\nErrorService\n```\n\n```text\nUsersModule\n```\n\n```text\nimport\n```\n\n```text\nErrorsModule\n```\n\n```text\nLoggerService\n```\n\n```text\n@Global\n```\n\n```text\nimport\n```\n\n```text\nAppModule\n```\n\n```text\nLoggerModule\n```\n\n```text\nimports\n```\n\n```text\nAppModule\n```\n\n```text\nLoggerService\n```\n\n```text\nimports: [\n    ConfigModule,\n    DatabaseModule,\n    GraphQLModule,\n    UsersModule,\n  ],\n  providers: [\n    ErrorService,\n  ],\n  exports: [\n    DatabaseModule,\n  ],\n})\nexport class AppModule implements NestModule {}\n```\n\n```text\n@Module({\n    imports: [\n        DatabaseModule,\n        ErrorService,\n    ],\n    providers: [\n        UsersService,\n        ...usersProviders,\n        UserResolver,\n    ],\n})\nexport class UsersModule {\n    constructor(private readonly errorService: ErrorService) {}\n}\n```\n\n```text\nexport class UsersModule {\n    constructor(\n         @Inject()\n         private readonly errorService: ErrorService\n     ) {}\n\n}\n```\n\n```text\nexport class UsersModule {\n    constructor(private readonly errorService: ErrorService) {}\n}\n```\n\n========================================\n\nComments:\n- Vlad, I'm getting this message with booting up Nestjs 5 and filed a Github issue for it. So have others with v5. We may be chasing our tails trying to solve this. I think I just saw another post recently, like hours ago, with this same message.\n- Could a link to the Github issue, please? @Preston\n- Oops, sorry. github.com/nestjs/nest/issues/723\n- I was thinking about adding Errors Module, but I thought that is possible to inject service in this way. Your solution with the module is great! Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":305,"estimatedTokens":1095}}423{"id":"stack-52991875","source":"stackoverflow","questionId":52991875,"title":"NestJS Injecting request or execution context in services","tags":["javascript","node.js","typescript","dependency-injection","nestjs"],"text":"Title: NestJS Injecting request or execution context in services\nTags: javascript, node.js, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow can I inject the request or the execution context in a service?\n\n========================================\n\nTop Answer:\n//jwt-auth.guard.ts\n\n```\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n constructor(\n private reflector: Reflector,\n @Inject(PointsRankUseCase) public pointsRanksUseCase: PointsRankUseCase,// //base.service.ts\n\n```\nexport abstract class BaseService {\n public executionContext: ExecutionContext;\n public get walletAddress(): WalletAddress {\n return this.executionContext.switchToHttp().getRequest().user;\n }\n}\n```\n\nwhen i need a execution context in a service, extend my service from BaseService, and set from canActivate.\n\n========================================\n\nCode:\n```js\nexport class AppService {\n  constructor(@Inject(REQUEST) private request) {}\n\n  load() {\n    const user = this.request.user;\n  }\n}\n```\n\n```text\nREQUEST\n```\n\n```text\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n    constructor(\n        private reflector: Reflector,\n        @Inject(PointsRankUseCase) public pointsRanksUseCase: PointsRankUseCase,// <- this is a service extended from my BaseService\n    ) {\n        super();\n\n    }\n\n    canActivate(context: ExecutionContext) {\n        //setting context\n        this.pointsRanksUseCase.executionContext = context; // <- im setting here.\n        return super.canActivate(context);\n    }\n\n    handleRequest(err: any, user: any) {\n        if (err || !user) {\n            throw err || new Error('Unauthorized');\n        }\n        return user;\n    }\n}\n```\n\n```js\nexport abstract class BaseService {\n    public executionContext: ExecutionContext;\n    public get walletAddress(): WalletAddress {\n        return this.executionContext.switchToHttp().getRequest().user;\n    }\n}\n```\n\n========================================\n\nComments:\n- What about execution context?\n- From where I need to import this REQUEST?\n- Got it: import { REQUEST } from '@nestjs/core'; import { Request } from 'express';\n- @SasanFarrokh //jwt-auth.guard.ts ``` @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') { constructor( private reflector: Reflector, @Inject(PointsRankUseCase) public pointsRanksUseCase: PointsRankUseCase,// <- this is a service extended from my BaseService ) { super(); } canActivate(context: ExecutionContext) { //setting context this.pointsRanksUseCase.executionContext = context; // <- im setting here. return super.canActivate(context); } handleRequest(err: any, user: any) {","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":89,"estimatedTokens":661}}424{"id":"stack-56213878","source":"stackoverflow","questionId":56213878,"title":"NestJS : transform responses","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: NestJS : transform responses\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nWith NestJS, we can transform incoming request `@Body()` using the validation pipe. \n\nSimilarly I would like my responses transformed using https://github.com/typestack/class-transformer `classToPlain`. \n\nThis is so that I can map field values to the response format, example: \n\n```\nexport class FoobarDto {\n\n @Transform((money: ExchangeableMoney) => money.localValues)\n public foobar: ExchangeableMoney;\n\n}\n```\n\nWhat is the idiomatic way to achieve this in NestJS?\n\n========================================\n\nTop Answer:\nAn update to this answer, if you've updated to the latest version of 'class-transformer' package.\n\n```\n@Transform(({ value }) => value.localMoney)\npublic foobar: ExchangeableMoney;\n```\n\n========================================\n\nCode:\n```text\nexport class FoobarDto {\n\n    @Transform((money: ExchangeableMoney) => money.localValues)\n    public foobar: ExchangeableMoney;\n\n}\n```\n\n```text\n@Body()\n```\n\n```text\nclassToPlain\n```\n\n```text\n@Transform((money: ExchangeableMoney) => money.localValues, {toPlainOnly: true})\npublic foobar: ExchangeableMoney;\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\napp.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\nclassToPlain\n```\n\n```text\ntoPlainOnly\n```\n\n```text\n@Transform(({ value }) => value.localMoney)\npublic foobar: ExchangeableMoney;\n```\n\n========================================\n\nComments:\n- Maybe you can use Interceptors. docs.nestjs.com/interceptors\n- Hello @Kim Kern. Is there a way to turn on the ClassSerializerInterceptor globally, just as we can with the ValidationPipe?\n- Hi @JasperBlues! You can enable any pipe globally with the `useGlobalPipes` method in your `main.ts` file. See docs.nestjs.com/pipes#class-validator for an example\n- Awesome, great answer, Kim Kern! And thank you @FWoelffel for the comment.\n- import { Reflector } from '@nestjs/core'; /* Why not use Reflector directly */ app.useGlobalInterceptors(new ClassSerializerInterceptor(Reflector));\n- Is there a way to refactor the `Transform` decorator to a function of some sorts so we can reuse a transformer somewhere else?","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":99,"estimatedTokens":588}}425{"id":"stack-72038893","source":"stackoverflow","questionId":72038893,"title":"NestJS, how and where to build response DTOs","tags":["javascript","node.js","spring","nestjs","typeorm"],"text":"Title: NestJS, how and where to build response DTOs\nTags: javascript, node.js, spring, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have been using the Java Spring framework for developing Microservices. Recently I started exploring NestJS and have a question regarding building response DTOs.\n\nIn Spring,\nThe controllers are lightweight, they hand over the call to Service Layer.\n\nThe service layer implements the business logic, and finally, they call the Mapper classes that are responsible for building the response DTOs. The mapper class might be as simple as cloning the entity to a DTO or might also build complex objects using multiple DB entity objects.\n\nIn NestJS, in most of the examples `class-transformer` is being used. But I am not sure the `class-transformer` is good enough for building complex objects. For me `class-transformer` is basically cloning the object. The equivalent for which in Spring is\n\n```\nBeanUtils.copyProperties(workingWellCompositeMemberContactTrace, workingWellDailyMemberAggEntity);\n```\n\nSo my question is in NestJS, what layer is responsible for building complex response objects? And Is sending Entity object to Controller a good practice?\n\n========================================\n\nTop Answer:\nNestjs provided helper methods like PartialType(), PickType(), OmitType() etc for DTO, you may want to read here: https://docs.nestjs.com/techniques/validation#stripping-properties\n\n========================================\n\nCode:\n```text\nBeanUtils.copyProperties(workingWellCompositeMemberContactTrace, workingWellDailyMemberAggEntity);\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-transformer\n```\n\n```js\nexport class UserDTO {\n    id: string;\n\n    name: string;\n\n    surname: string;\n\n    toEntity(dto:UserDTO) {\n        const model = new User();    \n        model.id = id;\n        model.fullname = `${dto.name}, ${dto.surname}`\n        return model;\n    }\n\n    fromEntity(entity:User) {\n        const dto = new UserDTO();\n        dto.id = entity.id;\n\n        const [ name, surname ] = entity.(fullname as string).split(', ').map((name) => {name.tirm()});\n        dto.name = name,\n        dto.surname = surname;\n    }\n}\n```\n\n```text\nwhat layer is responsible for building complex response objects?\n```\n\n```text\nIs sending Entity object to Controller a good practice?\n```\n\n```text\nclass-transformer\n```\n\n```text\ninstanceToPlain\n```\n\n```text\nplainToClass\n```\n\n```text\nExpose\n```\n\n```text\nExclude\n```\n\n========================================\n\nComments:\n- problem with sending entities as response is : When docs like Swagger render documentation on browser, due to some cyclic deps or related entities, the response payload comes out to be be too large and swagger ui goes in non-responsive mode - maybe I am going off topic but I am in favor of sending ResponseDTOs","metadata":{"transformedAt":"2026-08-18T18:33:02.442Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":102,"estimatedTokens":712}}426{"id":"stack-66569909","source":"stackoverflow","questionId":66569909,"title":"how to spyon same method but two different parameters in jest?","tags":["typescript","jestjs","nestjs"],"text":"Title: how to spyon same method but two different parameters in jest?\nTags: typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\njest\n .spyOn(webService.prototype, 'isEnabled')\n .mockImplementation(() => {\n return Promise.resolve(true)\n })\n jest\n .spyOn(webService.prototype, 'isEnabled')\n .mockImplementation(() => {\n return Promise.resolve(false)\n })\n```\n\nSo what I want is to return 'true' if parameter has 'YES' string in it. and return 'false' if parameter has 'NO' in it.\n\nthe typescript of function is like below..\n\n```\npublic isEnabled(featureId: string): Promise {\n return this.toggle.isEnabled(featureId)\n }\n```\n\n========================================\n\nTop Answer:\nIn addition to the last answer, I would create a utility function for mocking that method, this way you can initializate and clear this after each test execution, something like:\n\n**util:**\n\n```\nconst webServiceMock = {\n init(isEnabled) {\n jest.spyOn(webService.prototype, 'isEnabled')\n .mockImplementation(() => isEnabled);\n },\n destroy() {\n jest.clearAllMocks();\n }\n};\n```\n\n**tests:**\n\n```\ndescribe('webService', () => {\n afterEach(() => {\n webServiceMock.destroy();\n });\n\n test('is enabled', () => {\n webServiceMock.init(true);\n expect(webService.isEnabled()).toBe(true);\n });\n\n test('is disabled', () => {\n webServiceMock.init(false);\n expect(webService.isEnabled()).toBe(false);\n });\n});\n```\n\n========================================\n\nCode:\n```text\njest\n      .spyOn(webService.prototype, 'isEnabled')\n      .mockImplementation(() => {\n        return Promise.resolve(true)\n      })\n    jest\n      .spyOn(webService.prototype, 'isEnabled')\n      .mockImplementation(() => {\n        return Promise.resolve(false)\n      })\n```\n\n```text\npublic isEnabled(featureId: string): Promise<boolean> {\n    return this.toggle.isEnabled(featureId)\n  }\n```\n\n```js\njest.spyOn(webService.prototype, 'isEnabled')\n  .mockImplementation((yesOrNo: string) => {\n    if (yesOrNo.includes('YES')) {\n      return true;\n    } else {\n      return false;\n    }\n  });\n```\n\n```text\nYES\n```\n\n```text\nNO\n```\n\n```text\nconst webServiceMock = {\n  init(isEnabled) {\n    jest.spyOn(webService.prototype, 'isEnabled')\n      .mockImplementation(() => isEnabled);\n  },\n  destroy() {\n    jest.clearAllMocks();\n  }\n};\n```\n\n```text\ndescribe('webService', () => {\n  afterEach(() => {\n    webServiceMock.destroy();\n  });\n\n  test('is enabled', () => {\n    webServiceMock.init(true);\n    expect(webService.isEnabled()).toBe(true);\n  });\n\n  test('is disabled', () => {\n    webServiceMock.init(false);\n    expect(webService.isEnabled()).toBe(false);\n  });\n});\n```\n\n========================================\n\nComments:\n- `.mockImplementation((parameter) => ...)`?\n- Just a sidenote, but you can just `return yesOrNo.includes('YES')`. Great answer otherwise! ๐Ÿ™","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":143,"estimatedTokens":701}}427{"id":"stack-59268777","source":"stackoverflow","questionId":59268777,"title":"Validate Enum directly in controller function","tags":["typescript","rest","nestjs"],"text":"Title: Validate Enum directly in controller function\nTags: typescript, rest, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a query parameter in my REST API, which values should be restricted by an enum type. I'm looking for a way to throw a \"Bad Request\" error, when a client gives something different.\n\nMy enum looks like this:\n\n```\nexport enum Precision {\n S = 's',\n MS = 'ms',\n U = 'u',\n NS = 'ns',\n}\n```\n\nMy controller function looks like this:\n\n```\n@Get(':deviceId/:datapoint/last')\n @ApiOkResponse()\n @ApiQuery({name: 'precision', enum: Precision})\n getLastMeasurement(\n @Param('deviceId') deviceId: string,\n @Param('datapoint') datapoint: string,\n @Query('precision') precision: Precision = Precision.S,\n @Res() response: Response,\n ) {\n console.log(precision);\n ....\n response.status(HttpStatus.OK).send(body);\n }\n```\n\nMy problem here is that the function accepts other values, too (for example I can send an f as the query parameter's value). The Function won't return an error to the client, but I want to without writing an if else block at the beginning of each controller function.\n\nI guess there is a rather simple solution to this, but when I try to look it up on the internet I always get results for class validation in DTOs, but not for a simple enum validation directly in the query param/REST controller.\n\nThanks for your time,\n\nJ\n\n========================================\n\nTop Answer:\nYou should be able to create a class like `LastMeasurementQueryParams` that makes use of class-validator decorators, and use the built-in ValidationPipe to check and make sure that one of the expected values are sent in.\n\nThe class could look something like this:\n\n```\nexport class LastMeasurementQueryParams {\n\n @IsEnum(Precision)\n precision: Precision;\n}\n```\n\nAnd then your controller can look like this:\n\n```\n@Get(':deviceId/:datapoint/last')\n @ApiOkResponse()\n @ApiQuery({name: 'precision', enum: Precision})\n getLastMeasurement(\n @Param('deviceId') deviceId: string,\n @Param('datapoint') datapoint: string,\n @Query('precision') precision: LastMeasurementQueryParams = { precision: Precision.S },\n @Res() response: Response,\n ) {\n console.log(precision);\n ....\n response.status(HttpStatus.OK).send(body);\n }\n```\n\n========================================\n\nCode:\n```text\nexport enum Precision {\n    S = 's',\n    MS = 'ms',\n    U = 'u',\n    NS = 'ns',\n}\n```\n\n```text\n@Get(':deviceId/:datapoint/last')\n  @ApiOkResponse()\n  @ApiQuery({name: 'precision', enum: Precision})\n  getLastMeasurement(\n    @Param('deviceId') deviceId: string,\n    @Param('datapoint') datapoint: string,\n    @Query('precision') precision: Precision = Precision.S,\n    @Res() response: Response,\n  ) {\n    console.log(precision);\n    ....\n    response.status(HttpStatus.OK).send(body);\n  }\n```\n\n```text\ngetLastMeasurement(\n  ... // some other params\n    @Query('precision', new DefaultValuePipe(Precision.S)) precision: Precision\n  ) { \n  ... // do something\n}\n```\n\n```text\nimport { BadRequestException, PipeTransform } from '@nestjs/common';\nimport { isDefined, isEnum } from 'class-validator';\n\nexport class PrecisionValidationPipe implements PipeTransform<string, Promise<Precision>> {\n\n  transform(value: string): Promise<Precision> {\n    if (isDefined(value) && isEnum(value, Precision)) {\n      return Precision[value];\n    } else {\n      const errorMessage = `the value ${value} is not valid. See the acceptable values: ${Object.keys(\n        Precision\n      ).map(key => Precision[key])}`;\n      throw new BadRequestException(errorMessage);\n    }\n  }\n}\n```\n\n```text\ngetLastMeasurement(\n    @Query('precision', PrecisionValidationPipe, new DefaultValuePipe(Precision.S)) precision: Precision,\n  ) {\n    console.log(precision);\n    ....\n    response.status(HttpStatus.OK).send(body);\n  }\n```\n\n```text\nimport { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';\nimport { isDefined, isEnum } from 'class-validator';\n\n@Injectable()\nexport class EnumValidationPipe implements PipeTransform<string, Promise<any>> {\n  constructor(private enumEntity: any) {}\n  transform(value: string): Promise<any> {\n      if (isDefined(value) && isEnum(value, this.enumEntity)) {\n        return this.enumEntity[value];\n      } else {\n        const errorMessage = `the value ${value} is not valid. See the acceptable values: ${Object.keys(this.enumEntity).map(key => this.enumEntity[key])}`;\n        throw new BadRequestException(errorMessage);\n      }\n  }\n}\n```\n\n```text\ngetLastMeasurement(\n    @Query('precision', new EnumValidationPipe(Precision), new DefaultValuePipe(Precision.S)) precision: Precision,\n  ) {\n    console.log(precision);\n    ....\n    response.status(HttpStatus.OK).send(body);\n  }\n```\n\n```text\nprecision\n```\n\n```text\nDefaultValuePipe\n```\n\n```js\nexport class LastMeasurementQueryParams {\n\n  @IsEnum(Precision)\n  precision: Precision;\n}\n```\n\n```js\n@Get(':deviceId/:datapoint/last')\n  @ApiOkResponse()\n  @ApiQuery({name: 'precision', enum: Precision})\n  getLastMeasurement(\n    @Param('deviceId') deviceId: string,\n    @Param('datapoint') datapoint: string,\n    @Query('precision') precision: LastMeasurementQueryParams = { precision: Precision.S },\n    @Res() response: Response,\n  ) {\n    console.log(precision);\n    ....\n    response.status(HttpStatus.OK).send(body);\n  }\n```\n\n```text\nLastMeasurementQueryParams\n```\n\n```text\n${Object.keys(this.enumEntity).map(key => this.enumEntity[key])}\n```\n\n```text\n${Object.values(this.enumEntity)}\n```\n\n```text\n@Injectable()\nexport class EnumValidationPipe implements PipeTransform<string, Promise<any>> {\n  constructor(private enumEntity: any) {}\n  transform(value: string, metadata: ArgumentMetadata): Promise<any> {\n    if (isDefined(value) && isEnum(value, this.enumEntity)) {\n      return Promise.resolve(value);\n    } else {\n      const errorMessage = `the value ${value} from field ${\n        metadata.data\n      } is not valid. Acceptable values: ${Object.values(this.enumEntity)}`;\n      throw new BadRequestException(errorMessage);\n    }\n  }\n}\n```\n\n```js\nimport { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';\nimport { isDefined, isEnum } from 'class-validator';\n\ntype EnumKey = string | number | symbol;\n\n/**\n * A pipe that validates an enum value and sets a default value if none is provided.\n */\n@Injectable()\nexport class EnumValidationPipe<T extends Record<EnumKey, unknown>> implements PipeTransform<unknown, T[keyof T]> {\n  constructor(\n    private enumEntity: T,\n    private defaultValue?: T[keyof T],\n  ) {}\n\n  transform(value: unknown): T[keyof T] {\n    if (!isDefined(value) && isDefined(this.defaultValue)) {\n      return this.defaultValue;\n    }\n    if (isDefined(value) && isEnum(value, this.enumEntity)) {\n      return value as T[keyof T];\n    } else {\n      const errorMessage = `The value ${value} is not valid. See the acceptable values: ${Object.values(this.enumEntity).join(', ')}`;\n      throw new BadRequestException(errorMessage);\n    }\n  }\n}\n```\n\n```text\ngetLastMeasurement(\n  ... // some other params\n    @Query('precision', new EnumValidationPipe(Precision, Precision.S)) precision: Precision\n  ) { \n  ... // do something\n}\n```\n\n========================================\n\nComments:\n- Hi Jay, thanks for your answer. When I read your approach I wonder how the framework should know how to transform a query parameter into a member of an object, which has to be created, too? Anyways I tested your approach, but got an error: TypeError: Cannot read property 'constructor' of undefined\n- Hi @JWo I am currently facing the same issue as you, seems like you need to remove the TS typing from the query variable to make it work but it affects the rest of the code. Have you found a good solution ?\n- For the error message, `Object.values(this.enumEntity)` is enough (instead of the `Object.keys` followed by the `map`).\n- I second @JaviMarz&#225;n, though I would like to also add `.join(', ')` will make the readout a bit neater too.","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":278,"estimatedTokens":1984}}428{"id":"stack-69084933","source":"stackoverflow","questionId":69084933,"title":"NestJS DTO class set class-validator and class-transformer execution order","tags":["typescript","nestjs","decorator","class-validator","class-transformer"],"text":"Title: NestJS DTO class set class-validator and class-transformer execution order\nTags: typescript, nestjs, decorator, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nIs there a way to set the **execution order of decorators** when describing a DTO class in NestJS using `class-validator` and `class-transformer` packages ?\n\nFollowing code fails when the value of `foo` is set to `null` with the error:\n\nExpected a string but received a null\n\n```\n@IsOptional()\n@IsString()\n@IsByteLength(1, 2048)\n@Transform(({ value }) => validator.trim(value))\n@Transform(({ value }) => validator.stripLow(value))\nfoo: string;\n```\n\nEven though I have a `isString` decorator that should check that indeed a string was passed and must already fail to not pass the execution to the `@Transform` decorators, but it didn't fail.\n\n========================================\n\nTop Answer:\nControl @Transfrom and Validator Decorator execution order by 2 ValidationPipe\n\nmain.ts\n\n```\nimport { ValidationPipe } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n app.useGlobalPipes(\n new ValidationPipe({\n whitelist: true,\n }),\n\n new ValidationPipe({\n transform: true,\n transformOptions: { groups: ['transform'] },\n }),\n );\n\n await app.listen(4000);\n}\nbootstrap();\n```\n\ncreate-user.dto.ts\n\n```\nexport class CreateUserDto {\n @ApiProperty({\n description: 'username',\n minLength: 4,\n maxLength: 64,\n })\n @Length(4, 64)\n name: string;\n\n @ApiProperty({\n description: 'password',\n minLength: 4,\n maxLength: 64,\n })\n @Length(6, 64)\n @Transform(({ value }: { value: string }) => hashSync(value), {\n groups: ['transform'],\n })\n password: string;\n}\n```\n\nThis will run @Length first, and then @Transform.\n\nTranslation with Deepl\n\n========================================\n\nCode:\n```js\n@IsOptional()\n@IsString()\n@IsByteLength(1, 2048)\n@Transform(({ value }) => validator.trim(value))\n@Transform(({ value }) => validator.stripLow(value))\nfoo: string;\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nfoo\n```\n\n```text\nnull\n```\n\n```text\nisString\n```\n\n```text\n@Transform\n```\n\n```text\nplainToClass\n```\n\n```text\nclass-validator\n```\n\n```text\nValidationPipe\n```\n\n```text\n@Transform()\n```\n\n```text\n@Transform()\n```\n\n```js\nimport { ValidationPipe } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  app.useGlobalPipes(\n    new ValidationPipe({\n      whitelist: true,\n    }),\n\n    new ValidationPipe({\n      transform: true,\n      transformOptions: { groups: ['transform'] },\n    }),\n  );\n\n  await app.listen(4000);\n}\nbootstrap();\n```\n\n```js\nexport class CreateUserDto {\n  @ApiProperty({\n    description: 'username',\n    minLength: 4,\n    maxLength: 64,\n  })\n  @Length(4, 64)\n  name: string;\n\n  @ApiProperty({\n    description: 'password',\n    minLength: 4,\n    maxLength: 64,\n  })\n  @Length(6, 64)\n  @Transform(({ value }: { value: string }) => hashSync(value), {\n    groups: ['transform'],\n  })\n  password: string;\n}\n```\n\n```text\nclass GetGeneratorDto {  \n    @IsStringDOM({\n        message: 'ะะต ะฑั‹ะป ะฟะตั€ะตะดะฐะฝะฑะปะพะบ',\n    })\n    @Transform(({ value }) => {\n        try {\n            return cheerio.load(value);\n        } catch {}\n    })\n    blockContent: cheerio.CheerioAPI;\n}\n```\n\n```text\nimport { registerDecorator, ValidationOptions } from 'class-validator';\nimport * as cheerio from 'cheerio';\n\nexport function IsStringDOM(validationOptions?: ValidationOptions) {\n    return function (object: any, propertyName: string) {\n        registerDecorator({\n            name: 'isStringDOM',\n            target: object.constructor,\n            propertyName: propertyName,\n            options: validationOptions,\n            validator: {\n                validate(value: cheerio.CheerioAPI) {\n                    try {\n                        const $ = value;\n\n                        const recordType = Number(\n                            $('[data-record-type]').attr('data-record-type'),\n                        );\n\n                        if (recordType !== 396) {\n                            return false;\n                        }\n\n                        return true;\n                    } catch (error) {\n                        return false;\n                    }\n                },\n            },\n        });\n    };\n}\n```\n\n```text\nundefined\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":237,"estimatedTokens":1130}}429{"id":"stack-50935416","source":"stackoverflow","questionId":50935416,"title":"Role verification in nestJs framework using passport-jwt","tags":["typescript","passport.js","nestjs"],"text":"Title: Role verification in nestJs framework using passport-jwt\nTags: typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI implemented authentication strategy basing on that article: https://docs.nestjs.com/techniques/authentication. But I would like to expand that JwtStrategy on checking roles. It would be easiest to just add checks for oles in `jwt.strategy.ts` as there is already taken user basing on JWT payload. \n\nBut I don't know how to pass additional argument to `validate` function.\n\nWhat I would like to implement: \n\n```\nasync validate(payload: JwtPayload, done: Function, role: string) { \n const user = await this.authService.validateUser(payload);\n if (!user || user.role !== role) {\n return done(new UnauthorizedException(), false);\n }\n done(null, user);\n}\n```\n\nbut I don't know how I could pass additional `role` argument to that function. I am using decorator `@UseGuards(AuthGuard('jwt'))` for enabling guard. What I would like to achieve is add there as an additional parameter `role` string and using it in JWTStrategy. \n\nWhat is easiest way to implement that? Or do I need to implement two seperate guards?\n\nEDIT: Actually I wasn't aware that AuthGuard automatically attach user to request. Solution was just simply implement RoleGuard from url pointed by @hdias2310. (https://docs.nestjs.com/guards)\n\n========================================\n\nTop Answer:\nTo add to the accepted answer, I would like to point to auth0.com that has a good section about roles based authentication.\n\n========================================\n\nCode:\n```text\nasync validate(payload: JwtPayload, done: Function, role: string) {        \n    const user = await this.authService.validateUser(payload);\n    if (!user || user.role !== role) {\n        return done(new UnauthorizedException(), false);\n    }\n    done(null, user);\n}\n```\n\n```text\njwt.strategy.ts\n```\n\n```text\nvalidate\n```\n\n```text\nrole\n```\n\n```text\n@UseGuards(AuthGuard('jwt'))\n```\n\n```text\nrole\n```\n\n========================================\n\nComments:\n- You'd need two separate Guards.\n- Works like a charm. The problem was that I wasn't aware that AuthGuard automatically attach user to request which then could be use by RoleGuard.","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":70,"estimatedTokens":552}}430{"id":"stack-54361685","source":"stackoverflow","questionId":54361685,"title":"NestJs TypeORM configuration using env files","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJs TypeORM configuration using env files\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two .env files like `dev.env` and `staging.env`. I am using typeorm as my database ORM. I would like to know how to let typeorm read either of the config file whenever I run the application. `Error: No connection options were found in any of configurations file` from typeormmodule.\n\n========================================\n\nTop Answer:\n**1) i'm using `typeorm` to to use migration, but in this case i want to use two different folders for migrations(table structure) and seeds(default data to table)**\n\n**2) so this is how i resolved this in `nestjs` with `typeorm`**\n\n```\n// config for typeorm and used for mysql driver also\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nconfig();\nconst { MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, PATH_TO_RUN \n} =\nprocess.env;\nexport const dbConfig: DataSourceOptions = {\n type: 'mysql',\n host: MYSQL_HOST,\n port: 3306,\n username: MYSQL_USER,\n password: MYSQL_PASSWORD,\n database: MYSQL_DATABASE,\n entities: ['dist/**/*.entity.js'],\n migrations: [`dist/db/${PATH_TO_RUN}/*.js`], // update this path with env\n};\nexport default new DataSource(dbConfig);\n```\n\n**3) package.json look like after using `cross-env` this for typeorm**\n\n```\n// DON'T PLACE `cross-env` in build script use it in `typeorm` execution script\nscript: {\n\"migration:run\": \"yarn build && cross-env PATH_TO_RUN=migrations yarn typeorm migration:run -d dist/db/mysql.config.js\",\n\"seed:run\": \"yarn build && cross-env PATH_TO_RUN=seeds yarn typeorm migration:run -d dist/db/mysql.config.js\"\n}\n```\n\n**4) to run this npm script use this below command**\n\nyarn migration:run // to use migrations folder in typeorm\n\nyarn seed:run // to use seeds folder in typeorm\n\n**!! Before using Yarn and Cross-env please make sure it is installed !!**\n\n```\nnpm install --global yarn\nyarn add cross-env\n```\n\n========================================\n\nCode:\n```text\ndev.env\n```\n\n```text\nstaging.env\n```\n\n```text\nError: No connection options were found in any of configurations file\n```\n\n```text\n\"start:dev\": \"cross-env NODE_ENV=dev ts-node -r tsconfig-paths/register src/main.ts\",\n\"start:staging\": \"cross-env NODE_ENV=staging node dist/src/main.js\",\n```\n\n```text\n@Injectable()\nexport class ConfigService {\n  private readonly envConfig: EnvConfig;\n\n  constructor() {\n    this.envConfig = dotenv.parse(fs.readFileSync(`${process.env.NODE_ENV}.env`));\n  }\n\n  get databaseHost(): string {\n    return this.envConfig.DATABASE_HOST;\n  }\n}\n```\n\n```text\nTypeOrmModule.forRootAsync({\n  imports:[ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    type: configService.getDatabase()\n    // ...\n  }),\n  inject: [ConfigService]\n}),\n```\n\n```text\nNODE_ENV\n```\n\n```text\nNODE_ENV\n```\n\n```text\nConfigService\n```\n\n```text\n// config for typeorm and used for mysql driver also\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nconfig();\nconst { MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, PATH_TO_RUN \n} =\nprocess.env;\nexport const dbConfig: DataSourceOptions = {\n  type: 'mysql',\n  host: MYSQL_HOST,\n  port: 3306,\n  username: MYSQL_USER,\n  password: MYSQL_PASSWORD,\n  database: MYSQL_DATABASE,\n  entities: ['dist/**/*.entity.js'],\n  migrations: [`dist/db/${PATH_TO_RUN}/*.js`], // update this path with env\n};\nexport default new DataSource(dbConfig);\n```\n\n```text\n// DON'T PLACE `cross-env` in build script use it in `typeorm` execution script\nscript: {\n\"migration:run\": \"yarn build && cross-env PATH_TO_RUN=migrations yarn typeorm migration:run -d dist/db/mysql.config.js\",\n\"seed:run\": \"yarn build && cross-env PATH_TO_RUN=seeds yarn typeorm migration:run -d dist/db/mysql.config.js\"\n}\n```\n\n```text\nnpm install --global yarn\nyarn add cross-env\n```\n\n```text\ntypeorm\n```\n\n```text\nnestjs\n```\n\n```text\ntypeorm\n```\n\n```text\ncross-env\n```\n\n========================================\n\nComments:\n- in this approach you will need second configuration file in order to use typeorm CLI\n- Did you put this in the app.module.ts? I am getting errors saying `Error: No connection options were found in any of configurations file.`.\n- @rhlsthrm Yes, in `app.module.ts`. I haven't had an error like this, would need to look at this in more detail. If you can't solve it, maybe open a new question for it. :-)\n- @KimKern, thanks for the response. I opened a new question.\n- @grexlort is right, you will need a default export config file to use TypeORM CLI managing your migration for example. But this could be imported in your ConfigService as an exception or you can be generic and import them this way","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":174,"estimatedTokens":1182}}431{"id":"stack-55354102","source":"stackoverflow","questionId":55354102,"title":"Using 'nestjs/jwt' signing with dynamic/user-related secret","tags":["javascript","node.js","typescript","jwt","nestjs"],"text":"Title: Using 'nestjs/jwt' signing with dynamic/user-related secret\nTags: javascript, node.js, typescript, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a user token based on the secret of the user trying to log in. However instead of using a secret from the environment I want to use a secret assigned to a user object inside the database.\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { JwtService } from '@nestjs/jwt';\nimport { UserService } from '@src/modules/user/services';\n\n@Injectable()\nexport class AuthService {\n public constructor(private readonly jwtService: JwtService,\n private readonly userService: UserService) {}\n\n public async createToken(email: string): Promise {\n const expiresIn = 60 * 60 * 24;\n const user = await this.userService.user({ where: { email } });\n const accessToken = await this.jwtService.signAsync({ email: user.email },\n /* user.secret ,*/\n { expiresIn });\n\n return {\n accessToken,\n expiresIn,\n };\n }\n}\n```\n\nI'm new to Nestjs and maybe I'm missing something. \nnode-jsonwebtoken does provide the necessary parameter in the `sign(...)` function. `nestjs/jwt` is missing this parameter (see code). How would you solve it without using `node-jsonwebtoken` or maybe a more abstract question: does my way of handling user secret make sense here? Thanks.\n\n========================================\n\nTop Answer:\nThe option to add `secret` into JwtSignOptions has been added in `nestjs/jwt` version **7.1.0**.\n\nWith that, the example would be:\n\n```\npublic async createToken(email: string): Promise {\n const expiresIn = 60 * 60 * 24;\n const user = await this.userService.user({ where: { email } });\n const accessToken = await this.jwtService.signAsync(\n { email: user.email },\n { expiresIn,\n secret: user.secret,\n });\n\n return {\n accessToken,\n expiresIn,\n };\n }\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { JwtService } from '@nestjs/jwt';\nimport { UserService } from '@src/modules/user/services';\n\n@Injectable()\nexport class AuthService {\n  public constructor(private readonly jwtService: JwtService,\n                     private readonly userService: UserService) {}\n\n  public async createToken(email: string): Promise<JwtReply> {\n    const expiresIn = 60 * 60 * 24;\n    const user = await this.userService.user({ where: { email } });\n    const accessToken = await this.jwtService.signAsync({ email: user.email },\n                                                        /* user.secret ,*/\n                                                        { expiresIn });\n\n    return {\n      accessToken,\n      expiresIn,\n    };\n  }\n}\n```\n\n```text\nsign(...)\n```\n\n```text\nnestjs/jwt\n```\n\n```text\nnode-jsonwebtoken\n```\n\n```bash\ncurl -X GET https://yw7wz99zv1.sse.codesandbox.io/ \\\n      -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxIiwiaWF0IjoxNTUzNjQwMjc5fQ.E5o3djesqWVHNGe-Hi3KODp0aTiQU9X_H3Murht1R5U'\n```\n\n```text\nimport * as jwt from 'jsonwebtoken';\n\nexport class AuthService {\n  constructor(private readonly userService: UserService) {}\n\n  createToken(userId: string) {\n    const user = this.userService.getUser(userId);\n    return jwt.sign({ userId: user.userId }, user.secret, { expiresIn: 3600 });\n  }\n\n  // ...\n}\n```\n\n```text\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(\n    private readonly authService: AuthService,\n    private readonly userService: UserService,\n  ) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKeyProvider: (request, jwtToken, done) => {\n        const decodedToken: any = jwt.decode(jwtToken);\n        const user = this.userService.getUser(decodedToken.userId);\n        done(null, user.secret);\n      },\n    });\n  }\n\n  // ...\n}\n```\n\n```text\nJwtModule.register({})\n```\n\n```text\nJwtModule\n```\n\n```text\n'/'\n```\n\n```text\nAuthService\n```\n\n```text\njsonwebtoken\n```\n\n```text\ncreateToken\n```\n\n```text\nJwtStrategy\n```\n\n```text\nsecretOrKeyProvider\n```\n\n```text\nsecretOrKey\n```\n\n```text\nUserService\n```\n\n```text\nJwtModule\n```\n\n```text\nexpiresIn\n```\n\n```text\nAuthService\n```\n\n```text\nJwtModule\n```\n\n```text\nAuthService\n```\n\n```text\nProductService\n```\n\n```text\nUserService\n```\n\n```text\nkid\n```\n\n```text\npublic async createToken(email: string): Promise<JwtReply> {\n    const expiresIn = 60 * 60 * 24;\n    const user = await this.userService.user({ where: { email } });\n    const accessToken = await this.jwtService.signAsync(\n        { email: user.email },\n        { expiresIn,\n          secret: user.secret,\n        });\n\n    return {\n      accessToken,\n      expiresIn,\n    };\n }\n```\n\n```text\nsecret\n```\n\n```text\nnestjs/jwt\n```\n\n```text\nimport { JwtModule } from '@nestjs/jwt';\n@Module({\n  imports: [JwtModule.register({})],\n  providers: [],\n  controllers: []\n})\nexport class AuthModule {}\n```\n\n```text\n@Injectable()\nexport class ApiConfigService {\n    constructor(private configService: ConfigService) {   \n    }\n\n    get accessTokenConfig(): any {\n        return {\n            secret: this.configService.get('JWT_ACCESS_TOKEN_KEY'),\n            expiresIn: eval(this.configService.get('JWT_ACCESS_TOKEN_LIFETIME'))\n        }\n    }\n    get refreshTokenConfig(): any {\n        return {\n            secret: this.configService.get('JWT_REFRESH_TOKEN_KEY'),\n            expiresIn: eval(this.configService.get('JWT_REFRESH_TOKEN_LIFETIME'))\n        }\n    }\n}\n```\n\n```text\n@Injectable()\nexport class AuthService {\n\n    constructor(private jwtService: JwtService, private apiConfigService: ApiConfigService ) {}\n\n    login(user: any) {\n            let payload = {username: user.username, id: user.id};\n            let jwt = this.jwtService.sign(payload, this.apiConfigService.accessTokenConfig);\n            //\n            return { token: jwt };\n        }\n       \n    }\n```\n\n========================================\n\nComments:\n- This is precisely what I ended up doing (no other choise with `nestjs&#47;jwt`). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in `secretOrKeyProvider`). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.\n- Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property\n- This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a `secretOrKeyProvider` to temporarily accept previously used secrets?\n- Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry\n- Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers\n- Correct: github.com/nestjs/jwt/pull/336. You could do the same with `secretOrKeyProvider` that I contributed long time ago. Only difference is that it's not used for key management but solely for secrets handling.\n- Good clarification @TomSiwik. This got me wondering what would be the idiomatic way to define e.g. whether one wants to sign/verify with refresh token secret or access token secret if using the `secretOrKeyProvider` (in the use case of having different tokens). The `jwt.SignOptions` and `jwt.VerifyOptions` seem not to be for this purpose.\n- Good question that could probably deserve an answer rather than a comment. No idea. I'm using this on endpoints and the endpoint itself defines how to sign it `&#47;refresh` vs `&#47;verify`. You could probably get around it with a `sub` claim tools.ietf.org/html/rfc7519#section-4.1.2 . Again... no idea.","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":294,"estimatedTokens":1922}}432{"id":"stack-56726907","source":"stackoverflow","questionId":56726907,"title":"Create a custom NestJs Decorator inheriting @Body() or @Param() decorator?","tags":["typescript","nestjs"],"text":"Title: Create a custom NestJs Decorator inheriting @Body() or @Param() decorator?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm usin NestJs, and in many of my controllers I'm using :\n\n```\n@Post(\":id\")\npublic create(\n @Param('id', new ParseIntPipe()) id: number, \n @Body(new ValidationPipe({transform: true})) myData: MyClass) {\n // ... \n }\n```\n\nI would like to clean my code by creating a custom decorator, for instance:\n\n```\n@Bind() => @Body(new ValidationPipe({transform: true}))\n```\n\nor\n\n```\n@Id() => @Param('id', new ParseIntPipe())\n```\n\nthen the code would be much more cleaner than before:\n\n```\n@Post(\":id\")\npublic create(@Id() id: number, @Bind() myData: MyClass) {\n // ... \n}\n```\n\nWhat is the correct way to inherit those decorators like this?\n\nThanks\n\n========================================\n\nTop Answer:\nPlease use this code for custom nestjs body decorator with validate request\n\n```\nexport const RBody = createParamDecorator(\n async (value: any, ctx: ExecutionContext) => {\n // extract headers\n const reqBody = ctx.switchToHttp().getRequest().body;\n // Convert headers to DTO object\n const dto = plainToInstance(value, reqBody);\n return await validateOrReject(dto).then(\n (res) => {\n console.log(`Header validated successfully..${res}`);\n return dto;\n },\n (err) => {\n if (err.length > 0) {\n //Get the errors and push to custom array\n const validationErrors = err.map((obj, key) =>\n Object.values(obj.constraints)\n );\n throwException(validationErrors);\n }\n },\n );\n return dto;\n },\n);\n```\n\n========================================\n\nCode:\n```text\n@Post(\":id\")\npublic create(\n    @Param('id', new ParseIntPipe()) id: number, \n    @Body(new ValidationPipe({transform: true})) myData: MyClass) {\n        // ... \n    }\n```\n\n```text\n@Bind() => @Body(new ValidationPipe({transform: true}))\n```\n\n```text\n@Id() => @Param('id', new ParseIntPipe())\n```\n\n```text\n@Post(\":id\")\npublic create(@Id() id: number, @Bind() myData: MyClass) {\n    // ... \n}\n```\n\n```text\nimport { Body, Param, ParseIntPipe, ValidationPipe } from '@nestjs/common';\n\nexport const Bind = () => Body(\n  new ValidationPipe({transform: true}),\n);\n\nexport const Id = () => Param('id', new ParseIntPipe());\n```\n\n```text\nimport { Id, Bind } from './decorators';\n\n// ... \n\n@Post(\":id\")\npublic create(@Id() id: number, @Bind() myData: MyClass) {\n    // ... \n}\n```\n\n```text\nexport const RBody = createParamDecorator(\n  async (value: any, ctx: ExecutionContext) => {\n    // extract headers\n    const reqBody = ctx.switchToHttp().getRequest().body;\n    // Convert headers to DTO object\n    const dto = plainToInstance(value, reqBody);\n    return await validateOrReject(dto).then(\n      (res) => {\n        console.log(`Header validated successfully..${res}`);\n        return dto;\n      },\n      (err) => {\n        if (err.length > 0) {\n          //Get the errors and push to custom array\n          const validationErrors = err.map((obj, key) =>\n            Object.values(obj.constraints)\n          );\n          throwException(validationErrors);\n        }\n      },\n    );\n    return dto;\n  },\n);\n```\n\n========================================\n\nComments:\n- I was answering the question and this came up in the meantime, lol I can confirm this does in fact work.\n- The given example did not work for me because I have a global validation pipe. I spelled all of it out in a gist here: gist.github.com/josephdpurcell/9af97c36148673de596ecaa7e5eb6&zwnj;&#8203;a0a.","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":153,"estimatedTokens":858}}433{"id":"stack-62330271","source":"stackoverflow","questionId":62330271,"title":"NestJS: My controller doesn't send the response","tags":["nestjs"],"text":"Title: NestJS: My controller doesn't send the response\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI had a controller that didn't send the response back. \n\n```\n@Controller('/foo')\nexport class FooController {\n @Post()\n public async getBar(@Body() body: DTO, @Res() res) {\n const response = await this.doSomething(body);\n return response;\n }\n}\n```\n\nI had to use the `res.send` method:\n\n```\n@Controller('/foo')\nexport class FooController {\n @Post()\n public async getBar(@Body() body: DTO, @Res() res) {\n const response = await this.doSomething(body);\n res.send(response);\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou have to use `@Res({ passthrough: true })` if you want the response to be send using the Nest way.\n\nIf you want to send the response like on Express framework use `@Res()` and add code `res.status(200).send()`\n\nhttps://docs.nestjs.com/controllers\n\nWARNING Nest detects when the handler is using either @Res() or\n@Next(), indicating you have chosen the library-specific option. If\nboth approaches are used at the same time, the Standard approach is\nautomatically disabled for this single route and will no longer work\nas expected. To use both approaches at the same time (for example, by\ninjecting the response object to only set cookies/headers but still\nleave the rest to the framework), you must set the passthrough option\nto true in the @Res({ passthrough: true }) decorator.\n\n========================================\n\nCode:\n```text\n@Controller('/foo')\nexport class FooController {\n  @Post()\n  public async getBar(@Body() body: DTO, @Res() res) {\n    const response = await this.doSomething(body);\n    return response;\n  }\n}\n```\n\n```text\n@Controller('/foo')\nexport class FooController {\n  @Post()\n  public async getBar(@Body() body: DTO, @Res() res) {\n    const response = await this.doSomething(body);\n    res.send(response);\n  }\n}\n```\n\n```text\nres.send\n```\n\n```text\n@Controller('/foo')\nexport class FooController {\n  @Post()\n  public async getBar(@Body() body: DTO) {\n    const response = await this.doSomething(body);\n    return response;\n  }\n}\n```\n\n```text\n@Res() res\n```\n\n```text\n@Res({ passthrough: true })\n```\n\n```text\n@Res()\n```\n\n```text\nres.status(200).send()\n```\n\n========================================\n\nComments:\n- Incase you need to modify the response object, see this warning from Nest: Nest detects when the handler is using either @Res() or @Next(), indicating you have chosen the library-specific option. If both approaches are used at the same time, the Standard approach is automatically disabled for this single route and will no longer work as expected. To use both approaches at the same time (for example, by injecting the response object to only set cookies/headers but still leave the rest to the framework), you must set the passthrough option to true in the @Res({ passthrough: true }) decorator.\n- In my case, I removed the @Res() but all GET method don't return any response body. Do you guys know why it happen?","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":110,"estimatedTokens":747}}434{"id":"stack-53205581","source":"stackoverflow","questionId":53205581,"title":"How to return 202 Accepted and then continue processing the request in Nest.js","tags":["javascript","node.js","asynchronous","nestjs","long-running-processes"],"text":"Title: How to return 202 Accepted and then continue processing the request in Nest.js\nTags: javascript, node.js, asynchronous, nestjs, long-running-processes\nSource: Stack Overflow\n\nQuestion:\nI need a controller action that:\n\n- Authorizes the call\n\n- Validates it\n\n- Returns the 202 Accepted status\n\n- Continues processing the request\n\n- Makes a call to external API with the results of previously accepted and now processed request.\n\nFirst two points are easy, I use `AuthGuard` then `class-validator`. But I don't know how to return the HTTP response then continue with processing.\n\nAs the request consists of an array of (possibly long-running) tasks I thought of using interceptor that uses RxJS to observes the status of tasks and calls external PI upon their completion. However, I have no experience with using RxJS or interceptors (not this way) so I'd really don't know how to leave interceptor's process running but immediately pass control to controller's action. \n\nAlso, perhaps there is another, better way? No interceptor but just put all the flow logic in the controller? Some other option?\n\n========================================\n\nTop Answer:\nIf your service returns a promise you could do something like the following, the API will return 202 while the processing continues. Of course any processing with the 'then' is happening after 'beginProcessing' is complete.\n\n```\n@Post()\n@HttpCode(HttpStatus.ACCEPTED)\nbeginProcessing(@Req() request, @Body() data: Data): void {\n this.service.process(data).then(...);\n}\n```\n\n========================================\n\nCode:\n```text\nAuthGuard\n```\n\n```text\nclass-validator\n```\n\n```text\n@Injectable()\nexport class ExternalApiService {\n  constructor(private readonly httpService: HttpService) {}\n\n  makeApiCall(data): Observable<AxiosResponse<any>> {\n    return this.httpService.post('https://external.api', data);\n  }\n}\n```\n\n```text\n@Post()\n@UseGuards(AuthGuard('jwt'))\n@HttpCode(HttpStatus.ACCEPTED)\nasync post(@Body(new ValidationPipe()) myDataDto: MyDataDto) {\n  // The preprocessing might throw an exception, so we need to wait for the result\n  const preprocessedData = await this.preprocessService.preprocess(myDataDto);\n                           ^^^^^\n  // We do not need the result to respond to the request, so no await\n  this.externalApiService.makeApiCall(preprocessedData);\n  return 'Your data is being processed.';\n}\n```\n\n```text\nPromise\n```\n\n```text\nObservable\n```\n\n```text\nasync/await\n```\n\n```text\nPromise\n```\n\n```text\nObservable\n```\n\n```text\nthis.preprocessService.preprocess(myDataDto)\n```\n\n```text\nawait\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\n@Post()\n@HttpCode(HttpStatus.ACCEPTED)\nbeginProcessing(@Req() request, @Body() data: Data): void {\n    this.service.process(data).then(...);\n}\n```\n\n========================================\n\nComments:\n- If I wanted to use this to call an internal API, I could definitely just do a full http post, but not sure how to invoke my internal observable directly without awaiting it.\n- to answer my own comment, my solution is instead of returning the observable to the nest controller and relying on nest to call `subscribe` behind the scenes, I'm directly calling `.subscribe()` on the observable and then returning a value right away\n- @KyleMit Sorry for my late reply Kyle, I was very busy the last couple of weeks. -- Exactly, that's a good option, glad you found a solution so quickly. Alternatively, if you prefer working with promises, you can also call `toPromise` on the `Observable`.\n- Hey Kim, thanks very much for the answer and the update. I originally went with `toPromise` but then got some warnings that toPromise is being deprecated in v7 and removed in v8","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":123,"estimatedTokens":924}}435{"id":"stack-67614748","source":"stackoverflow","questionId":67614748,"title":"how to disable swagger for production in nestjs","tags":["swagger","nestjs","swagger-ui"],"text":"Title: how to disable swagger for production in nestjs\nTags: swagger, nestjs, swagger-ui\nSource: Stack Overflow\n\nQuestion:\nI am adding the swagger-ui to my nestjs app. I need to disable that swagger in production. I searched over the nestjs documentation, I didn't find any useful. I need a good resource or guidance to disable the swagger in production.\n\n========================================\n\nCode:\n```text\nMONGO_URI=\"mongodb://localhost:27017/quotesdb\"\nNODE_ENV=production\n```\n\n```text\nimport 'dotenv/config';\n\nimport { NestFactory } from '@nestjs/core';\nimport { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  app.enableCors();\n\n  if (process.env.NODE_ENV !== 'production') {\n    const options = new DocumentBuilder()\n      .setTitle('Quotes Api')\n      .setDescription('Quotes API Description')\n      .setVersion('1.1')\n      .addTag('quotes')\n      .build();\n\n    const document = SwaggerModule.createDocument(app, options);\n    SwaggerModule.setup('api/swagger', app, document);\n  }\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- if `@nestjs&#47;swagger` is only a dev dependency, then `main.ts` file will throw an error while running it after the build that it can't find `@nest&#47;swagger`. which might break the current solution\n- if you are talking in terms of docker since the same image needs to be deployed in lower(dev, qa,int, for instance) and prod, then putting the swagger in dev deps anyways is not the correct flow. because images are built pre deployment and we cant do, if else in that.\n- so far the best solution","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":50,"estimatedTokens":433}}436{"id":"stack-50274228","source":"stackoverflow","questionId":50274228,"title":"How to use HTTP/2 with Nest.js (Node)","tags":["node.js","express","http2","nestjs"],"text":"Title: How to use HTTP/2 with Nest.js (Node)\nTags: node.js, express, http2, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have read that Express 4.x is not compatible with Node.js native HTTP2 (from 8.4+), and I was hoping for more progess on Express 5.x than it has.\nBut as I started thinking that Express5.x will probably be released to late for my next Node.js project - I came over Nest.js.\n\nDoes anyone know if Nest.js can be used with native HTTP2 support ??\n\nThe only Node.js framework that I have heard of that supports this is Fastify.\nOr are there any other out there ? Preferable one that support Express plugins.\n\n========================================\n\nCode:\n```sh\nyarn add spdy\nyarn add -D @types/spdy\n```\n\n```sh\nopenssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout test.key -out test.crt\n```\n\n```js\n// main.ts\nasync function bootstrap() {\n\n  const expressApp: Express = express();\n\n  const spdyOpts: ServerOptions = {\n    key: fs.readFileSync('./test.key'),\n    cert: fs.readFileSync('./test.crt'),\n  };\n\n  const server: Server = spdy.createServer(spdyOpts, expressApp);\n\n  const app: NestApplication = await NestFactory.create(\n    AppModule,\n    new ExpressAdapter(expressApp),\n  );\n  \n  await app.init();\n  await server.listen(3000);\n}\n\nbootstrap();\n```\n\n```sh\n$ curl -I -k https://localhost:3000/\nHTTP/2 200 \nx-powered-by: Express\ncontent-type: text/html; charset=utf-8\ncontent-length: 12\netag: W/\"c-Lve95gjOVATpfV8EL5X4nxwjKHE\"\n```\n\n```text\nmain.ts\n```\n\n```text\nHTTP/2\n```\n\n========================================\n\nComments:\n- I donโ€™t know the answer to your question but as an alternative why not just through a webserver (e.g. Apache or Nginx) in front of it and keep Node on HTTP/1.1 until HTTP/2 is better supported on it? To be honest having a webserver in front for static resources is usually better anyway.\n- What are the .key and .crt file?","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":469}}437{"id":"stack-55491137","source":"stackoverflow","questionId":55491137,"title":"No metadata found for class-validator","tags":["javascript","node.js","typescript","nestjs","class-validator"],"text":"Title: No metadata found for class-validator\nTags: javascript, node.js, typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI am trying to use a `ValidationPipe` but no matter how I write my code I get the following warning when sending a request: `No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies`.\n\nMy route looks something like this:\n\n```\n@Get()\n@UsePipes(new ValidationPipe({ transform: true }))\nasync findAll(@Query() queryDto: QueryDto) {\n return await this.myService.findAll(queryDto);\n}\n```\n\nAnd my DTO looks something like this:\n\n```\nexport class queryDto\n{\n @ApiModelProperty({\n description: 'Maximum number of results',\n type: Number,\n example: 50,\n default: 50,\n required: false\n })\n readonly limit: number = 50;\n}\n```\n\nI tried using the `ValidationPipe` several ways, following the doc, but nothing works for me. I know it does not work because although the request gets a response, the default value that I wrote in my DTO for the property `limit`, which is `50`, is not used when the query is empty. Therefore, when no `limit` is provided in the query, `limit`'s value is undefined, whereas it should be `50` (which means the `ValidationPipe` is not used).\n\nMy `package.json` seems correct:\n\n```\nnpm ls class-validator\napi-sport@0.0.1 /home/pierre_t/Bureau/dev/ApiSport\nโ””โ”€โ”€ class-validator@0.9.1\n```\n\nFull `package.json`:\n\n```\n{\n \"name\": \"api-sport\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n \"start:dev\": \"nodemon\",\n \"start:debug\": \"nodemon --config nodemon-debug.json\",\n \"start:prod\": \"pm2 start ./src/main.js --no-daemon\",\n \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"^6.0.5\",\n \"@nestjs/core\": \"^6.0.5\",\n \"@nestjs/platform-express\": \"^6.0.5\",\n \"@nestjs/swagger\": \"^3.0.1\",\n \"@nestjs/typeorm\": \"^6.0.0\",\n \"@types/lodash\": \"^4.14.123\",\n \"class-transformer\": \"^0.2.0\",\n \"class-validator\": \"^0.9.1\",\n \"dotenv\": \"^7.0.0\",\n \"hbs\": \"^4.0.3\",\n \"mysql\": \"^2.16.0\",\n \"pm2\": \"^3.4.1\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.3.3\",\n \"swagger-ui-express\": \"^4.0.2\",\n \"typeorm\": \"^0.2.16\"\n },\n \"devDependencies\": {\n \"@nestjs/testing\": \"^6.0.5\",\n \"@types/express\": \"^4.16.0\",\n \"@types/jest\": \"^23.3.13\",\n \"@types/node\": \"^10.14.4\",\n \"@types/supertest\": \"^2.0.7\",\n \"jest\": \"^23.6.0\",\n \"nodemon\": \"^1.18.9\",\n \"prettier\": \"^1.15.3\",\n \"supertest\": \"^3.4.1\",\n \"ts-jest\": \"^23.10.5\",\n \"ts-node\": \"^7.0.1\",\n \"tsconfig-paths\": \"^3.7.0\",\n \"tslint\": \"5.12.1\",\n \"typescript\": \"^3.4.1\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"../coverage\",\n \"testEnvironment\": \"node\"\n }\n}\n```\n\nWhy do I get this message and how can I use `ValidationPipe`?\n\n========================================\n\nTop Answer:\nThe question has already been answered, but for future reference of people with the same problem...\n\nThe class-validator allows you to bypass the validation of certain property (**whitelisting**) special flags to validate any property.\n\nAs the docs: \n\n This will strip all properties that don't have any decorators. If no\n other decorator is suitable for your property, you can use **@Allow**\n decorator\n\ne.g:\n\n```\nimport {validate, Allow, Min} from \"class-validator\";\n\nexport class Post {\n\n @Allow()\n title: string;\n\n @Min(0)\n views: number;\n\n nonWhitelistedProperty: number;\n}\n```\n\n========================================\n\nCode:\n```text\n@Get()\n@UsePipes(new ValidationPipe({ transform: true }))\nasync findAll(@Query() queryDto: QueryDto) {\n    return await this.myService.findAll(queryDto);\n}\n```\n\n```text\nexport class queryDto\n{\n    @ApiModelProperty({\n        description: 'Maximum number of results',\n        type: Number,\n        example: 50,\n        default: 50,\n        required: false\n    })\n    readonly limit: number = 50;\n}\n```\n\n```text\nnpm ls class-validator\napi-sport@0.0.1 /home/pierre_t/Bureau/dev/ApiSport\nโ””โ”€โ”€ class-validator@0.9.1\n```\n\n```text\n{\n  \"name\": \"api-sport\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n    \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n    \"start:dev\": \"nodemon\",\n    \"start:debug\": \"nodemon --config nodemon-debug.json\",\n    \"start:prod\": \"pm2 start ./src/main.js --no-daemon\",\n    \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^6.0.5\",\n    \"@nestjs/core\": \"^6.0.5\",\n    \"@nestjs/platform-express\": \"^6.0.5\",\n    \"@nestjs/swagger\": \"^3.0.1\",\n    \"@nestjs/typeorm\": \"^6.0.0\",\n    \"@types/lodash\": \"^4.14.123\",\n    \"class-transformer\": \"^0.2.0\",\n    \"class-validator\": \"^0.9.1\",\n    \"dotenv\": \"^7.0.0\",\n    \"hbs\": \"^4.0.3\",\n    \"mysql\": \"^2.16.0\",\n    \"pm2\": \"^3.4.1\",\n    \"reflect-metadata\": \"^0.1.12\",\n    \"rimraf\": \"^2.6.2\",\n    \"rxjs\": \"^6.3.3\",\n    \"swagger-ui-express\": \"^4.0.2\",\n    \"typeorm\": \"^0.2.16\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/testing\": \"^6.0.5\",\n    \"@types/express\": \"^4.16.0\",\n    \"@types/jest\": \"^23.3.13\",\n    \"@types/node\": \"^10.14.4\",\n    \"@types/supertest\": \"^2.0.7\",\n    \"jest\": \"^23.6.0\",\n    \"nodemon\": \"^1.18.9\",\n    \"prettier\": \"^1.15.3\",\n    \"supertest\": \"^3.4.1\",\n    \"ts-jest\": \"^23.10.5\",\n    \"ts-node\": \"^7.0.1\",\n    \"tsconfig-paths\": \"^3.7.0\",\n    \"tslint\": \"5.12.1\",\n    \"typescript\": \"^3.4.1\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".spec.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  }\n}\n```\n\n```text\nValidationPipe\n```\n\n```text\nNo metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies\n```\n\n```text\nValidationPipe\n```\n\n```text\nlimit\n```\n\n```text\n50\n```\n\n```text\nlimit\n```\n\n```text\nlimit\n```\n\n```text\n50\n```\n\n```text\nValidationPipe\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nValidationPipe\n```\n\n```text\nimport { Min } from 'class-validator';\nexport class QueryDto {\n    @Min(1)\n    readonly limit: number = 50;\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nvalidate: false\n```\n\n```text\nbuildSchema\n```\n\n```text\nValidationPipe\n```\n\n```text\n@Query\n```\n\n```text\nlimit\n```\n\n```text\nstring\n```\n\n```text\nnumber\n```\n\n```text\nimport {validate, Allow, Min} from \"class-validator\";\n\nexport class Post {\n\n    @Allow()\n    title: string;\n\n    @Min(0)\n    views: number;\n\n    nonWhitelistedProperty: number;\n}\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```js\n/** this fails */\nimport {Body} from '@nestjs/common';\nimport type {CreatePageDto} from './pages/dto/create-page.dto';\n\ncreatePage(@Body() pageDto: CreatePageDto) { ... }\n```\n\n```js\n/** this works */\nimport {Body} from '@nestjs/common';\nimport {CreatePageDto} from './pages/dto/create-page.dto';\n\ncreatePage(@Body() pageDto: CreatePageDto) { ... }\n```\n\n```text\nclass-validator\n```\n\n```text\n0.14.1\n```\n\n```text\n@Body\n```\n\n```text\n@Query\n```\n\n```text\nclass-validator\n```\n\n```text\nCreatePageDto\n```\n\n========================================\n\nComments:\n- Can you add your `package.json`? It seems that you have multiple version of `class-validator` in your `node_modules`.\n- @KimKern I updated my answer with relevant informations concerning my `package.json`\n- Please post your complete `package.json`. It can be a sub-dependency of another library you used.\n- You can also try `npm ls class-validator`\n- @KimKern I added the whole file + npm ls\n- What is `buildSchema`? Where do I find/declare it?\n- (somehow, after trying what you suggested, I **cannot** manage to get `undefined` again. I reverted my code back to the version where I got `undefined` as default value, but I don't get `undefined` anymore, I get the default value, even without class-validator, and without a ValidationPipe. Wtf? That's black magic. But that's just a detail, my problem is pretty much solved it seems)\n- Glad it's working for you now. :-) I've just tried it without the `ValidationPipe` and it doesn't set default values for me. Important for setting the default value is that your dto class is actually instantiated. Otherwise it will be a plain javascript object.","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":417,"estimatedTokens":2303}}438{"id":"stack-67929800","source":"stackoverflow","questionId":67929800,"title":"NestJs Async controller method vs calling await / async inside a method","tags":["node.js","async-await","nestjs"],"text":"Title: NestJs Async controller method vs calling await / async inside a method\nTags: node.js, async-await, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm bit new to NodeJs & NestJs. I always wondered what's the difference between using async as the method return type inside a controller vs executing async operation inside a regular method ? How does NodeJs handles the request in both these cases if there is huge traffic on this API (eg. 40K req/min). Will it be blocking in the 2nd example and non blocking in the 1st or would it work in a similar way?\n\nFor Eg:\n\n```\n@Controller('cats')\nexport class CatsController {\n constructor(private catsService: CatsService) {}\n\n @Post()\n async sample() {\n return \"1234\";\n }\n}\n```\n\nvs\n\n```\n@Controller('cats')\nexport class CatsController {\n constructor(private catsService: CatsService) {}\n\n @Post()\n function sample() {\n return await methodX();\n }\n \n async function methodX(){\n return \"1234\"\n }\n```\n\nPlease ***ignore what the content in sample() & methodX() does*** its only for example.\n\n========================================\n\nTop Answer:\nRegarding performance under load it depends entirely on what is being awaited. Async - await patterns give a performance benefit if the awaited function is blocked (e.g. by disk access), and there is other useful work that can be done e.g. another non-IO blocked request. This allows the main thread to hand off processing to another worker thread, and then return back to it later when done. This can be very beneficial to responsiveness, as the request processing threads can execute many more requests that are long running. That's the theory.\n\nIt should be said in the trivial example you give async await will probably perform much worse under high load, as the method must paused, added to a queue, pulled off, executed, and then returned. These are expensive operations. Some JIT engines will optimise these steps away. I do not know if NodeJS has all these optimisations yet.\n\nIn my experience these kind of optimisations are hard to see in practice on requests shorter than 50ms. Above that, you will likely be concurrency locked on IO at this point which means there are other optimisations that will benefit first. Normally this involves moving slower performing blocking requests into a distinct separate microservice/process, to avoid slowing the high performance queries.\n\nTherefore I am unfashionable, and say given the extra code burden of the pattern, I think it rarely benefits projects and should be a late stage optimisation on key services, and avoided unless you know what you're doing. Unfortunately everyone seems to have drunk the async await cool-aid and use it everywhere...\n\n========================================\n\nCode:\n```text\n@Controller('cats')\nexport class CatsController {\n  constructor(private catsService: CatsService) {}\n\n  @Post()\n  async sample() {\n    return \"1234\";\n  }\n}\n```\n\n```text\n@Controller('cats')\nexport class CatsController {\n  constructor(private catsService: CatsService) {}\n\n  @Post()\n   function sample() {\n    return await methodX();\n  }\n  \n  async function methodX(){\n      return \"1234\"\n  }\n```\n\n```text\n@Post()\nasync function sample() {\n  // Now `await` can be used inside `sample`\n  return await methodX();\n}\n```\n\n```text\n// Sample 1\n@Post()\nasync sample() {\n  return \"1234\";\n}\n\n// Sample 2\n@Post()\nfunction async sample() {\n  return await methodX();\n}\n  \nasync function methodX(){\n  return \"1234\"\n}\n```\n\n```text\n@Post()\nsyncSample() {\n  return \"1234\";\n}\n```\n\n```text\n@Post()\nfunction async sample() {\n  return await methodX();\n}\n  \nasync function methodX(){\n  throw new Error('something failed')\n}\n```\n\n```text\n@Post()\nfunction async sample() {\n  const result = await methodX();\n\n  return result;\n}\n  \nasync function methodX(){\n  throw new Error('something failed')\n}\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nsample\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nmethodX\n```\n\n```text\nasync\n```\n\n```text\nasync\n```\n\n```text\nasync\n```\n\n```text\nsetTimeout\n```\n\n```text\nreturn await\n```\n\n```text\nsample\n```\n\n```text\nreturn await\n```\n\n```text\nmethodX\n```\n\n```text\nsample\n```\n\n========================================\n\nComments:\n- I think your second example should remove โ€œawaitโ€ keyword from the return statement to make your question clear and the code to be syntactically correct.\n- note that `return await` is syntactically correct. But the usage in there is useless since there's no error handling in `sample` method.\n- Is there a difference in returning a promise by not awaiting here. I have also seen that as a practice, but don't fully understand what that entails. Essentially, just `async methodX() { return methodY() }`. Inside the function, you are of course doing async await stuff, but you don't actually await the function return. What does the client receive as a response?\n- It works as well since the client receives a `Promise`. This is indeed a common pattern to return the `Promise` itself instead of awaiting it","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":205,"estimatedTokens":1248}}439{"id":"stack-69074405","source":"stackoverflow","questionId":69074405,"title":"NestJS - Cannot set headers after they are sent to the client","tags":["node.js","express","nestjs","http-status"],"text":"Title: NestJS - Cannot set headers after they are sent to the client\nTags: node.js, express, nestjs, http-status\nSource: Stack Overflow\n\nQuestion:\nIn my NestJs project, I am using decorator `@Res() res` and using the response object to set custom response header status by multiple cases.\nWhen calling, sometimes it logs: `Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client`\n\nAfter I viewed the issues list in Github and searching on the internet, I know this is relating to Express middleware and the built-in filter of NestJs.\n\nSo, I remove `.send()` and add `return;` at the end of the Controller method, the log will disappear.\n\nMy first code:\n\n```\n@Get()\nget(@Req() req, @Res() res) {\n const result = this.service.getData(req);\n res.status(result.statusCode).json(result.data).send(); // when using .send(), it will cause error\n}\n```\n\nCode after I fixed look like this:\n\n```\n@Get()\nget(@Req() req, @Res() res) {\n const result = this.service.getData(req);\n res.status(result.statusCode).json(result.data); // when remove .send(), it will succeed\n return;\n}\n```\n\nMy question: Do I have to add `return;` at the end of the method? Why using `.send()` **sometimes** cause error but not **always**?\n\n========================================\n\nCode:\n```text\n@Get()\nget(@Req() req, @Res() res) {\n  const result = this.service.getData(req);\n  res.status(result.statusCode).json(result.data).send(); // when using .send(), it will cause error\n}\n```\n\n```text\n@Get()\nget(@Req() req, @Res() res) {\n  const result = this.service.getData(req);\n  res.status(result.statusCode).json(result.data); // when remove .send(), it will succeed\n  return;\n}\n```\n\n```text\n@Res() res\n```\n\n```text\nError [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client\n```\n\n```text\n.send()\n```\n\n```text\nreturn;\n```\n\n```text\nreturn;\n```\n\n```text\n.send()\n```\n\n```text\nreturn res.status(result.statusCode).json(result.data);\n```\n\n```text\nres.status(result.statusCode).json(result.data); //response is sent\nlet a = \"Something good\"; // Code will be executed\nconsole.log(a); // Code will be executed\n```\n\n```text\nrequet.json({...})\n```\n\n```text\n.send()\n```\n\n```text\nrequet.json({...})\n```\n\n```text\nreturn\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.443Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":104,"estimatedTokens":558}}440{"id":"stack-72361047","source":"stackoverflow","questionId":72361047,"title":"Error: No \"exports\" main defined in graphql-upload/package.json","tags":["javascript","graphql","nestjs","express-graphql"],"text":"Title: Error: No \"exports\" main defined in graphql-upload/package.json\nTags: javascript, graphql, nestjs, express-graphql\nSource: Stack Overflow\n\nQuestion:\nHave installed graphql-upload, do\n\n`import { graphqlUploadExpress } from 'graphql-upload';`\n\nAnd getting this error:\nError: No \"exports\" main defined in graphql-upload/package.json\n\nDependencies:\n\n```\n\"graphql-upload\": \"^14.0.0\",\n\"graphql\": \"15.8.0\",\n\"graphql-request\": \"^4.2.0\",\n\"graphql-tools\": \"^8.2.0\",\n\"@nestjs/axios\": \"^0.0.7\",\n\"@nestjs/common\": \"^8.4.1\",\n\"@nestjs/config\": \"^1.1.5\",\n\"@nestjs/core\": \"^8.4.1\",\n\"@nestjs/graphql\": \"^9.1.2\",\n\"@nestjs/platform-express\": \"^8.0.0\",\n```\n\nThe version of node: v16.10.0\n\n========================================\n\nTop Answer:\nJust ran into this problem.\nApparently, the the new version `i.e. ^16` ,has a major update\n\nnow you need to do\n\n`const Upload = require('graphql-upload/Upload.mjs');`\n\nor\n\n`import { default as Upload } from 'graphql-upload/Upload.mjs';`\n\nInstead of `.js`, all the imports needs to be from `.mjs`.\n\nHope this helps!\n\n========================================\n\nCode:\n```text\n\"graphql-upload\": \"^14.0.0\",\n\"graphql\": \"15.8.0\",\n\"graphql-request\": \"^4.2.0\",\n\"graphql-tools\": \"^8.2.0\",\n\"@nestjs/axios\": \"^0.0.7\",\n\"@nestjs/common\": \"^8.4.1\",\n\"@nestjs/config\": \"^1.1.5\",\n\"@nestjs/core\": \"^8.4.1\",\n\"@nestjs/graphql\": \"^9.1.2\",\n\"@nestjs/platform-express\": \"^8.0.0\",\n```\n\n```text\nimport { graphqlUploadExpress } from 'graphql-upload';\n```\n\n```text\nimport Upload = require('graphql-upload/Upload.js');\n```\n\n```text\n\"exports\": {\n    \"./GraphQLUpload.js\": \"./GraphQLUpload.js\",\n    \"./graphqlUploadExpress.js\": \"./graphqlUploadExpress.js\",\n    \"./graphqlUploadKoa.js\": \"./graphqlUploadKoa.js\",\n    \"./package.json\": \"./package.json\",\n    \"./processRequest.js\": \"./processRequest.js\",\n    \"./Upload.js\": \"./Upload.js\"\n  },\n```\n\n```text\ngraphql-upload\n```\n\n```text\nindex.js\n```\n\n```text\npackage.json\n```\n\n```text\nexports\n```\n\n```text\nimport graphqlUploadKoa from \"graphql-upload/graphqlUploadKoa.js\";\n```\n\n```text\npackage.json\n```\n\n```text\ngraphql-upload\n```\n\n```text\n// @ts-ignore\nimport GraphQLUpload from 'graphql-upload/GraphQLUpload.js';\n// @ts-ignore\nimport Upload from 'graphql-upload/Upload.js';\n```\n\n```text\nconst graphqlUploadExpress = require('graphql-upload/graphqlUploadExpress.js');\n```\n\n```text\nconst GraphQLUpload = require('graphql-upload/GraphQLUpload.js');\n```\n\n```text\nimport { graphqlUploadExpress } from 'graphql-upload';\n```\n\n```text\ni.e. ^16\n```\n\n```text\nconst Upload = require('graphql-upload/Upload.mjs');\n```\n\n```text\nimport { default as Upload } from 'graphql-upload/Upload.mjs';\n```\n\n```text\n.js\n```\n\n```text\n.mjs\n```\n\n```text\nconst {\n  graphqlUploadExpress, // A Koa implementation is also exported.\n} = require(\"graphql-upload\");\nconst { GraphQLUpload } = require(\"graphql-upload\");\n```\n\n```text\nconst {\n  graphqlUploadExpress, // A Koa implementation is also exported.\n} = require(\"graphql-upload-minimal\");\nconst { GraphQLUpload } = require(\"graphql-upload-minimal\");\n```\n\n```text\n{\n   \"dependencies\": {\n      \"@nestjs/apollo\": \"^10.1.7\",\n      \"@nestjs/axios\": \"1.0.0\",\n      \"@nestjs/common\": \"^9.3.9\",\n      \"@nestjs/config\": \"^2.0.0\",\n      \"@nestjs/core\": \"^9.3.9\",\n      \"@nestjs/graphql\": \"10.2.0\",\n      \"@nestjs/platform-express\": \"^9.3.9\",\n      \"graphql\": \"^16.6.0\",\n      \"graphql-upload\": \"15.0.2\"\n   },\n   \"exports\": {\n     \"./GraphQLUpload.js\": \"./GraphQLUpload.js\",\n     \"./graphqlUploadExpress.js\": \"./graphqlUploadExpress.js\",\n     \"./graphqlUploadKoa.js\": \"./graphqlUploadKoa.js\",\n     \"./package.json\": \"./package.json\",\n     \"./processRequest.js\": \"./processRequest.js\",\n     \"./Upload.js\": \"./Upload.js\"\n   }\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"allowJs\": true,\n    \"maxNodeModuleJsDepth\": 10\n  }\n}\n```\n\n```text\n// @ts-ignore\n    import Upload = require('graphql-upload/Upload.js');\n    // @ts-ignore\n    import GraphQLUpload = require('graphql-upload/GraphQLUpload.js');\n    \n    ...\n    \n    @Mutation(() => Boolean, {\n       name: 'uploadImages',\n       description: 'Insert array photos',\n    })\n    async uploadImages(\n        @Args('files', { type: () => [GraphQLUpload] })\n        files: [Upload],\n        @Args('metadata')\n        metadata: UploadImagesMetadataArgs,\n      ): Promise<Boolean> {\n        const functionPrefix = 'uploadImages';\n        try {\n          let uploadImagesArgs: Array<UploadImagesArgs> = [];\n          for (const file of files) {\n            // @ts-ignore\n            const { filename, mimetype, encoding, createReadStream } = await file;\nconst stream = createReadStream();\n            const chunks = [];\n            for await (const chunk of stream) {\n               chunks.push(chunk);\n            }\n            const buffer = Buffer.concat(chunks);\n            uploadImagesArgs.push({ buffer, filename, mimetype });\n            // your code with connect with services for save your images\n            return true;\n          }\n        } catch(error){\n             // your code \n             return false;\n        }\n      }\n```\n\n========================================\n\nComments:\n- Then use app.use(graphqlUploadExpress()); and see an error: TypeError: (0 , graphqlUploadExpress_js_1.default) is not a function at Function.main (/blablabla/src/main.ts:28:33) at processTicksAndRejections (node:internal/process/task_queues:95:5) error Command failed with exit code 1.\n- For me by doing this `import graphqlUploadExpress from 'graphql-upload&#47;graphqlUploadExpress.js'`, type of `graphqlUploadExpress` returned a function. Make sure you write that `.js` extension in the import line also.","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":253,"estimatedTokens":1477}}441{"id":"stack-59194647","source":"stackoverflow","questionId":59194647,"title":"NestJS Swagger: Describe Map inside ApiProperty Decorator","tags":["json","typescript","swagger","nestjs"],"text":"Title: NestJS Swagger: Describe Map inside ApiProperty Decorator\nTags: json, typescript, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an NestJS API in front of an InfluxDB. In the API I want to add property description via the ApiProptery decorator from nestjs/swagger.\n\nMy Problem here is that I don't know how to create a proper description for a map.\n\nHere is my model:\n\n```\nimport { Precision } from '../shared/enums';\nimport { IsEnum, IsInt, IsOptional } from 'class-validator';\nimport { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';\nimport { IsPrimitive } from '../shared/decorator/decorators';\n\nexport class CreateMeasurementDto {\n @IsOptional()\n @IsInt()\n @ApiPropertyOptional()\n timestamp: number;\n\n @IsOptional()\n @IsEnum(Precision)\n @ApiPropertyOptional({ enum: Precision })\n precision: Precision;\n\n @ApiProperty({\n description:\n 'Key/value pairs; values can be of type string, boolean or number.',\n type: Map,\n })\n @IsPrimitive()\n datapoints: Map;\n}\n```\n\nWhat I get in the SwaggerUi schema section is this:\n\n```\nCreateMeasurementDto{\n timestamp number\n precision string\n Enum:[ s, ms, u, ns ]\n datapoints* Map {\n }\n}\n```\n\nI want at least give an example or describe an element of the map. Both would be awesome.\n\nThe map is allowed to have strings as keys, while values can be string, boolean or number.\n\nHere is a possible payload, that would be accepted:\n\n```\n{\n \"precision\": \"s\",\n \"datapoints\": {\n \"voltage\": 123.6456,\n \"current\": 123\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Precision } from '../shared/enums';\nimport { IsEnum, IsInt, IsOptional } from 'class-validator';\nimport { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';\nimport { IsPrimitive } from '../shared/decorator/decorators';\n\nexport class CreateMeasurementDto {\n  @IsOptional()\n  @IsInt()\n  @ApiPropertyOptional()\n  timestamp: number;\n\n  @IsOptional()\n  @IsEnum(Precision)\n  @ApiPropertyOptional({ enum: Precision })\n  precision: Precision;\n\n  @ApiProperty({\n    description:\n      'Key/value pairs; values can be of type string, boolean or number.',\n    type: Map,\n  })\n  @IsPrimitive()\n  datapoints: Map<string, string | boolean | number>;\n}\n```\n\n```text\nCreateMeasurementDto{\n    timestamp   number\n    precision   string\n                Enum:[ s, ms, u, ns ]\n    datapoints* Map {\n                }\n}\n```\n\n```text\n{\n    \"precision\": \"s\",\n    \"datapoints\": {\n            \"voltage\": 123.6456,\n            \"current\": 123\n        }\n}\n```\n\n```js\n@ApiProperty({\n  type: 'object',\n  additionalProperties: {\n    oneOf: [\n      { type: 'string' },\n      { type: 'number' },\n      { type: 'boolean' }\n    ]\n  }\n})\ndatapoints: Map<string, string | boolean | number>;\n```\n\n```text\nnestjs/swagger\n```\n\n========================================\n\nComments:\n- great thanks a lot. I just started with typescript and nestjs and didn't work with swagger for a (long) while.\n- Would you please take a look at this question stackoverflow.com/questions/64939247/nestjs-swagger-mixed-ty&zwnj;&#8203;pes","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":139,"estimatedTokens":759}}442{"id":"stack-62671831","source":"stackoverflow","questionId":62671831,"title":"How to implement multiple passport jwt authentication strategies in Nestjs","tags":["node.js","typescript","authentication","passport.js","nestjs"],"text":"Title: How to implement multiple passport jwt authentication strategies in Nestjs\nTags: node.js, typescript, authentication, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an existing authentication for users which is already working fine. The token for user authentication expires within an hour.\n\nI want to implement another separate authentication strategy a third API that is consuming my Nestjs API. There are separate endpoints for the third-party API, the token should expire with 24 hours. The API has to stay connected to my app for 24 hours.\n\nI don't mind using additional package to achieve this.\n\nI also need to create a guard called thirdParty Guard so that the 3rd part API alone will have access to that endpoint.\n\nThis is my jwt.strategy.ts\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: process.env.SECRETKEY\n });\n }\n\n async validate(payload: any, done: VerifiedCallback) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n return done(\n new HttpException('Unauthorised access', HttpStatus.UNAUTHORIZED),\n false,\n );\n }\n //return user;\n return done(null, user, payload.iat)\n }\n}\n```\n\nApiKey.strategy.ts\n\n```\n@Injectable()\nexport class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {\n constructor(private authService: AuthService) {\n super({\n header: 'api_key',\n prefix: ''\n }, true,\n (apikey: string, done: any, req: any, next: () => void) => {\n const checkKey = this.authService.validateApiKey(apikey);\n if (!checkKey) {\n return done(\n new HttpException('Unauthorized access, verify the token is correct', HttpStatus.UNAUTHORIZED),\n false,\n );\n }\n return done(null, true, next);\n });\n }\n}\n```\n\nand this is the auth.service.ts\n\n```\n@Injectable()\nexport class AuthService {\n constructor(private userService: UserService) { }\n\n async signPayLoad(payload: any) {\n return sign(payload, process.env.SECRETKEY, { expiresIn: '1h' });\n\n }\n\n async validateUser(payload: any) {\n const returnuser = await this.userService.findByPayLoad(payload);\n return returnuser;\n }\n\n validateApiKey(apiKey: string) {\n const keys = process.env.API_KEYS;\n const apiKeys = keys.split(',');\n return apiKeys.find(key => apiKey === key);\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor(private authService: AuthService) {\n        super({\n            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n            ignoreExpiration: false,\n            secretOrKey: process.env.SECRETKEY\n        });\n    }\n\n    async validate(payload: any, done: VerifiedCallback) {\n        const user = await this.authService.validateUser(payload);\n        if (!user) {\n            return done(\n                new HttpException('Unauthorised access', HttpStatus.UNAUTHORIZED),\n                false,\n            );\n        }\n        //return user;\n        return done(null, user, payload.iat)\n    }\n}\n```\n\n```text\n@Injectable()\nexport class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {\n    constructor(private authService: AuthService) {\n        super({\n            header: 'api_key',\n            prefix: ''\n        }, true,\n            (apikey: string, done: any, req: any, next: () => void) => {\n                const checkKey = this.authService.validateApiKey(apikey);\n                if (!checkKey) {\n                    return done(\n                        new HttpException('Unauthorized access, verify the token is correct', HttpStatus.UNAUTHORIZED),\n                        false,\n                    );\n                }\n                return done(null, true, next);\n            });\n    }\n}\n```\n\n```text\n@Injectable()\nexport class AuthService {\n    constructor(private userService: UserService) { }\n\n    async signPayLoad(payload: any) {\n        return sign(payload, process.env.SECRETKEY, { expiresIn: '1h' });\n\n    }\n\n    async validateUser(payload: any) {\n        const returnuser = await this.userService.findByPayLoad(payload);\n        return returnuser;\n    }\n\n    validateApiKey(apiKey: string) {\n        const keys = process.env.API_KEYS;\n        const apiKeys = keys.split(',');\n        return apiKeys.find(key => apiKey === key);\n    }\n}\n```\n\n```text\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { AuthGuard as NestAuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class AuthGuard extends NestAuthGuard(['jwt', 'headerapikey']) {\n  constructor(private readonly reflector: Reflector) {\n    super();\n  }\n\n  canActivate(context: ExecutionContext) {\n    const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n\n    if (isPublic) {\n      return true;\n    }\n\n    return super.canActivate(context);\n  }\n}\n```\n\n```text\nPassport-HeaderAPIKey\n```\n\n```text\nheaderapikey\n```\n\n========================================\n\nComments:\n- did you figure it out?\n- Do you have a GitHub repo that implements this trick?","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":201,"estimatedTokens":1306}}443{"id":"stack-50928311","source":"stackoverflow","questionId":50928311,"title":"How to use in-memory database with TypeORM in Nest","tags":["typescript","typeorm","nestjs"],"text":"Title: How to use in-memory database with TypeORM in Nest\nTags: typescript, typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a Nest server that other services depends on. In order to simplify testing of these other services, I would like to spin up a version of the Nest server that does not use a real database. Instead, it should use an in-memory db, like mongo-unit.\n\nMy idea would be to have a production main module, and a test main module, where the test module would keep everything the same, but use the in-memory db. However, I'm having trouble figuring out how to set this up.\n\nI know that I can use `async` providers, but I don't know how that works with imports, which is what `@nestjs/typeorm` exposes:\n\n```\n// app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n ...\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: 'localhost',\n port: 27017,\n database: 'production',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n ...\n ],\n})\nexport class AppModule {}\n```\n\nIt needs to be async, because mongo-unit returns a promise with the URL that it listens to. So I need to spin up mongo-unit, before I can initialize TypeORM. I imagine something like this:\n\n```\n// app.test.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport * as mongoUnit from 'mongo-unit';\n\n@Module({})\nexport class AppModule {\n static async forRoot() {\n const dbUrl = new URL(await mongoUnit.start());\n return {\n imports: [\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: dbUrl.host,\n port: dbUrl.port,\n database: 'test',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n ],\n };\n }\n}\n```\n\nHow can I swap out the database, if it is asynchronously started?\n\n(If there is another approach to this problem than two separate modules, then please tell me! :) )\n\n========================================\n\nCode:\n```text\n// app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n    ...\n    TypeOrmModule.forRoot({\n      type: 'mongodb',\n      host: 'localhost',\n      port: 27017,\n      database: 'production',\n      entities: [__dirname + '/**/*.entity{.ts,.js}'],\n      synchronize: true,\n    }),\n    ...\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n// app.test.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport * as mongoUnit from 'mongo-unit';\n\n@Module({})\nexport class AppModule {\n  static async forRoot() {\n    const dbUrl = new URL(await mongoUnit.start());\n    return {\n      imports: [\n        TypeOrmModule.forRoot({\n          type: 'mongodb',\n          host: dbUrl.host,\n          port: dbUrl.port,\n          database: 'test',\n          entities: [__dirname + '/**/*.entity{.ts,.js}'],\n          synchronize: true,\n        }),\n      ],\n    };\n  }\n}\n```\n\n```text\nasync\n```\n\n```text\n@nestjs/typeorm\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":127,"estimatedTokens":753}}444{"id":"stack-60908571","source":"stackoverflow","questionId":60908571,"title":"How to process axios httpservice observable response?","tags":["typescript","axios","nestjs"],"text":"Title: How to process axios httpservice observable response?\nTags: typescript, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI think I'm getting crazy as I'm pretty new to node and typescript...I simply want to retrieve, in a syncronous way, the result of an http get request.\n\nGiven:\n\n```\nimport { Injectable, HttpService } from '@nestjs/common';\nimport {} from '@nestjs/core';\n\n@Injectable()\nexport class AppService {\n private readonly DATA_URL:string = \"https://remote/data.json\";\n constructor(private httpService:HttpService){}\n getSomething(): Array {\n let resp = this.httpService.get(this.DATA_URL); //what do I do now?? It's an observable\n }\n}\n```\n\n**edit**: \nI'm writing here the full code as it could be useful to others learning the framework. I used Jay's response, but richbai also helped me a lot in understanding the theory behind. Of course improve/correct if it can still get better.\n\n- I added a type to have better control instead of Object\n\n- I needed to change the date field from the response from \"yyyy-mm-ddThh24:mi:ss\" to \"yyyy-mm-dd\"\nI also needed to filter the response based on a value\n\n```\ngetSomething(aFilterValue:number): Observable {\n return this.httpService.get(this.DATA_URL).pipe(\n map((axiosResponse : AxiosResponse) => (axiosResponse.data as \n RespDTO[])\n.filter((el:RespDTO) => el.aCode===aFilterValue)\n.map((el:RespDTO) => ({...el,aDateField:el.aDateField.split('T')[0]}))),\n);\n}\n```\n\n========================================\n\nTop Answer:\n**EDIT:**\n\nDisclaimer: I don't know much about Nest specifically, so this answer is from a purely vanilla JS perspective, different libraries have different built in abilities. What follows is an explanation of different ways to handle asynchronous requests and observables in javascript. I also highly recommend reading up on asynchronous javascript, observables, and promises as it will make your time in javascript far more pleasant.\n\nWeb requests in javascript happen asynchronously, meaning that they execute more or less in parallel with the rest of your synchronous code. You can imagine it like a separate thread, although it is not. This means that code that relies on the value from this web request must stall until the request is complete. From my original post below, the simplest option in your case is probably option 3. The code to use it might look a bit like this:\n\n```\n/**\n * A method in your rest controller that relies on the getSomething() \n * method as implemented in option 2 below\n */\nasync showRemoteData() { \n const remoteData = await appService.getSomething();\n // replace console.log with whatever method you use to return data to the client\n console.log(remoteData);\n}\n```\n\n**Original Answer**\n\nYou cannot retrieve a value from an observable in a synchronous way. You have to subscribe to it and do something once the value has been returned, or convert it to a promise and return the promise. Your options are these:\n\n```\n// option 1 change getSomething to doSomething, and do everything in that method\n\ndoSomething(): Array {\n let resp = this.httpService.get(this.DATA_URL);\n resp.subscribe((value) => { // do something })\n}\n\n// option 2 return the observable and subscribe to it outside of that method\ngetSomething(): Array {\n return this.httpService.get(this.DATA_URL);\n}\n// outside of the AppService you can use it like this\nappService.getSomething().subscribe((value) => {// do something})\n\n// option 3 convert the observable to a promise and return it\ngetSomething(): Array {\n return this.httpService.get(this.DATA_URL).toPromise();\n}\n// outside of the AppService you can use it like this\nlet value = await appService.getSomething();\nconsole.log(value);\n```\n\nOf the options, option 3 allows you to use async and await which is not synchronous but allows you treat the rest of your code in the async method as though it is, so that might be closest to what you want. I personally think option 2 is your best option though as you keep all the functionality of observables, including the whole sweet of operators available to you. Embrace asynchronous code in javascript, it is the best and often times only solution to many problems.\n\n========================================\n\nCode:\n```text\nimport { Injectable, HttpService } from '@nestjs/common';\nimport {} from '@nestjs/core';\n\n@Injectable()\nexport class AppService {\n  private readonly DATA_URL:string = \"https://remote/data.json\";\n  constructor(private httpService:HttpService){}\n  getSomething(): Array<Object> {\n   let resp = this.httpService.get(this.DATA_URL); //what do I do now?? It's an observable\n  }\n}\n```\n\n```text\ngetSomething(aFilterValue:number): Observable<RespDTO[]> {\n    return this.httpService.get(this.DATA_URL).pipe(\n    map((axiosResponse : AxiosResponse) => (axiosResponse.data as \n   RespDTO[])\n.filter((el:RespDTO) => el.aCode===aFilterValue)\n.map((el:RespDTO) => ({...el,aDateField:el.aDateField.split('T')[0]}))),\n);\n}\n```\n\n```js\nimport { Injectable, HttpService } from '@nesjts/common';\nimport { AxiosResponse } from 'axios';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class HttpConsumingService {\n  private readonly DATA_URL = 'http://remote/data.json';\n  constructor(private readonly http: HttpService) {}\n\n  callHttp(): Observable<Array<Object>> {\n    return this.http.get(this.DATA_URL).pipe(\n      map((axiosResponse: AxiosResponse) => {\n        return axiosResponse.data;\n      })\n    );\n  }\n}\n```\n\n```text\nmap\n```\n\n```text\n.pipe()\n```\n\n```text\nObservable\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nthis.httpConsumingService.callHttp()\n```\n\n```text\n/**\n * A method in your rest controller that relies on the getSomething() \n * method as implemented in option 2 below\n */\nasync showRemoteData() {  \n  const remoteData = await appService.getSomething();\n  // replace console.log with whatever method you use to return data to the client\n  console.log(remoteData);\n}\n```\n\n```text\n// option 1 change getSomething to doSomething, and do everything in that method\n\ndoSomething(): Array<Object> {\n  let resp = this.httpService.get(this.DATA_URL);\n  resp.subscribe((value) => { // do something })\n}\n\n// option 2 return the observable and subscribe to it outside of that method\ngetSomething(): Array<Object> {\n  return this.httpService.get(this.DATA_URL);\n}\n// outside of the AppService you can use it like this\nappService.getSomething().subscribe((value) => {// do something})\n\n// option 3 convert the observable to a promise and return it\ngetSomething(): Array<Object> {\n  return this.httpService.get(this.DATA_URL).toPromise();\n}\n// outside of the AppService you can use it like this\nlet value = await appService.getSomething();\nconsole.log(value);\n```\n\n```text\nconst resp = await this.httpService.get(this.DATA_URL).toPromise(); // Here you get the AxiosResponse object.\nconst body = resp.data; // Here you get the response body, which is automatically parsed in the .data property of the AxiosResponse.\n```\n\n```text\nconst body = (await this.httpService.get(this.DATA_URL).toPromise()).data;\n```\n\n```text\nthis.httpService.get(this.DATA_URL).toPromise()\n.then(resp => {\n    console.log(resp.data);\n})\n.catch(err => {\n    // Handle Error Here\n    console.error(err);\n})\n```\n\n```text\nexecute = async (): Promise<BondAssetType[]> => {\n       \n    var response : Observable<BondAssetType[]> = this._assetBondTypeService.findAll().pipe(map(x => x.data));\n    var result:BondAssetType[] = await firstValueFrom(response);\n\n    return result;\n}\n```\n\n========================================\n\nComments:\n- Have you tried this one? stackoverflow.com/questions/34190375/&hellip;\n- You can convert the rxjs Observable to a Promise (`.toPromise()`) and simply `await` it, for instance.\n- I'm very confused...that code is inside of a backend REST controller and it is called by an external API. I just want my server to retrieve the data, filter it and finally return it to the client...is that possible with method 2? Only one seems to be the 3 but can't understand why in a server side framework such as nest they make it so complicated :(\n- I added this code that seems the best option, could you also please tell me how, starting by the axiosResponse.data (which is an array) I can do some further fitering on the arrays elements?\n- The great thing, in my opinion, about Observables is that almost every operator can be chained against in the same `.pipe()` experession, so you can have multiple operators in the same pipe to keep things easy to work with. For example, you can have `.pipe(tap(), map(), concatMap(), retryWhen(), catchError())` and it's a valid pipe (so long as each of those functions does what it's supposed to). In you case, `map((resp => resp.data), map(arrayData => arrayData.map(data => someFunciton))` where `arrayData` is the data from axios and `arrayData.map` is the `Array.prototype.map` function\n- `toPromise()` has been deprecated in the RXJS 8, which the latest `@nestjs&#47;axios` uses. You get deprecation warnings for the code above.","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":237,"estimatedTokens":2251}}445{"id":"stack-52878055","source":"stackoverflow","questionId":52878055,"title":"How to unit test Controller and mock @InjectModel in the Service constructor","tags":["node.js","unit-testing","jestjs","nestjs"],"text":"Title: How to unit test Controller and mock @InjectModel in the Service constructor\nTags: node.js, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am getting issues while unit testing my controller and getting an error \"Nest can't resolve dependencies of my service\".\n\nFor maximum coverage I wanted to unit test controller and respective services and would like to mock external dependencies like mongoose connection. For the same I already tried suggestions mentioned in the below link but didn't find any luck with that:\n\nhttps://github.com/nestjs/nest/issues/194#issuecomment-342219043\n\nPlease find my code below:\n\n```\nexport const deviceProviders = [\n {\n provide: 'devices',\n useFactory: (connection: Connection) => connection.model('devices', DeviceSchema),\n inject: ['DbConnectionToken'],\n },\n];\n\nexport class DeviceService extends BaseService {\n constructor(@InjectModel('devices') private readonly _deviceModel: Model) {\n super();\n }\n\n async getDevices(group): Promise {\n try {\n return await this._deviceModel.find({ Group: group }).exec();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n}\n\n@Controller()\nexport class DeviceController {\n constructor(private readonly deviceService: DeviceService) {\n }\n\n @Get(':group')\n async getDevices(@Res() response, @Param('group') group): Promise {\n try {\n const result = await this.deviceService.getDevices(group);\n return response.send(result);\n }\n catch (err) {\n return response.status(422).send(err);\n }\n }\n}\n\n@Module({\n imports: [MongooseModule.forFeature([{ name: 'devices', schema: DeviceSchema }])],\n controllers: [DeviceController],\n components: [DeviceService, ...deviceProviders],\n})\nexport class DeviceModule { }\n```\n\nUnit test:\n\n```\ndescribe('DeviceController', () => {\n let deviceController: DeviceController;\n let deviceService: DeviceService;\n\n const response = {\n send: (body?: any) => { },\n status: (code: number) => response,\n };\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n controllers: [DeviceController],\n components: [DeviceService, ...deviceProviders],\n }).compile();\n\n deviceService = module.get(DeviceService);\n deviceController = module.get(DeviceController);\n });\n\n describe('getDevices()', () => {\n it('should return an array of devices', async () => {\n const result = [{\n Group: 'group_abc',\n DeviceId: 'device_abc',\n },\n {\n Group: 'group_xyz',\n DeviceId: 'device_xyz',\n }];\n jest.spyOn(deviceService, 'getDevices').mockImplementation(() => result);\n\n expect(await deviceController.getDevices(response, null)).toBe(result);\n });\n });\n});\n```\n\nWhen I am running my test case above, I am getting two errors:\n\nNest can't resolve dependencies of the DeviceService (?). Please make sure that the argument at index [0] is available in the current context.\n\nCannot spyOn on a primitive value; undefined given\n\n========================================\n\nTop Answer:\nYou are not injecting the correct token here. Instead of a plain string you have to use the function `getModelToken`.\n\n```\nimport { getModelToken } from '@nestjs/mongoose';\n\n// ...\n\n{ provide: getModelToken('devices'), useFactory: myFactory },\n```\n\n========================================\n\nCode:\n```text\nexport const deviceProviders = [\n    {\n        provide: 'devices',\n        useFactory: (connection: Connection) => connection.model('devices', DeviceSchema),\n        inject: ['DbConnectionToken'],\n    },\n];\n\n\nexport class DeviceService extends BaseService {\n    constructor(@InjectModel('devices') private readonly _deviceModel: Model<Device>) {\n        super();\n    }\n\n    async getDevices(group): Promise<any> {\n        try {\n            return await this._deviceModel.find({ Group: group }).exec();\n        } catch (error) {\n            return Promise.reject(error);\n        }\n    }\n}\n\n\n@Controller()\nexport class DeviceController {\n    constructor(private readonly deviceService: DeviceService) {\n    }\n\n   @Get(':group')\n   async getDevices(@Res() response, @Param('group') group): Promise<any> {\n        try {\n            const result = await this.deviceService.getDevices(group);\n            return response.send(result);\n        }\n        catch (err) {\n            return response.status(422).send(err);\n        }\n    }\n}\n\n\n@Module({\n    imports: [MongooseModule.forFeature([{ name: 'devices', schema: DeviceSchema }])],\n    controllers: [DeviceController],\n    components: [DeviceService, ...deviceProviders],\n})\nexport class DeviceModule { }\n```\n\n```text\ndescribe('DeviceController', () => {\n    let deviceController: DeviceController;\n    let deviceService: DeviceService;\n\n    const response = {\n        send: (body?: any) => { },\n        status: (code: number) => response,\n    };\n\n    beforeEach(async () => {\n        const module = await Test.createTestingModule({\n            controllers: [DeviceController],\n            components: [DeviceService, ...deviceProviders],\n        }).compile();\n\n        deviceService = module.get<DeviceService>(DeviceService);\n        deviceController = module.get<DeviceController>(DeviceController);\n    });\n\n    describe('getDevices()', () => {\n        it('should return an array of devices', async () => {\n            const result = [{\n                Group: 'group_abc',\n                DeviceId: 'device_abc',\n            },\n            {\n                Group: 'group_xyz',\n                DeviceId: 'device_xyz',\n            }];\n            jest.spyOn(deviceService, 'getDevices').mockImplementation(() => result);\n\n            expect(await deviceController.getDevices(response, null)).toBe(result);\n        });\n    });\n});\n```\n\n```text\nimport { Test } from '@nestjs/testing';\n\nimport { getModelToken } from '@nestjs/mongoose';\n\n\ndescribe('auth', () => {\n  let deviceController: DeviceController;\n  let deviceService: DeviceService;\n\n  const mockRepository = {\n    find() {\n      return {};\n    }\n  };\n\n  beforeAll(async () => {\n    const module = await Test.createTestingModule({\n      imports: [DeviceModule]\n    })\n      .overrideProvider(getModelToken('Auth'))\n      .useValue(mockRepository)\n      .compile();\n\n    deviceService = module.get<DeviceService>(DeviceService);\n  });\n\n  // ...\n\n\n});\n```\n\n```text\nimport { getModelToken } from '@nestjs/mongoose';\n\n// ...\n\n{ provide: getModelToken('devices'), useFactory: myFactory },\n```\n\n```text\ngetModelToken\n```\n\n```text\nimport { CategoriesService } from './../categories/categories.service';\nimport { getModelToken } from '@nestjs/mongoose';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { ProductsService } from './products.service';\n\ndescribe('ProductsService', () => {\n  let service: ProductsService;\n\n  beforeAll(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      // getModelToken to mock the MongoDB connection\n      providers: [\n        ProductsService,\n        CategoriesService,\n        {\n          provide: getModelToken('Product'),\n          useValue: {\n            find: jest.fn(),\n            findOne: jest.fn(),\n            findByIdAndUpdate: jest.fn(),\n            findByIdAndRemove: jest.fn(),\n            save: jest.fn(),\n          },\n        },\n        {\n          provide: getModelToken('Category'),\n          useValue: {\n            find: jest.fn(),\n            findOne: jest.fn(),\n            findByIdAndUpdate: jest.fn(),\n            findByIdAndRemove: jest.fn(),\n            save: jest.fn(),\n          },\n        },\n      ],\n    }).compile();\n\n    service = module.get<ProductsService>(ProductsService);\n  });\n  // your test case\n});\n```\n\n```text\n@injectModel\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":304,"estimatedTokens":1886}}446{"id":"stack-72836741","source":"stackoverflow","questionId":72836741,"title":"serialize nested objects using class-transformer : Nest js","tags":["typescript","nestjs","class-transformer"],"text":"Title: serialize nested objects using class-transformer : Nest js\nTags: typescript, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI am trying to serialize nested objects using a class transformer. I have two dtos like below. When I am trying to serialize using `plainToClass` the nested object gets removed from the output. only getting the parent object's data.\n\n**User dto:**\n\n```\nexport class UserDto extends AbstractDto {\n @Expose()\n email: string;\n\n @Expose()\n first_name: string;\n\n @Expose()\n last_name: string;\n\n @Expose()\n profile: ProfileDto\n\n}\n```\n\n**Profile dto:**\n\n```\nexport class ProfileDto extends AbstractDto {\n @Expose()\n date_of_birth: string;\n\n @Expose()\n address: string;\n\n @Expose()\n pincode: string;\n}\n```\n\n**Serializer:**\n\n```\nconst serialized = plainToClass(UserDto, user, {\n excludeExtraneousValues: true,\n});\n```\n\n**Expected Output:**\n\n```\n{\n email:'a@gmail.com',\n first_name: 'test',\n last_name: 'test',\n profile: {\n date_of_birth: '',\n address: '',\n pincode: ''\n }\n}\n```\n\n========================================\n\nTop Answer:\nThis question is not related to NestJS, but purely to class-transformer. NestJS might happen to use the `class-validator` & `class-transformer` packages as part of its pipes feature, but in the context of this question NestJS doesn't even need to be considered.\n\nLet's assume you have two classes, `Cat` and `Owner`. An owner can have a cat.\n\n```\nclass Cat {\n @Expose()\n name: string;\n\n @Expose()\n age: number;\n\n favoriteFood: string;\n\n constructor(name: string, age: number, favoriteFood: string) {\n this.name = name;\n this.age = age;\n this.favoriteFood = favoriteFood;\n }\n}\n\nclass Owner {\n @Expose()\n name: string;\n\n @Expose()\n cat: Cat;\n\n constructor(name: string, cat: Cat) {\n this.name = name;\n this.cat = cat;\n }\n}\n```\n\nLet's instantiate an instance of each.\n\n```\nconst cat = new Cat('Misty', 6, 'Dry cat food');\nconst owner = new Owner('Christophe', cat);\n```\n\nIf you want to convert the owner instance back into a plain JavaScript object then use the `instanceToPlain()` function with the `excludeAll` strategy from `class-transformer`. The `classToPlain()` function is deprecated.\n\n```\nconst serialized = instanceToPlain(owner, { strategy: 'excludeAll' });\n```\n\nThat will only serialize the properties you decorated with the `@Expose()` decorator:\n\n`{ name: 'Christophe', cat: { name: 'Misty', age: 6 } }`\n\nThe `plainToClass()` you used in your example is meant to convert a plain JavaScript back into an instance of the `Owner` class, or for \"deserializing\" rather.\n\nFor more information consult the `class-transformer` documentation.\n\nhttps://github.com/typestack/class-transformer\n\n========================================\n\nCode:\n```text\nexport class UserDto extends AbstractDto {\n    @Expose()\n    email: string;\n\n    @Expose()\n    first_name: string;\n\n    @Expose()\n    last_name: string;\n\n    @Expose()\n    profile: ProfileDto\n\n}\n```\n\n```text\nexport class ProfileDto extends AbstractDto {\n    @Expose()\n    date_of_birth: string;\n\n    @Expose()\n    address: string;\n\n    @Expose()\n    pincode: string;\n}\n```\n\n```text\nconst serialized = plainToClass(UserDto, user, {\n    excludeExtraneousValues: true,\n});\n```\n\n```text\n{\n    email:'a@gmail.com',\n    first_name: 'test',\n    last_name: 'test',\n    profile: {\n        date_of_birth: '',\n        address: '',\n        pincode: ''\n    }\n}\n```\n\n```text\nplainToClass\n```\n\n```text\nexport class UserDto extends AbstractDto {\n    @Expose()\n    email: string;\n\n    @Expose()\n    first_name: string;\n\n    @Expose()\n    last_name: string;\n\n    @Expose()\n    @Type(() => ProfileDto)\n    profile: ProfileDto\n\n}\n```\n\n```text\nconst serialized = plainToClass(UserDto, user, {\n    excludeExtraneousValues: true,\n    enableImplicitConversion: true\n    \n});\n```\n\n```text\nenableImplicitConversion: true\n```\n\n```text\n@Type\n```\n\n```text\nclass Cat {\n  @Expose()\n  name: string;\n\n  @Expose()\n  age: number;\n\n  favoriteFood: string;\n\n  constructor(name: string, age: number, favoriteFood: string) {\n    this.name = name;\n    this.age = age;\n    this.favoriteFood = favoriteFood;\n  }\n}\n\nclass Owner {\n  @Expose()\n  name: string;\n\n  @Expose()\n  cat: Cat;\n\n  constructor(name: string, cat: Cat) {\n    this.name = name;\n    this.cat = cat;\n  }\n}\n```\n\n```text\nconst cat = new Cat('Misty', 6, 'Dry cat food');\nconst owner = new Owner('Christophe', cat);\n```\n\n```text\nconst serialized = instanceToPlain(owner, { strategy: 'excludeAll' });\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nCat\n```\n\n```text\nOwner\n```\n\n```text\ninstanceToPlain()\n```\n\n```text\nexcludeAll\n```\n\n```text\nclass-transformer\n```\n\n```text\nclassToPlain()\n```\n\n```text\n@Expose()\n```\n\n```text\n{ name: 'Christophe', cat: { name: 'Misty', age: 6 } }\n```\n\n```text\nplainToClass()\n```\n\n```text\nOwner\n```\n\n```text\nclass-transformer\n```\n\n========================================\n\nComments:\n- If you're using `class-transformer` and `class-validator` together then you usually **do not** want to enable implicit conversion according to the docs github.com/typestack/class-transformer#implicit-type-convers&zwnj;&#8203;ion Issue is things like `myField: string` will pretty much always pass validation as almost everything can be converted to a string, including objects etc.\n- @TomManterfield I just ran into what you're referring to. Booleans will always be true even when set to strings. Do you have an alternative option for nested serialization?","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":312,"estimatedTokens":1358}}447{"id":"stack-66047096","source":"stackoverflow","questionId":66047096,"title":"Using class-validator DTO also in front-end","tags":["reactjs","nestjs","class-validator"],"text":"Title: Using class-validator DTO also in front-end\nTags: reactjs, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nA NestJS project uses a ValidationPipe with class-validator to validate POST requests. It would be nice to use the same class-validator DTO in the (react) front-end .\n\nHow could the entities in the DTO be linked to react elements ?\n\nThis may be similar to How to Sync Front end and back end validation, but more focused on specific tools.\n\n========================================\n\nTop Answer:\nWell Nestjs itself uses class-validators for DTOs,\n\nSo you can move them to an external package, there you'll be able to declare your DTOs.\n\nAfter doing that you can consume the DTOs from your NestJS app and also from your React app.\n\nFor example, this is my implementation of a DTO on a package:\n\n```\nexport const getCreateUserDto = (ApiPropertySwagger?: any) => {\n // We did this to avoid having to include all nest dependencies related to ApiProperty on the client side too\n // With this approach the value of this decorator will be injected by the server but wont affect the client\n const ApiProperty = ApiPropertySwagger || function () {};\n \n class CreateUserDto {\n @IsEmail()\n @ApiProperty({\n description: \"This is required and must be a valid email\",\n type: String,\n })\n email: string;\n \n @IsString()\n @MinLength(2)\n @ApiProperty({\n description: \"This is required and must be at least 2 characters long\",\n type: String,\n })\n firstName: string;\n \n @IsString()\n @IsOptional()\n lastName?: string;\n \n @IsString()\n @IsOptional()\n nationality?: string;\n }\n \n return CreateUserDto;\n };\n```\n\nIn your NestJS app you can do the following:\n\n```\nimport { ApiProperty } from '@nestjs/swagger';\n// Here we send `ApiProperty` dependency to be added to`CreateUserDto`\nexport const _CreateUserDto = getCreateUserDto(ApiProperty);\n\n// This allows using it as a TS type and as a constructor class\nexport class CreateUserDto extends _CreateUserDto {}\n```\n\nAnd in your react app you can do:\n\n```\nimport { getCreateUserDto } from \"@sample/dtos\"; \n // We don't need `ApiProperty` on the client,\n // so it will fallback on the default empty decorator \n const _CreateUserDto = getCreateUserDto();\n // This allows using it as a TS type and as a constructor class\n class CreateUserDto extends _CreateUserDto {}\n```\n\nI just posted a blog with this implementation:\n\nhttps://dev.to/facup3/fullstack-nestjs-dtos-for-your-web-app-4f60\n\nI used React + react-hook-form to run same validations on the client side than in the nest controllers.\n\n========================================\n\nCode:\n```js\nexport const getCreateUserDto = (ApiPropertySwagger?: any) => {\n      // We did this to avoid having to include all nest dependencies related to ApiProperty on the client side too\n      // With this approach the value of this decorator will be injected by the server but wont affect the client\n      const ApiProperty = ApiPropertySwagger || function () {};\n    \n      class CreateUserDto {\n        @IsEmail()\n        @ApiProperty({\n          description: \"This is required and must be a valid email\",\n          type: String,\n        })\n        email: string;\n    \n        @IsString()\n        @MinLength(2)\n        @ApiProperty({\n          description: \"This is required and must be at least 2 characters long\",\n          type: String,\n        })\n        firstName: string;\n    \n        @IsString()\n        @IsOptional()\n        lastName?: string;\n    \n        @IsString()\n        @IsOptional()\n        nationality?: string;\n      }\n    \n      return CreateUserDto;\n    };\n```\n\n```js\nimport { ApiProperty } from '@nestjs/swagger';\n// Here we send `ApiProperty` dependency to  be added to`CreateUserDto`\nexport const _CreateUserDto = getCreateUserDto(ApiProperty);\n\n// This allows using it as a TS type and as a constructor class\nexport class CreateUserDto extends _CreateUserDto {}\n```\n\n```js\nimport { getCreateUserDto } from \"@sample/dtos\";    \n    // We don't need `ApiProperty` on the client,\n    // so it will fallback on the default empty decorator \n    const _CreateUserDto = getCreateUserDto();\n    // This allows using it as a TS type and as a constructor class\n    class CreateUserDto extends _CreateUserDto {}\n```\n\n========================================\n\nComments:\n- If you want to bind validation rules to your form elements like input then you can try something like react-class-validator which is not depending on any form libraries.\n- Thanks, @VladGoldman , I had ruled out the react-class-validator, as it had seen very little use. Prematurely seemingly . Any example how that would work ?\n- @serv-inc did you check github.com/anigenero/react-class-validator or similar libraries?\n- Why didn't you go for a mono repo?\n- Hi! We used this solution because we intended to use the NPM package in several applications that don't relate to each other so we wanted to be as modular as possible. With NPM 7, we're using its workspaces feature to define monorepos for our latest projects, it's really convenient.\n- Absolutely brilliant, I am using this exact same structure with npm\n- Thanks for the answer. +1 If you post an extract here (or just as well the whole blog post), you might get more upvotes.\n- My apologies, I'm new answering ๐Ÿคฃ","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":152,"estimatedTokens":1310}}448{"id":"stack-66580508","source":"stackoverflow","questionId":66580508,"title":"Authorization in Nestjs using graphql","tags":["graphql","nestjs","nestjs-passport","nestjs-jwt"],"text":"Title: Authorization in Nestjs using graphql\nTags: graphql, nestjs, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI have started to learn Nestjs, express and graphql.\nI encountered a problem while trying to authorize access of user authenticated using jwt token.\nI followed the tutorial for authentication on the Nestjs website.\nI am able to get the current user, but when I try implementing the basic role base access control, I am unable to access the current user in the canActivate Method.\nI think it is because the Roles Guard is executed before the Graphql Guard.\n\nI will post the codes here\n\ngql-auth.guard.ts\n\n```\nimport { ExecutionContext } from \"@nestjs/common\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\nimport { AuthGuard } from \"@nestjs/passport\";\n\nexport class GqlAuthGuard extends AuthGuard(\"jwt\") {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n console.log(\"gql simple context: \", context);\n console.log(\"gqlContext: \", ctx.getContext());\n return ctx.getContext().req;\n }\n}\n```\n\nroles.guard.ts\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext) {\n const roles = this.reflector.get(\"roles\", context.getHandler());\n const ctx = GqlExecutionContext.create(context);\n console.log(\"roles: \", roles);\n console.log(\"context: \", context.switchToHttp().getRequest());\n console.log(\"gqlContext: \", ctx.getContext().req);\n\n return true;\n }\n}\n```\n\njwt.strategy.ts\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { ExtractJwt, Strategy } from \"passport-jwt\";\nimport { jwtConstants } from \"../constants\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: jwtConstants.secret,\n });\n }\n\n validate(payload: any) {\n console.log(\"payload: \", payload);\n\n return payload;\n }\n}\n```\n\nresolver\n\n```\n@UseGuards(GqlAuthGuard)\n@Roles(\"ADMIN\")\n@UseGuards(RolesGuard)\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n const select = new PrismaSelect(info).value;\n params = { ...params, ...select };\n return this.prismaService.specialty.findMany(params);\n}\n```\n\nHas anyone successfully implemented this before ?\n\n========================================\n\nTop Answer:\n```\nexport const Authorize = (roles?: string | string[]) =>\n applyDecorators(\n SetMetadata('roles', [roles].flat()),\n UseGuards(GqlAuthGuard, RolesGuard),\n );\n```\n\n```\n@Authorize(\"ADMIN\")\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n const select = new PrismaSelect(info).value;\n params = { ...params, ...select };\n return this.prismaService.specialty.findMany(params);\n}\n```\n\n========================================\n\nCode:\n```js\nimport { ExecutionContext } from \"@nestjs/common\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\nimport { AuthGuard } from \"@nestjs/passport\";\n\nexport class GqlAuthGuard extends AuthGuard(\"jwt\") {\n    getRequest(context: ExecutionContext) {\n        const ctx = GqlExecutionContext.create(context);\n        console.log(\"gql simple context: \", context);\n        console.log(\"gqlContext: \", ctx.getContext());\n        return ctx.getContext().req;\n    }\n}\n```\n\n```js\nimport { CanActivate, ExecutionContext, Injectable } from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n    constructor(private reflector: Reflector) {}\n\n    canActivate(context: ExecutionContext) {\n        const roles = this.reflector.get<string[]>(\"roles\", context.getHandler());\n        const ctx = GqlExecutionContext.create(context);\n        console.log(\"roles: \", roles);\n        console.log(\"context: \", context.switchToHttp().getRequest());\n        console.log(\"gqlContext: \", ctx.getContext().req);\n\n        return true;\n    }\n}\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { ExtractJwt, Strategy } from \"passport-jwt\";\nimport { jwtConstants } from \"../constants\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor() {\n        super({\n            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n            ignoreExpiration: false,\n            secretOrKey: jwtConstants.secret,\n        });\n    }\n\n    validate(payload: any) {\n        console.log(\"payload: \", payload);\n\n        return payload;\n    }\n}\n```\n\n```js\n@UseGuards(GqlAuthGuard)\n@Roles(\"ADMIN\")\n@UseGuards(RolesGuard)\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n    const select = new PrismaSelect(info).value;\n    params = { ...params, ...select };\n    return this.prismaService.specialty.findMany(params);\n}\n```\n\n```text\n@UseGuards()\n```\n\n```text\n@UseGuards(GqlAuthGuard, RolesGuard)\n```\n\n```text\nexport const Authorize = (roles?: string | string[]) =>\n  applyDecorators(\n    SetMetadata('roles', [roles].flat()),\n    UseGuards(GqlAuthGuard, RolesGuard),\n  );\n```\n\n```text\n@Authorize(\"ADMIN\")\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n    const select = new PrismaSelect(info).value;\n    params = { ...params, ...select };\n    return this.prismaService.specialty.findMany(params);\n}\n```\n\n```text\n@Injectable()\nexport class RolesGuard_ implements CanActivate {\n  constructor(private reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const ctx = GqlExecutionContext.create(context);\n\n    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n\n    if (!requiredRoles) {\n      return true;\n    }\n\n    const { user } = ctx.getContext().req;\n    return requiredRoles.some((role) => user.role?.includes(role));\n  }\n}\n```\n\n========================================\n\nComments:\n- Hi, why using an empty &#180;@UseGuards()&#180; ?\n- I was mentioning the decorator by it's full name. Don't look too much into it","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":245,"estimatedTokens":1701}}449{"id":"stack-56549704","source":"stackoverflow","questionId":56549704,"title":"NestJS NATS request-response","tags":["javascript","node.js","typescript","nestjs","nats.io"],"text":"Title: NestJS NATS request-response\nTags: javascript, node.js, typescript, nestjs, nats.io\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use NestJS and the NATS microservice. There is good documentation for setting up a basic request-response.\n\nWhat I did is the following:\n\nRan a local NATS server.\n\nSet up my `main.ts` to connect to the server:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(AppModule, {\n options: {\n url: \"nats://localhost:4222\",\n },\n transport: Transport.NATS,\n });\n app.listen(() => console.log(\"Microservice is listening\"));\n}\nbootstrap();\n```\n\nCreated a ClientProxyFactory to send back messages:\n\n```\nexport const NatsClientProvider: Provider = {\n inject: [ConfigService],\n provide: NatsClientProviderId,\n useFactory: async (config: ConfigService) =>\n ClientProxyFactory.create({\n options: {\n servers: config.getNatsConfig().servers,\n },\n transport: Transport.NATS,\n }),\n};\n```\n\nSet up a controller `app.controller.ts` to respond to a certain pattern:\n\n```\n@Controller()\nexport class AppController {\n constructor(\n private readonly appService: AppService,\n @Inject(NatsClientProviderId) private readonly natsClient: ClientProxy,\n ) {}\n\n @MessagePattern(\"hello\")\n async getHello(data: string) {\n console.log(\"data: \", data);\n console.log(\"getHello!!\");\n await this.natsClient.send(\"hello\", this.appService.getHello());\n return this.appService.getHello();\n }\n\n async onModuleInit() {\n await this.natsClient.connect();\n console.log(\"Nats connected!\");\n }\n```\n\nSet up a test file to try sending a request-response message:\n\n```\nimport { connect } from \"ts-nats\";\n\nasync function start() {\n const nc = await connect({\n servers: [\"nats://localhost:4222\"],\n });\n\n const msg = await nc.request(\"hello\", 5000, \"me\");\n console.log(\"msg: \", msg);\n}\n\nstart();\n```\n\nWhen I run my Nest app, I can see the subscription created properly in the NATS server logs.\n\nWhen I run the `test.ts` file, it times out with `NatsError: Request timed out.`. However, I can see my console logs (although the data is `undefined` even though I am specifying it in the published message.\n\nNeither the `return` nor the `client.send` methods are working to receive messages back from the app.\n\nAny help is appreciated!\n\nEDIT:\nStill looking into and stuck on this issue. In the \"Sending Messages\" section of the Microservice docs, it says \"The pattern has to be equal to this one defined in the @MessagePattern() decorator while payload is a message that we want to transmit to another microservice.\". If I do that, the Nest app detects the message it sends and gets stuck in an infinite loop of sending a message and receiving the same message back and forth to itself forever.\n\n========================================\n\nTop Answer:\nWhen using the ClientProxy, `send` and `emit` return Observables. You need to \"activate\" those for them to do anything. So you can either `subscribe` to them, or change it to a Promise.\n\nsince you are using `await` you probably want to do\n\n```\nawait this.natsClient.send(\"hello\", this.appService.getHello()).toPromise();\n```\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice(AppModule, {\n    options: {\n      url: \"nats://localhost:4222\",\n    },\n    transport: Transport.NATS,\n  });\n  app.listen(() => console.log(\"Microservice is listening\"));\n}\nbootstrap();\n```\n\n```text\nexport const NatsClientProvider: Provider = {\n  inject: [ConfigService],\n  provide: NatsClientProviderId,\n  useFactory: async (config: ConfigService) =>\n    ClientProxyFactory.create({\n      options: {\n        servers: config.getNatsConfig().servers,\n      },\n      transport: Transport.NATS,\n    }),\n};\n```\n\n```text\n@Controller()\nexport class AppController {\n  constructor(\n    private readonly appService: AppService,\n    @Inject(NatsClientProviderId) private readonly natsClient: ClientProxy,\n  ) {}\n\n  @MessagePattern(\"hello\")\n  async getHello(data: string) {\n    console.log(\"data: \", data);\n    console.log(\"getHello!!\");\n    await this.natsClient.send(\"hello\", this.appService.getHello());\n    return this.appService.getHello();\n  }\n\n  async onModuleInit() {\n    await this.natsClient.connect();\n    console.log(\"Nats connected!\");\n  }\n```\n\n```text\nimport { connect } from \"ts-nats\";\n\nasync function start() {\n  const nc = await connect({\n    servers: [\"nats://localhost:4222\"],\n  });\n\n  const msg = await nc.request(\"hello\", 5000, \"me\");\n  console.log(\"msg: \", msg);\n}\n\nstart();\n```\n\n```text\nmain.ts\n```\n\n```text\napp.controller.ts\n```\n\n```text\ntest.ts\n```\n\n```text\nNatsError: Request timed out.\n```\n\n```text\nundefined\n```\n\n```text\nreturn\n```\n\n```text\nclient.send\n```\n\n```text\n@MessagePattern(\"hello\")\nasync getHello(data: string) {\n  console.log(\"data: \", data);\n  return \"Hello World!\";\n}\n```\n\n```text\n// Nest expects the data to have the following structure\nconst reply = await nc.request(\"hello\", 500, JSON.stringify({ data: \"Hello\", id: \"myid\" }));\nconsole.log({ reply });\n```\n\n```text\ndata: Hello\n```\n\n```text\n{ reply:\n   { subject: '_INBOX.GJGL6RJFYXKMCF8CWXO0HB.GJGL6RJFYXKMCF8CWXO0B5',\n     sid: 1,\n     reply: undefined,\n     size: 50,\n     data: '{\"err\":null,\"response\":\"Hello World!\",\"id\":\"myid\"}' \n} }\n```\n\n```text\nnatsClient.send\n```\n\n```text\nMessagePattern\n```\n\n```text\nthis.appService.getHello()\n```\n\n```text\nid\n```\n\n```js\nawait this.natsClient.send(\"hello\", this.appService.getHello()).toPromise();\n```\n\n```text\nsend\n```\n\n```text\nemit\n```\n\n```text\nsubscribe\n```\n\n```text\nawait\n```\n\n```text\n// service 1: data-source controller\n\n@Controller()\nexport class AppController {\n  @MessagePattern('data-source.status')\n  async status() {\n    return 'Ok!';\n  }\n}\n```\n\n```js\n// service 2 somewere in the code... \n\nimport { firstValueFrom } from 'rxjs';\n...\nconst req = this.nats.send('data-source.status', {}); // Observable\nconst res = await firstValueFrom(req).catch((e) => console.error(e));\nconsole.log({ res });\n...\n// out\n{ res: 'Ok!' }\n```\n\n```text\n// both services has same NATS configuration\n\nconst logger = new Logger();\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice<MicroserviceOptions>(\n    AppModule,\n    {\n      logger: logger,\n      transport: Transport.NATS,\n      options: {\n        servers: process.env.NATS,\n      },\n    },\n  );\n  await app.listen();\n}\n\nbootstrap();\n```\n\n```text\n// and NATS provider to inject in services and send requests...\n\nimport { Provider } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { ClientProxyFactory, Transport } from '@nestjs/microservices';\n\nexport const NATS = 'NATS_CLIENT';\n\nexport const NatsProvider: Provider = {\n  provide: NATS,\n  useFactory: (configService: ConfigService) => {\n    return ClientProxyFactory.create({\n      transport: Transport.NATS,\n      options: {\n        url: configService.get('NATS'),\n      },\n    });\n  },\n  inject: [ConfigService],\n};\n```\n\n```text\nMessagePattern\n```\n\n========================================\n\nComments:\n- Hmm, thanks for the info. I tried this and I'm still getting the infinite loop where the service keeps responding to its own message (seems like this is due to the `@MessagePattern` message being the same as the subject that is being sent. Although I assume it would have to be like this in order for the request-response to work, I just don't understand how to make it not respond to itself, since both the ClientProxy and the Nest microservice are connected to the same NATS server.\n- This does not use the Request-Response pattern: github.com/nats-io/nats.ts. I should just be able to use `let msg = await nc.request('greeter', 1000, 'me');` which takes care of the full subscription, publish, and response. You may have figured out my data issue though.\n- To clarify, if I send the request like this: `const msg = await nc.request(JSON.stringify({ cmd: \"hello\" }),5000,JSON.stringify({data: \"me\",}));` I can console log the correct data, but my Nest app is not sending the response back.\n- Also, I tried the approach you mentioned, I do get the response from the test script but that is from the same script receiving its own message, nothing is received from the Nest app properly. The Nest app needs to send a response to my NATS server that the client (the test script) picks up and logs.\n- Sorry, you are right, this was not correct. Please see my edit. The missing bit was the `id` field.\n- Thanks for the help! Is there any way to also get the subject of the input message in Nest? For example if I want to subscribe to `user.get.>` so that I can receive messages to `user.get.MY_USER_ID` and be able to see that `MY_USER_ID` was the in the subject.\n- Not that I know of. :/ Does it even work with wildcards in nest?\n- If it does not work with wildcards, that is a non-starter for me. I worked around this issue by implementing my own NATS pub/sub layer, but I would have liked to use the Nest framework. I will open an issue with Nest about this. Thank you for all the help.\n- I just tested and it does in fact work with wildcard subscriptions the as per the example I provided (`@MessagePattern('hello.>')` and request subject `hello.world`). Now if I can just get the subject to print out I will be set.\n- I don't think this part of the API, but you could open an issue (or even pull request) for it. Shouldn't be to hard I think.","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":351,"estimatedTokens":2338}}450{"id":"stack-57771616","source":"stackoverflow","questionId":57771616,"title":"How to use Jest to mock winston logger instance encapsulated in service class","tags":["typescript","jestjs","nestjs","winston"],"text":"Title: How to use Jest to mock winston logger instance encapsulated in service class\nTags: typescript, jestjs, nestjs, winston\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock a *winston.Logger* instance that is encapsulated within a service class created with NestJS. I have included my code below. \n\nI cannot get the mocked logger instance to be triggered from within the service class. Can anyone explain where I am going wrong?\n\n```\nimport * as winston from 'winston';\n\nimport { loggerOptions } from '../logger/logger.config';\nimport { LoggingService } from '../logger/logger.service';\n\nconst logger: winston.Logger = winston.createLogger(loggerOptions);\n\n// trying to mock createLogger to return a specific logger instance\nconst winstonMock = jest.mock('winston', () => (\n {\n format: {\n colorize: jest.fn(),\n combine: jest.fn(),\n label: jest.fn(),\n timestamp: jest.fn(),\n printf: jest.fn()\n },\n createLogger: jest.fn().mockReturnValue(logger),\n transports: {\n Console: jest.fn()\n }\n })\n);\n\ndescribe(\"-- Logging Service --\", () => {\n let loggerMock: winston.Logger;\n\n test('testing logger log function called...', () => { \n const mockCreateLogger = jest.spyOn(winston, 'createLogger');\n const loggingService: LoggingService = LoggingService.Instance;\n loggerMock = mockCreateLogger.mock.instances[0];\n expect(loggingService).toBeInstanceOf(LoggingService)\n expect(loggingService).toBeDefined();\n expect(mockCreateLogger).toHaveBeenCalled()\n\n // spy on the winston.Logger instance within this test and check\n // that it is called - this is working from within the test method\n const logDebugMock = jest.spyOn(loggerMock, 'log');\n loggerMock.log('debug','test log debug');\n expect(logDebugMock).toHaveBeenCalled();\n\n // now try and invoke the logger instance indirectly through the service class\n // check that loggerMock is called a second time - this fails, only called once\n // from the preceding lines in this test\n loggingService.debug('debug message');\n expect(logDebugMock).toHaveBeenCalledTimes(2);\n });\n\n ...\n```\n\n**LoggingService debug method code**\n\n```\npublic debug(message: string) {\n this.logger.log(\n {\n level: types.LogLevel.DEBUG,\n message: message,\n meta: {\n context: this.contextName\n }\n }\n );\n }\n```\n\n**Update: 3/09/2019**\n\nRefactored my nestjs LoggingService to dependency inject winston logger instance in constructor to facilitate unit testing. This enables me to use *jest.spyOn* on the winston logger's log method and check that it has been called within the service instance:\n\n```\n// create winstonLoggerInstance here, e.g. in beforeEach()....\nconst winstonLoggerMock = jest.spyOn(winstonLoggerInstance, 'log');\nserviceInstance.debug('debug sent from test');\nexpect(winstonLoggerMock).toHaveBeenCalled();\n```\n\n========================================\n\nTop Answer:\nI recently had the same question and solved it by using jest.spyOn with my custom logger.\n\n**NOTE: You shouldn't have to unit test winston.createLogger(). The Winston module has its own unit tests that cover that functionality.**\n\nSome function that logs an error(i.e. `./controller.ts`):\n\n```\nimport defaultLogger from '../config/winston';\n\nexport const testFunction = async () => {\n try {\n throw new Error('This error should be logged');\n } catch (err) {\n defaultLogger.error(err);\n return;\n }\n};\n```\n\nThe test file for that function (i.e. `./tests/controller.test.ts):\n\n```\nimport { Logger } from 'winston';\nimport defaultLogger from '../../config/winston';\nimport testFunction from '../../controller.ts';\n\nconst loggerSpy = jest.spyOn(defaultLogger, 'error').mockReturnValue(({} as unknown) as Logger);\n\ntest('Logger should have logged', async (done) => {\n await testFunction();\n\n expect(loggerSpy).toHaveBeenCalledTimes(1);\n});\n```\n\n========================================\n\nCode:\n```js\nimport * as winston from 'winston';\n\nimport { loggerOptions } from '../logger/logger.config';\nimport { LoggingService } from '../logger/logger.service';\n\nconst logger: winston.Logger = winston.createLogger(loggerOptions);\n\n// trying to mock createLogger to return a specific logger instance\nconst winstonMock = jest.mock('winston', () => (\n    {\n        format: {\n            colorize: jest.fn(),\n            combine: jest.fn(),\n            label: jest.fn(),\n            timestamp: jest.fn(),\n            printf: jest.fn()\n        },\n        createLogger: jest.fn().mockReturnValue(logger),\n        transports: {\n            Console: jest.fn()\n        }\n    })\n);\n\n\ndescribe(\"-- Logging Service --\", () => {\n    let loggerMock: winston.Logger;\n\n    test('testing logger log function called...', () => {        \n        const mockCreateLogger = jest.spyOn(winston, 'createLogger');\n        const loggingService: LoggingService = LoggingService.Instance;\n        loggerMock = mockCreateLogger.mock.instances[0];\n        expect(loggingService).toBeInstanceOf(LoggingService)\n        expect(loggingService).toBeDefined();\n        expect(mockCreateLogger).toHaveBeenCalled()\n\n        // spy on the winston.Logger instance within this test and check\n        // that it is called - this is working from within the test method\n        const logDebugMock = jest.spyOn(loggerMock, 'log');\n        loggerMock.log('debug','test log debug');\n        expect(logDebugMock).toHaveBeenCalled();\n\n        // now try and invoke the logger instance indirectly through the service class\n        // check that loggerMock is called a second time - this fails, only called once\n        // from the preceding lines in this test\n        loggingService.debug('debug message');\n        expect(logDebugMock).toHaveBeenCalledTimes(2);\n    });\n\n   ...\n```\n\n```text\npublic debug(message: string) {\n        this.logger.log(\n            {\n                level: types.LogLevel.DEBUG,\n                message: message,\n                meta: {\n                    context: this.contextName\n                }\n            }\n        );\n    }\n```\n\n```js\n// create winstonLoggerInstance here, e.g. in beforeEach()....\nconst winstonLoggerMock = jest.spyOn(winstonLoggerInstance, 'log');\nserviceInstance.debug('debug sent from test');\nexpect(winstonLoggerMock).toHaveBeenCalled();\n```\n\n```text\nconst logger = {\n  debug: jest.fn(),\n  log: jest.fn()\n};\n\n// IMPORTANT First mock winston\njest.mock(\"winston\", () => ({\n  format: {\n    colorize: jest.fn(),\n    combine: jest.fn(),\n    label: jest.fn(),\n    timestamp: jest.fn(),\n    printf: jest.fn()\n  },\n  createLogger: jest.fn().mockReturnValue(logger),\n  transports: {\n    Console: jest.fn()\n  }\n}));\n\n// IMPORTANT import the mock after\nimport * as winston from \"winston\";\n// IMPORTANT import your service (which imports winston as well)\nimport { LoggingService } from \"../logger/logger.service\";\n```\n\n```text\nconst logger = {\n  debug: jest.fn(),\n  log: jest.fn()\n};\n```\n\n```text\nconst logger = {\n  debug: jest.fn(),\n  log: jest.fn()\n};\n\n// trying to mock createLogger to return a specific logger instance\njest.mock(\"winston\", () => ({\n  format: {\n    colorize: jest.fn(),\n    combine: jest.fn(),\n    label: jest.fn(),\n    timestamp: jest.fn(),\n    printf: jest.fn()\n  },\n  createLogger: jest.fn().mockReturnValue(logger),\n  transports: {\n    Console: jest.fn()\n  }\n}));\n\nimport * as winston from \"winston\";\nimport { LoggingService } from \"./logger.service\";\n\ndescribe(\"-- Logging Service --\", () => {\n  let loggerMock: winston.Logger;\n\n  test(\"testing logger log function called...\", () => {\n    const mockCreateLogger = jest.spyOn(winston, \"createLogger\");\n    const loggingService: LoggingService = LoggingService.Instance;\n    loggerMock = mockCreateLogger.mock.instances[0];\n    expect(loggingService).toBeInstanceOf(LoggingService);\n    expect(loggingService).toBeDefined();\n    expect(mockCreateLogger).toHaveBeenCalled();\n\n    // spy on the winston.Logger instance within this test and check\n    // that it is called - this is working from within the test method\n    logger.log(\"debug\", \"test log debug\");\n    expect(logger.log).toHaveBeenCalled();\n\n    // now try and invoke the logger instance indirectly through the service class\n    // check that loggerMock is called a second time - this fails, only called once\n    // from the preceding lines in this test\n    loggingService.debug(\"debug message\");\n\n    expect(logger.debug).toHaveBeenCalledTimes(1); // <- here\n  });\n});\n```\n\n```text\nimport * as winston from \"winston\";\n\nexport class LoggingService {\n  logger: winston.Logger;\n\n  static get Instance() {\n    return new LoggingService();\n  }\n\n  constructor() {\n    this.logger = winston.createLogger();\n  }\n\n  debug(message: string) {\n    this.logger.debug(message);\n  }\n}\n```\n\n```text\nlog\n```\n\n```text\ndebug\n```\n\n```text\nimport defaultLogger from '../config/winston';\n\nexport const testFunction = async () => {\n  try {\n    throw new Error('This error should be logged');\n  } catch (err) {\n    defaultLogger.error(err);\n    return;\n  }\n};\n```\n\n```text\nimport { Logger } from 'winston';\nimport defaultLogger from '../../config/winston';\nimport testFunction from '../../controller.ts';\n\nconst loggerSpy = jest.spyOn(defaultLogger, 'error').mockReturnValue(({} as unknown) as Logger);\n\ntest('Logger should have logged', async (done) => {\n  await testFunction();\n\n  expect(loggerSpy).toHaveBeenCalledTimes(1);\n});\n```\n\n```text\n./controller.ts\n```\n\n```text\njest.mock(\"winston\", () => {\n    const winston = jest.requireActual(\"winston\");\n    winston.transports.Console.prototype.log = jest.fn();\n    return winston;\n});\n```\n\n```js\n// logger.ts\nexport const _intercept: { enabled: boolean, logs: string[] } = {\n  enabled: false,\n  logs: []\n}\n\nfunction createInterceptTransport() {\n  return new winston.transports.Stream({\n    stream: new Writable({\n      write(chunk, encoding, callback) {\n        if (_intercept.enabled) {\n          _intercept.logs.push(String(chunk))\n        }\n        callback()\n      },\n    })\n  })\n}\n\nconst transports: winston.transport[] = [new winston.transports.Console()]\n\nif (isTest) {\n  transports.push(createInterceptTransport())\n}\n\nconst winstonLogger = winston.createLogger({\n  // ... ,\n  transports\n})\n```\n\n```js\n// test.ts\nafterEach(() => {\n  _intercept.enabled = false\n  _intercept.logs = []\n})\n\nit(\"logs contain user information, but not the token\", async () => {\n  _intercept.enabled = true\n  // do some loggable stuff...\n\n  expect(_intercept.logs).toIncludeSomething()\n})\n```\n\n========================================\n\nComments:\n- Thanks B&#225;lint, your answer has been very helpful. So the key lesson I have learned here is to define any mocks first and ensure that they are independent of the library being mocked, e.g mock any API objects returned from the library functions, such as winston.createLogger in this example. After the mocks have been defined then do the imports. Not sure I understand what mean by you don't need to spy on what you have mocked once, do you mean the line `const mockCreateLogger = jest.spyOn(winston, \"createLogger\");`? Thanks again B&#225;lint, this has been very helpful :)\n- You must mock the module before import it for the actual usage. This is important. I bet Jest replace the result of the import when it mocks some module. If you already have the reference of the actual module (not the mock), I'm afraid `Jest` cannot deal with it. You don't have to spy the mocked function, because it already has the behaviour of a spy. `Jest` can do the same assertions both with spies or mocks.\n- Ok thanks B&#225;lint, so I could do..`const winstonMock = { format: { colorize: jest.fn(), combine: jest.fn(), label: jest.fn(), timestamp: jest.fn(), printf: jest.fn() }, createLogger: jest.fn().mockReturnValue(logger), transports: { Console: jest.fn() } } &#47;&#47; trying to mock createLogger to return a specific logger instance jest.mock(\"winston\", () => (winstonMock));` and then test createLogger mock function has been called with the line expect(winstonMock.createLogger).toHaveBeenCalled(); instead of using spyOn?? apologies re code format!!!!\n- Exactly! It's simpler and safer. Don't forget to restore mocked module at the end of your test suit.\n- Got it. Many thanks again for your help Balint, appreciated :)\n- According to Jest doc, jest.mock() are hoisted to the top of the file - see jestjs.io/docs/es6-class-mocks (section Calling jest.mock() with the module factory parameter, warning part): CAUTION Since calls to jest.mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables. By default, you cannot first define a variable and then use it in the factory. Jest will disable this check for variables that start with the word mock. However, it is still up to you to guarantee that they will be initialized on time. Be aware of Temporal Dead Zone.","metadata":{"transformedAt":"2026-08-18T18:33:02.444Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":410,"estimatedTokens":3167}}451{"id":"stack-71589818","source":"stackoverflow","questionId":71589818,"title":"Why npm install failed only in ElasticBeanstalk?","tags":["node.js","amazon-web-services","amazon-elastic-beanstalk","nestjs"],"text":"Title: Why npm install failed only in ElasticBeanstalk?\nTags: node.js, amazon-web-services, amazon-elastic-beanstalk, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a Nest.js (Node.js) application, and I want to deploy it on ElasticBeanstalk (Node 16 version, AL2 5.5.0).\nMy deployment keeps failing, and I found the error in `eb-engine.log`.\n\n```\n...\n2022/03/23 15:11:48.570759 [INFO] Executing instruction: StageApplication\n2022/03/23 15:11:48.570846 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/\n2022/03/23 15:11:48.570860 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/\n2022/03/23 15:11:49.274806 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully\n2022/03/23 15:11:49.289272 [INFO] Executing instruction: RunAppDeployPreBuildHooks\n2022/03/23 15:11:49.289292 [INFO] Executing platform hooks in .platform/hooks/prebuild/\n2022/03/23 15:11:49.289306 [INFO] The dir .platform/hooks/prebuild/ does not exist\n2022/03/23 15:11:49.289311 [INFO] Executing instruction: Install customer specified node.js version\n2022/03/23 15:11:49.289314 [INFO] installing specified nodejs version...\n2022/03/23 15:11:49.289467 [INFO] there is no nodejs version specified in package.json, skip installing specified version of nodejs\n2022/03/23 15:11:49.289476 [INFO] Executing instruction: Use NPM to install dependencies\n2022/03/23 15:11:49.289484 [INFO] use npm to install dependencies\n2022/03/23 15:11:49.289505 [INFO] Running command /bin/sh -c npm config set jobs 1\n2022/03/23 15:11:49.574486 [INFO] Running command /bin/sh -c npm --production install\n2022/03/23 15:12:06.913580 [ERROR] An error occurred during execution of command [app-deploy] - [Use NPM to install dependencies]. Stop running the command. Error: Command /bin/sh -c npm --production install failed with error signal: killed \n...\n```\n\nI think the error occurs when installing npm packages in production mode, but I'm really wondering why this happens. I executed `npm --production install` in my local computer, the installing was successful with the exactly same versions of node & npm. (Node 16.14.0, npm 8.3.1 - AL2 5.5.0 latest for now).\n\nI want to know why this happens and how to debug more details (why npm install failed in the elastic beanstalk environment).\n\n========================================\n\nTop Answer:\nThe accepted answer DOES NOT resolve the underlying issue:\n\n`npm --production install failed with error signal: killed`\n\nIt's my understandind that most of the times it means a memory leak / time out issue. And it seems to be common to npm v7+ version.\n\n**SOLUTION**\n\n- Create node_modules with a prebuild hook:\n\n`mkdir node_modules`\n\nIn doing so, you prevent AWS to install dependencies (because the folder node_modules will already exists).\n\n- Install dependencies with a predeploy hook:\n\n`npm install --omit=dev`\n\nSource (see `pmoleri` answer)\n\nAWS Hooks (official documentation)\n\nStep by Step Solution (from AWS Support)\n\n========================================\n\nCode:\n```text\n...\n2022/03/23 15:11:48.570759 [INFO] Executing instruction: StageApplication\n2022/03/23 15:11:48.570846 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/\n2022/03/23 15:11:48.570860 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/\n2022/03/23 15:11:49.274806 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully\n2022/03/23 15:11:49.289272 [INFO] Executing instruction: RunAppDeployPreBuildHooks\n2022/03/23 15:11:49.289292 [INFO] Executing platform hooks in .platform/hooks/prebuild/\n2022/03/23 15:11:49.289306 [INFO] The dir .platform/hooks/prebuild/ does not exist\n2022/03/23 15:11:49.289311 [INFO] Executing instruction: Install customer specified node.js version\n2022/03/23 15:11:49.289314 [INFO] installing specified nodejs version...\n2022/03/23 15:11:49.289467 [INFO] there is no nodejs version specified in package.json, skip installing specified version of nodejs\n2022/03/23 15:11:49.289476 [INFO] Executing instruction: Use NPM to install dependencies\n2022/03/23 15:11:49.289484 [INFO] use npm to install dependencies\n2022/03/23 15:11:49.289505 [INFO] Running command /bin/sh -c npm config set jobs 1\n2022/03/23 15:11:49.574486 [INFO] Running command /bin/sh -c npm --production install\n2022/03/23 15:12:06.913580 [ERROR] An error occurred during execution of command [app-deploy] - [Use NPM to install dependencies]. Stop running the command. Error: Command /bin/sh -c npm --production install failed with error signal: killed \n...\n```\n\n```text\neb-engine.log\n```\n\n```text\nnpm --production install\n```\n\n```text\nt2.medium\n```\n\n```text\nnpm --production install failed with error signal: killed\n```\n\n```text\nmkdir node_modules\n```\n\n```text\nnpm install --omit=dev\n```\n\n```text\npmoleri\n```\n\n========================================\n\nComments:\n- `killed` is an indication of `SIGKILL`, which most common cause is out of memory.\n- Can't we just prevent `npm --production install` execution in the elastic beanstalk environment. I'm using the bitbucket pipeline to build the app.\n- @ashenmadusanka Use prebuild hooks to make node_modules or include some node_modules folder into your source bundle before eb is trying to isntall packages. EB will not install packages when node_modules are already ready in your source bundle.\n- yes, this is the best option.\n- This solution does not resolve the underlying issue (and upgrading instance costs money). You need to use the prebuild and predeploy hooks in order to install the dependencies.\n- This solved the issue for me, and deploys are quite fast again on .small and .micro instances. Thanks!\n- Yes, this saved my bacon, deploys fast again on t3.micro instances","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":120,"estimatedTokens":1482}}452{"id":"stack-53995130","source":"stackoverflow","questionId":53995130,"title":"NestJS - Combine HTTP with RabbitMQ in microservices","tags":["node.js","events","rabbitmq","microservices","nestjs"],"text":"Title: NestJS - Combine HTTP with RabbitMQ in microservices\nTags: node.js, events, rabbitmq, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a few microservices, which are exposed through an API-Gateway. The gateway takes care of handling authentication and routing into the system. The services behind the gateway are mostly simple CRUD-Services. Each service exposes its own API and they communicate synchronously via HTTP. All of these services, including the API-Gateway, are \"default\" NestJS applications.\n\nLet's stick with the Cats example. Whenever the `Cat-Service` updates or creates a new `Cat`, I want an `CatCreatedEvent` or `CatUpdatedEvent` to be emmited. The event should be pushed into some message broker like RabbitMQ and another service should listen to this event and process the event asynchronously.\n\nI am not sure how to achive this, in terms of how to \"inject\" RabbitMQ the right way and I am wondering if this approach makes sense in generel. I have seen the CQRS Module for NestJS, but i think CQRS is a bit too much for this domain. Especially because there is no benefit in this domain to split read- and write-models. Maybe I am totally on the wrong track, so I hope you can give me some advises.\n\n========================================\n\nTop Answer:\nNote startAllMicroservicesAsync is depricated****\n\n```\nimport { Transport, MicroserviceOptions } from '@nestjs/microservices';\n const app = await NestFactory.create(AppModule);\n app.connectMicroservice({\n transport: Transport.TCP,\n options: { retryAttempts: 5, retryDelay: 3000 },\n });\n \n await app.startAllMicroservices();\n await app.listen(3001);\n console.log(`Application is running on: ${await app.getUrl()}`);\n```\n\n========================================\n\nCode:\n```text\nCat-Service\n```\n\n```text\nCat\n```\n\n```text\nCatCreatedEvent\n```\n\n```text\nCatUpdatedEvent\n```\n\n```text\n// Create your regular nest application.\nconst app = await NestFactory.create(ApplicationModule);\n\n// Then combine it with a RabbitMQ microservice\nconst microservice = app.connectMicroservice({\n  transport: Transport.RMQ,\n  options: {\n    urls: [`amqp://localhost:5672`],\n    queue: 'my_queue',\n    queueOptions: { durable: false },\n  },\n});\n\nawait app.startAllMicroservices();\nawait app.listen(3001);\n```\n\n```text\nimport { Transport, MicroserviceOptions } from '@nestjs/microservices';\n        const app = await NestFactory.create(AppModule);\n              app.connectMicroservice<MicroserviceOptions>({\n                transport: Transport.TCP,\n                options: { retryAttempts: 5, retryDelay: 3000 },\n              });\n            \n              await app.startAllMicroservices();\n              await app.listen(3001);\n              console.log(`Application is running on: ${await app.getUrl()}`);\n```\n\n========================================\n\nComments:\n- Thank you! After a bit of trying, I got this working. In the `CatService` I added this, which is called by the `CatController` after a POST request to `&#47;cats` `emitCatCreatedEvent() { return this.client.send({ name: 'catCreatedEvent'}, 'something happend').toPromise(); }` Would you say this approch goes in the right direction?\n- Yes, looks good. :-) It's a bit tricky to understand how to use `this.client`.\n- @user2534584 can you please your example?\n- Yes, and obiviously the emitCatCreatedEvent() call should always be the last thing done on the happy path, since signals that the \"cat creation\" is actually happened. Maybe it could be better if the event signalling is done on a controller level, since it looks like more application logic than business logic. Am I wrong?\n- @user2534584 in your post above, where does `this.client` come from? Is that a standard NestJS service? A node driver for RabbitMQ?\n- nvm; I think it is a `ClientProxy` from docs.nestjs.com/microservices/basics#client","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":88,"estimatedTokens":961}}453{"id":"stack-47861633","source":"stackoverflow","questionId":47861633,"title":"Versioning Nestjs routes?","tags":["nestjs"],"text":"Title: Versioning Nestjs routes?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm just getting started with Nestjs and am wondering how I can version my API using either a route prefix or through an Express Router instance?\n\nIdeally, I would like to make endpoints accessible via:\n\n```\n/v1\n/v2\n```\n\netc, so I can gracefully degrade endpoints. I'm not seeing where I could add the version prefix. I know it's possible to set a global prefix on the application instance, but that's not for a particular set of endpoints.\n\n========================================\n\nTop Answer:\nRouter Module comes to rescue, with Nest `RouterModule` it's now a painless organizing your routes.\n\nSee How it easy to setup.\n\n```\nconst routes: Routes = [\n {\n path: '/ninja',\n module: NinjaModule,\n children: [\n {\n path: '/cats',\n module: CatsModule,\n },\n {\n path: '/dogs',\n module: DogsModule,\n },\n ],\n },\n ];\n\n@Module({\n imports: [\n RouterModule.forRoutes(routes), // setup the routes\n CatsModule,\n DogsModule,\n NinjaModule\n ], // as usual, nothing new\n})\nexport class ApplicationModule {}\n```\n\nthis will produce something like this:\n\n```\nninja\n โ”œโ”€โ”€ /\n โ”œโ”€โ”€ /katana\n โ”œโ”€โ”€ cats\n โ”‚ โ”œโ”€โ”€ /\n โ”‚ โ””โ”€โ”€ /ketty\n โ”œโ”€โ”€ dogs\n โ”œโ”€โ”€ /\n โ””โ”€โ”€ /puppy\n```\n\nand sure, for Versioning the routes you could do similar to this\n\n```\nconst routes: Routes = [\n {\n path: '/v1',\n children: [CatsModule, DogsModule],\n },\n {\n path: '/v2',\n children: [CatsModule2, DogsModule2],\n },\n ];\n```\n\nNice !\n\ncheck it out Nest Router\n\n========================================\n\nCode:\n```text\n/v1\n/v2\n```\n\n```text\nRouterModule\n```\n\n```text\nv1\n```\n\n```text\nv2\n```\n\n```text\n@Controller()\n```\n\n```text\nconst routes: Routes = [\n    {\n      path: '/ninja',\n      module: NinjaModule,\n      children: [\n        {\n          path: '/cats',\n          module: CatsModule,\n        },\n        {\n          path: '/dogs',\n          module: DogsModule,\n        },\n      ],\n    },\n  ];\n\n@Module({\n  imports: [\n      RouterModule.forRoutes(routes), // setup the routes\n      CatsModule,\n      DogsModule,\n      NinjaModule\n      ], // as usual, nothing new\n})\nexport class ApplicationModule {}\n```\n\n```text\nninja\n    โ”œโ”€โ”€ /\n    โ”œโ”€โ”€ /katana\n    โ”œโ”€โ”€ cats\n    โ”‚   โ”œโ”€โ”€ /\n    โ”‚   โ””โ”€โ”€ /ketty\n    โ”œโ”€โ”€ dogs\n        โ”œโ”€โ”€ /\n        โ””โ”€โ”€ /puppy\n```\n\n```text\nconst routes: Routes = [\n    {\n      path: '/v1',\n      children: [CatsModule, DogsModule],\n    },\n    {\n      path: '/v2',\n      children: [CatsModule2, DogsModule2],\n    },\n  ];\n```\n\n```text\nRouterModule\n```\n\n```text\nimport { VersioningType } from \"@nestjs/common\";\n     \napp.enableVersioning({\n        type: VersioningType.URI,\n      });\n\n      app.setGlobalPrefix(\"api/v1\"); //edit your prefix as per your requirements!\n```\n\n```text\napp.setGlobalPrefix('v1', {\n  exclude: [{ path: 'health', method: RequestMethod.GET }], // replace your endpoints in the place of health!\n});\n```\n\n```text\napp.setGlobalPrefix('v1', { exclude: ['cats'] }); // replace your endpoints in the place of cats!\n```\n\n```text\n// Versioning\n  app.enableVersioning({\n    type: VersioningType.URI,\n    defaultVersion: '1',\n    prefix: 'api/v',\n  });\n```\n\n```text\nmain.ts\n```\n\n```text\nconst app = await NestFactory.create(AppModule)\n```\n\n```text\n/api/v1\n```\n\n```text\n@Controller({version:'2'})\n```\n\n```text\n@Version('2')\n```\n\n```text\napp.enableVersioning()\n```\n\n```text\nSwaggerModule.createDocument()\n```\n\n========================================\n\nComments:\n- NestJS supports versioning out-of-the-box now: docs.nestjs.com/techniques/versioning\n- Thank you for the link! That also answers my other question on how to group routes.\n- great suggestion, now we have nest-route package but still I want to ask, do you feel any drawback of having version route prefix to the controller level over module level(as suggested in nest-route package)\n- @Kamil Myล›liwiec, can you version in the following manner: `1.x`, or just `1`?\n- any drawback of adding version prefix to the controller itself and include multiple controllers in single module ?","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":232,"estimatedTokens":992}}454{"id":"stack-60616889","source":"stackoverflow","questionId":60616889,"title":"class-validator doesn't appear to do anything in NestJS application","tags":["nestjs","class-validator"],"text":"Title: class-validator doesn't appear to do anything in NestJS application\nTags: nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a new NestJS application, and I've just added class-validator in order to validate controller input, but it seems to be completely ignored. This is the DTO:\n\n```\nimport {IsString} from 'class-validator';\n\nexport class CreateCompanyDto {\n @IsString()\n name: string | undefined;\n}\n```\n\nThis is the controller:\n\n```\nimport {\n Body,\n Controller,\n InternalServerErrorException,\n Post,\n Request,\n UseGuards, ValidationPipe\n} from '@nestjs/common';\nimport * as admin from 'firebase-admin';\nimport {User} from 'firebase';\nimport {AuthGuard} from '../auth/auth.guard';\nimport {CurrentUser} from '../auth/current-user.decorator';\nimport {CreateCompanyDto} from './dto/create-company.dto';\n\n@Controller('vendor')\nexport class VendorController {\n\n @Post()\n @UseGuards(AuthGuard)\n async create(@CurrentUser() user: User, @Request() req: any, @Body(new ValidationPipe({ transform: true })) company: CreateCompanyDto) {\n console.log(JSON.stringify(company));\n throw new InternalServerErrorException('meh?');\n\n // irrelevant code\n }\n\n}\n```\n\nI would expect the code to throw a validation error and never hit the method itself, but instead it runs into the exception, and the object is logged exactly as it came in.\n\npackage.json:\n\n```\n{\n \"name\": \"functions\",\n \"scripts\": {\n \"lint\": \"tslint --project tsconfig.json\",\n \"prebuild\": \"(cd src && rm settings.json && ln -s ../configs/prod.json settings.json)\",\n \"build\": \"tsc\",\n \"prebuild:dev\": \"(cd src && rm settings.json && ln -s ../configs/dev.json settings.json)\",\n \"build:dev\": \"tsc\",\n \"serve\": \"concurrently \\\"npm run build:dev -- --watch\\\" \\\"firebase emulators:start --only functions\\\"\",\n \"shell\": \"npm run build && firebase functions:shell\",\n \"start\": \"npm run shell\",\n \"deploy\": \"firebase deploy --only functions\",\n \"logs\": \"firebase functions:log\"\n },\n \"engines\": {\n \"node\": \"8\"\n },\n \"main\": \"lib/functions/src/index.js\",\n \"dependencies\": {\n \"@elastic/elasticsearch\": \"^7.6.0\",\n \"@nestjs/common\": \"^6.11.11\",\n \"@nestjs/core\": \"^6.11.11\",\n \"@nestjs/platform-express\": \"^6.11.11\",\n \"@types/airtable\": \"^0.5.7\",\n \"@types/nodemailer\": \"^6.4.0\",\n \"airtable\": \"^0.8.1\",\n \"class-transformer\": \"^0.2.3\",\n \"class-validator\": \"^0.11.0\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^4.17.1\",\n \"firebase\": \"^7.10.0\",\n \"firebase-admin\": \"^8.9.2\",\n \"firebase-functions\": \"^3.3.0\",\n \"nodemailer\": \"^6.4.4\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rxjs\": \"^6.5.4\",\n \"slugify\": \"^1.4.0\"\n },\n \"devDependencies\": {\n \"concurrently\": \"^5.1.0\",\n \"tslint\": \"^6.0.0\",\n \"typescript\": \"~3.7.5\"\n },\n \"private\": true\n}\n```\n\nWhat am I missing here?\n\n**Update**\nI did a little debugging, and I can tell where it's going wrong, even though I still don't know why.\n\nIn the ValidationPipe.transform method, it returns the raw input, because metatype is undefined:\n\n```\nasync transform(value, metadata) {\n const { metatype } = metadata;\n if (!metatype || !this.toValidate(metadata)) {\n return value;\n }\n\n // ...\n }\n```\n\n========================================\n\nTop Answer:\nin `main.ts` add `app.useGlobalPipes(new ValidationPipe());`:\n\n```\nimport { ValidationPipe } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.enableCors();\n app.useGlobalPipes(new ValidationPipe());\n await app.listen(process.env.PORT || 3000);\n}\n\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nimport {IsString} from 'class-validator';\n\nexport class CreateCompanyDto {\n    @IsString()\n    name: string | undefined;\n}\n```\n\n```text\nimport {\n    Body,\n    Controller,\n    InternalServerErrorException,\n    Post,\n    Request,\n    UseGuards, ValidationPipe\n} from '@nestjs/common';\nimport * as admin from 'firebase-admin';\nimport {User} from 'firebase';\nimport {AuthGuard} from '../auth/auth.guard';\nimport {CurrentUser} from '../auth/current-user.decorator';\nimport {CreateCompanyDto} from './dto/create-company.dto';\n\n@Controller('vendor')\nexport class VendorController {\n\n    @Post()\n    @UseGuards(AuthGuard)\n    async create(@CurrentUser() user: User, @Request() req: any, @Body(new ValidationPipe({ transform: true })) company: CreateCompanyDto) {\n        console.log(JSON.stringify(company));\n        throw new InternalServerErrorException('meh?');\n\n         // irrelevant code\n    }\n\n}\n```\n\n```text\n{\n    \"name\": \"functions\",\n    \"scripts\": {\n        \"lint\": \"tslint --project tsconfig.json\",\n        \"prebuild\": \"(cd src && rm settings.json && ln -s ../configs/prod.json settings.json)\",\n        \"build\": \"tsc\",\n        \"prebuild:dev\": \"(cd src && rm settings.json && ln -s ../configs/dev.json settings.json)\",\n        \"build:dev\": \"tsc\",\n        \"serve\": \"concurrently \\\"npm run build:dev -- --watch\\\" \\\"firebase emulators:start --only functions\\\"\",\n        \"shell\": \"npm run build && firebase functions:shell\",\n        \"start\": \"npm run shell\",\n        \"deploy\": \"firebase deploy --only functions\",\n        \"logs\": \"firebase functions:log\"\n    },\n    \"engines\": {\n        \"node\": \"8\"\n    },\n    \"main\": \"lib/functions/src/index.js\",\n    \"dependencies\": {\n        \"@elastic/elasticsearch\": \"^7.6.0\",\n        \"@nestjs/common\": \"^6.11.11\",\n        \"@nestjs/core\": \"^6.11.11\",\n        \"@nestjs/platform-express\": \"^6.11.11\",\n        \"@types/airtable\": \"^0.5.7\",\n        \"@types/nodemailer\": \"^6.4.0\",\n        \"airtable\": \"^0.8.1\",\n        \"class-transformer\": \"^0.2.3\",\n        \"class-validator\": \"^0.11.0\",\n        \"cors\": \"^2.8.5\",\n        \"express\": \"^4.17.1\",\n        \"firebase\": \"^7.10.0\",\n        \"firebase-admin\": \"^8.9.2\",\n        \"firebase-functions\": \"^3.3.0\",\n        \"nodemailer\": \"^6.4.4\",\n        \"reflect-metadata\": \"^0.1.13\",\n        \"rxjs\": \"^6.5.4\",\n        \"slugify\": \"^1.4.0\"\n    },\n    \"devDependencies\": {\n        \"concurrently\": \"^5.1.0\",\n        \"tslint\": \"^6.0.0\",\n        \"typescript\": \"~3.7.5\"\n    },\n    \"private\": true\n}\n```\n\n```text\nasync transform(value, metadata) {\n        const { metatype } = metadata;\n        if (!metatype || !this.toValidate(metadata)) {\n            return value;\n        }\n\n        // ...\n    }\n```\n\n```text\n\"emitDecoratorMetadata\": true\n```\n\n```text\ntsconfig.json\n```\n\n```js\nimport { ValidationPipe } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    app.enableCors();\n    app.useGlobalPipes(new ValidationPipe());\n    await app.listen(process.env.PORT || 3000);\n}\n\nbootstrap();\n```\n\n```text\nmain.ts\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe());\n```\n\n```text\nnpm install class-transformer --save\n```\n\n```text\n@Post('register')\n  async register(@Body() localRegisterDto: LocalRegisterDto) { <--- this @Body()\n  }\n```\n\n========================================\n\nComments:\n- I ran into a similar issues where all my code was fine, just a silly mistake I had done was, I had put the line `app.useGlobalPipes(new ValidationPipe());` after app.listen\n- For me it still doesn't work and I added @UsePipes(new ValidationPipe({transform: true})) @Controller() export class MyFooController { }\n- this was the case for me too, thanks for sharing a link to a related question","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":286,"estimatedTokens":1841}}455{"id":"stack-59460475","source":"stackoverflow","questionId":59460475,"title":"Nestjs Config access to config in bootstrap level","tags":["nestjs","nestjs-swagger","nestjs-config"],"text":"Title: Nestjs Config access to config in bootstrap level\nTags: nestjs, nestjs-swagger, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nAccording to this documentation you import your config in AppModule.\n\nI'm trying to access to config in bootstrap level in my main.ts file.\nSomething like this:\n\n```\nconst app = await NestFactory.create(AppModule);\n if (config.get('swagger.enabled'))\n {\n initSwagger(app);\n }\n await app.listen(8080);\n```\n\nThe problem that I don't have access to config in this point, only other moudle will get access to config like this:\n\n```\n@Injectable()\nexport class SomeService {\n constructor(private readonly httpService: HttpService,\n private readonly config: ConfigService) {}\n}\n```\n\nMy question: How to access to 'nestjs-config' in bootstrap level\n\n========================================\n\nCode:\n```text\nconst app = await NestFactory.create(AppModule);\n  if (config.get('swagger.enabled'))\n  {\n    initSwagger(app);\n  }\n  await app.listen(8080);\n```\n\n```text\n@Injectable()\nexport class SomeService {\n    constructor(private readonly httpService: HttpService,\n                  private readonly config: ConfigService) {}\n}\n```\n\n```text\nmain.ts\n```\n\n```text\nconst config = app.get(ConfigService)\n```\n\n```text\nConfigService\n```\n\n========================================\n\nComments:\n- How if the app wasn't initialized, for example when using microservice with Kafka?","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":67,"estimatedTokens":348}}456{"id":"stack-62298246","source":"stackoverflow","questionId":62298246,"title":"How to define mongoose method in schema class with using nestjs/mongoose?","tags":["node.js","mongodb","typescript","mongoose","nestjs"],"text":"Title: How to define mongoose method in schema class with using nestjs/mongoose?\nTags: node.js, mongodb, typescript, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to implement method in schema class like below.\n\n```\nimport { SchemaFactory, Schema, Prop } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\nimport bcrypt from 'bcrypt';\n\n@Schema()\nexport class Auth extends Document {\n @Prop({ required: true, unique: true })\n username: string;\n\n @Prop({ required: true })\n password: string;\n\n @Prop({\n methods: Function,\n })\n async validatePassword(password: string): Promise {\n return bcrypt.compareAsync(password, this.password);\n }\n}\nexport const AuthSchema = SchemaFactory.createForClass(Auth);\n```\n\nthis schema return undefined when log the method . How can I write method in class schema with nestjs/mongoose package?\n\n========================================\n\nTop Answer:\nTry `AuthSchema.loadClass(Auth)` (Advanced Schemas: Creating from ES6 Classes Using loadClass()):\n\n```\nimport { SchemaFactory, Schema, Prop } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\nimport bcrypt from 'bcrypt';\n\n@Schema()\nexport class Auth extends Document {\n @Prop({ required: true, unique: true })\n username: string;\n\n @Prop({ required: true })\n password: string;\n\n async validatePassword(password: string): Promise {\n return bcrypt.compareAsync(password, this.password);\n }\n}\nexport const AuthSchema = SchemaFactory.createForClass(Auth);\n\n// This function lets you pull in methods, statics, and virtuals from an ES6 class.\nAuthSchema.loadClass(Auth);\n```\n\nMake sure all the properties you use in your method are annotated with the `@Prop()` decorator, otherwise, they will be undefined.\n\n========================================\n\nCode:\n```text\nimport { SchemaFactory, Schema, Prop } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\nimport bcrypt from 'bcrypt';\n\n@Schema()\nexport class Auth extends Document {\n  @Prop({ required: true, unique: true })\n  username: string;\n\n  @Prop({ required: true })\n  password: string;\n\n  @Prop({\n    methods: Function,\n  })\n  async validatePassword(password: string): Promise<boolean> {\n    return bcrypt.compareAsync(password, this.password);\n  }\n}\nexport const AuthSchema = SchemaFactory.createForClass(Auth);\n```\n\n```text\n@Schema()\nexport class Auth extends Document {\n    ...\n    \n    validatePassword: Function;\n}\n\nexport const AuthSchema = SchemaFactory.createForClass(Auth);\n\nAuthSchema.methods.validatePassword = async function (password: string): Promise<boolean> {\n    return bcrypt.compareAsync(password, this.password);\n};\n```\n\n```text\nexport function createSchema(document: any) {\n  const schema = SchemaFactory.createForClass(document);\n\n  const instance = Object.create(document.prototype);\n\n  for (const objName of Object.getOwnPropertyNames(document.prototype)) {\n    if (\n      objName != 'constructor' &&\n      typeof document.prototype[objName] == 'function'\n    ) {\n      schema.methods[objName] = instance[objName];\n    }\n  }\n\n  return schema;\n}\n```\n\n```text\nSchemaFactory.createForClass(Auth)\n```\n\n```js\nimport { SchemaFactory, Schema, Prop } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\nimport bcrypt from 'bcrypt';\n\n@Schema()\nexport class Auth extends Document {\n  @Prop({ required: true, unique: true })\n  username: string;\n\n  @Prop({ required: true })\n  password: string;\n\n  async validatePassword(password: string): Promise<boolean> {\n    return bcrypt.compareAsync(password, this.password);\n  }\n}\nexport const AuthSchema = SchemaFactory.createForClass(Auth);\n\n// This function lets you pull in methods, statics, and virtuals from an ES6 class.\nAuthSchema.loadClass(Auth);\n```\n\n```text\nAuthSchema.loadClass(Auth)\n```\n\n```text\n@Prop()\n```\n\n========================================\n\nComments:\n- That would be instance methods. Are you looking for static methods?\n- No i'm looking for instance methods. I can't define it inside class\n- The Schema will definitely return `undefined` for `validatePassword` since it is an instance method which it is on the model, not the schema.\n- Ya,you say true but the point is how to write method on schema\n- Hi, new to typed mongo in nestjs. Why cant we define these instance methods in the `@Schema` decorator with methods option. I tired this but it doesnt seem to work! Thanks for your solution, it works! Just wondering why its provided in the decorator and if you are aware of how to use it @Suroor Ahmmad\n- With the `@Schema()` decorator, you can only specify the schema and not define the method inside it.\n- Ok thanks, just wondering why we can define an instance/methods object with functions in it in @Schema() decorator in @nestjs/mongoose. But yes it does not work I am wondering what is the use of this option that we can pass to the @Schema decorator.\n- @SuroorAhmmad thank you for this. When I try a similar approach, I cannot reference `this` within the method: it complains that it `is possibly 'undefined'`. Any hints as to why that is? Thanks in advance!","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":168,"estimatedTokens":1257}}457{"id":"stack-60016995","source":"stackoverflow","questionId":60016995,"title":"How to use only dependency injection container from Nest.js framework?","tags":["javascript","dependency-injection","nestjs"],"text":"Title: How to use only dependency injection container from Nest.js framework?\nTags: javascript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs it possible to use just DI and IoC functionality from the Nest.js framework? If it is, how to achieve that?\n\nI tried to implement it in this way:\n\n```\nimport { NestFactory } from \"@nestjs/core\";\nimport { Module, Injectable } from \"@nestjs/common\";\n\n@Injectable()\nclass AppRepository {\n sayHi() {\n console.log(\"app repository\");\n console.log(\"Hello\");\n }\n}\n\n@Injectable()\nclass AppService {\n constructor(private appRepository: AppRepository) {}\n sayHi() {\n console.log(\"app service\");\n this.appRepository.sayHi();\n }\n}\n\n@Module({\n imports: [],\n providers: [AppService, AppRepository]\n})\nclass AppModule {\n constructor(private appService: AppService) {}\n sayHi() {\n console.log(\"app module\");\n this.appService.sayHi();\n }\n}\n\nasync function bootstrap() {\n const app = await NestFactory.createApplicationContext(AppModule);\n const module = app.get(AppModule);\n module.sayHi();\n}\n\nbootstrap();\n```\n\nBut when I run the code I get:\n\n```\napp module\n(node:70976) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sayHi' of undefined\n at AppModule.sayHi (/Users/jakub/projects/nest-di-clean/build/main.js:47:25)\n at /Users/jakub/projects/nest-di-clean/build/main.js:60:16\n at Generator.next ()\n at fulfilled (/Users/jakub/projects/nest-di-clean/build/main.js:11:58)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n at startup (internal/bootstrap/node.js:283:19)\n at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n```\n\nSo I get instance of `AppModule`, but an instance of `AppService` isn't injected.\n\nI would like to use it in a library I'm contributing to which doesn't need controllers and other server-side stuff.\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from \"@nestjs/core\";\nimport { Module, Injectable } from \"@nestjs/common\";\n\n@Injectable()\nclass AppRepository {\n  sayHi() {\n    console.log(\"app repository\");\n    console.log(\"Hello\");\n  }\n}\n\n@Injectable()\nclass AppService {\n  constructor(private appRepository: AppRepository) {}\n  sayHi() {\n    console.log(\"app service\");\n    this.appRepository.sayHi();\n  }\n}\n\n@Module({\n  imports: [],\n  providers: [AppService, AppRepository]\n})\nclass AppModule {\n  constructor(private appService: AppService) {}\n  sayHi() {\n    console.log(\"app module\");\n    this.appService.sayHi();\n  }\n}\n\nasync function bootstrap() {\n  const app = await NestFactory.createApplicationContext(AppModule);\n  const module = app.get<AppModule>(AppModule);\n  module.sayHi();\n}\n\nbootstrap();\n```\n\n```text\napp module\n(node:70976) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sayHi' of undefined\n    at AppModule.sayHi (/Users/jakub/projects/nest-di-clean/build/main.js:47:25)\n    at /Users/jakub/projects/nest-di-clean/build/main.js:60:16\n    at Generator.next (<anonymous>)\n    at fulfilled (/Users/jakub/projects/nest-di-clean/build/main.js:11:58)\n    at process._tickCallback (internal/process/next_tick.js:68:7)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n    at startup (internal/bootstrap/node.js:283:19)\n    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\n```\n\n```text\nAppModule\n```\n\n```text\nAppService\n```\n\n```text\n{\n  \"name\": \"nest-di-clean\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n    \"compile\": \"yarn tsc\",\n    \"start\": \"node ./build/main.js\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"@nestjs/common\": \"^6.11.5\",\n    \"@nestjs/core\": \"^6.11.5\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rxjs\": \"^6.5.4\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^13.7.0\",\n    \"typescript\": \"^3.7.5\"\n  }\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2015\",                     \n    \"module\": \"commonjs\",                   \n    \"outDir\": \"./build\",                    \n    \"strict\": true,                         \n    \"esModuleInterop\": true,                \n    \"experimentalDecorators\": true,         \n    \"emitDecoratorMetadata\": true,          \n    \"forceConsistentCasingInFileNames\": true\n  }\n}\n```\n\n```text\nnest-cli\n```\n\n```text\n@nestjs/common\n```\n\n```text\n@nestjs/core\n```\n\n```text\ntsconfig.json\n```\n\n```text\nemitDecoratorMetadata\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\npackage.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nmain.js\n```\n\n========================================\n\nComments:\n- What version of Nest are you using? Spinning up a new project and copy-pasting your code I got no errors\n- @JayMcDoniel Thanks for trying this out. I had a wrong tsconfig as described in my answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":222,"estimatedTokens":1208}}458{"id":"stack-54941329","source":"stackoverflow","questionId":54941329,"title":"interfaces between API and frontend","tags":["angular","git","typescript","nestjs"],"text":"Title: interfaces between API and frontend\nTags: angular, git, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am developing both sides. An API is in nest.js and frontend in Angular. Both sides uses typescript and I am facing problem of sharing interfaces, that should be same. For example ILoginRequest and ILoginResponse. I want to have both projects in separate GIT Repositories. Should I use GIT submodule with 3rd shared GIT repo or somehow create shared npm package or is there some good tool to generate classes automatically (from swagger definition) into frontend or anything else?\n\nEDIT: to generate code for client from swagger, look at openapi-generator\n\n========================================\n\nTop Answer:\nHaving faced the same problem and looked at a few alternatives. Here's what I considered and what I choose:\n\n- Separating the entity definitions into a separate code base - potentially in a different git repo. The problem here is that Nest uses decorators that Angular doesn't understand. That would mean I'd have to include Nest as a dependency which seems like a bad idea or create stub decorators - a waste of time. Rejected\n\n- Creating a node package - same problems as #1. Rejected\n\n- Copy paste. Both the backend and frontend projects have an entity folder. The backend's entities are *classes* that are decorated with TypeORM decorators (for me). I copy them to the frontend's entity directory and convert them to *interfaces* because what you get back from the httpclient library (objects that should conform to the interface - not class instances). Adopted\n\nFinally, looking at the comments, I don't see how GraphQL helps here since you aren't attempting to leverage an existing interface - looking to hear from someone on that :)\n\n========================================\n\nCode:\n```text\nworkspace\n  โ”œโ”€backend        <- repo #1\n  โ”‚   โ”œโ”€src\n  โ”‚   โ”‚   โ”œโ”€shared <- shared code goes here\n  โ”‚   โ”‚   โ””โ”€proxy.ts\n  โ”‚   โ””โ”€tsconfig.json\n  โ””โ”€frontend       <- repo #2\n      โ”œโ”€src\n      โ”‚   โ””โ”€proxy.ts\n      โ””โ”€tsconfig.json\n```\n\n```text\n{\n    ...\n    \"paths\": {\n        \"@shared/*\": [ \"src/shared/*\" ],\n    }\n}\n```\n\n```text\n{\n    ...\n    \"paths\": {\n        \"@shared/*\": [ \"../backend/src/shared/*\" ],\n\n        // if you're using TypeORM, this package has dummy decorators\n        \"typeorm\": [ \"node_modules/typeorm/typeorm-model-shim.js\" ]\n        // you can do the same for other packages, point them to dummy paths\n\n        // altirnatively you can route the shared imports through the proxy.ts\n        // and replace them in frontend/src/proxy.ts with dummy ones\n    }\n}\n```\n\n```text\nimport { PrimaryGeneratedColumn, Column } from 'typeorm';\n\nexport class UserEntity\n{\n    @PrimaryGeneratedColumn() id: number;\n    @Column() name: string;\n    @Column() password: string;\n}\n```\n\n```text\nimport { UserEntity } from '@shared/model/user.entity';\n```\n\n```text\nbackend/tsconfig.json\n```\n\n```text\nfrontend/tsconfig.json\n```\n\n```text\nnpm i typeorm\n```\n\n```text\nbackend/src/shared/user.entity.ts\n```\n\n```text\n@shared/model/user.entity\n```\n\n```text\n../backend/src/shared/model/user.entity\n```\n\n```text\nimport from 'typeorm'\n```\n\n========================================\n\nComments:\n- Creating an npm package would be the easiest way. All you need is your interfaces and a package.json in order to publish it.\n- Anyone coming across this now, might want to consider tRPC\n- Regarding graphql: You can create (and update) frontend type definitions with a script from a running server. This is an easy way to (semi)automatically type definitions between repos while still having full control and lose coupling. Have a look at apollo schema:download & apollo client:codegen\n- I'm not sure how option 3 can work, when it's two different repositories?\n- How about using monorepo (e.g. Yarn workspaces, lerna) for sharing\n- Thx for this, for me this is the way to go without the need to maintain a repo just with the entities\n- hey Peter Dub, can you mark this as an answer?\n- What we have here to my mind pretty much a monorepo check out nx.dev for a really great tool set for managing mongo repos\n- Thanks a lot for this. I'm creating an app with a NestJS backend with an Angular frontend. A thing I had to adjust was the sourceRoot in the nest-cli.json file adding the folders to the src. For instance, the value was src and I had to change to backend/app/src which was my folder structure.\n- Link no longer works; here is the best I could find nx.dev/getting-started/nx-and-angular","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":119,"estimatedTokens":1124}}459{"id":"stack-60632660","source":"stackoverflow","questionId":60632660,"title":"Can I access request headers in my graphql query, in nestjs?","tags":["graphql","ip-address","nestjs"],"text":"Title: Can I access request headers in my graphql query, in nestjs?\nTags: graphql, ip-address, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to access the ip-address of the user in the query of graphql. But I cannot reach any header information. How can I access the context I am creating in my factory, inside of my graphql requests?\n\n```\n// app.module.ts\n...\n\n@Module({\n imports: [\n ConfigModule,\n GraphQLModule.forRootAsync({\n imports: [ \n LanguageModule,\n SearchModule],\n inject: [ConfigService],\n useFactory: () => ({\n autoSchemaFile: 'schema.gql',\n debug: true,\n fieldResolverEnhancers: ['guards'],\n formatError: (error: GraphQLError): GraphQLFormattedError => {\n return error.originalError instanceof BaseException\n ? error.originalError.serialize()\n : error;\n },\n context: ({ req }): object => {\n console.log(\"req.ip: \", req.ip); // Here I have the ip\n return { req };\n },\n }),\n }), \n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```\n// search.resolver.ts\n...\n\n@Resolver(() => Search)\nexport class SearchResolver {\n constructor(private readonly service: service) {}\n\n @Query(() => Search)\n async search(@Args() args: SearchArgs): Promise {\n\n // I want the ip here, I want to send it as an argument into the query function below\n const response = await this.service.query(args.query, {\n language: args.language,\n });\n return response;\n }\n}\n```\n\n========================================\n\nTop Answer:\nThe default context seems to be:\n\n```\nimport { IncomingMessage } from \"node:http\";\n\ninterface Context {\n req: IncomingMessage;\n}\n```\n\nBut you can also set your own context as shown here:\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n driver: ApolloDriver,\n context: (request) => ({\n foo: 'bar',\n request,\n }),\n }),\n ],\n providers: [CustomContextResolver],\n})\nexport class CustomContextModule {}\n```\n\nAnd use it like this:\n\n```\nimport { Resolver, Query, Context } from '@nestjs/graphql';\n\n@Resolver()\nexport class CustomContextResolver {\n @Query(() => String)\n fooFromContext(@Context() ctx: Record) {\n return ctx.foo;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// app.module.ts\n...\n\n@Module({\n  imports: [\n    ConfigModule,\n    GraphQLModule.forRootAsync({\n      imports: [ \n        LanguageModule,\n        SearchModule],\n      inject: [ConfigService],\n      useFactory: () => ({\n        autoSchemaFile: 'schema.gql',\n        debug: true,\n        fieldResolverEnhancers: ['guards'],\n        formatError: (error: GraphQLError): GraphQLFormattedError => {\n          return error.originalError instanceof BaseException\n            ? error.originalError.serialize()\n            : error;\n        },\n        context: ({ req }): object => {\n          console.log(\"req.ip: \", req.ip); // Here I have the ip\n          return { req };\n        },\n      }),\n    }), \n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n// search.resolver.ts\n...\n\n@Resolver(() => Search)\nexport class SearchResolver {\n  constructor(private readonly service: service) {}\n\n  @Query(() => Search)\n  async search(@Args() args: SearchArgs): Promise<Search> {\n\n    // I want the ip here, I want to send it as an argument into the query function below\n    const response = await this.service.query(args.query, {\n      language: args.language,\n    });\n    return response;\n  }\n}\n```\n\n```text\ncontext\n```\n\n```text\nreq\n```\n\n```text\n(parent, args, context, info)\n```\n\n```js\nimport { IncomingMessage } from \"node:http\";\n\ninterface Context {\n  req: IncomingMessage;\n}\n```\n\n```js\n@Module({\n  imports: [\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n      context: (request) => ({\n        foo: 'bar',\n        request,\n      }),\n    }),\n  ],\n  providers: [CustomContextResolver],\n})\nexport class CustomContextModule {}\n```\n\n```js\nimport { Resolver, Query, Context } from '@nestjs/graphql';\n\n@Resolver()\nexport class CustomContextResolver {\n  @Query(() => String)\n  fooFromContext(@Context() ctx: Record<string, unknown>) {\n    return ctx.foo;\n  }\n}\n```\n\n========================================\n\nComments:\n- Thanks! I could access it with the context argument exactly like you said. Like this: '''@Query(() => Search) async search(@Args() args: SearchArgs, @Context() context): Promise { console.log(context); ... }'''\n- This works for me on localhost but when app is deployed context is null","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":216,"estimatedTokens":1106}}460{"id":"stack-66900133","source":"stackoverflow","questionId":66900133,"title":"How to mock a promise rejection with Jest","tags":["unit-testing","promise","jestjs","nestjs","ts-jest"],"text":"Title: How to mock a promise rejection with Jest\nTags: unit-testing, promise, jestjs, nestjs, ts-jest\nSource: Stack Overflow\n\nQuestion:\n### What am I doing?\n\nI am following a course on nestjs which has some unit testing it it. I wrote this test that checks the signUp method in an repository class. The problem is that in order to trigger the exceptions the line `user.save()` should return a promise rejection (simulating some problem writing to db). I tried a few ways (see below) but none that work.\n\n### The problem\n\nThe result is that the test succeeds, but there is an `unhandled Promise rejection`. This way even if I assert that is does `not.toThow()` it will succeed with the same `unhandled Promise rejection`\n\n```\n(node:10149) UnhandledPromiseRejectionWarning: Error: expect(received).rejects.toThrow()\n\nReceived promise resolved instead of rejected\nResolved to value: undefined\n(Use `node --trace-warnings ...` to show where the warning was created)\n```\n\nHow do I make it reject the promise correctly?\n\n### The code\n\nBelow is the code of my test and the function under test.\n\n```\nimport { ConflictException } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport { AuthCredentialsDto } from './dto/auth-credentials.dto';\nimport { UserRepository } from './user.repository';\n\ndescribe('UserRepository', () => {\n let userRepository: UserRepository;\n\n let authCredentialsDto: AuthCredentialsDto = {\n username: 'usahh',\n password: 'passworD12!@',\n };\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n providers: [UserRepository],\n }).compile();\n\n userRepository = module.get(UserRepository);\n });\n\n describe('signUp', () => {\n let save: any;\n beforeEach(() => {\n save = jest.fn();\n userRepository.create = jest.fn().mockReturnValue({ save });\n });\n\n it('throws a conflict exception if user already exist', () => {\n // My first try:\n // save.mockRejectedValue({\n // code: '23505',\n // });\n\n // Then I tried this, with and without async await:\n save.mockImplementation(async () => {\n await Promise.reject({ code: '23505' });\n });\n expect(userRepository.signUp(authCredentialsDto)).rejects.toThrow(\n ConflictException,\n );\n });\n });\n});\n```\n\nThe function under test here is:\n\n```\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n async signUp(authCredentialsDto: AuthCredentialsDto): Promise {\n const { username, password } = authCredentialsDto;\n const user = this.create();\n\n user.salt = await bcrypt.genSalt();\n user.username = username;\n user.password = await this.hashPassword(password, user.salt);\n\n try {\n await user.save();\n } catch (e) {\n if (e.code === '23505') {\n throw new ConflictException('Username already exists');\n } else {\n throw new InternalServerErrorException();\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n(node:10149) UnhandledPromiseRejectionWarning: Error: expect(received).rejects.toThrow()\n\nReceived promise resolved instead of rejected\nResolved to value: undefined\n(Use `node --trace-warnings ...` to show where the warning was created)\n```\n\n```text\nimport { ConflictException } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport { AuthCredentialsDto } from './dto/auth-credentials.dto';\nimport { UserRepository } from './user.repository';\n\ndescribe('UserRepository', () => {\n  let userRepository: UserRepository;\n\n  let authCredentialsDto: AuthCredentialsDto = {\n    username: 'usahh',\n    password: 'passworD12!@',\n  };\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      providers: [UserRepository],\n    }).compile();\n\n    userRepository = module.get<UserRepository>(UserRepository);\n  });\n\n  describe('signUp', () => {\n    let save: any;\n    beforeEach(() => {\n      save = jest.fn();\n      userRepository.create = jest.fn().mockReturnValue({ save });\n    });\n\n    it('throws a conflict exception if user already exist', () => {\n      // My first try:\n      // save.mockRejectedValue({\n      //   code: '23505',\n      // });\n\n      // Then I tried this, with and without async await:\n      save.mockImplementation(async () => {\n        await Promise.reject({ code: '23505' });\n      });\n      expect(userRepository.signUp(authCredentialsDto)).rejects.toThrow(\n        ConflictException,\n      );\n    });\n  });\n});\n```\n\n```text\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n  async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void> {\n    const { username, password } = authCredentialsDto;\n    const user = this.create();\n\n    user.salt = await bcrypt.genSalt();\n    user.username = username;\n    user.password = await this.hashPassword(password, user.salt);\n\n    try {\n      await user.save();\n    } catch (e) {\n      if (e.code === '23505') {\n        throw new ConflictException('Username already exists');\n      } else {\n        throw new InternalServerErrorException();\n      }\n    }\n  }\n}\n```\n\n```text\nuser.save()\n```\n\n```text\nunhandled Promise rejection\n```\n\n```text\nnot.toThow()\n```\n\n```text\nunhandled Promise rejection\n```\n\n```text\nit('throws a conflict exception if user already exist', async () => {\n  ...\n  await expect(userRepository.signUp(authCredentialsDto)).rejects.toThrow(\n    ConflictException,\n  );\n});\n```\n\n```text\nexpect(...).rejects...\n```\n\n```text\nmockImplementation\n```\n\n```text\nmockRejectedValue\n```\n\n```text\nmockImplementation(async () => ...)\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":222,"estimatedTokens":1350}}461{"id":"stack-57408349","source":"stackoverflow","questionId":57408349,"title":"Nestjs: How to build nestjs app and generate dist folder?","tags":["node.js","nestjs"],"text":"Title: Nestjs: How to build nestjs app and generate dist folder?\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to write jenkins shell script to deploy nestjs app,\nI try \"npm run start:prod\" this generate dist folder, but it serve also the app which I dont need it,\n\nHow to just build the app ?\n\n========================================\n\nTop Answer:\nAdd the following command in the `script` tag in the **package.json**\n\n```\n\"scripts\": {\n \"build\": \"nest build\"\n ...\n },\n```\n\nthen run :\n\n```\nnpm run build\n```\n\nor you can run the following command in the terminal:\n\n```\nnpx tsc -p tsconfig.build.json\n```\n\n========================================\n\nCode:\n```text\n{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"**/*spec.ts\"]\n}\n```\n\n```text\nnpm run build\n```\n\n```text\n\"build\": \"tsc -p tsconfig.build.json\"\n```\n\n```text\ntsconfig.build.json\n```\n\n```text\n\"scripts\": {\n    \"build\": \"nest build\"\n    ...\n  },\n```\n\n```text\nnpm run build\n```\n\n```text\nnpx tsc -p tsconfig.build.json\n```\n\n```text\nscript\n```\n\n========================================\n\nComments:\n- I dont have build script in package.json, can you write it here ?","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":79,"estimatedTokens":291}}462{"id":"stack-57568559","source":"stackoverflow","questionId":57568559,"title":"How do I organise throwing business-logic exceptions in NestJs services?","tags":["javascript","node.js","typescript","architecture","nestjs"],"text":"Title: How do I organise throwing business-logic exceptions in NestJs services?\nTags: javascript, node.js, typescript, architecture, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a few doubts regarding this github issue discussion: https://github.com/nestjs/nest/issues/310\n\nI want to throw business-domain exceptions from my service's methods as `shekohex` suggested. I wonder where exactly should I keep them? I believe many of them will be quite similiar across domains (like `EntityNotFoundException`, `ActionForbiddenException` etc.) so it would make sense to keep them on the application level (some kind of shared module). On the other hand that makes particular domain less independent (for example, what if I need to extract few of them into another application some time in the future?). What is more, some of the exceptions can be domain-specific and I'd have to keep them inside appropriate domain module's structure.\n\nLet's assume I do keep some of them in the shared module and the rest in the individual domain catalogues. How do I map them to the proper `HttpExceptions`? If I make global exception filter I also make my domain controllers even more dependent on the application-layer. How do I map domain-specific exceptions? Do I create another module-level exception filter?\n\nIs creating global- or module-level filters a way to go? Decorating every endpoint with `UseFilters` seems pretty cumbersome.\n\nThanks in advance for your input!\n\n========================================\n\nTop Answer:\nOk let's focus on keeping the exception in the shared folder from there we got the approach you say from creating a global exception filter for HttpExceptions it is not a bad approach and you can format the output in the exception itself. Other way could be to create a BusinessDomainFilter and catch only the exceptions that are domain related:\n\n```\n@Catch(EntityNotFoundException, ActionForbiddenException)\n@Injectable()\nexport class BusinessDomainFilter implements ExceptionFilter {\n...\n```\n\nand map there only those exceptions leaving the rest to the application filter\n\n========================================\n\nCode:\n```text\nshekohex\n```\n\n```text\nEntityNotFoundException\n```\n\n```text\nActionForbiddenException\n```\n\n```text\nHttpExceptions\n```\n\n```text\nUseFilters\n```\n\n```js\nimport { NotFoundException, Logger } from '@nestjs/common';\nimport { UserBusinessErrors } from '../../shared/errors/user/user.business-errors';\n\n// some code ...\n\n// Find the users from the usersIds array\nconst dbUsers = await this.userRepository.find({ id: In(usersIds) });\n// If none was found, raise an error\nif (!dbUsers) {\n    Logger.error(`Could not find user with IDs: ${usersIds}`, '', 'UserService', true);\n    throw new NotFoundException(UserBusinessErrors.NotFound);\n}\n```\n\n```js\nexport const UserBusinessErrors = {\n    // ... other errors\n\n    NotFound: {\n        apiErrorCode: 'E_0002_0002',\n        errorMessage: 'User not found',\n        reason: `Provided user ids doesn't exist in DB`\n    },\n\n    // ... other errors\n}\n```\n\n```js\nimport { InternalServerErrorException, Logger } from '@nestjs/common';\nimport { SharedBusinessErrors } from '../../shared/errors/shared.business-errors';\n\n// some code ...\n\ntry {\n    // ...\n} catch (error) {\n    Logger.log(SharedBusinessErrors.DbSaveError, 'UserService');\n    throw new InternalServerErrorException(SharedBusinessErrors.DbSaveError, error.stack);\n}\n```\n\n```js\nexport const SharedBusinessErrors = {\n    DbSaveError: {\n        apiErrorCode: 'E_0001_0001',\n        errorMessage: `Error when trying to save resource into the DB`,\n        reason: 'Internal server error'\n    },\n\n    // ... other errors\n}\n```\n\n```text\nuser.service.ts\n```\n\n```text\nuser.business-errors.ts\n```\n\n```text\nsrc/shared/errors/user/user.business-errors.ts\n```\n\n```text\nshared.business-errors.ts\n```\n\n```text\n@Catch(EntityNotFoundException, ActionForbiddenException)\n@Injectable()\nexport class BusinessDomainFilter implements ExceptionFilter {\n...\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":129,"estimatedTokens":994}}463{"id":"stack-63560382","source":"stackoverflow","questionId":63560382,"title":"Testing Class with @Injectable Scope / @Inject(REQUEST) NestJS","tags":["nestjs","nestjs-testing"],"text":"Title: Testing Class with @Injectable Scope / @Inject(REQUEST) NestJS\nTags: nestjs, nestjs-testing\nSource: Stack Overflow\n\nQuestion:\nI have set up a MongooseConfigService to allow us to dynamically switch out the connection string for certain requests and am trying to get the tests set up correctly.\n\n```\n@Injectable({scope: Scope.REQUEST})\nexport class MongooseConfigService implements MongooseOptionsFactory {\n constructor(\n @Inject(REQUEST) private readonly request: Request) {\n }\n```\n\nI am however having trouble providing `request` to the test context.\n\n```\nlet service: Promise;\n \n beforeEach(async () => {\n const req = new JestRequest();\n \n const module: TestingModule = await Test.createTestingModule({\n providers: [\n MongooseConfigService,\n {\n provide: getModelToken(REQUEST),\n inject: [REQUEST],\n useFactory: () => ({\n request: req,\n }),\n },\n ],\n }).compile();\n \n service = module.resolve(MongooseConfigService);\n });\n```\n\nThis is as far as I have gotten, have tried it without the `inject` and with/without `useValue`, however `this.request` remains undefined when trying to run the tests.\n\nTIA\n\n========================================\n\nTop Answer:\nI faced the same issue today and found a slightly easier method.\n\n```\nlet service: MongooseConfigService;\n\nbeforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n MongooseConfigService, // or whatever your service is\n {\n provide: REQUEST,\n useValue: { user: { idpId: 'idpId' } },\n },\n ],\n }).compile();\n service = await module.resolve(MongooseConfigService);\n});\n```\n\nIn my case I only needed to retrieve certain user details from the request, so this was easy. You could easily substitute the useValue here with the JestRequest noted in the other answer. My experience is that you are often already using multiple providers in this way, which makes this quite easy to add as just another provider.\n\n========================================\n\nCode:\n```text\n@Injectable({scope: Scope.REQUEST})\nexport class MongooseConfigService implements MongooseOptionsFactory {\n  constructor(\n    @Inject(REQUEST) private readonly request: Request) {\n  }\n```\n\n```text\nlet service: Promise<MongooseConfigService>;\n  \n  beforeEach(async () => {\n    const req = new JestRequest();\n    \n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        MongooseConfigService,\n        {\n          provide: getModelToken(REQUEST),\n          inject: [REQUEST],\n          useFactory: () => ({\n            request: req,\n          }),\n        },\n      ],\n    }).compile();\n    \n    service = module.resolve<MongooseConfigService>(MongooseConfigService);\n  });\n```\n\n```text\nrequest\n```\n\n```text\ninject\n```\n\n```text\nuseValue\n```\n\n```text\nthis.request\n```\n\n```text\nlet service: Promise<MongooseConfigService>;\n  \n  beforeEach(async () => {\n    const req = new JestRequest();\n    \n    const module: TestingModule = await Test.createTestingModule({\n      imports: [appModule]\n    }).overrideProvider(REQUEST)\n      .useValue(req)\n      .compile();\n    \n    service = module.resolve<MongooseConfigService>(MongooseConfigService);\n  });\n```\n\n```js\nlet service: MongooseConfigService;\n\nbeforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n        providers: [\n            MongooseConfigService, // or whatever your service is\n            {\n                provide: REQUEST,\n                useValue: { user: { idpId: 'idpId' } },\n            },\n        ],\n    }).compile();\n    service = await module.resolve(MongooseConfigService);\n});\n```\n\n========================================\n\nComments:\n- Have you taken a look at the docs on testing request scoped services?\n- @JayMcDoniel, yeah, but with 5 lines of code and no apparent context around how to actually use, it does not get one very far.\n- What is JestRequest()? Did you created it yourself or is part of the Jest dependency?\n- @CedricAchi I can only assume it's part of their dependencies or another package, have not touched this project or JS for that matter in over a year.\n- Awesome, thanks, although you pass req into useValue, not compile.","metadata":{"transformedAt":"2026-08-18T18:33:02.445Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":159,"estimatedTokens":1037}}464{"id":"stack-65086829","source":"stackoverflow","questionId":65086829,"title":"NestJS what is the best practice to initialise and pass request context","tags":["typescript","nestjs"],"text":"Title: NestJS what is the best practice to initialise and pass request context\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a global interceptor that needs to initialize my own request context DTO and I want this DTO to be accessible in Controller which handles the current request.\n\nThe solution i found so far is to create Request scoped injectable RequestContext class:\n\n```\nimport {\n Injectable,\n Scope\n} from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class RequestContext {\n public headers: IncomingHttpHeaders;\n ....\n\n initialize(request: Request) {\n this.headers = request.headers;\n .....\n }\n}\n```\n\nAnd inject this class into the interceptor:\n\n```\nimport {\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n Injectable,\n Inject\n} from '@nestjs/common';\nimport { Request } from 'express';\nimport { Observable } from 'rxjs';\nimport { tap } from 'rxjs/operators';\nimport { RequestContext } from '../dto';\n\n@Injectable()\nexport class RequestContextInterceptor implements NestInterceptor {\n constructor(\n @Inject(RequestContext)\n protected requestContext: RequestContext\n ) { }\n\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n const request = context.switchToHttp().getRequest();\n this.requestContext.initialize(request);\n\n return next.handle()\n .pipe(\n tap(() => {\n // decorate response\n }));\n }\n}\n```\n\nAnd then inject this RequestContext in each controller...\n\n```\nimport {\n Controller,\n UseInterceptors,\n Inject,\n Get\n} from '@nestjs/common';\nimport { BaseMicroserviceController } from '../core/base/base-microservice.controller';\nimport { RequestContext } from '../dto';\nimport { DispatchService } from '../services';\n\n@Controller('api/v1/example')\nexport class ExampleController extends BaseMicroserviceController {\n\n constructor (\n @Inject(RequestContext)\n protected requestContext: RequestContext,\n protected dispatcheService: DispatchService\n ) {\n super(dispatcheService);\n }\n\n @Get()\n test() {\n return 'test';\n }\n}\n```\n\nThere is huge workaround to achieve this simple functionality IMHO\nIn addition, I have this article which describes why to use Scope based injection is not good: https://guxi.me/posts/why-you-should-avoid-using-request-scope-injection-in-nest-js/\n\nMy service will be huge, with a huge amount of controllers and a huge amount of injectable services. According to this article - my service will be not scalable in terms of performance and memory usage.\n\nMy question is how to achieve the functionality I need in NestJS and what is the best practice?\nAnother \"bonus question\" - the RequestContext class has `initialize` method which receives express Request and parses it. I don't like it, I want each property of this class to be read-only and initialize this class in a traditional way by calling the constructor with `request` object... How I can achieve it with `@Inject` strategy?\n\n========================================\n\nTop Answer:\nAn approach for sharing a request context is to use a Continuation-local storage (CLS) package like express-http-context. You can then\n\n- use a middleware to set the relevant context data\n\n- define a provider that wraps the CLS logic\n\n- inject this provider in you controllers\n\n```\n// request-context.ts\nimport { createParamDecorator, HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response, NextFunction } from 'express';\nimport httpContext from 'express-http-context';\n\n@Injectable()\nexport class RequestContextProvider {\n get(key) {\n return httpContext.get(key)\n }\n\n set(key, value) {\n return httpContext.set(key, value)\n }\n}\n\n@Injectable()\nexport class RequestContextMiddleware implements NestMiddleware {\n constructor(private requestContextProvider: RequestContextProvider) { }\n\n use(req: Request, res: Response, next: NextFunction) {\n\n // first run express-http-context middleware\n httpContext.middleware(req, res, () => {\n // set context data\n // for example extract user data from JWT\n const [, token] = req.headers.authorization.split(' ')\n const decoded: Record = jwt_decode(token)\n this.requestContextProvider.set('userId', decoded.userId)\n next();\n })\n }\n}\n```\n\nAppy middleware in the app\n\n```\n//app.module.ts\n\nimport { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';\nimport { RequestContextMiddleware, RequestContextProvider } from './common/request-context';\nimport { MyModule } from './my/my.module';\n\n@Module({\n imports: [MyModule],\n providers: [RequestContextProvider]\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(RequestContextMiddleware)\n .forRoutes('*');\n }\n}\n```\n\nInject in controllers like this\n\n```\n//my.controller.ts\n\nimport { Controller, Post } from '@nestjs/common';\n\n@Controller('my')\nexport class MyController {\n constructor(private requestContextProvider: RequestContextProvider) { }\n @Post()\n doSomething(): string {\n const userId = this.requestContextProvider.get('userId')\n // do something with user ID\n //...\n }\n}\n```\n\nYou can also use decorators\n\n```\n// request-context.ts\n\nexport const UserId = createParamDecorator(() => {\n const userId = httpContext.get('userId')\n if (!userId) {\n throw new HttpException(\n 'Missing authorisation credentials',\n HttpStatus.FORBIDDEN\n )\n }\n return userId;\n})\n```\n\nThe full NestJS shared request context example\n\n========================================\n\nCode:\n```text\nimport {\n    Injectable,\n    Scope\n} from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class RequestContext {\n    public headers: IncomingHttpHeaders;\n    ....\n\n    initialize(request: Request) {\n        this.headers = request.headers;\n        .....\n    }\n}\n```\n\n```text\nimport {\n    NestInterceptor,\n    ExecutionContext,\n    CallHandler,\n    Injectable,\n    Inject\n} from '@nestjs/common';\nimport { Request } from 'express';\nimport { Observable } from 'rxjs';\nimport { tap } from 'rxjs/operators';\nimport { RequestContext } from '../dto';\n\n@Injectable()\nexport class RequestContextInterceptor implements NestInterceptor {\n    constructor(\n        @Inject(RequestContext)\n        protected requestContext: RequestContext\n    ) { }\n\n    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n        const request = context.switchToHttp().getRequest<Request>();\n        this.requestContext.initialize(request);\n\n        return next.handle()\n            .pipe(\n                tap(() => {\n                    // decorate response\n                }));\n    }\n}\n```\n\n```text\nimport {\n    Controller,\n    UseInterceptors,\n    Inject,\n    Get\n} from '@nestjs/common';\nimport { BaseMicroserviceController } from '../core/base/base-microservice.controller';\nimport { RequestContext } from '../dto';\nimport { DispatchService } from '../services';\n\n@Controller('api/v1/example')\nexport class ExampleController extends BaseMicroserviceController {\n\n    constructor (\n        @Inject(RequestContext)\n        protected requestContext: RequestContext,\n        protected dispatcheService: DispatchService\n    ) {\n        super(dispatcheService);\n    }\n\n    @Get()\n    test() {\n        return 'test';\n    }\n}\n```\n\n```text\ninitialize\n```\n\n```text\nrequest\n```\n\n```text\n@Inject\n```\n\n```text\nintercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const request = context.switchToHttp().getRequest<Request>();\n    const customRequestContext = initialize(request); // whatever you need to do to build this\n\n    request.customRequestContext = customRequestContext;\n\n    return next.handle();\n}\n```\n\n```text\nexport const RequestContext = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return request.customRequestContext;\n  },\n);\n```\n\n```text\n@Get()\nasync findOne(@RequestContext() requestContext: RequestContextInterface) {\n  // do whatever you need to do with it in your controllers\n}\n```\n\n```text\nRequestContext\n```\n\n```js\n// request-context.ts\nimport { createParamDecorator, HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response, NextFunction } from 'express';\nimport httpContext from 'express-http-context';\n\n@Injectable()\nexport class RequestContextProvider {\n    get(key) {\n        return httpContext.get(key)\n    }\n\n    set(key, value) {\n        return httpContext.set(key, value)\n    }\n}\n\n\n@Injectable()\nexport class RequestContextMiddleware implements NestMiddleware {\n    constructor(private requestContextProvider: RequestContextProvider) { }\n\n    use(req: Request, res: Response, next: NextFunction) {\n\n        // first run express-http-context middleware\n        httpContext.middleware(req, res, () => {\n            // set context data\n            // for example extract user data from JWT\n            const [, token] = req.headers.authorization.split(' ')\n            const decoded: Record<string, unknown> = jwt_decode(token)\n            this.requestContextProvider.set('userId', decoded.userId)\n            next();\n        })\n    }\n}\n```\n\n```js\n//app.module.ts\n\nimport { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';\nimport { RequestContextMiddleware, RequestContextProvider } from './common/request-context';\nimport { MyModule } from './my/my.module';\n\n@Module({\n    imports: [MyModule],\n    providers: [RequestContextProvider]\n})\nexport class AppModule implements NestModule {\n    configure(consumer: MiddlewareConsumer) {\n        consumer\n            .apply(RequestContextMiddleware)\n            .forRoutes('*');\n    }\n}\n```\n\n```js\n//my.controller.ts\n\nimport { Controller, Post } from '@nestjs/common';\n\n@Controller('my')\nexport class MyController {\n    constructor(private requestContextProvider: RequestContextProvider) { }\n    @Post()\n    doSomething(): string {\n        const userId = this.requestContextProvider.get('userId')\n        //  do something with user ID\n        //...\n    }\n}\n```\n\n```js\n// request-context.ts\n\nexport const UserId = createParamDecorator(() => {\n    const userId = httpContext.get('userId')\n    if (!userId) {\n        throw new HttpException(\n            'Missing authorisation credentials',\n            HttpStatus.FORBIDDEN\n        )\n    }\n    return userId;\n})\n```\n\n```text\nimport {\n  UseInterceptors,\n  NestInterceptor,\n  ExecutionContext,\n  CallHandler,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { plainToClass } from 'class-transformer';\n\n//  nest will take dto and turn it to the json and send it back as response\n\n// with implement, this class will satisfy either an abstract class or an interface\nexport class MyCustomInterceptor implements NestInterceptor {\n    // passing dto will make this class reusable\n    constructor(private dto:any){\n\n    }\n  intercept(context: ExecutionContext, handler: CallHandler): Observable<any> {\n\n    // this is where  you run code before request is handled\n    return handler.handle().pipe(\n      \n      map((data: any) => {\n         // data is the response\n         // here you can manipulate the response\n        });\n      }),\n    );\n  }\n}\n```\n\n```text\nimport {UseInterceptors} from '@nestjs/common';\n\n\n// U can manipulate the request for this route\n@UseInterceptors(new MyCustomInterceptor(YourDto))\n  // each part of the request is string. thats why param is string\n  @Get('/:id')\n  async findUser(@Param('id') id: string) {\n   // logic...\n  }\n```\n\n```text\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\nย  ย  imports: [RequestScopeModule],\n})\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\nimport { RequestScope } from 'nj-request-scope';\nimport { NJRS_REQUEST } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestContext {\nย  ย  public headers: IncomingHttpHeaders;\nย  ย  ....\n\nย  ย  constructor(@Inject(NJRS_REQUEST) private readonly request: Request) {\nย  ย  ย  ย  this.headers = request.headers;\nย  ย  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\nimport { NJRS_REQUEST } from 'nj-request-scope';\n\n@Injectable()\nexport class RequestContext {\n\nย  ย  constructor(@Inject(NJRS_REQUEST) private readonly request: Request) {\nย  ย  }\n\nย  ย  public get headers(): IncomingHttpHeaders {\nย  ย  ย  ย  return this.request.headers;\nย  ย  }\n}\n```\n\n```text\nRequestScopeModule\n```\n\n```text\nRequestContext\n```\n\n```text\nRequestContext\n```\n\n```text\nRequestContext\n```\n\n```text\nrequest\n```\n\n```text\nRequestContext\n```\n\n========================================\n\nComments:\n- I have tested this package and it works surprisingly well","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":547,"estimatedTokens":3208}}465{"id":"stack-73324480","source":"stackoverflow","questionId":73324480,"title":"NestJS - How does AuthGuard knows about the Passport Strategy?","tags":["node.js","nestjs","passport.js"],"text":"Title: NestJS - How does AuthGuard knows about the Passport Strategy?\nTags: node.js, nestjs, passport.js\nSource: Stack Overflow\n\nQuestion:\nI am having a hard time figuring out the NestJS and PassportJS combination when it comes to the authentication/authorization process, and I am a type of developer who does not like magic when it comes to developing.\n\n### Issue\n\nBasically, my goal is to understand how does AuthGuard knows about the Passport Strategy being implemented in the project, it could be Local Strategy, or any other, for example JWT Strategy. I have two modules **AuthModule** and **UserModule** and this is how the **AuthService** looks like:\n\n```\n@Injectable()\nexport class AuthService {\n constructor(private usersService: UsersService){}\n\n async validateUser(username: string, password: string): Promise {\n const user = await this.usersService.findOne(username);\n\n if (user && user.password === password) {\n const {password, ...result} = user\n return result\n }\n return null\n }\n}\n```\n\n**UserService**:\n\n```\nimport { Injectable } from '@nestjs/common';\n\nexport type User = any;\n\n@Injectable()\nexport class UsersService {\n\n private readonly users = [\n {\n userId: 1,\n username: 'John Marston',\n password: 'rdr1',\n },\n {\n userId: 2,\n username: 'Arthur Morgan',\n password: 'rdr2',\n },\n ]\n\n async findOne(username: string): Promise {\n return this.users.find(user => user.username === username)\n }\n}\n```\n\n### Passport\n\nAfter installing the packages for Passport and NestJS, I imported **PassportModule** and implemented the **LocalStrategy** and also imported that strategy as a provider inside the **AuthModule**\n\n**LocalStrategy**:\n\n```\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private authService: AuthService) {\n super()\n }\n\n async validate(username: string, password: string): Promise {\n const user = await this.authService.validateUser(username, password);\n\n if (!user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\n```\n@Module({\n imports: [UsersModule, PassportModule],\n providers: [AuthService, LocalStrategy]\n})\nexport class AuthModule {}\n```\n\n### Login route\n\n```\nimport { Controller, Post, Request, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n \n @UseGuards(AuthGuard('local'))\n @Post('login')\n async login(@Request() req) {\n return req.user;\n }\n}\n```\n\nI understand everything up until this part. I do also understand how we get the req.user object etc. but I do not understand how does the **AuthGuard** knows, that we implemented Passport Local Strategy. Does it look through the files (sorry if this is dumb to say) and finds where we imported the **PassportModule** and also where we implemented the **LocalStrategy** since that class extends the PassportStrategy class, but also important to say, imported from passport-local.\n\nI do understand that **AuthGuard** is a special type of Guard, but I am not sure if I understand it properly.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class AuthService {\n    constructor(private usersService: UsersService){}\n\n    async validateUser(username: string, password: string): Promise<any> {\n        const user = await this.usersService.findOne(username);\n\n        if (user && user.password === password) {\n            const {password, ...result} = user\n            return result\n        }\n        return null\n    }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\n\nexport type User = any;\n\n@Injectable()\nexport class UsersService {\n\n    private readonly users = [\n        {\n            userId: 1,\n            username: 'John Marston',\n            password: 'rdr1',\n        },\n        {\n            userId: 2,\n            username: 'Arthur Morgan',\n            password: 'rdr2',\n        },\n    ]\n\n    async findOne(username: string): Promise<User | undefined> {\n        return this.users.find(user => user.username === username)\n    }\n}\n```\n\n```text\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n    constructor(private authService: AuthService) {\n        super()\n    }\n\n    async validate(username: string, password: string): Promise<any> {\n        const user = await this.authService.validateUser(username, password);\n\n        if (!user) {\n            throw new UnauthorizedException();\n        }\n\n        return user;\n    }\n}\n```\n\n```text\n@Module({\n  imports: [UsersModule, PassportModule],\n  providers: [AuthService, LocalStrategy]\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Controller, Post, Request, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n  \n  @UseGuards(AuthGuard('local'))\n  @Post('login')\n  async login(@Request() req) {\n    return req.user;\n  }\n}\n```\n\n```text\nStrategy\n```\n\n```text\npassport-*\n```\n\n```text\nname\n```\n\n```text\npassport-local\n```\n\n```text\nname\n```\n\n```text\nlocal\n```\n\n```text\npassport-jwt\n```\n\n```text\n'jwt'\n```\n\n```text\npassport.use()\n```\n\n```text\npassport.authenticate()\n```\n\n```text\npassport.use\n```\n\n```text\nPassportStrategy\n```\n\n```text\n@nestjs/passport\n```\n\n```text\npassport.authenticate\n```\n\n```text\nAuthGuard()\n```\n\n```text\nlocal\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":263,"estimatedTokens":1313}}466{"id":"stack-54265304","source":"stackoverflow","questionId":54265304,"title":"Nestjs:validate function not working with jwt","tags":["node.js","typescript","jwt","nestjs"],"text":"Title: Nestjs:validate function not working with jwt\nTags: node.js, typescript, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use jwt in nest following document\n\nEverything is ok, but validate function is not working in jwt.strategy.ts\n\nthis is my jwt.strategy.ts:\n\n```\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),\n secretOrKey: 'secretKey',\n });\n }\n\n async validate(payload: JwtPayload) {\n console.log(payload)\n // const user = await this.authService.validateUser(payload);\n // if (!user) {\n // throw new UnauthorizedException();\n // }\n // return user;\n }\n}\n```\n\nauth.module.ts:\n\n```\nimport { Module } from '@nestjs/common';\nimport { JwtModule } from '@nestjs/jwt';\nimport { PassportModule } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n secretOrPrivateKey: 'secretKey',\n signOptions: {\n expiresIn: 3600,\n },\n }),\n ],\n providers: [AuthService, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\napp.module.ts:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserModule } from './user/user.module';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AuthModule } from './auth/auth.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n GraphQLModule.forRoot({\n typePaths: ['./**/*.graphql'],\n }),\n AuthModule,\n UserModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nWhen i request in postman, I don't got any log, It doesn't seem to enter this validate function.:\n\nhttps://i.sstatic.net/gEi0O.png\n\nthis is Complete code\n\nsorry, my English is bad, this is my first-time use stackoverflow, thanks for your help\n\n========================================\n\nTop Answer:\nI would also add my scenario.\n\n**Case 1: JWT token is malformed**\n\nBasically, when your JWT token is **malformed (don't confuse with not valid)** the **validate** function would **NOT** call. In other words, when you debug token via jwt.io and it shows signature is not valid.\nIt appears from my side even if I was login in succesfully on local via\n`@auth0/auth0-angular`, I was not providing **audience** url(available on APIs section in auth0). The getting started docs was not mentioning this, so below is working code\n\n```\n// Angular side\n\n AuthModule.forRoot({\n domain: `${auth.domain}`,\n clientId: 'client-id',\n useRefreshTokens: true,\n audience: `https://${auth.audience}/`\n }),\n```\n\n**Case 2: JWT token is not valid**\n\nIn that case, I found out that URLs provided in JwtStrategy in NestJs, the URLs must be an exact match. So if you forget to add `/` at the end of the URL, it would not pass `AuthGuard`.\n\n```\n// NestJs side\n\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n secretOrKeyProvider: passportJwtSecret({\n cache: true,\n rateLimit: true,\n jwksRequestsPerMinute: 5,\n jwksUri: `https://${auth.domain}/.well-known/jwks.json`,\n }),\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n audience: `https://${auth.audience}/`,\n issuer: `https://${auth.domain}}/`,\n algorithms: ['RS256'],\n });\n }\n\n public validate(payload: any): unknown {\n return payload;\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),\n      secretOrKey: 'secretKey',\n    });\n  }\n\n  async validate(payload: JwtPayload) {\n    console.log(payload)\n    // const user = await this.authService.validateUser(payload);\n    // if (!user) {\n    //   throw new UnauthorizedException();\n    // }\n    // return user;\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { JwtModule } from '@nestjs/jwt';\nimport { PassportModule } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.register({\n      secretOrPrivateKey: 'secretKey',\n      signOptions: {\n        expiresIn: 3600,\n      },\n    }),\n  ],\n  providers: [AuthService, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserModule } from './user/user.module';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AuthModule } from './auth/auth.module';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    GraphQLModule.forRoot({\n      typePaths: ['./**/*.graphql'],\n    }),\n    AuthModule,\n    UserModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nvalidate\n```\n\n```text\nJwtStrategy\n```\n\n```text\nsecretKey\n```\n\n```text\nvalidate\n```\n\n```text\n// Angular side\n\n    AuthModule.forRoot({\n      domain: `${auth.domain}`,\n      clientId: 'client-id',\n      useRefreshTokens: true,\n      audience: `https://${auth.audience}/`\n    }),\n```\n\n```text\n// NestJs side\n\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      secretOrKeyProvider: passportJwtSecret({\n        cache: true,\n        rateLimit: true,\n        jwksRequestsPerMinute: 5,\n        jwksUri: `https://${auth.domain}/.well-known/jwks.json`,\n      }),\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      audience: `https://${auth.audience}/`,\n      issuer: `https://${auth.domain}}/`,\n      algorithms: ['RS256'],\n    });\n  }\n\n  public validate(payload: any): unknown {\n    return payload;\n  }\n}\n```\n\n```text\n@auth0/auth0-angular\n```\n\n```text\n/\n```\n\n```text\nAuthGuard\n```\n\n========================================\n\nComments:\n- Thank you, I find the reason,at here\"ExtractJwt.fromAuthHeaderWithScheme('jwt')\", โ€œjwtโ€ is lower case๏ผŒbut \"JWT\" is capital in header Authorization , This is a silly mistake.\n- Yeah, it's always the silly little things that take hours to solve. Glad it's working now. :) And welcome to stackoverflow! :)\n- How could you intercept these failures? I want to return a custom error message?\n- `So if you forget to add &#47; at the end of the URL, it would not pass AuthGuard` This was my problem! Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":294,"estimatedTokens":1819}}467{"id":"stack-64344534","source":"stackoverflow","questionId":64344534,"title":"How to make database request in Nest.js decorator?","tags":["node.js","typescript","nestjs"],"text":"Title: How to make database request in Nest.js decorator?\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to find a table row by request parameter. I know how to do it in service but I'm trying\nto do it also in decorator.\n\nMy decorator:\n\n```\nimport { BadRequestException, createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const GetEvent = createParamDecorator((data: unknown, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n const { eventId } = request.params;\n // Something like in service:\n // const event = await this.eventModel.findByPk(eventId);\n // return event;\n});\n```\n\nI know that it's impossible to inject service in decorator but maybe some hacks to make database requests before calling service methods?\n\n========================================\n\nCode:\n```text\nimport { BadRequestException, createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const GetEvent = createParamDecorator((data: unknown, ctx: ExecutionContext) => {\n  const request = ctx.switchToHttp().getRequest();\n  const { eventId } = request.params;\n  // Something like in service:\n  // const event = await this.eventModel.findByPk(eventId);\n  // return event;\n});\n```\n\n```text\ntypeorm\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":42,"estimatedTokens":316}}468{"id":"stack-68390441","source":"stackoverflow","questionId":68390441,"title":"NestJS/GraphQL/Passport - getting unauthorised error from guard","tags":["graphql","nestjs","passport-local","nestjs-passport"],"text":"Title: NestJS/GraphQL/Passport - getting unauthorised error from guard\nTags: graphql, nestjs, passport-local, nestjs-passport\nSource: Stack Overflow\n\nQuestion:\nI'm trying to along with this tutorial and I'm struggling to convert the implementation to GraphQL.\n\n**local.strategy.ts**\n\n```\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authenticationService: AuthenticationService) {\n super();\n }\n\n async validate(email: string, password: string): Promise {\n const user = await this.authenticationService.getAuthenticatedUser(\n email,\n password,\n );\n\n if (!user) throw new UnauthorizedException();\n\n return user;\n }\n}\n```\n\n**local.guard.ts**\n\n```\n@Injectable()\nexport class LogInWithCredentialsGuard extends AuthGuard('local') {\n async canActivate(context: ExecutionContext): Promise {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n req.body = ctx.getArgs();\n\n await super.canActivate(new ExecutionContextHost([req]));\n await super.logIn(req);\n return true;\n }\n}\n```\n\n**authentication.type.ts**\n\n```\n@InputType()\nexport class AuthenticationInput {\n @Field()\n email: string;\n\n @Field()\n password: string;\n}\n```\n\n**authentication.resolver.ts**\n\n```\n@UseGuards(LogInWithCredentialsGuard)\n@Mutation(() => User, { nullable: true })\nlogIn(\n @Args('variables')\n _authenticationInput: AuthenticationInput,\n @Context() req: any,\n) {\n return req.user;\n}\n```\n\n**mutation**\n\n```\nmutation {\n logIn(variables: {\n email: \"email@email.com\",\n password: \"123123\"\n } ) {\n id\n email\n }\n}\n```\n\nEven the above credentials are correct, I'm receiving an unauthorized error.\n\n========================================\n\nTop Answer:\nI've been able to get a successful login with a guard like this:\n\n```\n@Injectable()\nexport class LocalGqlAuthGuard extends AuthGuard('local') {\n constructor() {\n super();\n }\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n req.body = ctx.getArgs();\n return req;\n }\n async canActivate(context: ExecutionContext) {\n await super.canActivate(context);\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n await super.logIn(req);\n return true;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authenticationService: AuthenticationService) {\n    super();\n  }\n\n  async validate(email: string, password: string): Promise<any> {\n    const user = await this.authenticationService.getAuthenticatedUser(\n      email,\n      password,\n    );\n\n    if (!user) throw new UnauthorizedException();\n\n    return user;\n  }\n}\n```\n\n```text\n@Injectable()\nexport class LogInWithCredentialsGuard extends AuthGuard('local') {\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const ctx = GqlExecutionContext.create(context);\n    const { req } = ctx.getContext();\n    req.body = ctx.getArgs();\n\n    await super.canActivate(new ExecutionContextHost([req]));\n    await super.logIn(req);\n    return true;\n  }\n}\n```\n\n```text\n@InputType()\nexport class AuthenticationInput {\n  @Field()\n  email: string;\n\n  @Field()\n  password: string;\n}\n```\n\n```text\n@UseGuards(LogInWithCredentialsGuard)\n@Mutation(() => User, { nullable: true })\nlogIn(\n  @Args('variables')\n  _authenticationInput: AuthenticationInput,\n  @Context() req: any,\n) {\n  return req.user;\n}\n```\n\n```text\nmutation {\n  logIn(variables: {\n    email: \"email@email.com\",\n    password: \"123123\"\n  } ) {\n    id\n    email\n  }\n}\n```\n\n```js\n@Injectable()\nexport class LogInWithCredentialsGuard extends AuthGuard('local') {\n  // Override this method so it can be used in graphql\n  getRequest(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    const gqlReq = ctx.getContext().req;\n    if (gqlReq) {\n      const { variables } = ctx.getArgs();\n      gqlReq.body = variables;\n      return gqlReq;\n    }\n    return context.switchToHttp().getRequest();\n  }\n}\n```\n\n```js\n@UseGuards(LogInWithCredentialsGuard)\n@Mutation(() => User, { nullable: true })\nlogIn(\n  @Args('variables')\n  _authenticationInput: AuthenticationInput,\n  @Context() context: any, // <----------- it's not request\n) {\n  return context.req.user;\n}\n```\n\n```text\nLogInWithCredentialsGuard\n```\n\n```text\ncanAcitavte\n```\n\n```text\nreq.body\n```\n\n```text\nreq.body\n```\n\n```text\ngetRequest\n```\n\n```js\n@Injectable()\nexport class LocalGqlAuthGuard extends AuthGuard('local') {\n  constructor() {\n    super();\n  }\n  getRequest(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    const req = ctx.getContext().req;\n    req.body = ctx.getArgs();\n    return req;\n  }\n  async canActivate(context: ExecutionContext) {\n    await super.canActivate(context);\n    const ctx = GqlExecutionContext.create(context);\n    const req = ctx.getContext().req;\n    await super.logIn(req);\n    return true;\n  }\n}\n```\n\n```text\nconstructor(private authenticationService: AuthenticationService) {\n    //you should pass this {usernameField: 'email'} object to super ๐Ÿ‘‡\n    super({\n      usernameField: 'email' \n    });\n  }\n```\n\n========================================\n\nComments:\n- related information: github.com/jaredhanson/passport-local, github.com/nestjs/passport/blob/&hellip;\n- Hi @Ellie. Iโ€™m trying to learn NestJS and am having this issue. Did you manage to solve it?\n- Thanks, the guard works, but it won't set a session cookie without overriding the canActivate method.\n- @EllieG I am currently having the same problem, did you resolve it in the end? How can I get the correct request and also overwrite canActivate to set a session cookie?\n- Basicly you don't need a session and you don't need to override the canActivate method. Per definition, JWT is stateless. Maybe you missed to call something like an AuthService.login method, to return the JWT in the resolver? I know, it's a year ago, but when you still have issues, I will have a look in this thread.\n- I have tried to implement the AuthGuard like this but I still get an `unauthorized` when sending a login request. Is there any chance you have more detail on your solution?","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":278,"estimatedTokens":1554}}469{"id":"stack-55148009","source":"stackoverflow","questionId":55148009,"title":"Testing private methods in JestJS","tags":["typescript","unit-testing","jestjs","private-members","nestjs"],"text":"Title: Testing private methods in JestJS\nTags: typescript, unit-testing, jestjs, private-members, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am making an API with NestJS (using TypeScript) and it uses JestJS as the default test framework. I am writing a test for a service class and I am trying to access its private functions (Enforced with TypeScript), but I cannot for obvious reasons.\n\nThe traditional solution in other languages (like Java) is to change the functions to be in *package* or *internal* scope, but this doesn't exist in TypeScript.\n\nHow can I access those functions for testing purposes, but still enforce the private access (as good practice)?\n\n========================================\n\nTop Answer:\nMy solution was to make the functions \"protected\" and extend the class in a class inside the test file, with those functions exposed. \n\nExample:\n\n```\nclass ClassToTest {\n protected add(x: number, y: number}: number {\n return x + y;\n }\n}\n```\n\nIn the test file:\n\n```\nclass PublicClassToTest extends ClassToTest {\n public add(x: number, y: number): number {\n return super.add(x, y);\n }\n}\n\ndescribe('ClassToTest', () => {\n\n const obj = new PublicClassToTest();\n\n it('adding 2 numbers', () => {\n // GIVEN x is 6\n const x = 6;\n\n // AND y is 2\n const y = 2;\n\n // WHEN we add them\n const result = obj.add(x, y);\n\n // THEN the result is 8\n expect(result).toBe(8);\n });\n});\n```\n\n**As a bonus feature:** This not only solved my issue with this, but also provided a nice way for me to see my function headers from within the test file, without needing to switch back and forth between my test and the class I am testing.\n\n========================================\n\nCode:\n```text\nclass ClassToTest {\n    protected add(x: number, y: number}: number {\n        return x + y;\n    }\n}\n```\n\n```text\nclass PublicClassToTest extends ClassToTest {\n    public add(x: number, y: number): number {\n        return super.add(x, y);\n    }\n}\n\ndescribe('ClassToTest', () => {\n\n    const obj = new PublicClassToTest();\n\n    it('adding 2 numbers', () => {\n        // GIVEN x is 6\n        const x = 6;\n\n        // AND y is 2\n        const y = 2;\n\n        // WHEN we add them\n        const result = obj.add(x, y);\n\n        // THEN the result is 8\n        expect(result).toBe(8);\n    });\n});\n```\n\n========================================\n\nComments:\n- One solution is to access private properties with bracket, that is `obj['privateMethod']()` However, the private method must be called by a public one, and that's what you should be testing/callinginstead.\n- I am testing the public one, but I want to make sure the simple i/o algorithms in the private functions work properly. Thanks for the suggestion.\n- I'm not sure whether or not the question has non-opinionated answers, but I disagree with the idea that this answer should be a comment (it seeks to answer the question, not to further it)\n- This may be true, but in my case these actions will never be used outside of the service class (the one I want to test), so making another class isn't a good idea, but I see what you mean. Also, I won't do environment switching, as the examples I've seen are too messy. I will post a good solution that I am using.\n- Apart from many good advice here, there is one logical flaw. Changing something private into public will certainly change its accessibility. But, if tests are fragile when testing something private, why would they not be fragile any more only by making that same private thing public?\n- @dirkhermann It wasnโ€™t my intention to imply that it would be a good idea to do so. Iโ€™ve replaced this part with a link describing the anti-pattern here, with some good solutions. Thanks!\n- I accepted this answer as it is the better solution. But I also provided a direct answer below that will work for most people. Sometimes you work at a company and your manager asks you to do something and you just do it, even if it is bad practice. I don't want to argue, I just want to get it done, and I'm sure others do too. Thanks.\n- @dirkhermann I didnโ€™t properly address your question. The reason the tests will become more fragile is because by testing the private methods weโ€™re testing the internal implementation rather than whether the class functions as expected. If we test private methods and then decide to refactor, we need to rewrite all those tests, which wouldnโ€™t be necessary if we were only testing the public API. Private methods are normally much more open to change than public methods since theyโ€™d only affect the class itself and not external consumers\n- TypeScript doesn't let you extend a private method in a subclass and make it public\n- My mistake! I forgot to say that I made the functions \"protected\". I updated my answer. Thanks for noticing :)\n- The problem is that when someone looks at the class, they are going to think this method is intended to be overridden when it really isn't. I would the other suggestions instead. When something isn't easily testable, it's often a sign that it could use some refactoring\n- I agree that this is not the perfect solution and that the other is better, but I wanted to provide people with an option that works and would be fine for most cases, like mine. But, in general, I would suggest using the solution in the other answer. I will accept that one instead of mine.","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":110,"estimatedTokens":1329}}470{"id":"stack-74660025","source":"stackoverflow","questionId":74660025,"title":"Nest.js app becomes unresponsive following an Error thrown in an async function without an await","tags":["nestjs"],"text":"Title: Nest.js app becomes unresponsive following an Error thrown in an async function without an await\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nThe issue that if there is an exception thrown in an `async` function but that function was called without an `await`, the Nest application goes into a state where it no longer responds to requests but the process does not exist.\n\nThere may be times where we want to call a function in a request but don't need to wait for it to finish before returning to response to the caller but most of the time that we encounter this it was just an accidental omission of an `await`. The fact that it renders the server useless has been very problematic.\n\nI suspect there may be a simple solution to this problem but I have been unsuccessful in finding it myself.\n\napp.controller.ts\n\n```\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get()\n getHello(): string {\n return this.appService.getHello();\n }\n\n @Get('/crash')\n public async crash(): Promise {\n await this.appService.crash();\n }\n}\n```\n\napp.service.ts\n\n```\nimport { Injectable } from '@nestjs/common';\n\nconst sleep = async (ms: number): Promise => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n};\n\nconst functionThatThrows = async (): Promise => {\n await sleep(2000);\n throw new Error('this will crash the app');\n};\n\n@Injectable()\nexport class AppService {\n getHello(): string {\n return 'Hello World!';\n }\n\n public async crash(): Promise {\n console.log('crashing the app in 3 seconds...');\n await sleep(1000);\n functionThatThrows(); // async function called without await\n }\n}\n```\n\nCalling the endpoint the first time succeeds:\n\n`curl http://localhost:3000/crash`\n\nCalling it afterward and the server does not respond:\n\n`curl http://localhost:3000/crash`\n\n`curl: (7) Failed to connect to localhost port 3000 after 5 ms: Connection refused`\n\n========================================\n\nCode:\n```js\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getHello(): string {\n    return this.appService.getHello();\n  }\n\n  @Get('/crash')\n  public async crash(): Promise<void> {\n    await this.appService.crash();\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\n\nconst sleep = async (ms: number): Promise<void> => {\n  return new Promise((resolve) => {\n    setTimeout(resolve, ms);\n  });\n};\n\nconst functionThatThrows = async (): Promise<void> => {\n  await sleep(2000);\n  throw new Error('this will crash the app');\n};\n\n@Injectable()\nexport class AppService {\n  getHello(): string {\n    return 'Hello World!';\n  }\n\n  public async crash(): Promise<void> {\n    console.log('crashing the app in 3 seconds...');\n    await sleep(1000);\n    functionThatThrows(); // async function called without await\n  }\n}\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nawait\n```\n\n```text\ncurl http://localhost:3000/crash\n```\n\n```text\ncurl http://localhost:3000/crash\n```\n\n```text\ncurl: (7) Failed to connect to localhost port 3000 after 5 ms: Connection refused\n```\n\n```text\nawait\n```\n\n```text\nprocess.on('unhandledRejection', errorHandler)\n```\n\n========================================\n\nComments:\n- They have to add a try catch block somewhere most preferably in the service\n- @Craques actually because the promise is not `await`ed they have to use `.catch` on the promise","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":161,"estimatedTokens":897}}471{"id":"stack-68460951","source":"stackoverflow","questionId":68460951,"title":"Use interface as a swagger schema - NestJS DTO","tags":["swagger","nestjs","swagger-ui"],"text":"Title: Use interface as a swagger schema - NestJS DTO\nTags: swagger, nestjs, swagger-ui\nSource: Stack Overflow\n\nQuestion:\nI have the following code:\n\n```\nimport { IsNotEmpty, IsArray, ArrayMinSize } from 'class-validator';\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class PublishDto {\n @IsNotEmpty()\n @IsArray()\n @ArrayMinSize(1)\n @ApiProperty({\n type: [Product]\n })\n products: Product[];\n}\n\ninterface Product {\n id: string;\n title: string;\n sku: string;\n stock: number;\n description: string;\n shortDescription: string;\n imagesUrl: string[];\n price: number;\n department: string;\n category: string;\n brand: string;\n keywords: string[];\n isActive: boolean;\n}\n```\n\nhttps://i.sstatic.net/s8gn5.png\n\nI'm trying to put the interface *`Product`* as a schema on swagger, but it's not working, I am getting an error.\nAny idea?\n\n========================================\n\nCode:\n```text\nimport { IsNotEmpty, IsArray, ArrayMinSize } from 'class-validator';\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class PublishDto {\n  @IsNotEmpty()\n  @IsArray()\n  @ArrayMinSize(1)\n  @ApiProperty({\n    type: [Product]\n  })\n  products: Product[];\n}\n\ninterface Product {\n  id: string;\n  title: string;\n  sku: string;\n  stock: number;\n  description: string;\n  shortDescription: string;\n  imagesUrl: string[];\n  price: number;\n  department: string;\n  category: string;\n  brand: string;\n  keywords: string[];\n  isActive: boolean;\n}\n```\n\n```text\nProduct\n```\n\n```text\nString\n```\n\n========================================\n\nComments:\n- What's the error that you're getting?\n- I'm getting an error on the code. It doesn't compile, because the type attribute is not accepting the Product interface. If you take a look at the image I uploaded, you'll see the error on ApiProperty.\n- I can see that there's a red line indicating that there is an error. Please the actual text of the error\n- this error: error TS2693: 'Product' only refers to a type, but is being used as a value here.\n- Unless i'm missing something, even with Swagger-CLI (the plugin made by Nest to like automatically use DTOs and stuff in routes), it still doesn't work with interface\n- It can't work with Interfaces, they don't exist at runtime.\n- Okay that's what i understood. Your sentence \"You'll have to convert it to a Class\" [...] \"otherwhise you could take a look at using the NestJS Swagger\" is kinda misleading to me, make is sound like it would work with it to me.\n- Sometimes, you just import an SDK and it's full of interfaces. Converting a 100 plus generated interfaces to classes is just so tedious... Any way around it?","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":96,"estimatedTokens":648}}472{"id":"stack-62054703","source":"stackoverflow","questionId":62054703,"title":"Avoiding circular dependencies the right way - NestJS","tags":["typescript","design-patterns","dependency-injection","graphql","nestjs"],"text":"Title: Avoiding circular dependencies the right way - NestJS\nTags: typescript, design-patterns, dependency-injection, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nSay I have a `StudentService` with a method that adds lessons to a student and a `LessonService` with a method that adds students to a lesson. In both my Lesson and Student Resolvers I want to be able to update this lesson student relationship. So in my `LessonResolver` I have something along the lines of:\n\n```\nasync assignStudentsToLesson(\n @Args('assignStudentsToLessonInput')\n assignStudentsToLesson: AssignStudentsToLessonInput,\n ) {\n const { lessonId, studentIds } = assignStudentsToLesson;\n await this.studentService.assignLessonToStudents(lessonId, studentIds); **** A.1 ****\n return this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****\n }\n```\n\nand essentially the reverse in my `StudentResolver`\n\nThe difference between **A.1** and **A.2** above is that the `StudentService` has access to the `StudentRepository` and the `LessonService` has access to the `LessonRepository` - which I believe adheres to a solid separation of concerns.\n\nHowever, it seems to be an anti-pattern that the `StudentModule` must import the `LessonModule` and the `LessonModule` must import the `StudentModule`. This is fixable using the `forwardRef` method, but in the NestJS Documentation it mentions this pattern should be avoided if possible:\n\n While circular dependencies should be avoided where possible, you\n can't always do so. *(is this one of those cases?)*\n\nThis seems like it should be a common issue when using DI, but I'm struggling to get a definitive answer as to what options are available that can eliminate this situation, or if I've stumbled upon a situation where it's unavoidable.\n\nThe ultimate goal is for me to be able to write the two GraphQL queries below:\n\n```\nquery {\n students {\n firstName\n lessons {\n name\n }\n }\n}\n\nquery {\n lessons {\n name\n students {\n firstName\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nasync assignStudentsToLesson(\n    @Args('assignStudentsToLessonInput')\n    assignStudentsToLesson: AssignStudentsToLessonInput,\n  ) {\n    const { lessonId, studentIds } = assignStudentsToLesson;\n    await this.studentService.assignLessonToStudents(lessonId, studentIds); **** A.1 ****\n    return this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****\n  }\n```\n\n```text\nquery {\n  students {\n    firstName\n    lessons {\n      name\n    }\n  }\n}\n\nquery {\n  lessons {\n    name\n    students {\n      firstName\n    }\n  }\n}\n```\n\n```text\nStudentService\n```\n\n```text\nLessonService\n```\n\n```text\nLessonResolver\n```\n\n```text\nStudentResolver\n```\n\n```text\nStudentService\n```\n\n```text\nStudentRepository\n```\n\n```text\nLessonService\n```\n\n```text\nLessonRepository\n```\n\n```text\nStudentModule\n```\n\n```text\nLessonModule\n```\n\n```text\nLessonModule\n```\n\n```text\nStudentModule\n```\n\n```text\nforwardRef\n```\n\n```text\nasync assign({ lessonId, studentIds }: AssignStudentsToLessonInput) {\n  await this.studentService.assignLessonToStudents(lessonId, studentIds);\n  return this.lessonService.assignStudentsToLesson(lessonId, studentIds);\n}\n```\n\n```text\ntype AssignCallback = (assignStudentsToLesson: AssignStudentsToLessonInput) => Promise<void>;\n\nclass LessonResolver {  // and similar for StudentResolver\n  private assignCallbacks: AssignCallback[] = [];\n\n  // ... dependencies, constructor etc.\n\n  onAssign(callback: AssignCallback) {\n    assignCallbacks.push(callback);\n  }\n\n  async assignStudentsToLesson(\n    @Args('assignStudentsToLessonInput')\n    assignStudentsToLesson: AssignStudentsToLessonInput,\n  ) {\n    const { lessonId, studentIds } = assignStudentsToLesson;\n    await this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****\n    for (const cb of assignCallbacks) {\n      await cb(assignStudentsToLesson);\n    }\n  }\n}\n\n// In another module\nthis.lessonResolver.onAssign(({ lessonId, studentIds }) => {\n  this.studentService.assignLessonToStudents(lessonId, studentIds);\n});\nthis.studentResolver.onAssign(({ lessonId, studentIds }) => {\n  this.lessonService.assignStudentsToLesson(lessonId, studentIds);\n});\n```\n\n```text\nStudentLessonResolver\n```\n\n```text\nResolverModule\n```\n\n```text\nStudentModule\n```\n\n```text\nLessonModule\n```\n\n```text\nResolverModule\n```\n\n```text\nStudentModule\n```\n\n```text\nLessonModule\n```\n\n```text\nSubject<AssignStudentsToLessonInput>\n```\n\n```text\nLessonRepository\n```\n\n```text\nLessonService\n```\n\n```text\nLessonModule\n```\n\n========================================\n\nComments:\n- interesting approach! I had thought of using a third resolver but wasn't sure if that was me over-engineering and failing to see a simpler solution. One idea I just thought of was to alternatively inject the `StudentRepository` and `LessonRepository` into both the `StudentService` and `LessonService`. This way each service has both repos and can update them accordingly. My only gripe about this method is it seems to introduce duplicate business logic. Curious what your thoughts are?\n- I just tried your first approach and it works great. I appreciate your feedback!\n- Thanks! I also updated the answer to consider your proposal.\n- What if I use async events everywhere instead of using forwardRef, resolver module, etc.? @mperktold\n- That's illustrated by the second code example, isn't it?","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":229,"estimatedTokens":1340}}473{"id":"stack-54157097","source":"stackoverflow","questionId":54157097,"title":"While creating a dynamic module in Nest.js should i use registerAsync or forRootAsync?","tags":["node.js","typescript","nestjs"],"text":"Title: While creating a dynamic module in Nest.js should i use registerAsync or forRootAsync?\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhile creating a dynamic module some of the nestjs modules are using **registerAsync()** some use **forRootAsync()**. which is the recommended method or is there any difference between these two?\n\n```\nPassportModule.registerAsync({\n imports: [ConfigModule],\n useExisting: PassportConfigService,\n}),\n\nTypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useExisting: TypeormConfigService,\n}),\n```\n\n========================================\n\nCode:\n```text\nPassportModule.registerAsync({\n  imports: [ConfigModule],\n  useExisting: PassportConfigService,\n}),\n\nTypeOrmModule.forRootAsync({\n  imports: [ConfigModule],\n  useExisting: TypeormConfigService,\n}),\n```\n\n```text\nforRoot\n```\n\n```text\nforChild\n```\n\n```text\nMyDatabaseModule.populate(data)\n```\n\n```text\nMyDatabaseModule.createConnection(configuration)\n```\n\n```text\nasync\n```\n\n========================================\n\nComments:\n- stackoverflow.com/questions/66371656/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":58,"estimatedTokens":273}}474{"id":"stack-57730120","source":"stackoverflow","questionId":57730120,"title":"How to test Nestjs interceptor?","tags":["typescript","unit-testing","jestjs","interceptor","nestjs"],"text":"Title: How to test Nestjs interceptor?\nTags: typescript, unit-testing, jestjs, interceptor, nestjs\nSource: Stack Overflow\n\nQuestion:\nI can't find any explanation on how to test interceptors in NestJS\n\nThis simple example intercepts a POST query to add an attribute to an Example Model provided in the body. \n\n```\n@Injectable()\nexport class SubscriberInterceptor implements NestInterceptor {\n async intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Promise> {\n let body: ExampleModel = context.switchToHttp().getRequest().body;\n body = {\n ...body,\n addedAttribute: 'example',\n };\n context.switchToHttp().getRequest().body = body;\n return next.handle();\n }\n}\n```\n\nI would like to test what's happening in the intercept function.\n\nSo far: \n\n```\nconst interceptor = new SubscriberInterceptor();\n\ndescribe('SubscriberInterceptor', () => {\n it('should be defined', () => {\n expect(interceptor).toBeDefined();\n });\n\n describe('#intercept', () => {\n it('should add the addedAttribute to the body', async () => {\n expect(await interceptor.intercept(arg1, arg2)).toBe({ ...bodyMock, addedAttribute: 'example' });\n });\n });\n});\n```\n\nMy question: Should I mock only `arg1: ExecutionContext` and `arg2: CallHandler`? If so, how to mock `arg1` and `arg2`? Else How should I proceed?\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class SubscriberInterceptor implements NestInterceptor {\n  async intercept(\n    context: ExecutionContext,\n    next: CallHandler,\n  ): Promise<Observable<ExampleModel>> {\n    let body: ExampleModel = context.switchToHttp().getRequest().body;\n    body = {\n      ...body,\n      addedAttribute: 'example',\n    };\n    context.switchToHttp().getRequest().body = body;\n    return next.handle();\n  }\n}\n```\n\n```js\nconst interceptor = new SubscriberInterceptor();\n\ndescribe('SubscriberInterceptor', () => {\n  it('should be defined', () => {\n    expect(interceptor).toBeDefined();\n  });\n\n  describe('#intercept', () => {\n    it('should add the addedAttribute to the body', async () => {\n      expect(await interceptor.intercept(arg1, arg2)).toBe({ ...bodyMock, addedAttribute: 'example' });\n    });\n  });\n});\n```\n\n```text\narg1: ExecutionContext\n```\n\n```text\narg2: CallHandler\n```\n\n```text\narg1\n```\n\n```text\narg2\n```\n\n```text\ninterface ExecutionContext {\n  switchToHttp(): any;\n}\ninterface CallHandler {\n  handle(): any;\n}\ninterface Observable<T> {}\ninterface ExampleModel {}\n\ninterface NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>>;\n}\n\nexport class SubscriberInterceptor implements NestInterceptor {\n  public async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>> {\n    let body: ExampleModel = context.switchToHttp().getRequest().body;\n    body = {\n      ...body,\n      addedAttribute: 'example'\n    };\n    context.switchToHttp().getRequest().body = body;\n    return next.handle();\n  }\n}\n```\n\n```text\nimport { SubscriberInterceptor } from './';\n\nconst interceptor = new SubscriberInterceptor();\n\nconst executionContext = {\n  switchToHttp: jest.fn().mockReturnThis(),\n  getRequest: jest.fn().mockReturnThis()\n};\n\nconst callHandler = {\n  handle: jest.fn()\n};\n\ndescribe('SubscriberInterceptor', () => {\n  it('should be defined', () => {\n    expect(interceptor).toBeDefined();\n  });\n  describe('#intercept', () => {\n    it('t1', async () => {\n      (executionContext.switchToHttp().getRequest as jest.Mock<any, any>).mockReturnValueOnce({\n        body: { data: 'mocked data' }\n      });\n      callHandler.handle.mockResolvedValueOnce('next handle');\n      const actualValue = await interceptor.intercept(executionContext, callHandler);\n      expect(actualValue).toBe('next handle');\n      expect(executionContext.switchToHttp().getRequest().body).toEqual({\n        data: 'mocked data',\n        addedAttribute: 'example'\n      });\n      expect(callHandler.handle).toBeCalledTimes(1);\n    });\n  });\n});\n```\n\n```sh\nPASS  src/mock-function/57730120/index.spec.ts\n  SubscriberInterceptor\n    โœ“ should be defined (10ms)\n    #intercept\n      โœ“ t1 (11ms)\n\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        1.235s, estimated 3s\n```\n\n```text\narg1\n```\n\n```text\narg2\n```\n\n```text\nintercept\n```\n\n```text\nSubscriberInterceptor.ts\n```\n\n```text\nexecutionContext\n```\n\n========================================\n\nComments:\n- How does this work when getRequest is not a method of ExecutionContext? It is a method of the object returned from switchtoHttp().\n- This works because using `.mockReturnThis()` as the return value for all the mocks will return executionContext in all cases.","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":203,"estimatedTokens":1166}}475{"id":"stack-60974334","source":"stackoverflow","questionId":60974334,"title":"Obtaining XML in the Request Body for Post in Nest.js","tags":["xml","http-post","nestjs"],"text":"Title: Obtaining XML in the Request Body for Post in Nest.js\nTags: xml, http-post, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am curious if it is possible to obtain XML data in the Request Body of Nest.js.\n\n### Dependencies\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^7.0.0\",\n \"@nestjs/core\": \"^7.0.0\",\n \"@nestjs/platform-express\": \"^7.0.0\",\n```\n\n### Requirement\n\nI wish to have an HTTP POST API called `/EPCIS/capture` that would obtain XML documents like the following:\n\n```\n\n \n \n \n 2008-03-16T22:13:16.397+01:00\n +01:00\n \n urn:epc:id:sgtin:0614141.107346.2017\n urn:epc:id:sgtin:0614141.107346.2018\n \n OBSERVE\n urn:epcglobal:epcis:bizstep:fmcg:shipped\n urn:epcglobal:epcis:disp:fmcg:unknown\n \n urn:epc:id:sgln:0614141.07346.1234\n \n \n urn:epcglobal:fmcg:loc:0614141073467.A23-49\n \n \n \n http://transaction.acme.com/po/12345678\n \n \n \n \n \n\n```\n\nWithin my Controller:\n\n```\nPost('capture')\n addEPCDocument(@Body() epcDocument: any): any {\n console.log(epcDocument)\n }\n```\n\nBut all I get is `{}` when logging the incoming Request Body. My POSTMAN setting already mentions:\n\n`Content-Type: application/xml`\n\nand within the `Body` I have the above mentioned XML pasted. The Response is HTTP 400 Bad Request.\n\nWhat is normally a way to extract XML from the Request Body in Nest.JS?\n\n========================================\n\nTop Answer:\nAs Jay mentioned, middleware for parsing the xml requests can be added.\n\n```\n// xml.middleware.ts\n\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport * as bodyParser from 'body-parser';\n\nconst bodyParserXML = bodyParser.text({\n type: 'application/xml',\n});\n\n@Injectable()\nexport class XMLMiddleware implements NestMiddleware {\n use(req: any, res: any, next: () => void) {\n bodyParserXML(req, res, next);\n }\n}\n```\n\nAdd this middleware in app.module.ts\n\n```\nimport { XMLMiddleware } from './middileware/xml.middleware';\n \nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(XMLMiddleware).forRoutes({\n path: '/*',\n method: RequestMethod.GET,\n });\n }\n}\n```\n\nreference: https://chowdera.com/2022/117/202204271800482265.html\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\n    \"@nestjs/common\": \"^7.0.0\",\n    \"@nestjs/core\": \"^7.0.0\",\n    \"@nestjs/platform-express\": \"^7.0.0\",\n```\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<epcis:EPCISDocument\n    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n    xmlns:epcis=\"urn:epcglobal:epcis:xsd:1\"\n    xmlns:epcglobal=\"urn:epcglobal:xsd:1\"\n    xsi:schemaLocation=\"urn:epcglobal:epcis:xsd:1 EPCglobal-epcis-1_0.xsd\"\n    creationDate=\"2008-03-16T22:13:16.397+01:00\"\n    schemaVersion=\"1.0\">\n  <EPCISBody>\n    <EventList>\n      <ObjectEvent>\n        <eventTime>2008-03-16T22:13:16.397+01:00</eventTime>\n        <eventTimeZoneOffset>+01:00</eventTimeZoneOffset>\n        <epcList>\n          <epc>urn:epc:id:sgtin:0614141.107346.2017</epc>\n          <epc>urn:epc:id:sgtin:0614141.107346.2018</epc>\n        </epcList>\n        <action>OBSERVE</action>\n        <bizStep>urn:epcglobal:epcis:bizstep:fmcg:shipped</bizStep>\n        <disposition>urn:epcglobal:epcis:disp:fmcg:unknown</disposition>\n        <readPoint>\n          <id>urn:epc:id:sgln:0614141.07346.1234</id>\n        </readPoint>\n        <bizLocation>\n          <id>urn:epcglobal:fmcg:loc:0614141073467.A23-49</id>\n        </bizLocation>\n        <bizTransactionList>\n          <bizTransaction type=\"urn:epcglobal:fmcg:btt:po\">\n            http://transaction.acme.com/po/12345678\n          </bizTransaction>\n        </bizTransactionList>\n      </ObjectEvent>\n    </EventList>\n  </EPCISBody>\n</epcis:EPCISDocument>\n```\n\n```js\nPost('capture')\n    addEPCDocument(@Body() epcDocument: any): any {\n        console.log(epcDocument)\n    }\n```\n\n```text\n/EPCIS/capture\n```\n\n```text\n{}\n```\n\n```text\nContent-Type: application/xml\n```\n\n```text\nBody\n```\n\n```text\napplication/json\n```\n\n```text\napplicaiton/x-www-form-urlencoded\n```\n\n```js\n// xml.middleware.ts\n\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport * as bodyParser from 'body-parser';\n\nconst bodyParserXML = bodyParser.text({\n  type: 'application/xml',\n});\n\n@Injectable()\nexport class XMLMiddleware implements NestMiddleware {\n  use(req: any, res: any, next: () => void) {\n    bodyParserXML(req, res, next);\n  }\n}\n```\n\n```js\nimport { XMLMiddleware } from './middileware/xml.middleware';\n    \nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(XMLMiddleware).forRoutes({\n      path: '/*',\n      method: RequestMethod.GET,\n    });\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":217,"estimatedTokens":1151}}476{"id":"stack-69471840","source":"stackoverflow","questionId":69471840,"title":"Cannot query across one-to-many for property NestJS and TypeORM","tags":["javascript","postgresql","nestjs","typeorm"],"text":"Title: Cannot query across one-to-many for property NestJS and TypeORM\nTags: javascript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities one is `car` and another one is `carAvailability`\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';\nimport { CarAvailability } from 'src/car-availabilitys/car-availability.entity';\n\n@Entity('cars')\nexport class Car {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => CarAvailability, (carAvailability) => carAvailability.car, {\n eager: true,\n cascade: true,\n })\n availabilities: CarAvailability[];\n}\n```\n\nI am trying to add a service that queries and filters cars based on the availabilities. In My Service and tried two ways:\n\nMethod 1 with repo functions:\n\n```\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return await this.repo.find({\n relations: ['availabilities'],\n where: {\n availabilities: {\n start_date_time: startDateTime\n }\n }\n });\n}\n```\n\nMethod 2 with query builder:\n\n```\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return this.repo.createQueryBuilder('cars')\n .innerJoin('cars.availabilities', 'car_availabilities')\n .where(\"cars.availabilities.start_date_time = :startDateTime\", { startDateTime })\n .getMany();\n}\n```\n\nMethod 1 error:\n\n```\nError: Cannot query across one-to-many for property availabilities\n```\n\nMethod 2 error:\n\n```\nQueryFailedError: missing FROM-clause entry for table \"availabilities\"\n```\n\nI feel like I am missing something but I am not sure. Have referred both NestJS and TypeORM docs but can't seem to figure out what went wrong.\n\n========================================\n\nTop Answer:\nUsing Method 1 repo functions with nested query builder:\n\n```\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return await this.repo.find({\n relations: ['availabilities'],\n where: (qb) => {\n qb.where('availabilities.start_date_time = :startDateTime', {\n startDateTime\n });\n }\n });\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';\nimport { CarAvailability } from 'src/car-availabilitys/car-availability.entity';\n\n@Entity('cars')\nexport class Car {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  name: string;\n\n  @OneToMany(() => CarAvailability, (carAvailability) => carAvailability.car, {\n    eager: true,\n    cascade: true,\n  })\n  availabilities: CarAvailability[];\n}\n```\n\n```text\nasync test () {\n  const startDateTime = '2012-04-24 02:25:43.511';\n\n  return await this.repo.find({\n    relations: ['availabilities'],\n    where: {\n      availabilities: {\n        start_date_time: startDateTime\n      }\n    }\n  });\n}\n```\n\n```text\nasync test () {\n  const startDateTime = '2012-04-24 02:25:43.511';\n\n  return this.repo.createQueryBuilder('cars')\n    .innerJoin('cars.availabilities', 'car_availabilities')\n    .where(\"cars.availabilities.start_date_time = :startDateTime\", { startDateTime })\n    .getMany();\n}\n```\n\n```text\nError: Cannot query across one-to-many for property availabilities\n```\n\n```text\nQueryFailedError: missing FROM-clause entry for table \"availabilities\"\n```\n\n```text\ncar\n```\n\n```text\ncarAvailability\n```\n\n```text\ncar_availabilities.start_date_time\n```\n\n```text\ncars.availabilities.start_date_time\n```\n\n```text\ncar.availabilities\n```\n\n```text\ncar_availabilities\n```\n\n```text\nwhere\n```\n\n```text\nasync test () {\n  const startDateTime = '2012-04-24 02:25:43.511';\n\n  return await this.repo.find({\n    relations: ['availabilities'],\n    where: (qb) => {\n      qb.where('availabilities.start_date_time = :startDateTime', {\n        startDateTime\n      });\n    }\n  });\n}\n```\n\n```text\n{\n  cascade: true,\n  onDelete: 'CASCADE',\n  onUpdate:'CASCADE'\n}\n```\n\n```text\ncascade\n```\n\n```text\noneToMany\n```\n\n```text\nmanyToOne\n```\n\n```text\n['availabilities']\n```\n\n```text\neager: true\n```\n\n```text\nreturn await this.repository.find({relations: ['availabilities'])\n.then((cars) => cars.filter((car) => car.start_date_time === startDateTime));\n```\n\n========================================\n\nComments:\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- This is not a preferred method because you are doing the filtering in code instead of in SQL (not very efficient). This method always returns all results and then loops thru them to filter the ones you want.\n- You're right but this is the only solution i could find","metadata":{"transformedAt":"2026-08-18T18:33:02.446Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":232,"estimatedTokens":1158}}477{"id":"stack-58623541","source":"stackoverflow","questionId":58623541,"title":"extend existing API with custom endpoints","tags":["javascript","rest","express","nestjs"],"text":"Title: extend existing API with custom endpoints\nTags: javascript, rest, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm creating an API for multiple customers. The core endpoints like `/users` are used by every customer but some endpoints rely on individual customization. So it might be that *User A* wants a special endpoint `/groups` and no other customer will have that feature. *Just as a sidenote*, each customer would also use his own database schema because of those extra features.\n\nI personally use NestJs (Express under the hood). So the `app.module` currently registers all my core modules (with their own endpoints etc.)\n\n```\nimport { Module } from '@nestjs/common';\n\nimport { UsersModule } from './users/users.module'; // core module\n\n@Module({\n imports: [UsersModule]\n})\nexport class AppModule {}\n```\n\nI think this problem is not related to NestJs so how would you handle that in theory? \n\n*I basically need an infrastructure that is able to provide a basic system. There are no core endpoints anymore because each extension is unique and multiple `/users` implementations could be possible. When developing a new feature the core application should not be touched. Extensions should integrate themselves or should get integrated on startup. The core system ships with no endpoints but will be extended from those external files.*\n\nSome ideas come to my mind\n\n**First approach:**\n\nEach extension represents a new repository. Define a path to a custom external folder holding all that extension projects. This custom directory would contain a folder `groups` with a `groups.module`\n\n```\nimport { Module } from '@nestjs/common';\n\nimport { GroupsController } from './groups.controller';\n\n@Module({\n controllers: [GroupsController],\n})\nexport class GroupsModule {}\n```\n\nMy API could loop through that directory and try to import each module file.\n\npros:\n\n- The custom code is kept away from the core repository\n\ncons:\n\nNestJs uses Typescript so I have to compile the code first. How would I manage the API build and the builds from the custom apps? (Plug and play system)\n\nThe custom extensions are very loose because they just contain some typescript files. Due to the fact they don't have access to the node_modules directory of the API, my editor will show me errors because it can't resolve external package dependencies.\n\nSome extensions might fetch data from another extension. Maybe the groups service needs to access the users service. Things might get tricky here.\n\n**Second approach:**\nKeep each extension inside a subfolder of the src folder of the API. But add this subfolder to the .gitignore file. Now you can keep your extensions inside the API.\n\npros:\n\nYour editor is able to resolve the dependencies\n\nBefore deploying your code you can run the build command and will have a single distribution\n\nYou can access other services easily (`/groups` needs to find a user by id)\n\ncons:\n\n- When developing you have to copy your repository files inside that subfolder. After changing something you have to copy these files back and override your repository files with the updated ones.\n\n**Third approach:**\n\nInside an external custom folder, all extensions are fully fledged standalone APIs. Your main API would just provide the authentication stuff and could act as a proxy to redirect the incoming requests to the target API.\n\npros:\n\n- New extensions can be developed and tested easily\n\ncons:\n\nDeployment will be tricky. You will have a main API and *n* extension APIs starting their own process and listening to a port.\n\nThe proxy system could be tricky. If the client requests `/users` the proxy needs to know which extension API listens for that endpoint, calls that API and forwards that response back to the client.\n\nTo protect the extension APIs (authentication is handled by the main API) the proxy needs to a secret with those APIs. So the extension API will only pass incoming requests if that matching secret is provided from the proxy.\n\n**Fourth approach:**\n\nMicroservices might help. I took a guide from here https://docs.nestjs.com/microservices/basics\n\nI could have a microservice for the user management, group management etc. and consume those services by creating a small api / gateway / proxy that calls those microservices.\n\npros:\n\nNew extensions can be developed and tested easily\n\nSeparated concerns\n\ncons:\n\nDeployment will be tricky. You will have a main API and *n* microservices starting their own process and listening to a port.\n\nIt seems that I would have to create a new gateway api for each customer if I want to have it customizable. So instead of extending an application I would have to create a customized comsuming API each time. That wouldn't solve the problem.\n\nTo protect the extension APIs (authentication is handled by the main API) the proxy needs to a secret with those APIs. So the extension API will only pass incoming requests if that matching secret is provided from the proxy.\n\n========================================\n\nTop Answer:\nI would go for external packages option.\n\nYou can structure your app to have a `packages` folder. I would have UMD compiled builds of external packages in that folder so that your compiled typescript won't have any issues with the packages. All packages should have an `index.js` file on each package's root folder.\n\nAnd your app can run a loop through the packages folder using `fs` and `require` all the packages `index.js` into your app.\n\nThen again dependency installation is something you have to take care of. I think a configuration file on each package could solve that too. You can have a custom `npm` script on main app to install all the package dependencies before starting the application.\n\nThis way, you can just add new packages to your app by copy pasting the package into the packages folder and rebooting the app. Your compiled typescript files won't be touched and you don't have to use private npm for your own packages.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\n\nimport { UsersModule } from './users/users.module'; // core module\n\n@Module({\n  imports: [UsersModule]\n})\nexport class AppModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\n\nimport { GroupsController } from './groups.controller';\n\n@Module({\n  controllers: [GroupsController],\n})\nexport class GroupsModule {}\n```\n\n```text\n/users\n```\n\n```text\n/groups\n```\n\n```text\napp.module\n```\n\n```text\n/users\n```\n\n```text\ngroups\n```\n\n```text\ngroups.module\n```\n\n```text\n/groups\n```\n\n```text\n/users\n```\n\n```text\n{\n    \"path\": \"relative path where plugins should be stored\",\n    \"plugins\": [\n        { \n           \"module\":\"name of service\", \n           \"dir\":\"location within plugin folder\",\n           \"source\":\"link to git repository\"\n        }\n    ]\n}\n```\n\n```text\n{\n    \"path\": \"./plugins\",\n    \"plugins\": [\n        {\n            \"module\": \"palindrome\",\n            \"dir\": \"locomotion-plugin-example\",\n            \"source\": \"https://github.com/drcircuit/locomotion-plugin-example.git\"\n        }\n    ]\n}\n```\n\n```text\nloco.then((svc) => {\n    let pal = svc.locate(\"palindrome\"); //get the palindrome service\n    if (pal) {\n        console.log(\"Is: no X in Nixon! a palindrome? \", (pal.isPalindrome(\"no X in Nixon!\")) ? \"Yes\" : \"no\"); // test if it works :)\n    }\n}).catch((err) => {\n    console.error(err);\n});\n```\n\n```text\nnpm install -s locomotion\n```\n\n```text\nplugins.json\n```\n\n```text\npackages\n```\n\n```text\nindex.js\n```\n\n```text\nfs\n```\n\n```text\nrequire\n```\n\n```text\nindex.js\n```\n\n```text\nnpm\n```\n\n========================================\n\nComments:\n- this might help github.com/nestjs/nest/issues/3277\n- Thanks for the link. But I don't think I should have the custom extensions within my code. I will check if microservices will solve the problem docs.nestjs.com/microservices/basics\n- I think your problem is related to authorization rather than rest.\n- @ adnanmuttaleb would you mind explaining why =?\n- Thanks. Two problems come up, it seems we rely on npm then and have to setup a self hosted registry. The second thing is that private npm is not free anymore. I was hoping to find a basic technical solution. But +1 for the idea :)\n- added a reference implementation of a rudimentary solution for this kind of system.\n- thanks for your reply. I think this sounds like the solution @ Espen already posted, no?\n- @hrp8sfH4xQ4 Yes, to an extend. I added it after reading your comment on not wanting to use `npm`. Above is a solution you can do to avoid private npm account. Moreover, I believe you don't need to add packages created by someone outside your organization. Right?\n- btw. but it would be awesome to support that too ... somehow ...\n- If you need option to add third party packages, then `npm` is the way to do it or any other package manager. In such cases, my solution won't suffice.\n- If you don't mind I would like to wait to collect as many approaches as possible","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":259,"estimatedTokens":2233}}478{"id":"stack-52334277","source":"stackoverflow","questionId":52334277,"title":"nestjs intercept and modify outgoing http request","tags":["typescript","http","nestjs"],"text":"Title: nestjs intercept and modify outgoing http request\nTags: typescript, http, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo I'm likely missing something or doing something wrong.\nI have a NestJS application that is trying to make an http request to an external API.\nI'd like to be able to intercept this outgoing request and modify headers on it before executing it.\n\nI've tried using Interceptors to no avail, the incoming http requests get intercepted but not the outgoing.\nAny suggestions or help would be greatly appreciated.\n\n========================================\n\nTop Answer:\nI had a similar problem modifying / adding response headers.\nFollowing code worked for me:\n\n```\n@Injectable()\nexport class TransformHeadersInterceptor implements NestInterceptor {\n intercept(\n context: ExecutionContext,\n call$: Observable,\n ): Observable {\n\n return call$.pipe(\n map((data) => {\n // pipe call to add / modify header(s) after remote method\n let req = context.switchToHttp().getRequest();\n req.res.header('x-api-key', 'pretty secure');\n return data;\n }),\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class TransformHeadersInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    // Get request headers, e.g.\n    const userAgent = context.switchToHttp().getRequest().headers['user-agent'];\n\n    // Not sure if headers are writeable like this, give it a try\n    context.switchToHttp().getResponse().headers['x-api-key'] = 'pretty secure';\n\n    return call$;\n  }\n}\n```\n\n```text\nreturn call$.pipe(map(data => {\n    // Your code here\n    return data;\n}));\n```\n\n```text\nimport { HTTP_TOKEN } from './constants';\nimport * as http from 'request-promise-native';\n\nexport const httpProviders: any = [\n  {\n    provide: HTTP_TOKEN,\n    useFactory: () => {\n      return http.defaults({\n        headers: {\n          'Accept': 'application/json',\n          'Content-type': 'application/json',\n          'User-agent': 'my-๐Ÿช-app',\n        },\n      });\n    },\n  },\n];\n```\n\n```text\nimport { PaginateModel, PaginateResult, Document } from 'mongoose';\nimport { AxiosInstance } from 'axios';\nimport { UseGuards, InternalServerErrorException, Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { Context } from './decorators/ctx.decorator';\n\n@Injectable()\n@UseGuards(AuthGuard('jwt'))\nexport abstract class ServiceBase<T extends Document> {\n    protected abstract readonly path: string;\n\n    constructor(protected readonly externals: Object, protected readonly model: PaginateModel<T>) {}\n\n    async create(data: T, ctx: Context): Promise<T> {\n        try {\n            this.validate(data);\n            const { lng, core } = this.separate(data);\n            const catalog = new this.model(core);\n            const head = await catalog.save();\n            Object.assign(head, lng);\n            const Authorization = ctx.token;\n            const axios: AxiosInstance = this.externals[ctx.lang];\n            try {\n                const resp = await axios.post(`${this.path}`, head, { headers: { Authorization } });\n                return resp.data;\n            } catch (err) {\n                // in case of any error the head record should be removed.\n                catalog.remove();\n                throw err;\n            }\n        } catch (err) {\n            console.log(err);\n            throw new InternalServerErrorException(err);\n        }\n    }\n\n    abstract async validate(data: T): Promise<any>;\n\n    abstract separate(data: T);\n\n    async update(id: string, data: T, ctx: Context): Promise<T> {\n        try {\n            const curr = await this.model.findById(id).exec();\n            const { lng, core } = this.separate(data);\n            Object.assign(curr, core);\n            await curr.save();\n            Object.assign(core, lng);\n            const Authorization = ctx.token;\n            const axios: AxiosInstance = this.externals[ctx.lang];\n            const resp = await axios.put(`${this.path}/${id}`, core, { headers: { Authorization } });\n            return resp.data;\n        } catch (err) {\n            throw new InternalServerErrorException(err);\n        }\n    }\n\n    async get(id: string, ctx: Context): Promise<T> {\n        try {\n            const Authorization = ctx.token;\n            const axios: AxiosInstance = this.externals[ctx.lang];\n            const resp = await axios.get(`${this.path}/${id}`, { headers: { Authorization } });\n            return resp.data;\n        } catch (err) {\n            console.log(err);\n            return null;\n        }\n    }\n\n    async findOne(query: object): Promise<T> {\n        const data = await this.model.findOne(query, { _class: 0 }).exec();\n        return data;\n    }\n\n    async findAll(ctx: Context): Promise<T[]> {\n        try {\n            const Authorization = ctx.token;\n            const axios: AxiosInstance = this.externals[ctx.lang];\n            const resp = await axios.get(`${this.path}`, {\n                headers: { Authorization },\n            });\n            return resp.data;\n        } catch (err) {\n            console.log(err);\n            return null;\n        }\n    }\n\n    async find(query: {} = {}, page: number, rows: number, ctx: Context): Promise<PaginateResult<T>> {\n        try {\n            const Authorization = ctx.token;\n            const axios: AxiosInstance = this.externals[ctx.lang];\n            const resp = await axios.get(`${this.path}`, {\n                params: { page, rows },\n                headers: { Authorization },\n            });\n            return resp.data;\n        } catch (err) {\n            console.log(err);\n            return null;\n        }\n    }\n}\n```\n\n```text\nimport axios, { AxiosInstance } from 'axios';\n\nconst config = require('../../config/settings.json');\n\nexport const externalProviders = {\n    provide: 'ExternalToken',\n    useFactory: () => {\n        const externals = {};\n        for (const lang in config.externals) {\n            externals[lang] = axios.create({\n                baseURL: config.externals[lang],\n            });\n        }\n        return externals;\n    }\n};\n```\n\n```text\n@Injectable()\nexport class TransformHeadersInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n\n    return call$.pipe(\n            map((data) => {\n                // pipe call to add / modify header(s) after remote method\n                let req = context.switchToHttp().getRequest();\n                req.res.header('x-api-key', 'pretty secure');\n                return data;\n            }),\n        );\n  }\n}\n```\n\n========================================\n\nComments:\n- if you call an external api you should use http/axios or something and you create a client with headers. This call is independent from nestjs. Personally I use axios client and nestjs cannot bind interceptors because it does not know anything about the inner logic.\n- This answer worked for me\n- does it mean that we cannot append http headers to outgoing requests? I have ran into a situation where i need to intercept an outgoing request and append headers to it before the request is called. stackoverflow.com/questions/60809063/&hellip; @Upvote?\n- Might want to add ` const res = context.switchToHttp().getResponse(); if (!res.headersSent) { // for res.redirect()`\n- this doesn't seem to add any headers for me. ๐Ÿค”\n- why changing response? you need to secure the request!","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":239,"estimatedTokens":1874}}479{"id":"stack-62670332","source":"stackoverflow","questionId":62670332,"title":"Nestjs passport authentication with multiple strategies","tags":["nestjs"],"text":"Title: Nestjs passport authentication with multiple strategies\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have multiple authentication strategies, example for one of them:\n\n```\n@Injectable()\nexport class EmployeeStrategy extends PassportStrategy(Strategy, 'employee') {\n constructor(\n private authService: AuthService,\n @Inject(appConfig.KEY)\n configService: ConfigType,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: configService.EMPLOYEE_KEY,\n });\n }\n\n async validate({ phone }: JwtPayload) {\n const employee = await this.authService.authByRole(phone, Role.Employee);\n\n if (!employee) {\n throw new UnauthorizedException('insufficient scope');\n }\n\n return employee;\n }\n```\n\nAnd some others mostly like this one. But because i throw unauthorized exception inside it, i cannot use multiple of them at the same route/controller. E.g.\n\n```\n@UseGuards(AuthGuard(['employee', 'admin']))\n```\n\nThe first one that crashes leading to error. How to solve that problem?\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class EmployeeStrategy extends PassportStrategy(Strategy, 'employee') {\n  constructor(\n    private authService: AuthService,\n    @Inject(appConfig.KEY)\n    configService: ConfigType<typeof appConfig>,\n  ) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: configService.EMPLOYEE_KEY,\n    });\n  }\n\n  async validate({ phone }: JwtPayload) {\n    const employee = await this.authService.authByRole(phone, Role.Employee);\n\n    if (!employee) {\n      throw new UnauthorizedException('insufficient scope');\n    }\n\n    return employee;\n  }\n```\n\n```text\n@UseGuards(AuthGuard(['employee', 'admin']))\n```\n\n```text\nvalidate()\n```\n\n```text\nuser\n```\n\n```text\nEmployeeGuard\n```\n\n```text\nEmployeeGuard implements CanActivete\n```\n\n```text\ncanActivate()\n```\n\n========================================\n\nComments:\n- Sorry, but I didn't understand your question. What do you wanna do exactly?\n- why do you need multiple on the same route? just make different login routes like `&#47;login&#47;employee` and `&#47;login&#47;admin`\n- Can you the `AuthGuard`?","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":98,"estimatedTokens":541}}480{"id":"stack-54652415","source":"stackoverflow","questionId":54652415,"title":"Nestjs Response Serialization with array of objects","tags":["node.js","typescript","serialization","nestjs","class-transformer"],"text":"Title: Nestjs Response Serialization with array of objects\nTags: node.js, typescript, serialization, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI want to serialize a controller response by the nestjs serialization technique. I didn't find any approach and my solution is as follows:\n\n### User Entity\n\n```\nexport type UserRoleType = \"admin\" | \"editor\" | \"ghost\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn() id: number;\n\n @Column('text')\n username: string;\n @Column('text') \n password: string;\n @Column({\n type: \"enum\",\n enum: [\"admin\", \"editor\", \"ghost\"],\n default: \"ghost\"\n })\n roles: UserRoleType;\n @Column({ nullable: true })\n profileId: number; \n}\n```\n\n### User Response Classes\n\n```\nimport { Exclude } from 'class-transformer';\n\nexport class UserResponse {\n id: number;\n\n username: string;\n\n @Exclude()\n roles: string;\n\n @Exclude()\n password: string;\n\n @Exclude()\n profileId: number; \n\n constructor(partial: Partial) {\n Object.assign(this, partial);\n }\n}\n\nimport { Exclude, Type } from 'class-transformer';\nimport { User } from 'src/_entities/user.entity';\nimport { UserResponse } from './user.response';\n\nexport class UsersResponse {\n\n @Type(() => UserResponse)\n users: User[] \n\n constructor() { }\n}\n```\n\n### Controller\n\n```\n@Controller('user')\nexport class UsersController {\n constructor(\n private readonly userService: UserService\n ) {\n\n }\n @UseInterceptors(ClassSerializerInterceptor)\n @Get('all')\n async findAll(\n ): Promise {\n let users = await this.userService.findAll().catch(e => { throw new NotAcceptableException(e) })\n let rsp =new UsersResponse() \n rsp.users = users\n return rsp\n }\n```\n\nIt works, but I must explicitly assign the db query result to the response users member.\nIs there a better way? Thanks a lot\n\nHere the actual Response and wanted result, for a better explanation.\n\n### Result in this Approach\n\n```\n{\n \"users\": [\n {\n \"id\": 1,\n \"username\": \"a\"\n },\n {\n \"id\": 2,\n \"username\": \"bbbbbb\"\n }\n ]\n}\n```\n\n### Result Wanted\n\n```\n{\n {\n \"id\": 1,\n \"username\": \"a\"\n },\n {\n \"id\": 2,\n \"username\": \"bbbbbb\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nYour approach is recommended by nestjs but that has a fault. You are excluding some properties from being exposed to the client. What if, you work in a project that has an admin and admin wants to see all the data about the users or products. If you exclude fields in the entities, your admin won't see those fields either. Instead, leave the entities as it is, and write dto's for each controller or for each request handler and in this dto's just list the properties you want to expose.\n\nThen write a custom interceptor and create specific dto for ecah entity. For example in your example, you create a userDto:\n\n```\nimport { Expose } from 'class-transformer';\n\n// this is a serizalization dto\nexport class UserDto {\n @Expose()\n id: number;\n @Expose()\n roles: UserRoleType;\n @Expose()\n albums: Album[];\n // Basically you list what you wanna expose here\n}\n```\n\ncustom interceptor is a little messy:\n\n```\nimport {\n UseInterceptors,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { plainToClass } from 'class-transformer';\n\n// Normally user entity goes into the interceptor and nestjs turns it into the JSON. But we we ill turn it to User DTO which will have all the serialization rules.then nest will take dto and turn it to the json and send it back as response\n\nexport class SerializerInterceptor implements NestInterceptor {\n // dto is the variable. so you can use this class for different entities\n constructor(private dto:any){\n\n }\n intercept(context: ExecutionContext, handler: CallHandler): Observable {\n // you can write some code to run before request is handled\n return handler.handle().pipe(\n // data is the incoming user entity\n map((data: any) => {\n return plainToClass(this.dto, data, {\n // this takes care of everything. this will expose things that are set in the UserDto\n excludeExtraneousValues: true,\n });\n }),\n );\n }\n}\n```\n\nNow you use this in the controller:\n\n```\n// See we passed UserDto. for different entities, we would just write a new dto for that entity and our custom interceptor would stay reusable\n@UseInterceptors(new SerializerInterceptor(UserDto))\n@Get('all')\n async findAll(\n ): Promise {\n let users = await this.userService.findAll().catch(e => { throw new NotAcceptableException(e) })\n let rsp =new UsersResponse() \n rsp.users = users\n return rsp\n }\n```\n\n========================================\n\nCode:\n```text\nexport type UserRoleType = \"admin\" | \"editor\" | \"ghost\";\n\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn() id: number;\n\n    @Column('text')\n        username: string;\n    @Column('text') \n        password: string;\n    @Column({\n        type: \"enum\",\n        enum: [\"admin\", \"editor\", \"ghost\"],\n        default: \"ghost\"\n    })\n    roles: UserRoleType;\n        @Column({ nullable: true })\n                profileId: number;  \n}\n```\n\n```text\nimport { Exclude } from 'class-transformer';\n\nexport class UserResponse {\n    id: number;\n\n    username: string;\n\n    @Exclude()\n    roles: string;\n\n    @Exclude()\n    password: string;\n\n    @Exclude()\n    profileId: number;  \n\n    constructor(partial: Partial<UserResponse>) {\n        Object.assign(this, partial);\n    }\n}\n\nimport { Exclude, Type } from 'class-transformer';\nimport { User } from 'src/_entities/user.entity';\nimport { UserResponse } from './user.response';\n\nexport class UsersResponse {\n\n    @Type(() => UserResponse)\n    users: User[]   \n\n    constructor() { }\n}\n```\n\n```text\n@Controller('user')\nexport class UsersController {\n    constructor(\n        private readonly userService: UserService\n    ) {\n\n    }\n    @UseInterceptors(ClassSerializerInterceptor)\n    @Get('all')\n    async findAll(\n    ): Promise<UsersResponse> {\n        let users = await this.userService.findAll().catch(e => { throw new   NotAcceptableException(e) })\n        let rsp =new UsersResponse() \n        rsp.users = users\n        return rsp\n    }\n```\n\n```text\n{\n  \"users\": [\n    {\n      \"id\": 1,\n      \"username\": \"a\"\n    },\n    {\n      \"id\": 2,\n      \"username\": \"bbbbbb\"\n    }\n  ]\n}\n```\n\n```text\n{\n    {\n      \"id\": 1,\n      \"username\": \"a\"\n    },\n    {\n      \"id\": 2,\n      \"username\": \"bbbbbb\"\n    }\n}\n```\n\n```text\nreturn isArray\n  ? (response as PlainLiteralObject[]).map(item =>\n      this.transformToPlain(item, options),\n    )\n  : this.transformToPlain(response, options);\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n@Get('all')\nasync findAll(): Promise<User> {\n    return this.userService.findAll()\n}\n```\n\n```text\nimport { serialize } from 'class-transformer';\n\n@Get('all')\nasync findAll(): Promise<UsersResponse> {\n  const users: User[] = await this.userService.findAll();\n  return {users: serialize(users)};\n}\n```\n\n```text\n@Exclude\n```\n\n```text\nUser\n```\n\n```text\nUserResponse\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nreturn users\n```\n\n```text\nreturn {users: users}\n```\n\n```text\nserialize\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n@Get('all')\nasync findAll(\n): Promise<User> {\n    return await this.userService.findAll().catch(e => { throw new NotAcceptableException(e) })\n}\n```\n\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn, OneToMany } from 'typeorm';\nimport { Profile } from './profile.entity';\nimport { Photo } from './photo.entity';\nimport { Album } from './album.entity';\nimport { Exclude } from 'class-transformer';\n\nexport type UserRoleType = \"admin\" | \"editor\" | \"ghost\";\n\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn() id: number;\n    @Column('text')\n    username: string;\n\n    @Exclude()\n    @Column('text')\n    password: string;\n\n    @Column({\n        type: \"enum\",\n        enum: [\"admin\", \"editor\", \"ghost\"],\n        default: \"ghost\"\n    })\n    roles: UserRoleType;\n\n    @Exclude()\n    @Column({ nullable: true })\n    profileId: number;\n\n    @OneToMany(type => Photo, photo => photo.user)\n    photos: Photo[];\n\n    @OneToMany(type => Album, albums => albums.user)\n    albums: Album[];\n\n    @OneToOne(type => Profile, profile => profile.user)\n    @JoinColumn()\n    profile: Profile;\n}\n```\n\n```text\n[\n  {\n    \"id\": 1,\n    \"username\": \"a\",\n    \"roles\": \"admin\"\n  },\n  {\n    \"id\": 2,\n    \"username\": \"bbbbbb\",\n    \"roles\": \"ghost\"\n  }\n]\n```\n\n```text\nimport { serialize, deserialize } from 'class-transformer';\nimport { User } from './users.entity';\n\n@Get('all')\nasync findAll() {\n  const users = serialize(await this.userService.findAll());\n  return {\n     status: 200,\n     message: 'ok',\n     users: deserialize(User, users)\n  };\n}\n```\n\n```text\nimport { Param } from '@nestjs/common';    \nimport { serialize, deserialize } from 'class-transformer';\nimport { User } from './users.entity';\n\n@Get(':id')\nasync findById(@Param('id') id: number) {\n  const user = serialize(await this.userService.findById(id));\n  return {\n    status: 200,\n    message: 'ok',\n    user: deserialize(User, user)\n  };\n}\n```\n\n```text\nimport { Expose } from 'class-transformer';\n\n// this is a serizalization dto\nexport class UserDto {\n  @Expose()\n  id: number;\n  @Expose()\n  roles: UserRoleType;\n  @Expose()\n  albums: Album[];\n // Basically you list what you wanna expose here\n}\n```\n\n```text\nimport {\n  UseInterceptors,\n  NestInterceptor,\n  ExecutionContext,\n  CallHandler,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { plainToClass } from 'class-transformer';\n\n// Normally user entity goes into the interceptor and nestjs turns it into the JSON. But we we ill turn it to User DTO which will have all the serialization rules.then nest will take dto and turn it to the json and send it back as response\n\n\nexport class SerializerInterceptor implements NestInterceptor {\n    // dto is the variable. so you can use this class for different entities\n    constructor(private dto:any){\n\n    }\n  intercept(context: ExecutionContext, handler: CallHandler): Observable<any> {\n   // you can write some code to run before request is handled\n    return handler.handle().pipe(\n      // data is the incoming user entity\n      map((data: any) => {\n        return plainToClass(this.dto, data, {\n          //   this takes care of everything. this will expose things that are set in the UserDto\n          excludeExtraneousValues: true,\n        });\n      }),\n    );\n  }\n}\n```\n\n```text\n// See we passed UserDto. for different entities, we would just write a new dto for that entity and our custom interceptor would stay reusable\n@UseInterceptors(new SerializerInterceptor(UserDto))\n@Get('all')\n    async findAll(\n    ): Promise<UsersResponse> {\n        let users = await this.userService.findAll().catch(e => { throw new   NotAcceptableException(e) })\n        let rsp =new UsersResponse() \n        rsp.users = users\n        return rsp\n    }\n```\n\n========================================\n\nComments:\n- stackoverflow.com/questions/58343262/&hellip; should help\n- Thanks so lot for your answer, that gives me more details and i edited my question with the wanted result.\n- Great, then you can just return the users array directly from your controller `return users`. For that to work, don't forget to add the `@Exclude()` decorators directly to your `UserEntity` class. If this solves your problem, consider accepting an answer. Of course, you can also leave it open and wait for another answer. see stackoverflow.com/help/someone-answers\n- any reason of not recommending the duplicate dto(entity) for you db entity ? I'm designing new nestJs app with the same hierarchy mentioned by the OP in the question i.e. db entity -> db entity abstract dto(same exact fields with no decorators) -> request dto extending db entity dto(with validations decorators) -> response dto expending db entity dto(transformation decorators). Just curious to understand why you recommend to use entities for response rather a separate dto.\n- Great, thanks for sharing your code! :-) Little side note: `return await` is always redundant unless you use it with try-catch. So I'd recommend to use try-catch instead of the chained `catch` or, alternatively, to remove the `await`.\n- better to decorate your main entity with Exclude decorators and then add Expose to the properties (you want to send) explicitly.\n- stackoverflow.com/questions/68744139/&hellip; can you help me in this problem.. its kind of similar","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":532,"estimatedTokens":3116}}481{"id":"stack-68404610","source":"stackoverflow","questionId":68404610,"title":"Configure nest-cli.json to include non TS file into the dist folder","tags":["typescript","compilation","handlebars.js","nestjs","mailer"],"text":"Title: Configure nest-cli.json to include non TS file into the dist folder\nTags: typescript, compilation, handlebars.js, nestjs, mailer\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a solution for several hours now:\n\nI'm creating an email service with nestJS and nest mailer.\nEverything work find until I want to include a template with my mail.\nThose templates are hbs files located in src/mail/templates\nI know that nest doesn't include non TS files when compile so:\n\nI tried to configure the nest-cli.json, following this link added :\n\n```\n\"compilerOptions\": {\n\"assets\":[\"**/*.hbs\"],\n\"watchAssets\": true,\n}\n```\n\nOR\n\n```\n\"assets\": [\n { \"include\": \"**/*.hbs\",\"watchAssets\": true },\n]\n```\n\nMy nest-cli.json file looks like this:\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"assets\": [\n { \"include\": \"**/*.hbs\",\"watchAssets\": true },\n ]\n}\n\n}\n```\n\nBut nothing is copied into the dist folder.\nSo I solve this with a modification of the package.json, added a cp command to do it manually but I don't think this is the right way do do it...\nIs anyone figured out include some non TS files with the assets\n\nPS: hbs is for handlebar (mail templating)\n\nThanks for your help :)\n\n========================================\n\nCode:\n```text\n\"compilerOptions\": {\n\"assets\":[\"**/*.hbs\"],\n\"watchAssets\": true,\n}\n```\n\n```text\n\"assets\": [\n  { \"include\": \"**/*.hbs\",\"watchAssets\": true },\n]\n```\n\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n  \"assets\": [\n      { \"include\": \"**/*.hbs\",\"watchAssets\": true },\n    ]\n}\n\n}\n```\n\n```text\n\"assets\": [\n  { \"include\": \"mail/sendbox/\",\"watchAssets\": true },\n]\n```\n\n========================================\n\nComments:\n- Where are your assets located relative to your code ?\n- My assets are in src/mail/templates\n- Okay. For information, the \"include\" is relative to the `sourceRoot` of the project's config in `nest-cli.json`. Could you provide a minimal example of what your `nest-cli.json` looks like ?\n- nest-cli.json added above.","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":94,"estimatedTokens":512}}482{"id":"stack-55095234","source":"stackoverflow","questionId":55095234,"title":"Record won't save to database with Nestjs and TypeOrm (querying works)","tags":["nestjs","typeorm"],"text":"Title: Record won't save to database with Nestjs and TypeOrm (querying works)\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen I post a request, it doesn't save my entity to the database and doesn't report any errors or warnings.\n\nController:\n\n```\n@Controller('recipes')\n\nexport class RecipesController {\n constructor(private readonly recipeService: RecipesService) {}\n @Get()\n async findAll(): Promise {\n return this.recipeService.findAll();\n }\n\n @Post()\n async create(@Body() createRecipeDto: Recipe) {\n this.recipeService.create(createRecipeDto);\n }\n}\n```\n\nService:\n\n```\n@Injectable()\nexport class RecipesService {\n constructor(@InjectRepository(Recipe) private readonly recipeRepository: Repository) {}\n\n async create(recipe: Recipe) {\n const d = await this.recipeRepository.create(recipe);\n console.log(\"d:\", d);\n }\n\n async findAll() {\n return await this.recipeRepository.find();\n }\n}\n```\n\nEntity:\n\n```\n@Entity()\nexport class Recipe {\n @PrimaryGeneratedColumn()\n id: number;\n\n // @IsString()\n @Column()\n name: string;\n\n // @IsString()\n @Column('text')\n description?: string;\n\n // @IsString()\n @Column()\n image: string;\n\n // @IsArray()\n ingredients: string[];\n\n // @IsArray()\n instructions: string[];\n\n // @IsString()\n @Column()\n prepTime?: string;\n\n // @IsString()\n @Column()\n cookTime?: string;\n\n // @IsString()\n @Column()\n yield?: string;\n\n // @IsNumber()\n @Column('int')\n rating?: number;\n\n // @IsArray()\n keywords?: string[];\n\n // @IsArray()\n categories: string[];\n\n // @IsString()\n @Column()\n cuisine?: string;\n\n // @IsBoolean()\n @Column('boolean')\n draft?: boolean;\n}\n```\n\nMy request using Postman:\n\n```\ncurl -X POST \\\n http://localhost:3000/recipes \\\n -H 'Content-Type: application/json' \\\n -H 'Postman-Token: f23b5d42-1c40-4dae-b9b8-b32b733f38b4' \\\n -H 'cache-control: no-cache' \\\n -d '{\n \"name\":\"recipe5\",\n \"description\": \"desc\",\n \"image\": \"http://..\",\n \"ingredients\": [\"-\"],\n \"instructions\": [\"1\"],\n \"prepTime\": \"1:20\",\n \"cookTime\": \"1:00\",\n \"yield\": \"8 servings\",\n \"rating\": 4,\n \"keywords\": [\"1\"],\n \"categories\": [\"cat1\", \"cat2\"],\n \"cuisine\": \"American\",\n \"draft\": false\n}'\n```\n\nIt returns 201.\nMy GET call only returns the entry I created manually.\n\n========================================\n\nCode:\n```text\n@Controller('recipes')\n\nexport class RecipesController {\n  constructor(private readonly recipeService: RecipesService) {}\n  @Get()\n  async findAll(): Promise<Recipe[]> {\n    return this.recipeService.findAll();\n  }\n\n  @Post()\n  async create(@Body() createRecipeDto: Recipe) {\n    this.recipeService.create(createRecipeDto);\n  }\n}\n```\n\n```text\n@Injectable()\nexport class RecipesService {\n    constructor(@InjectRepository(Recipe) private readonly recipeRepository: Repository<Recipe>) {}\n\n    async create(recipe: Recipe) {\n        const d = await this.recipeRepository.create(recipe);\n        console.log(\"d:\", d);\n    }\n\n    async findAll() {\n        return await this.recipeRepository.find();\n    }\n}\n```\n\n```text\n@Entity()\nexport class Recipe {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  //   @IsString()\n  @Column()\n  name: string;\n\n  //   @IsString()\n  @Column('text')\n  description?: string;\n\n  //   @IsString()\n  @Column()\n  image: string;\n\n  //   @IsArray()\n  ingredients: string[];\n\n  //   @IsArray()\n  instructions: string[];\n\n  //   @IsString()\n  @Column()\n  prepTime?: string;\n\n  //   @IsString()\n  @Column()\n  cookTime?: string;\n\n  //   @IsString()\n  @Column()\n  yield?: string;\n\n  //   @IsNumber()\n  @Column('int')\n  rating?: number;\n\n  //   @IsArray()\n  keywords?: string[];\n\n  //   @IsArray()\n  categories: string[];\n\n  //   @IsString()\n  @Column()\n  cuisine?: string;\n\n  //   @IsBoolean()\n  @Column('boolean')\n  draft?: boolean;\n}\n```\n\n```text\ncurl -X POST \\\n  http://localhost:3000/recipes \\\n  -H 'Content-Type: application/json' \\\n  -H 'Postman-Token: f23b5d42-1c40-4dae-b9b8-b32b733f38b4' \\\n  -H 'cache-control: no-cache' \\\n  -d '{\n    \"name\":\"recipe5\",\n    \"description\": \"desc\",\n    \"image\": \"http://..\",\n    \"ingredients\": [\"-\"],\n    \"instructions\": [\"1\"],\n    \"prepTime\": \"1:20\",\n    \"cookTime\": \"1:00\",\n    \"yield\": \"8 servings\",\n    \"rating\": 4,\n    \"keywords\": [\"1\"],\n    \"categories\": [\"cat1\", \"cat2\"],\n    \"cuisine\": \"American\",\n    \"draft\": false\n}'\n```\n\n```text\nconst d = await this.recipeRepository.create(recipe);\n```\n\n```text\nconst d = await this.recipeRepository.save(recipe);\n```\n\n```text\nRepository.save\n```\n\n========================================\n\nComments:\n- I wish the NestJS documentation made this clear..","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":261,"estimatedTokens":1122}}483{"id":"stack-61687679","source":"stackoverflow","questionId":61687679,"title":"Nest JS build does does not generate the dist folder","tags":["node.js","nestjs"],"text":"Title: Nest JS build does does not generate the dist folder\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have implemented rest api project with nest js.it is working fine on local environment.(pm start)\n\nI want to build it and deploy. but build command does not generate the dust folder. following is my configurations\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es6\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true,\n \"allowJs\": true,\n \"checkJs\": true, \n \"noEmit\": true\n },\n \"exclude\": [\"node_modules\"],\n \"paths\": {\n \"@app/*\": [\"src/*\"],\n \"@test/*\": [\"test/*\"]\n }\n}\n```\n\npackage.json\n\n```\n\"scripts\": {\n \"build\": \"tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n \"start\": \"npm run start:prod\",\n \"start:dev\": \"concurrently --handle-input \\\"wait-on dist/main.js && nodemon\\\" \\\"tsc -w -p tsconfig.build.json\\\" \",\n \"start:prod\": \"node dist/src/main.js\",\n \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n \"gcp-build\": \"npm run build\"\n }\n```\n\nwhen I execute the `npm run build` nothing happens. no errors. no dist folder.\ncan any one help me to fix this issue?\n\n========================================\n\nTop Answer:\nHad the same issue, the problem is TS compiler won't generate `/dist` (compile JS to TS) if there're some `.tsbuildinfo` files (when `incremental` option is on).\n\nSo, basically what you need to do is remove all `.tsbuildinfo` files before you build the project.\n\nOr simply turn off the `incremental` and `noEmit` options in your tsconfig.json:\n\n```\n\"noEmit\": false // <- remove this or set to false\n\"incremental\": false, // <- remove this or set to false\n```\n\n========================================\n\nCode:\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es6\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"resolveJsonModule\": true,\n    \"esModuleInterop\": true,\n    \"allowJs\": true,\n    \"checkJs\": true, \n    \"noEmit\": true\n  },\n  \"exclude\": [\"node_modules\"],\n  \"paths\": {\n    \"@app/*\": [\"src/*\"],\n    \"@test/*\": [\"test/*\"]\n  }\n}\n```\n\n```text\n\"scripts\": {\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n    \"start\": \"npm run start:prod\",\n    \"start:dev\": \"concurrently --handle-input \\\"wait-on dist/main.js && nodemon\\\" \\\"tsc -w -p tsconfig.build.json\\\" \",\n    \"start:prod\": \"node dist/src/main.js\",\n    \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n    \"gcp-build\": \"npm run build\"\n  }\n```\n\n```text\nnpm run build\n```\n\n```text\n\"typescript\": \"3.7.2\",\n```\n\n```text\n\"noEmit\": false       // <- remove this or set to false\n\"incremental\": false, // <- remove this or set to false\n```\n\n```text\n/dist\n```\n\n```text\n.tsbuildinfo\n```\n\n```text\nincremental\n```\n\n```text\n.tsbuildinfo\n```\n\n```text\nincremental\n```\n\n```text\nnoEmit\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"deleteOutDir\": false\n  }\n}\n```\n\n```text\ndist            // or your chosen output directory\n*.tsbuildinfo\n```\n\n```text\nstart:dev\n```\n\n```text\ndeleteOutDir\n```\n\n```text\nfalse\n```\n\n```text\nnest-cli.json\n```\n\n```text\n.gitignore\n```\n\n```text\n--watch\n```\n\n```text\n.tsbuildinfo\n```\n\n========================================\n\nComments:\n- Do you have any `tsconfig.buildinfo` files? If so, try deleting those. Sometimes those can make an incremental build have problems regenerating the dist\n- @JayMcDoniel No I don't have tsconfig.buildinfo files\n- Try changing the build script to - \"nest build\"\n- This should be correct answer. I'm on `typescript: ^4.7.4, nest: 9`\n- Solved the same problem for me\n- huge thank you. This stopped working after migrating to a turborepo with a shared typescript config, I couldn't figure out which settings were the culprits.\n- Solved my issue. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":209,"estimatedTokens":1148}}484{"id":"stack-73419905","source":"stackoverflow","questionId":73419905,"title":"Using import for an ESM Module in nest.js gives [ERR_REQUIRE_ESM]: require() of ES Module not supported","tags":["typescript","nestjs"],"text":"Title: Using import for an ESM Module in nest.js gives [ERR_REQUIRE_ESM]: require() of ES Module not supported\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use nest.js with typescript and wanted to add\n\n```\nimport { DRACOLoader, GLTFLoader, TextureLoader } from 'node-three-gltf';\n```\n\nin one of my modules. However that results in below error\n\n```\nc:\\m3\\dist\\src\\gltftest\\gltftest.controller.js:23\nconst node_three_gltf_1 = require(\"node-three-gltf\");\n ^\nError [ERR_REQUIRE_ESM]: require() of ES Module c:\\m3\\node_modules\\node-three-gltf\\build\\index.js from c:\\m3\\dist\\src\\gltftest\\gltftest.controller.js not supported.Instead change the require of index.js in c:\\m3\\dist\\src\\gltftest\\gltftest.controller.js to a dynamic import() which is available in all CommonJS modules.\n at Object. (c:\\m3\\dist\\src\\gltftest\\gltftest.controller.js:23:27)\n at Object. (c:\\m3\\dist\\src\\gltftest\\gltftest.module.js:12:30)\n```\n\nAnd node-three-gltf@1.0.3 which I use is just an esm module. Resulting in the (at least to me - fairly new to this suff) weird situation of me using ESM import syntax in my typescript module/controller to import the ESM module node-three-gltf and getting this error.\n\nSeems to be due to the fact that nest.js build of my project transforms my ES syntax to CJS syntax and thus replaces my import with require but does not transform the node-three-gltf module and then complains.\n\nmy tsconfig goes like this:\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"moduleResolution\": \"Node\",\n \"target\": \"esnext\",\n...\n```\n\nTheoretically I see the following options:\n\n- ensure i build everything as ESM ( I tried that via setting module in my tsconfig to ES2020 and adding \"type\":\"module\" to my package.json which then lead to a new import error for a different dependency (\n\nnode_modules\\connect-typeorm\\out' is not supported resolving ES\nmodules imported from C:\\m3\\dist\\src\\main.js Did you mean to import\nconnect-typeorm/out/index.js?\n\n- make sure the node-three-gltf provides a cjs version as build, for which it appears I could raise a PR but would need to undestand the build tools fo that dependency, so not really good option\n\n- upgrade to node-three-gltf@1.10.0 as that has a cjs export but which however requires Node 18 which I cannot use in production at this time for reasons out of my control\n\n- adapt the nest.js build in way that it does transform esm dependencies to cjs - which I don't know how to do.\n\nSo I wonder if sb can advise me on how to adjust the nest.js build config to do the esm->cjs transformation for dependencies or point me in another direction?\n\nThanks!\nT\n\n========================================\n\nCode:\n```text\nimport { DRACOLoader, GLTFLoader, TextureLoader } from 'node-three-gltf';\n```\n\n```text\nc:\\m3\\dist\\src\\gltftest\\gltftest.controller.js:23\nconst node_three_gltf_1 = require(\"node-three-gltf\");\n                          ^\nError [ERR_REQUIRE_ESM]: require() of ES Module c:\\m3\\node_modules\\node-three-gltf\\build\\index.js from c:\\m3\\dist\\src\\gltftest\\gltftest.controller.js not supported.Instead change the require of index.js in c:\\m3\\dist\\src\\gltftest\\gltftest.controller.js to a dynamic import() which is available in all CommonJS modules.\n    at Object.<anonymous> (c:\\m3\\dist\\src\\gltftest\\gltftest.controller.js:23:27)\n    at Object.<anonymous> (c:\\m3\\dist\\src\\gltftest\\gltftest.module.js:12:30)\n```\n\n```text\n{\n   \"compilerOptions\": {\n      \"module\": \"commonjs\",\n      \"moduleResolution\": \"Node\",\n      \"target\": \"esnext\",\n...\n```\n\n```text\nimport()\n```\n\n========================================\n\nComments:\n- I saw that `node-three-gltf@1.1.0` exposes a CJS version. I didn't get why your app is loading the ESM one. Regarding ESM support on Nestjs, see: github.com/nestjs/nest/pull/8736\n- @MicaelLevi The reason is that for production I can only use Node 16 at this time and since node-three-gltf@1.1.0 requires Node 18 I cannot use that. Reason seems to be that fetch is out of the box with Node 18 whch is used by node-three-gltf@1.1.0. Thus the option of using node-three-gltf@1.0.3 adjusting the build as in 1.1.0 and raising a PR but there must be an easier way - especially since I have no clue about roll-up","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":1046}}485{"id":"stack-59368042","source":"stackoverflow","questionId":59368042,"title":"How to enable NestJs swagger 4.x plugin","tags":["nestjs"],"text":"Title: How to enable NestJs swagger 4.x plugin\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nHow do you use the new swagger plugin? I have it in my compiler options:\n\n```\n\"compilerOptions\": {\n \"plugins\": [\"@nestjs/swagger/plugin\"]\n }\n```\n\nAnd I am running the application with `nest start` as described: https://docs.nestjs.com/recipes/swagger#migration-to-40\n\nHowever, no automated-magic documentation appears to be happening.\n\n========================================\n\nTop Answer:\nMy fix was...\n\nThe plugin filters the files it looks up based on a suffix rule.\n\n- If you use a different naming convention than Angular's, you need to pass custom plugin options to fix it;\n\n- If your controller or Dto is not inside a file with the name suffix, it wont be upgraded.\n\n========================================\n\nCode:\n```text\n\"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger/plugin\"]\n  }\n```\n\n```text\nnest start\n```\n\n```text\n\"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger/plugin\"]\n  }\n```\n\n```text\nincremental\n```\n\n```text\nyarn global upgrade upgrade @nestjs/cli\n```\n\n```text\nnpm update -g @nestjs/cli\n```\n\n```text\nnest update\n```\n\n```text\nnest-cli.json\n```\n\n```text\nnest start\n```\n\n```text\nnest start:dev\n```\n\n```text\n\"plugins\": [\n  \"node_modules/@nestjs/swagger/plugin\"\n]\n```\n\n```text\nreflect-metadata\n```\n\n========================================\n\nComments:\n- I'm trying to reproduce your environment with a basic est ew project with swagger ad I'm rather getting the error: Error \"@nestjs/swagger/plugin\" plugin could not be found! Can you please provide your package.json, did you istall the swagger plugin....\n- Please precise that we should run `nest start` to start the server. I was actually running `npm run start:dev` (which use nodemon) and it was not working. Now everything is OK, thanks !\n- I did all the steps, used a file named *.dto.ts, and it's still not working : /\n- Very helpful answer, this solved my problem. It works with and without watch-mode for me now.\n- Removing the /dist/ folder and starting again solved my problem, with and without the watch flag\n- As of now, only `\"plugins\": [\"@nestjs&#47;swagger\"]`is necessary.\n- after following all the steps, it is still not working for me, can anybody guide me what am i missing here?\n- In my case, the issue was that the DTOs were defined in a file whose name did not end with `.dto.ts`.\n- Deleting the dist fixed my issue (after successfully wasted hours on it)\n- since nest v9.0.0 the nest update command was removed. Alternative ways to update can be found here: stackoverflow.com/a/57512819/16360249\n- You just saved me from going crazy, had the DTO inlined for testing... I was close to getting mad.","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":99,"estimatedTokens":673}}486{"id":"stack-66448619","source":"stackoverflow","questionId":66448619,"title":"Use data from .env file in main.ts - NestJS","tags":["node.js","environment-variables","nestjs"],"text":"Title: Use data from .env file in main.ts - NestJS\nTags: node.js, environment-variables, nestjs\nSource: Stack Overflow\n\nQuestion:\nNestJS allows us to read .env file through ConfigModule and I can do that easily in my modules with code like following\n\n```\n@Module({\n imports: [ConfigModule.forRoot()],\n providers: [\n NVFullNameSearchService,\n NVPartialNameSearchService,\n NVPersistService,\n ],\n controllers: [NvController],\n})\n```\n\nBut above code is more to deal within modules, how can I read content from .env file in main.ts. Say I need to set port and host for my Redis service?\n\n```\nconst microserviceOptions = {\n name: 'plscorecard',\n transport: Transport.REDIS,\n options: {\n url: 'redis://localhost:6379',\n },\n};\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(\n NVModule,\n microserviceOptions,\n );\n app.listen(() => {\n logger.log('NameVerification Redis microservice is listening ... ');\n });\n}\nbootstrap();\n```\n\nAs you can see app is yet to be created in this case. Should I directly use dotenv? As you'd expect in any enterprise environment, I have different env files for DEV, QA, UAT and Production. What's the easiest/right way to achieve it?\n\n========================================\n\nTop Answer:\nThe easiest solution is actually to just import dotenv and initiialize it immediately after. It is particulary important that these are the first two things you do in your main.ts, like this:\n\n```\nimport * as dotenv from 'dotenv';\ndotenv.config();\nimport ...\n...\nasync function bootstrap(){\n...\n}\n```\n\nNo config module is needed to access variables in a .env file after doing that.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [ConfigModule.forRoot()],\n  providers: [\n    NVFullNameSearchService,\n    NVPartialNameSearchService,\n    NVPersistService,\n  ],\n  controllers: [NvController],\n})\n```\n\n```text\nconst microserviceOptions = {\n  name: 'plscorecard',\n  transport: Transport.REDIS,\n  options: {\n    url: 'redis://localhost:6379',\n  },\n};\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice(\n    NVModule,\n    microserviceOptions,\n  );\n  app.listen(() => {\n    logger.log('NameVerification Redis microservice is listening ... ');\n  });\n}\nbootstrap();\n```\n\n```text\n**app.module.ts**\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n      envFilePath: `config/${process.env.NODE_ENV}.env`,\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n**main.ts**\nimport { Logger } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Transport } from '@nestjs/microservices';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\n\nasync function bootstrap() {\n  const logger = new Logger('main');\n  const app = await NestFactory.create(AppModule);\n  const configService = app.get(ConfigService);\n  const REDIS_HOST = configService.get<string>('REDIS_HOST');\n  const REDIS_PORT = configService.get<number>('REDIS_PORT');\n  const microserviceOptions = {\n    transport: Transport.REDIS,\n    options: {\n      url: `redis://${REDIS_HOST}:${REDIS_PORT}`,\n    },\n  };\n  app.connectMicroservice(microserviceOptions);\n  const PORT = configService.get<number>('PORT');\n  const environment = configService.get<string>('NODE_ENV');\n  const title = configService.get<string>('ENVIRONMENT_TITLE');\n  await app.listen(PORT);\n  logger.log(\n    `${environment}, Microservice ready to receive Redis messages in PORT - ${PORT}\\n Environment - ${title}`,\n  );\n}\nbootstrap();\n```\n\n```js\nimport * as dotenv from 'dotenv';\ndotenv.config();\nimport ...\n...\nasync function bootstrap(){\n...\n}\n```\n\n```js\nimport { ConfigurationService } from './core/configuration/configuration.service';\n\nasync function bootstrap() {\n  const configurationService = app.get(ConfigurationService);\n\n  await app.listen(configurationService.expressPort);\n}\n```\n\n```text\nmain.ts\n```\n\n```text\napp.get()\n```\n\n```text\ndotenv\n```\n\n```text\n@nestjs/config\n```\n\n```text\nMongooseModule\n```\n\n```text\n.env\n```\n\n```text\ndotenv\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\n{\n  // For production\n  \"start\": \"nest start\",\n\n  // For local development\n  \"start:dev\": \"env-cmd -f ./.env nest start\"\n}\n```\n\n```text\nimport { ConfigService } from \"@nestjs/config\";\nasync function bootstrap() {\n  const configService = app.get(ConfigService);\n  const port = configService.get(\"PORT\") || 8000;\n  await app.listen(port);\n}\n```\n\n========================================\n\nComments:\n- did you ever tried the approach that nestjs's docs covers?\n- Does this answer your question? How to use config module on main.ts file\n- Nest has a doc session for that: docs.nestjs.com/techniques/configuration#using-in-the-maints\n- The Best Solution! I needed env variables before instance app. Thanks!\n- I prefer this approach as well. However, if `ConfigurationService` doesn't load the env vars while initialising (in the constructor), this won't work. The `port` is assigned when the Nest core bootstrapping starts (1st step) and other lifecycle events come after that. So if one is reading the env vars onModuleInit or onApplicationBootstrap, `expressPort` would be `NaN`. To get it to work, either call a method of the `configurationService` to load and assign env vars, so calling `configurationService.expressPort` gives us the port#. Or use `ConfigService` as the answer suggests.","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":230,"estimatedTokens":1406}}487{"id":"stack-53649032","source":"stackoverflow","questionId":53649032,"title":"Type of object received during file upload using @UploadFile","tags":["javascript","node.js","file-upload","multer","nestjs"],"text":"Title: Type of object received during file upload using @UploadFile\nTags: javascript, node.js, file-upload, multer, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn the REST API below, what is the type of file object that is received. \n\n```\n@Post('/:folderId/documents/:fileName')\n@UseInterceptors(FileInterceptor('file'))\n@ApiConsumes('multipart/form-data')\n@ApiImplicitParam({ name: 'folderId', description: ' Folder Id' })\n@ApiImplicitParam({ name: 'fileName', description: ' File Name' })\n@ApiImplicitFile({ name: 'file', required: true, description: 'PDF File' })\nasync uploadFile(@UploadedFile() file, @Param() folderId, @Param() fileName) {\n/**\n * I need to know the type of file object (first argument) of uploadFile\n */\n this.folderService.uploadFile(file, folderId, fileName);\n}\n```\n\nI need to write a file received in the request to disk. How to do that?\n\n========================================\n\nTop Answer:\nYou can import the type from the package. `'@types/multer'` and then qualify the file as:\n\n```\n@UploadedFile() file: Express.Multer.File,\n```\n\nhttps://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/multer/index.d.ts#L103\n\n========================================\n\nCode:\n```text\n@Post('/:folderId/documents/:fileName')\n@UseInterceptors(FileInterceptor('file'))\n@ApiConsumes('multipart/form-data')\n@ApiImplicitParam({ name: 'folderId', description: ' Folder Id' })\n@ApiImplicitParam({ name: 'fileName', description: ' File Name' })\n@ApiImplicitFile({ name: 'file', required: true, description: 'PDF File' })\nasync uploadFile(@UploadedFile() file, @Param() folderId, @Param() fileName) {\n/**\n * I need to know the type of file object (first argument) of uploadFile\n */\n    this.folderService.uploadFile(file, folderId, fileName);\n}\n```\n\n```text\n// files will be saved in the /uploads folder\n@UseInterceptors(FileInterceptor('file', {dest: 'uploads'}))\n```\n\n```text\nimport { diskStorage } from 'multer';\n\nexport const myStorage = diskStorage({\n  // Specify where to save the file\n  destination: (req, file, cb) => {\n    cb(null, 'uploads');\n  },\n  // Specify the file name\n  filename: (req, file, cb) => {\n    cb(null, Date.now() + '-' + file.originalname);\n  },\n});\n```\n\n```text\n@UseInterceptors(FileInterceptor('file', {storage: myStorage}))\n```\n\n```text\nMulterOptions\n```\n\n```text\ndiskStorage\n```\n\n```text\nstorage\n```\n\n```text\n@UploadedFile() file: Express.Multer.File,\n```\n\n```text\n'@types/multer'\n```\n\n```text\n@Post(':userid/avatar')\n    @UseInterceptors(FileInterceptor('file',\n      {\n        storage: diskStorage({\n          destination: './avatars', \n          filename: (req, file, cb) => {\n          const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')\n          return cb(null, `${randomName}${extname(file.originalname)}`)\n        }\n        })\n      }\n    )\n    )\n    uploadAvatar(@Param('userid') userId, @UploadedFile() file) {\n      this.userService.setAvatar(Number(userId), `${this.SERVER_URL}${file.path}`);\n    }\n```\n\n========================================\n\nComments:\n- Did you figured out the type of file object?\n- These are 2 separated questions.\n- npm i -D @types/multer","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":122,"estimatedTokens":794}}488{"id":"stack-60758496","source":"stackoverflow","questionId":60758496,"title":"typeorm querybuilder: select relation of relation only","tags":["sql","node.js","nestjs","typeorm"],"text":"Title: typeorm querybuilder: select relation of relation only\nTags: sql, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nSo I have those entities:\n\n```\nGroup {\n id: number;\n name: string;\n persons: Person[];\n}\n\nPerson {\n name: string;\n items: Item[];\n}\n\nItem {\n name: string;\n active: boolean;\n}\n```\n\n**What I have avaible**: an array of group id's `groupIds`.\n\n**My Goal**: To get an array of `Item` but only the one that are containt in a group that `group.id` is within the group array I have and also that have the property `active` `true`.\n\nI tried to build a querybuilder like this:\n\n```\nthis.groupRepository.createQueryBuilder('group')\n .innerJoin('group.persons', 'persons')\n .innerJoinAndSelect('persons.items', 'items')\n .where({'items.active': true, 'group.id': In(groupIds)})\n .getMany();\n```\n\nBut I only get an array of `group` (without any relations) that have a valid `item` in it.\n\nWhat do I Need to Change, if this is even possible with a single query?\n\n========================================\n\nCode:\n```text\nGroup {\n    id: number;\n    name: string;\n    persons: Person[];\n}\n\nPerson {\n    name: string;\n    items: Item[];\n}\n\nItem {\n    name: string;\n    active: boolean;\n}\n```\n\n```text\nthis.groupRepository.createQueryBuilder('group')\n                      .innerJoin('group.persons', 'persons')\n                      .innerJoinAndSelect('persons.items', 'items')\n                      .where({'items.active': true, 'group.id': In(groupIds)})\n                      .getMany();\n```\n\n```text\ngroupIds\n```\n\n```text\nItem\n```\n\n```text\ngroup.id\n```\n\n```text\nactive\n```\n\n```text\ntrue\n```\n\n```text\ngroup\n```\n\n```text\nitem\n```\n\n```text\nthis.groupRepository.createQueryBuilder('group')\n   .leftJoinAndSelect('group.persons', 'persons')\n   .leftJoinAndSelect('persons.items', 'items')\n   .where('items.active =:active', {active: true})\n   .andWhere('group.id IN (:...groupIds)', {groupIds})       \n   .getMany();\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":108,"estimatedTokens":484}}489{"id":"stack-58077788","source":"stackoverflow","questionId":58077788,"title":"Nest.js: initialization of property from controller's superclass","tags":["javascript","typescript","testing","jestjs","nestjs"],"text":"Title: Nest.js: initialization of property from controller's superclass\nTags: javascript, typescript, testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a question regarding unit testing controllers in Nest.js framework. Problem is that property from a superclass is not initialized in the controller class when creating a test module.\n\nThis is a sample code I'm talking about:\n\n```\nexport class MyController extends SomeOtherController {\n\n // Inherited from SomeOtherController\n async initSomeObject() {\n this.someObject = await initializeThisSomehow();\n }\n\n async controllerMethod(args: string) {\n // Do something\n }\n\n}\n\nexport abstract class SomeOtherController implements OnModuleInit {\n\n protected someObject: SomeObject;\n\n async onModuleInit() {\n await this.initSomeObject();\n }\n\n abstract async initSomeObject(): Promise;\n}\n```\n\nAnd this is how I've created my test\n\n```\ndescribe('MyController', () => {\n let module: TestingModule;\n let controller: MyController;\n let service: MyService;\n\n beforeEach(async () => {\n module = await Test.createTestingModule({\n imports: [],\n controllers: [MyController],\n providers: [\n MyService,\n {\n provide: MyService,\n useFactory: () => ({\n controllerMethod: jest.fn(() => Promise.resolve()),\n }),\n },\n ],\n }).compile();\n\n controller = module.get(MyController);\n service = module.get(MyService);\n });\n\n describe('controller method', () => {\n it('should do something', async () => {\n jest.spyOn(service, 'controllerMethod').mockImplementation(async _ => mockResult);\n expect(await controller.controllerMethod(mockArgs)).toBe(mockResult);\n });\n });\n});\n```\n\nNow, if I were to run the application in development mode, the `someObject` property would get initialized, and code works. But when running tests, it seems like the test module is not initializing it (so it is undefined).\n\nAny sort of help is much appreciated.\n\n========================================\n\nCode:\n```js\nexport class MyController extends SomeOtherController {\n\n    // Inherited from SomeOtherController\n    async initSomeObject() {\n        this.someObject = await initializeThisSomehow();\n    }\n\n    async controllerMethod(args: string) {\n        // Do something\n    }\n\n}\n\nexport abstract class SomeOtherController implements OnModuleInit {\n\n    protected someObject: SomeObject;\n\n    async onModuleInit() {\n        await this.initSomeObject();\n    }\n\n    abstract async initSomeObject(): Promise<void>;\n}\n```\n\n```js\ndescribe('MyController', () => {\n  let module: TestingModule;\n  let controller: MyController;\n  let service: MyService;\n\n  beforeEach(async () => {\n    module = await Test.createTestingModule({\n      imports: [],\n      controllers: [MyController],\n      providers: [\n        MyService,\n        {\n          provide: MyService,\n          useFactory: () => ({\n            controllerMethod: jest.fn(() => Promise.resolve()),\n          }),\n        },\n      ],\n    }).compile();\n\n    controller = module.get(MyController);\n    service = module.get(MyService);\n  });\n\n  describe('controller method', () => {\n    it('should do something', async () => {\n      jest.spyOn(service, 'controllerMethod').mockImplementation(async _ => mockResult);\n      expect(await controller.controllerMethod(mockArgs)).toBe(mockResult);\n    });\n  });\n});\n```\n\n```text\nsomeObject\n```\n\n```text\nawait module.init(); // this is where onModuleInit is called\n```\n\n```text\nafterEach(async () => await module.close());\n```\n\n========================================\n\nComments:\n- Where is `initStuff()` (`SomeOtherController`) called?\n- My code was missing crucial details: the `initStuff()` method is actually called `onModuleInit()` and it comes from the `OnModuleInit` interface which is part of `@nestjs&#47;common`. I apologize for making a mistake of not being more careful. Question is updated.","metadata":{"transformedAt":"2026-08-18T18:33:02.447Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":155,"estimatedTokens":952}}490{"id":"stack-50977202","source":"stackoverflow","questionId":50977202,"title":"NestJS JwtStrategy use configService to pass secret key","tags":["typescript","nestjs","passport-jwt"],"text":"Title: NestJS JwtStrategy use configService to pass secret key\nTags: typescript, nestjs, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nI have the JwtStrategy class from docs example (https://docs.nestjs.com/techniques/authentication):\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n private readonly authService: AuthService,\n private readonly configService: ConfigService,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: this.configService.getSecretKey,\n });\n }\n // ...\n}\n```\n\nWhen I am trying access `this` before calling super() I get an error. But I still want to use configService to get secret key. \n\nI know that I can use env var to do that, but service approach is more clearer solution, in my opinion. \n\nHow can I use configService or maybe get value from it and pass to super() call? Thanks.\n\n========================================\n\nTop Answer:\nin nestjs v10.0.0 this can be achived like this\n\n**jwt.strategy.ts**\n\n```\nexport class JwtStrategy extends PassportStrategy(PassportJwtStrategy) {\n constructor(\n private readonly authService: AuthService,\n @Inject(ConfigService) private readonly configService: ConfigService, // **app.module.ts**\n\n```\n@Module({\n imports: [\n UserModule,\n ConfigModule.forRoot({\n validationSchema: envValidationSchema,\n isGlobal: true, // <- * register the config module globally\n validationOptions: {\n allowUnknown: true,\n abortEarly: true,\n },\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor(\n        private readonly authService: AuthService,\n        private readonly configService: ConfigService,\n    ) {\n        super({\n            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n            secretOrKey: this.configService.getSecretKey,\n        });\n    }\n    // ...\n}\n```\n\n```text\nthis\n```\n\n```text\nsecretOrKey: configService.getSecretKey\n```\n\n```text\nthis.\n```\n\n```text\nconfigService\n```\n\n```text\nexport class JwtStrategy extends PassportStrategy(PassportJwtStrategy) {\n  constructor(\n    private readonly authService: AuthService,\n    @Inject(ConfigService) private readonly configService: ConfigService, // <- injected config service here\n  ) {\n    console.log(`${configService.get('JWT_SECRET')}`);\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: configService.getOrThrow('JWT_SECRET'), // <- using config service inside the super constructor\n    });\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n    UserModule,\n    ConfigModule.forRoot({\n      validationSchema: envValidationSchema,\n      isGlobal: true, // <- * register the config module globally\n      validationOptions: {\n        allowUnknown: true,\n        abortEarly: true,\n      },\n    }),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- Using nestjs version 9 it is not working\n- To avoid \"Property 'configService' is declared but its value is never read.\" I also had to drop the `private` from `private readonly configService: ConfigService`.\n- I can confirm, you cannot have `private` keyword and use that property in the `super()` call within `constructor`\n- To add on the above answer and comment, replace `private` with `protected`\n- But nothing said here helped to me. I have the same code.","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":139,"estimatedTokens":884}}491{"id":"stack-65929178","source":"stackoverflow","questionId":65929178,"title":"Logout JWT with nestJS","tags":["nestjs","passport-jwt"],"text":"Title: Logout JWT with nestJS\nTags: nestjs, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nI'm using JWT passaport to login module:\n\n```\nasync validateUser(userEmail: string, userPassword: string) {\n const user = await this.userService.findByEmail(userEmail);\n if (user && user.password === userPassword) {\n const { id, name, email } = user;\n return { id: id, name, email };\n }else {\n throw new UnauthorizedException({\n error: 'Incorrect username or password'\n });\n }\n }\n\n async login(user: any) {\n const payload = { email: user.email, sub: user.id };\n return {\n access_token: this.jwtService.sign(payload),\n };\n }\n```\n\nThis part is running.\nMy question is: how do the logout? I read about creating a blacklist and adding the token to it, but how do I get the user's access token?\n\n========================================\n\nTop Answer:\nGenerally when a logout request would be sent the `Authorization` header should be present, so you can grab the token from there. Then you can save the token to the database's restrict list table.\n\n========================================\n\nCode:\n```js\nasync validateUser(userEmail: string, userPassword: string) {\n    const user = await this.userService.findByEmail(userEmail);\n    if (user && user.password === userPassword) {\n      const { id, name, email } = user;\n      return { id: id, name, email };\n    }else {\n      throw new UnauthorizedException({\n        error: 'Incorrect username or password'\n      });\n    }\n  }\n\n  async login(user: any) {\n    const payload = { email: user.email, sub: user.id };\n    return {\n      access_token: this.jwtService.sign(payload),\n    };\n  }\n```\n\n```text\nAuthorization\n```\n\n```text\nconst tokenVarify = await this.jwtService.verify(token);\n```\n\n========================================\n\nComments:\n- If you delete the token at client-side, that token is still valid and can be used by a malicious user who has copied it before!\n- @Kreshnik JWT tokens expire extremely quickly. So, usually within minutes. So, the likelihood of a token being misused is very small.\n- The best solution for you is to set the token time to maybe 5 minutes and implement a refresh token that is valid for 7 days. Inside your refresh token generation logic, you can check in your database if that user still has the right to access your API or not before generating a new token for him\n- how can we achieve this ??\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":76,"estimatedTokens":663}}492{"id":"stack-70730514","source":"stackoverflow","questionId":70730514,"title":"Unable to connect to the database. Retrying","tags":["node.js","typescript","mongodb","mongoose","nestjs"],"text":"Title: Unable to connect to the database. Retrying\nTags: node.js, typescript, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to connect to the database, seems like the set-up is correct, but for some reason, it says that it is not available.\n\n`app.module.ts`\n\n```\nimport { Module } from \"@nestjs/common\"\nimport { MongooseModule } from \"@nestjs/mongoose\";\nimport { ConfigModule } from \"../config\";\nimport { CreatorModule } from \"./creator.module\";\n\n@Module({\n imports: [\n MongooseModule.forRoot('mongodb://localhost:27017/snaptoon', {\n useCreateIndex: true,\n useUnifiedTopology: true,\n useNewUrlParser: true,\n }),\n CreatorModule,\n ],\n controllers: [],\n providers: []\n})\n\nexport class AppModule {}\n```\n\nThe error is: `ERROR [MongooseModule] Unable to connect to the database. Retrying (9)...`\n\nI'm using `'@nestjs/mongoose': '9.0.2'`\n\n========================================\n\nTop Answer:\nUse `mongodb://127.0.0.1:27017/snaptoon` instead of `mongodb://localhost:27017/snaptoon` as connection string. It worked for me.\n\n========================================\n\nCode:\n```text\nimport { Module } from \"@nestjs/common\"\nimport { MongooseModule } from \"@nestjs/mongoose\";\nimport { ConfigModule } from \"../config\";\nimport { CreatorModule } from \"./creator.module\";\n\n@Module({\n    imports: [\n        MongooseModule.forRoot('mongodb://localhost:27017/snaptoon', {\n            useCreateIndex: true,\n            useUnifiedTopology: true,\n            useNewUrlParser: true,\n        }),\n        CreatorModule,\n    ],\n    controllers: [],\n    providers: []\n})\n\nexport class AppModule {}\n```\n\n```text\napp.module.ts\n```\n\n```text\nERROR [MongooseModule] Unable to connect to the database. Retrying (9)...\n```\n\n```text\n'@nestjs/mongoose': '9.0.2'\n```\n\n```text\nWARN @nestjs/mongoose@9.0.2 requires a peer of mongoose@^6.0.2 but none is installed. You must install peer dependencies yourself.\n```\n\n```text\nnpm install mongoose@6.2.2 --save\n```\n\n```text\nnestjs/mongoose\n```\n\n```text\nuseNewUrlParser: true\n```\n\n```js\nMongooseModule.forRoot(\n  `mongodb://${host}:${port}/${dbName}`,\n),\n```\n\n```js\nMongooseModule.forRoot(\n  `mongodb://${host}:${port}/${dbName}?directConnection=true`,\n),\n```\n\n```text\n\"@nestjs/mongoose\": \"^8.0.0\"\n```\n\n```text\n\"@nestjs/mongoose\": \"^9.0.0\"\n```\n\n```text\nmongodb://127.0.0.1:27017/snaptoon\n```\n\n```text\nmongodb://localhost:27017/snaptoon\n```\n\n```text\n?authSource=admin&directConnection=true\n```\n\n```text\nmongodb://username:password@host:port/dbname?authSource=admin&directConnection=true\n```\n\n```text\nMongoParseError: Password contains unescaped characters\n```\n\n```text\nencodeURIComponent\n```\n\n```text\nmongodb://username:${encodeURIComponent(password)}@host:port/dbname?authSource=admin&directConnection=true\n```\n\n```text\nuseCreateIndex: true\n```\n\n```text\nuseCreateIndex: undefined\n```\n\n```text\nMongooseModule.forRoot()\n```\n\n```text\nlocalhost\n```\n\n```text\n::1:\n```\n\n```text\n127.0.0.1\n```\n\n```text\n127.0.0.1\n```\n\n```text\nmongodb://127.0.0.1:27017/snaptoon\n```\n\n```text\nmongodb+srv://<DataBaseName>:<password>@<clusterName>.gsr9ucc.mongodb.net/?retryWrites=true&w=majority\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { CatModule } from './cat/cat.module';\n\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://127.0.0.1:27017/nest', {\n      useNewUrlParser: true, useUnifiedTopology: true\n    }),\n    CatModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { CatController } from './cat.controller';\nimport { CatService } from './cat.service';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { Cat, CatSchema } from './cat.model';\n\n@Module({\n  imports: [\n    MongooseModule.forFeature([\n      { name: Cat.name, schema: CatSchema },\n    ])\n  ],\n  controllers: [CatController],\n  providers: [CatService]\n})\nexport class CatModule { }\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectConnection, InjectModel } from '@nestjs/mongoose';\nimport { Cat, CatDocument } from './cat.model';\nimport { Connection, Model } from 'mongoose';\nimport { CreateCatDto } from './dto/create-cat.dto';\n\n@Injectable()\nexport class CatService {\n    constructor(\n        @InjectModel(Cat.name) private catModel: Model<CatDocument>) { }\n}\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from \"@nestjs/mongoose\";\nimport { Document } from 'mongoose';\n\nexport type CatDocument = Cat & Document;\n\n@Schema()\nexport class Cat {\n    @Prop()\n    id: number;\n\n    @Prop()\n    name: string;\n\n    @Prop()\n    health: string;\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\n========================================\n\nComments:\n- Have you been able to connect to the database from CLI?\n- Considered using forRootAsync: `MongooseModule.forRootAsync({ useFactory: () => ({ uri: 'mongodb:&#47;&#47;localhost:27017&#47;snaptoon', }), }),`\n- There are 10 retries that the connection goes through by default. After the tenth, the full error is printed out. Most likely, your version of mongo does not support one or more of the options you are passing\n- In my case, I removed `useCreateIndex:true` and it connected.\n- Mongose 6 are no longer to support the options: useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex. Cause useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. mongoosejs.com/docs/&hellip; credits to @Alex G\n- That this change has not been promoted more heavily in the documentation, is beyond me. Thanks for saving us some time here, buddy.\n- For whoever curious, this is due to Node is now prefer IPv6 which translates localhost to ::1 instead of 127.0.0.1\n- update & note: 1. I solved the issue after adding useNewUrlParser: true, useUnifiedTopology: true, and my nestJs could connect to mongodb 2. after that i tried removing useNewUrlParser: true, useUnifiedTopology: true, but still working i didnt know what just happened, but it solved the issue. please correct my answer or comment If you have better explanation.","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":262,"estimatedTokens":1556}}493{"id":"stack-67597203","source":"stackoverflow","questionId":67597203,"title":"How to use multiple global interceptors in NestJS","tags":["http","web","nestjs","interceptor"],"text":"Title: How to use multiple global interceptors in NestJS\nTags: http, web, nestjs, interceptor\nSource: Stack Overflow\n\nQuestion:\nI had already know we could create global interceptors from this code below:\n\n```\nimport { Module } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n providers: [\n {\n provide: APP_INTERCEPTOR,\n useClass: LoggingInterceptor,\n },\n ],\n})\nexport class AppModule {}\n```\n\nSource: documentation\n\nHowever, what if I want to have let say, `UserInterceptor`.\n\n`UserInterceptor` will get user from database and transform the request.\n\n`UserInterceptor` need to inject let say `UserService`.\n\nAnd I want to use `UserInterceptor` globally.\n\n```\n@Injectable()\nexport class UserInterceptor {\n constructor(private readonly service: UserService) {}\n}\n```\n\nFrom documentation, we can't do `app.useGlobalInterceptors(new UserInterceptor())` because `UserInterceptor` need 1 argument in the constructor (UserService).\n\nAnd since we had use `APP_INTERCEPTOR` for `LoggingInterceptor`, I didn't found another way to assign another value to `APP_INTERCEPTOR` to use the interceptor globally.\n\nFor example I think the problem will solved if we could do:\n\n```\nproviders: [\n {\n provide: APP_INTERCEPTOR,\n useClass: [LoggingInterceptor, UserInterceptor]\n }\n]\n```\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: LoggingInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n@Injectable()\nexport class UserInterceptor {\n  constructor(private readonly service: UserService) {}\n}\n```\n\n```text\nproviders: [\n  {\n    provide: APP_INTERCEPTOR,\n    useClass: [LoggingInterceptor, UserInterceptor]\n  }\n]\n```\n\n```text\nUserInterceptor\n```\n\n```text\nUserInterceptor\n```\n\n```text\nUserInterceptor\n```\n\n```text\nUserService\n```\n\n```text\nUserInterceptor\n```\n\n```text\napp.useGlobalInterceptors(new UserInterceptor())\n```\n\n```text\nUserInterceptor\n```\n\n```text\nAPP_INTERCEPTOR\n```\n\n```text\nLoggingInterceptor\n```\n\n```text\nAPP_INTERCEPTOR\n```\n\n```js\nproviders: [\n  {\n    provide: APP_INTERCEPTOR,\n    useClass: LoggingInterceptor\n  },\n  {\n    provide: APP_INTERCEPTOR,\n    useClass: UserInterceptor\n  }\n]\n```\n\n========================================\n\nComments:\n- Wow! It's really staightforward and simple. Could someone explain to me how this could work? or where to find how this could work? I never think this way because I think the APP_INTERCEPTOR in nutshell only assignable to an instance.\n- Very quick explanation of how: Nest is watching for these `APP_*` providers, and ends up attaching a uuid to the token so that you can have multiple values for the single provider token.\n- This is documented somewhere ? I have not found here it and I was about to ask the same question on SO.\n- @FlavienVolken nope, I just figure it out by reading the source code.\n- @IvanElianto Inside app.module.ts, you need to add.","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":149,"estimatedTokens":755}}494{"id":"stack-72864723","source":"stackoverflow","questionId":72864723,"title":"which is Better in typeorm Save Or Update","tags":["nestjs","typeorm","node.js-typeorm"],"text":"Title: which is Better in typeorm Save Or Update\nTags: nestjs, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI was working on a project and I wanted to update the data but I don't know which is the faster way to update data SAVE() method or Update()\n\n```\nthis.repo.save({\nid:id,\ndata})\n```\n\n========================================\n\nTop Answer:\nActually they are for different purposes\n\n**save()**\nit saves the entity you provided if your entry doesn't have an identifier (id) or the id doesn't exist in the DB, it tries to create a new one. Otherwise, it updates the entity itself.\n\n**update()**\nit executes a simple `UPDATE table SET....` query. It means you can use it for updating an entity 'partially'. It's handy for 'patching' things.\n\nTL;TR\n\n- use `save()` for creating a new record or updating the whole entity at once\n\n- use `update()` for updating an entity partially.\n\n========================================\n\nCode:\n```text\nthis.repo.save({\nid:id,\ndata})\n```\n\n```text\nUPDATE table SET....\n```\n\n```text\nsave()\n```\n\n```text\nupdate()\n```\n\n========================================\n\nComments:\n- Hi thank you for the help and i really appreciate your support ........!!!! but I need to know which method is more faster in querying like taking less time and more optimize way\n- if you want to update a record; `update()` would be faster. Because you don't need to fetch the actual record itself, you can directly call the update with the id and fields you want to update.\n- then what is the difference and use case of upsert?\n- and save will update or create new one , on which condition save willl update? can i pass custom criteria for that?\n- This is a super important detail: `update()` does not contain the entity for subscribers (it will undefined).","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":444}}495{"id":"stack-72108412","source":"stackoverflow","questionId":72108412,"title":"Why skip() and take() not works when I use getRawMany() in nestJS with typeorm?","tags":["nestjs","typeorm"],"text":"Title: Why skip() and take() not works when I use getRawMany() in nestJS with typeorm?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere is the code I currently use.\n\nwith getRawMany() - skip and take not works!\n\n\r\n\r\n\n```\nconst data = await getRepository(Enquiry)\n .createQueryBuilder('enq')\n .select([\n 'enq.id AS id',\n 'enq.location AS location',\n 'enqStatus.name AS status'\n ])\n .leftJoin('enq.status', 'enqStatus')\n .skip(1)\n .take(3)\n .where(payload)\n .getRawMany()\n```\n\n========================================\n\nTop Answer:\nStrangely, `skip()` and `take()` do not work well with joins, you should use `offset()` and `limit()`.\nYou can read more about this in this open issue in TypeORM repository:\nhttps://github.com/typeorm/typeorm/issues/4742\n\n========================================\n\nCode:\n```js\nconst data = await getRepository(Enquiry)\n  .createQueryBuilder('enq')\n  .select([\n    'enq.id AS id',\n    'enq.location AS location',\n    'enqStatus.name AS status'\n  ])\n  .leftJoin('enq.status', 'enqStatus')\n  .skip(1)\n  .take(3)\n  .where(payload)\n  .getRawMany()\n```\n\n```text\nconst data = await getRepository(Enquiry)\n  .createQueryBuilder('enq')\n  .select([\n    'enq.id AS id',\n    'enq.location AS location',\n    'enqStatus.name AS status'\n  ])\n  .leftJoin('enq.status', 'enqStatus')\n  .where(payload)\n  .offset(meta.page)\n  .limit(meta.pageSize)\n  .getRawMany()\n```\n\n```text\nskip()\n```\n\n```text\ntake()\n```\n\n```text\noffset()\n```\n\n```text\nlimit()\n```\n\n========================================\n\nComments:\n- you need leftJoinAndSelect, late answer but I think it will work ~\n- I tried this but not worked! :(\n- Did you try with `limit` and `offset`? I think the `leftJoin` would cause this issue.\n- limit and offset works! Thank bro :)\n- in conjunction joins this will not work as expected as it limits to total of all child-records (e.g. joining an article with keywords, then you'll get only one article but 3 keywords when doing \"limit 3\"\n- Great it worked but itd be much better if its explained why this works and skip take doesnt","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":92,"estimatedTokens":514}}496{"id":"stack-51056158","source":"stackoverflow","questionId":51056158,"title":"NestJS Create Base CRUD Service","tags":["nestjs"],"text":"Title: NestJS Create Base CRUD Service\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am writing my first REST API with nestjs.\n\nI have several entities for which I have to define basic CRUD operations.\nI was wondering if there is a way to create a base crud service that I can use in order not to repeat the same code for all entities.\nIn this base-crud service I would have the four CRUD methods that call the repository in order to actually do the db related stuff.\n\nBasically I was hoping to have a `BaseCrudService` and than have a `UserService` that `extends BaseCrudService`.\nThis way I could \"override\" methods in the derived class to do extra logic business and than call the base method to actually insert, delete etc.\n\nIs it possible? If so, how would you go about to do it?\n\n========================================\n\nTop Answer:\nI've built a package that helps to create CRUD services and controllers without inheritance https://www.npmjs.com/package/@nestjsx/crud\n\n========================================\n\nCode:\n```text\nBaseCrudService<T>\n```\n\n```text\nUserService\n```\n\n```text\nextends BaseCrudService<UserEntity>\n```\n\n```text\nexport class BaseCrudService<Entity extends BaseEntity> {\n\n    constructor(\n        public repository: Repository<Entity>,\n    ) { }\n\n    async insertAsync(entity: Entity): Promise<InsertResult> {\n        return this.repository.insert(entity);\n    }\n    ...\n}\n```\n\n```text\n@Injectable()\nexport class UserService extends BaseCrudService<UserEntity>{\n  constructor(\n    @InjectRepository(UserEntity)\n    public repository: Repository<UserEntity>,\n  ) {\n    super(repository);\n  }\n}\n```\n\n```text\nBaseCrudController\n```\n\n========================================\n\nComments:\n- You would have to dynamically construct the functions on both the controller and service. Probably impossible with params in the REST URL. Maybe you could create some kind of factory on the server. It is nice to be DRY but this could be much more work than it is worth. I've cut back on DRY a bit in Angular because my code on the components was getting complicated and confusing just so I could have generic http services. So to keep it simple and clear I plan to have a separate Nestjs controller and service for each module of my app.\n- @Preston thanks for your reply! Yeah I understand the controller part, but what about service and repository? Do you think it would be possible? I would still have one service per controller but at least basic CRUD operations would be delegated to the base crud service\n- The only way I know of is to use a specific repository for each type of service, just as membersRepository and Members in the promise. I see no way to make that same service also work for another repo and model.\n- I see! Thanks for your help :)\n- Just to add to this answer, here's my `BaseService` if you happen to use MongoDB: gist.github.com/nartc/c93716ecde5837896ffc30feb84c719d\n- Furthermore, If you want to extend this idea to controllers, I added the possibility to extend a base controller. See github.com/nestjs/nest/pull/387.\n- Excellent, i will edit the answer and include your guys suggestions :)\n- It is easy to confuse create and insert function of the repository... that example is quite useful.\n- This makes sense, but how to apply authGuard from child controller? For example, I create baseCrudController and extend it by UserController and TodoController. Now I want to allow users to only allow add/update to todos but not users and allow admin to do everything. How to do this?\n- @ChauTran just to bump this - I'm curious about how that works with creation. Right now, I'm writing my own base service and I can't declare the parameter to be the same as my entity because fields like id, date and createdAt etc. are missing (since they're calculated fields). What do you do about that?\n- @robertmain Partial\n- Is that still alive?","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":81,"estimatedTokens":969}}497{"id":"stack-69568781","source":"stackoverflow","questionId":69568781,"title":"How to create a custom health check for Prisma with @nestjs/terminus?","tags":["nestjs","prisma","health-check"],"text":"Title: How to create a custom health check for Prisma with @nestjs/terminus?\nTags: nestjs, prisma, health-check\nSource: Stack Overflow\n\nQuestion:\nSince @nestjs/terminus doesn't provide a health check for Prisma, I'm trying to create it based on their Mongoose health check.\n\nWhen I try:\n\n```\nimport * as Prisma from 'prisma';\n...\n...\n private getContextConnection(): any | null {\n const {\n getConnectionToken,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('prisma') as typeof Prisma;\n\n try {\n return this.moduleRef.get(getConnectionToken('DatabaseConnection') as string, {\n strict: false,\n });\n } catch (err) {\n return null;\n }\n }\n...\n...\n const connection = options.connection || this.getContextConnection();\n\n if (!connection) {\n throw new ConnectionNotFoundError(\n this.getStatus(key, isHealthy, {\n message: 'Connection provider not found in application context',\n }),\n );\n }\n```\n\nI always seem to get: \"message\": \"Connection provider not found in application context\".\nThere is a problem with the connection or I don't really understand how the health check actually works\n\n========================================\n\nTop Answer:\nThis question helped me build a Prisma health check for NestJS.\n\nHere's what I made:\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { HealthCheckError, HealthIndicator, HealthIndicatorResult } from \"@nestjs/terminus\";\nimport { PrismaService } from \"./prisma.service\";\n\n@Injectable()\nexport class PrismaHealthIndicator extends HealthIndicator {\n constructor(private readonly prismaService: PrismaService) {\n super();\n }\n\n async isHealthy(key: string): Promise {\n try {\n await this.prismaService.$queryRaw`SELECT 1`;\n return this.getStatus(key, true);\n } catch (e) {\n throw new HealthCheckError(\"Prisma check failed\", e);\n }\n }\n}\n```\n\nThis injects a `PrismaService` exactly as it is shown in the NestJS docs. https://docs.nestjs.com/recipes/prisma#use-prisma-client-in-your-nestjs-services\n\nYou could alternatively replace `prismaService` with `new PrismaClient()`.\n\n========================================\n\nCode:\n```text\nimport * as Prisma from 'prisma';\n...\n...\n  private getContextConnection(): any | null {\n    const {\n      getConnectionToken,\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n    } = require('prisma') as typeof Prisma;\n\n    try {\n      return this.moduleRef.get(getConnectionToken('DatabaseConnection') as string, {\n        strict: false,\n      });\n    } catch (err) {\n      return null;\n    }\n  }\n...\n...\n    const connection = options.connection || this.getContextConnection();\n\n    if (!connection) {\n      throw new ConnectionNotFoundError(\n        this.getStatus(key, isHealthy, {\n          message: 'Connection provider not found in application context',\n        }),\n      );\n    }\n```\n\n```js\nprisma.$queryRaw`SELECT 1`\n```\n\n```text\nNestJSMongoose\n```\n\n```text\nPrisma\n```\n\n```text\ngetConnectionToken\n```\n\n```text\nPrisma\n```\n\n```text\nterminus\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\nimport { HealthCheckError, HealthIndicator, HealthIndicatorResult } from \"@nestjs/terminus\";\nimport { PrismaService } from \"./prisma.service\";\n\n@Injectable()\nexport class PrismaHealthIndicator extends HealthIndicator {\n  constructor(private readonly prismaService: PrismaService) {\n    super();\n  }\n\n  async isHealthy(key: string): Promise<HealthIndicatorResult> {\n    try {\n      await this.prismaService.$queryRaw`SELECT 1`;\n      return this.getStatus(key, true);\n    } catch (e) {\n      throw new HealthCheckError(\"Prisma check failed\", e);\n    }\n  }\n}\n```\n\n```text\nPrismaService\n```\n\n```text\nprismaService\n```\n\n```text\nnew PrismaClient()\n```\n\n```js\n// keep in mind that it is not recommended to send server errors directly to the client,\n// you may not want to expose your DB location or other sensitive data\nLogger.error(error, `${PrismaHealthIndicator.name}::isHealthy`)\n\nthrow new HealthCheckError(\n  'cannot perform DB checks',\n  this.getStatus(key, false, {\n    message: 'cannot perform DB checks'\n  })\n)\n```\n\n========================================\n\nComments:\n- Since there's no NestJS Prisma package and therefore nobody registers the `DatabaseConnection` token, it probably makes more sense to do `PrismaClient.$connect()` in the health check.\n- Could you please add an example of how you'd use `PrismaHealthIndicator` in a health check controller","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":186,"estimatedTokens":1095}}498{"id":"stack-62017839","source":"stackoverflow","questionId":62017839,"title":"How to access headers in the nestjs pipe?","tags":["nestjs"],"text":"Title: How to access headers in the nestjs pipe?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm writing a validation pipe and it needs to get certain infornmation from the token, so I have to somehow pass headers to the validation pipe.\n\n========================================\n\nTop Answer:\nTo access the request object and its attributes in my CustomPipe, I first create a custom decorator:\n\n**request.decorator.ts**\n\n```\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const ReqDec = createParamDecorator(\n (data: unknown, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n return request;\n }\n)\n```\n\nThen I use my decorator in my controller to decorate my CustomPipe:\n\n**mycontroller.ts**\n\n```\nimport { ReqDec } from '../../decorators/request.decorator';\n\n@Get()\nasync get(@ReqDec(new CustomPipe()) request): Promise \n{...}\n```\n\nFinally I can access the request object in my CustomPipe like this:\n\n**custom.pipe.ts**\n\n```\nimport { Injectable, PipeTransform } from '@nestjs/common';\n\n@Injectable()\nexport class CustomPipe implements PipeTransform {\n constructor() { }\n\n transform(request: any) {\n // you can use request, request.query, request.params, request.headers, ...\n return request;\n }\n}\n```\n\n========================================\n\nCode:\n```js\nexport const CustomHeaders = createParamDecorator((data: unknown, ctx: ExecutionContext) => {\n  const req = ctx.switchToHttp().getRequest();\n  return data ? req.headers[data] : req.headers;\n})\n```\n\n```text\n@Headers()\n```\n\n```text\n@CustomHeaders()\n```\n\n```js\ncanActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    const request = context.switchToHttp().getRequest();\n    return validateRequest(request);\n  }\n```\n\n```text\nRequest\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const ReqDec = createParamDecorator(\n    (data: unknown, ctx: ExecutionContext) => {\n        const request = ctx.switchToHttp().getRequest();\n        return request;\n    }\n)\n```\n\n```text\nimport { ReqDec } from '../../decorators/request.decorator';\n\n@Get()\nasync get(@ReqDec(new CustomPipe()) request): Promise<any> \n{...}\n```\n\n```text\nimport { Injectable, PipeTransform } from '@nestjs/common';\n\n@Injectable()\nexport class CustomPipe implements PipeTransform {\n  constructor() { }\n\n  transform(request: any) {\n    // you can use request, request.query, request.params, request.headers, ...\n    return request;\n  }\n}\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({ validateCustomDecorators: true }))\n```\n\n========================================\n\nComments:\n- I know that I can access it in a guard but it's not what I'm looking for. Guards are executed before pipes, and since I have a bunch of validation pipes I don't want to write a validation guard that will work separately.\n- Brilliant! That's what I need.","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":128,"estimatedTokens":727}}499{"id":"stack-69079742","source":"stackoverflow","questionId":69079742,"title":"Cannot read property 'resolve' of undefined when using import path from 'path'","tags":["node.js","typescript","nestjs"],"text":"Title: Cannot read property 'resolve' of undefined when using import path from 'path'\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen using :\n\n```\nimport path from 'path';\n\npath.resolve('/')\n```\n\nI get the title error, but when I use\n\n```\nrequire('path').resolve('messages.json'))\n```\n\nhttps://i.sstatic.net/HrhWk.png\n\n```\nimport { readFile, writeFile } from 'fs/promises';\nimport { v4 as uuidv4 } from 'uuid';\nimport path from 'path';\n\ninterface MessagesJson {\n messages: Array;\n}\n\nexport class MessagesRepository {\n async findOne(id: string): Promise {\n return id;\n }\n\n async findAll(): Promise {\n return null;\n }\n\n async create(message: any): Promise {\n console.log(' dirname', require('path').resolve('messages.json'));\n console.log(' path.resolve', path.resolve('/'));\n // console.log(' path.resolve', path.resolve(__dirname, '/src'));\n const messages: any = await readFile('src/messages.json', 'utf-8');\n\n const parsedMessages: MessagesJson = JSON.parse(messages);\n\n const newMessage = {\n content: message,\n id: uuidv4(),\n };\n\n await parsedMessages.messages.push(newMessage);\n\n await writeFile('src/messages.json', JSON.stringify(parsedMessages));\n\n return parsedMessages;\n }\n}\n```\n\nFor the problem context, I'm working on a small project with nestjs, any option for path.foo() gets the same error as listed above, is it something related for after the compiling of the code?\n\nIm very lost to where/what doc and/or information should i be reading to be able to understand what is happening.\n\n========================================\n\nTop Answer:\nYou can change your tsconfig.json.\n\nlike:\n\n```\n{\n \"compilerOptions\": {\n \"esModuleInterop\": true,\n ...\n },\n ...\n}\n```\n\nAfter doing that, you don't need to use `* as xx` anymore.\n\nMore information: https://www.typescriptlang.org/tsconfig#esModuleInterop\n\n========================================\n\nCode:\n```js\nimport path from 'path';\n\npath.resolve('/')\n```\n\n```js\nrequire('path').resolve('messages.json'))\n```\n\n```js\nimport { readFile, writeFile } from 'fs/promises';\nimport { v4 as uuidv4 } from 'uuid';\nimport path from 'path';\n\ninterface MessagesJson {\n  messages: Array<{ content: string; id: string }>;\n}\n\nexport class MessagesRepository {\n  async findOne(id: string): Promise<string> {\n    return id;\n  }\n\n  async findAll(): Promise<any> {\n    return null;\n  }\n\n  async create(message: any): Promise<any> {\n    console.log(' dirname', require('path').resolve('messages.json'));\n    console.log(' path.resolve', path.resolve('/'));\n    // console.log(' path.resolve', path.resolve(__dirname, '/src'));\n    const messages: any = await readFile('src/messages.json', 'utf-8');\n\n    const parsedMessages: MessagesJson = JSON.parse(messages);\n\n    const newMessage = {\n      content: message,\n      id: uuidv4(),\n    };\n\n    await parsedMessages.messages.push(newMessage);\n\n    await writeFile('src/messages.json', JSON.stringify(parsedMessages));\n\n    return parsedMessages;\n  }\n}\n```\n\n```text\nrequire\n```\n\n```text\nimport * as path from 'path'\n```\n\n```text\npath.resolve\n```\n\n```text\nimport { resolve } from 'path';\n```\n\n```text\nresolve()\n```\n\n```json\n{\n  \"compilerOptions\": {\n   \"esModuleInterop\": true,\n   ...\n  },\n  ...\n}\n```\n\n```text\n* as xx\n```\n\n========================================\n\nComments:\n- `import * as path from 'path';`\n- This was a very silly mistake on my part, thank you very much for the answer!","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":178,"estimatedTokens":848}}500{"id":"stack-72471939","source":"stackoverflow","questionId":72471939,"title":"@UseGuards for @ResolveField in NestJS GraphQL","tags":["graphql","nestjs"],"text":"Title: @UseGuards for @ResolveField in NestJS GraphQL\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use @UseGuards functionality for a @ResolveField, because I want the main query to be public, but specific things to be visible only for specific users.\nI don't want to use another query or another type of guard.\n\n========================================\n\nCode:\n```text\nGraphQLModule.forRoot({\n  fieldResolverEnhancers: ['guards'],\n  ...\n}\n```\n\n========================================\n\nComments:\n- Thanks! It helped a lot, another thing is should I use another custom guard or my current authGuard throwing unauthorised is good enough?","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":22,"estimatedTokens":164}}501{"id":"stack-54328563","source":"stackoverflow","questionId":54328563,"title":"Serialization: How to exclude Entity columns in json response but not internal queries in Nestjs","tags":["javascript","node.js","typescript","nestjs","class-transformer"],"text":"Title: Serialization: How to exclude Entity columns in json response but not internal queries in Nestjs\nTags: javascript, node.js, typescript, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\n**Edit**:\n\nI have looked at this question/answer How to exclude entity field from controller json\n\nBut, as per below - this is excluding that field from all queries (to the porint where when trying to process user validation, the password field is excluded using the findOne repository query on a route/controller method that does not have ClassSerializerInterceptor\n\nI have an entity within nest.js / typeorm; I am trying to exclude the password field from the returned json, but not exclude the password field from any repository queries within my service. For example:\n\n`user.entity.ts`:\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, \nUpdateDateColumn, ManyToOne } from 'typeorm';\nimport { Exclude } from 'class-transformer';\nimport { Account } from '../accounts/account.entity';\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n\n @Column({\n unique: true,\n })\n email: string;\n\n @Column()\n password: string;\n}\n```\n\n`auth.controller.ts`:\n\n```\nimport { Controller, Post, Body, Request, Req, Get, UseInterceptors, ClassSerializerInterceptor, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\nimport { IUserRequest } from '../../interfaces/user-request.interface';\n\n@Controller('auth')\nexport class AuthController {\n constructor(private readonly authService: AuthService) {}\n\n @Post('/login')\n async login(@Request() req: Request) {\n const user = await this.authService.checkCredentials(req.body);\n return this.authService.logUserIn(user.id);\n }\n\n @Get('/profile')\n @UseGuards(AuthGuard())\n @UseInterceptors(ClassSerializerInterceptor)\n async profile(@Request() req: IUserRequest) {\n const profile = await this.authService.getLoggedInProfile(req.user.id);\n return { profile };\n }\n}\n```\n\nIf I add `Exclude()` to password like so\n\n```\n@Exclude()\n@Column()\npassword: string;\n```\n\nthe password is included in the response\n\nIf I remove the `Column()` from password, \n\n```\n@Exclude()\npassword: string;\n```\n\nPassword is excluded from response **and** all internal queries such as: \n\n```\nconst user = await this.userRepository.findOne({ where: { id }, relations: ['account']});\n```\n\nIs this possible in nest.js using the `ClassSerializerInterceptor`?\n\nIf so, would appreciate a pointer in the right direction.\n\n========================================\n\nTop Answer:\nWould advice also looking at TypeOrm hidden-columns \nHere you have `@Column({select: false})` on your password column , all requests using a standard find or query will exclude the password column. \n\n```\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n@PrimaryGeneratedColumn()\nid: number;\n\n@Column()\nname: string;\n\n@Column({select: false})\npassword: string;\n}\n```\n\nThen during validations/cases where you need the password you do \n\n```\nconst users = await connection.getRepository(User)\n.createQueryBuilder()\n.select(\"user.id\", \"id\")\n.addSelect(\"user.password\")\n.getMany();\n```\n\n========================================\n\nCode:\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, \nUpdateDateColumn, ManyToOne } from 'typeorm';\nimport { Exclude } from 'class-transformer';\nimport { Account } from '../accounts/account.entity';\n\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column()\n  firstName: string;\n\n  @Column()\n  lastName: string;\n\n  @Column({\n    unique: true,\n  })\n  email: string;\n\n @Column()\n password: string;\n}\n```\n\n```text\nimport { Controller, Post, Body, Request, Req, Get, UseInterceptors, ClassSerializerInterceptor, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\nimport { IUserRequest } from '../../interfaces/user-request.interface';\n\n@Controller('auth')\nexport class AuthController {\n  constructor(private readonly authService: AuthService) {}\n\n  @Post('/login')\n  async login(@Request() req: Request) {\n    const user = await this.authService.checkCredentials(req.body);\n    return this.authService.logUserIn(user.id);\n  }\n\n  @Get('/profile')\n  @UseGuards(AuthGuard())\n  @UseInterceptors(ClassSerializerInterceptor)\n  async profile(@Request() req: IUserRequest) {\n    const profile = await this.authService.getLoggedInProfile(req.user.id);\n    return { profile };\n  }\n}\n```\n\n```text\n@Exclude()\n@Column()\npassword: string;\n```\n\n```text\n@Exclude()\npassword: string;\n```\n\n```text\nconst user = await this.userRepository.findOne({ where: { id }, relations: ['account']});\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nauth.controller.ts\n```\n\n```text\nExclude()\n```\n\n```text\nColumn()\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\n@Column()\n@Exclude({ toPlainOnly: true })\npassword: string;\n```\n\n```text\n@Post()\n@UseInterceptors(ClassSerializerInterceptor)\naddUser(@Body(new ValidationPipe({transform: true})) user: User) {\n  // Logs user with password\n  console.log(user);\n  // Returns user as JSON without password\n  return user;\n  }\n```\n\n```text\nasync profile(@Request() req: IUserRequest) {\n  // Profile comes from the database so it will be an entity class instance already\n  const profile = await this.authService.getLoggedInProfile(req.user.id);\n  // Since we are not returning the entity directly, we have to transform it manually\n  return { profile: plainToClass(profile) };\n}\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nValidationPipe\n```\n\n```text\n{ transform: true}\n```\n\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n@PrimaryGeneratedColumn()\nid: number;\n\n@Column()\nname: string;\n\n@Column({select: false})\npassword: string;\n}\n```\n\n```text\nconst users = await connection.getRepository(User)\n.createQueryBuilder()\n.select(\"user.id\", \"id\")\n.addSelect(\"user.password\")\n.getMany();\n```\n\n```text\n@Column({select: false})\n```\n\n========================================\n\nComments:\n- Thanks for your answer. Unfortunately, for some reason, this still did not work with the @UseInterceptors(ClassSerializerInterceptor). However, adding the class-transform @TransformClassToPlain() did the trick\n- Ahh, I only just saw that you are not returning the entity directly. The `ClassSerializerInterceptor` will only work, if the entity itself is returned, so `return profile` instead of `return {profile}`. If you are not returning it directly, you have to transform it manually with `plainToClass()`.\n- not working for me. i also have made this interceptor global. yet couldn't exclude password field on post response.","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":298,"estimatedTokens":1723}}502{"id":"stack-65557077","source":"stackoverflow","questionId":65557077,"title":"PassportJS, NestJS: canActivate method of AuthGuard('jwt')","tags":["passport.js","nestjs","passport-jwt","nestjs-passport","nestjs-jwt"],"text":"Title: PassportJS, NestJS: canActivate method of AuthGuard('jwt')\nTags: passport.js, nestjs, passport-jwt, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nDoes anybody know where I can see the full code of canActivate method in AuthGuard('jwt')? I realized that canActivate method calls JwtStrategy validate method by using console.log() like this:\n\n```\n// jwt.strategy.ts\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n private readonly configService: ConfigService,\n private readonly usersService: UsersService,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: true,\n secretOrKey: configService.get('JWT_SECRET'),\n });\n }\n\n async validate(payload: any) {\n try {\n const user = await this.usersService.getUserById(payload.id);\n // console.log is here\n console.log(user);\n return user;\n } catch (e) {\n console.log(e);\n return null;\n }\n }\n}\n```\n\nIf I use the original canActivate method, console.log is called. I thought that JwtStrategy is a middleware so the validate method is called whenever there is a request. However, when I try to override canActivate method to add authorization, console.log in JwtStrategy validate method is not called:\n\n```\n// jwt-auth.guard.ts\n\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n\n canActivate(context: ExecutionContext): boolean {\n try {\n // Override: handle authorization\n // return true or false\n // Should JwtStrategy.validate(something) be called here?\n } catch (e) {\n console.log(e);\n return false;\n }\n }\n}\n```\n\nThen I tried to find the original code of AuthGuard('jwt') in order to understand its logic, but I was not able to. Any help would be appreciated, thanks!\n\n========================================\n\nCode:\n```js\n// jwt.strategy.ts\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(\n    private readonly configService: ConfigService,\n    private readonly usersService: UsersService,\n  ) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: true,\n      secretOrKey: configService.get<string>('JWT_SECRET'),\n    });\n  }\n\n  async validate(payload: any) {\n    try {\n      const user = await this.usersService.getUserById(payload.id);\n      // console.log is here\n      console.log(user);\n      return user;\n    } catch (e) {\n      console.log(e);\n      return null;\n    }\n  }\n}\n```\n\n```js\n// jwt-auth.guard.ts\n\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  getRequest(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    return ctx.getContext().req;\n  }\n\n  canActivate(context: ExecutionContext): boolean {\n    try {\n      // Override: handle authorization\n      // return true or false\n      // Should JwtStrategy.validate(something) be called here?\n    } catch (e) {\n      console.log(e);\n      return false;\n    }\n  }\n}\n```\n\n```js\n@Injectable()\nexport class CustomAuthGuard extends AuthGuard('jwt') {\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    // custom logic can go here\n    const parentCanActivate = (await super.canActivate(context)) as boolean; // this is necessary due to possibly returning `boolean | Promise<boolean> | Observable<boolean>\n    // custom logic goes here too\n    return parentCanActivate && customCondition;\n  }\n}\n```\n\n```text\nMiddleware\n```\n\n```text\nAuthGuard()#canActivate()\n```\n\n```text\nPassportStrategy\n```\n\n```text\npassport.use()\n```\n\n```text\nvalidate\n```\n\n```text\npassport.verify()\n```\n\n```text\npassportFn\n```\n\n```text\npassportFn\n```\n\n```text\npassport.verify\n```\n\n```text\ncanActivate()\n```\n\n```text\nsuper.canActivate(context)\n```\n\n```text\ncanActivate()\n```\n\n```text\npassport.authenticate()\n```\n\n```text\n<Strategy>#validate\n```\n\n========================================\n\nComments:\n- Thank you so much! Then, is there any way to get access to the return value of `#validate` outside of `super.canActivate(context)`? For example, the Strategy verifies the token and `validate` returns the valid payload containing userId. I want to find a user with the userId in the database, and handle authorization using the 'role' of the user which is saved in the database. Or, as my custom strategy already returns the full user entity, so I think being able to get the return value of `validate` would be enough.\n- Under the hood, `passport` will take whatever is returned by `validate` and set `req.user` to it, so if you Need ``'s return value, you can get it from `req.user`\n- Oh, that's great! To sum up, `super.canActivate(context)` returns a boolean whether the valid token is issued for the valid user, and after calling it `req.user` is set, so I can work with further logic using `req.user`. Thanks for your help!","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":203,"estimatedTokens":1310}}503{"id":"stack-61423936","source":"stackoverflow","questionId":61423936,"title":"Failed to lookup view \"index\" in views directory NestJs","tags":["node.js","express","nestjs"],"text":"Title: Failed to lookup view \"index\" in views directory NestJs\nTags: node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am getting the following error from nestjs:\n\n```\nFailed to lookup view \"index\" in views directory \"/api/dist/views\"\n```\n\nI am trying to use handlebars templating engine with NestJs. I have followed the NestJs documentation here directly without changing a thing. For some weird reason i still get the same error.\n\nI have even created a fresh project using the `nestjs cli`, followed the direction in the documentation above and still getting thesame error.\n\nI have also followed the help in this stackoverflow answer here and added `\"assets\": [\"**/*.hbs\"]` to my `nest-cli.json` at the root of the project. Still getting thesame error. \n\nCan anyone help me please? or Has anyone experienced this or is it just me?\n\n========================================\n\nTop Answer:\nFound a solution that helped me. Hope this saves a dev's life:\n\n**First** \n\nmove `public` and `views` folder into your `src` folder\n\n**Next**\nin your `main.ts` file\n\n`import {resolve } from 'path';`\n\n**Then**\n\nchange this :\n\n```\napp.useStaticAssets(join(__dirname, '..', 'public'));\napp.setBaseViewsDir(join(__dirname, '..', 'views'));\napp.setViewEngine('hbs');\n```\n\nto this :\n\n```\napp.useStaticAssets(resolve('./src/public'));\n app.setBaseViewsDir(resolve('./src/views'));\n app.setViewEngine('hbs');\n```\n\nyou are good to go.\n\n========================================\n\nCode:\n```text\nFailed to lookup view \"index\" in views directory \"/api/dist/views\"\n```\n\n```text\nnestjs cli\n```\n\n```text\n\"assets\": [\"**/*.hbs\"]\n```\n\n```text\nnest-cli.json\n```\n\n```text\n\"compilerOptions\": {    \n    \"assets\": [\n      {\n        \"include\": \"../views\",\n        \"outDir\": \"dist/views\",\n        \"watchAssets\": true\n      }\n    ]\n  }\n```\n\n```text\n\"include\": \"../views\"\n```\n\n```text\nnest-cli.json\n```\n\n```text\napp.useStaticAssets(join(__dirname, '..', 'public'));\napp.setBaseViewsDir(join(__dirname, '..', 'views'));\napp.setViewEngine('hbs');\n```\n\n```text\napp.useStaticAssets(resolve('./src/public'));\n app.setBaseViewsDir(resolve('./src/views'));\n app.setViewEngine('hbs');\n```\n\n```text\npublic\n```\n\n```text\nviews\n```\n\n```text\nsrc\n```\n\n```text\nmain.ts\n```\n\n```text\nimport {resolve } from 'path';\n```\n\n```text\ndocker cp public {container-name}:/usr/app/dist\ndocker cp views {container-name}:/usr/app/dist\n```\n\n```text\ndist\n```\n\n```text\nviews\n```\n\n```text\nsrc\n```\n\n```text\nviews\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- Thank You, It solves the problem, I am having an exactly a similar issue\n- I kept my public at root level and used`app.useStaticAssets(resolve('.&#47;public'))` and this worked too","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":158,"estimatedTokens":681}}504{"id":"stack-69907142","source":"stackoverflow","questionId":69907142,"title":"Is there a native method in nestjs to decode JWT?","tags":["jwt","nestjs","nestjs-passport","nestjs-jwt"],"text":"Title: Is there a native method in nestjs to decode JWT?\nTags: jwt, nestjs, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nIn nestjs I create JWT (tokens) by creating a payload object and signing it. Something like this:\n\n```\nconst jwtPayload: JwtPayload = \n {\n iss: issuer,\n sub: info,\n aud: audience,\n // exp: - populated by fn: this.jwtService.sign(payload),\n // iat: - populated by fn: this.jwtService.sign(payload),\n jti: 'XXXX1234' \n }\n\nconst signedJwtAccessToken: string = this.jwtService.sign(jwtPayload);\n```\n\nNest encodes the jwtPayload into a string.\n\nFor cleanup work I would like to know when exactly the JWT expires. This is automatically encoded into the '*signedJwtAccessToken*' - property *.exp* - by the .sign() function.\n\nTo access it right after the signing, it needs to be decoded.\n\nWhat would be the simplest way to decode the *signedJwtAccessToken* in the same method right after it has been signed ???\n\nNote:\n\nWhen the JWT comes back from client, nestjs decodes it when accessing the fn: validate(), but I want to decode right after signing it - before sending the response to client, something like:\n\n```\n// signing - encoding\nconst signedJwtAccessToken: string = this.jwtService.sign(jwtPayload);\n\n // decoding\nconst decodedJwtAccessToken: string = decodeJwt(signedJwtAccessToken);\n\n // parsing back to an object\nconst updatedJwtPayload: JwtPayload = JSON.parse(decodedJwtAccessToken);\n\n // reading property of .exp\nconst expires = updatedJwtPayload.exp;\n```\n\n========================================\n\nTop Answer:\nif don't want to inject jwtService you can use this way:\n\n```\nimport { decode } from 'jsonwebtoken';\n\nconst jwtPayload = decode(yourJwtToken);\n```\n\njsonwebtoken npm lib docs\n\n========================================\n\nCode:\n```text\nconst jwtPayload: JwtPayload = \n    {\n      iss:                issuer,\n      sub:                info,\n      aud:                audience,\n   // exp:                - populated by fn: this.jwtService.sign(payload),\n   // iat:                - populated by fn: this.jwtService.sign(payload),\n      jti:                'XXXX1234' \n    }\n\nconst signedJwtAccessToken: string = this.jwtService.sign(jwtPayload);\n```\n\n```text\n// signing - encoding\nconst signedJwtAccessToken: string = this.jwtService.sign(jwtPayload);\n\n                            // decoding\nconst decodedJwtAccessToken: string = decodeJwt(signedJwtAccessToken);\n\n                            // parsing back to an object\nconst updatedJwtPayload: JwtPayload  = JSON.parse(decodedJwtAccessToken);\n\n                            // reading property of .exp\nconst expires = updatedJwtPayload.exp;\n```\n\n```text\nconst decodedJwtAccessToken: JwtPayload = this.jwtService.decode(signedJwtAccessToken);\n\nconst expires = decodedJwtAccessToken.exp;\n```\n\n```text\nconst base64Payload = signedJwtAccessToken.split('.')[1];\nconst payloadBuffer = Buffer.from(base64Payload, 'base64');\nconst updatedJwtPayload: JwtPayload = JSON.parse(payloadBuffer.toString()) as JwtPayload;\nconst expires = updatedJwtPayload.exp;\n```\n\n```text\nimport { decode } from 'jsonwebtoken';\n\nconst jwtPayload = decode(yourJwtToken);\n```\n\n========================================\n\nComments:\n- Obviously, it was just staring into my face. Thanks for the reminder. Just a slight adjustment for TS to be happy: const decodedJwtAccessToken: JwtPayload = this.jwtService.decode(signedJwtAccessToken) as JwtPayload;\n- Also you'll need to resolve the import: `import { JwtPayload } from 'jsonwebtoken';`","metadata":{"transformedAt":"2026-08-18T18:33:02.448Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":115,"estimatedTokens":876}}505{"id":"stack-60777204","source":"stackoverflow","questionId":60777204,"title":"TypeError: Repository method is not a function (NestJS / TypeORM)","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: TypeError: Repository method is not a function (NestJS / TypeORM)\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm working with NestJS and TypeORM. When trying to call the createMailLogEntry method of the repository, I'm getting the following error: `TypeError: this.mailLogEntryRepository.createMailLogEntry is not a function`\n\nI can't figure out what's going wrong.\n\n**mailing.service.ts**\n\n```\n@Injectable()\nexport class MailingService {\n\n constructor(@InjectRepository(MailLogEntryRepository) private mailLogEntryRepository: MailLogEntryRepository) { }\n\n // ...\n\n if(transferResult) {\n await this.mailLogEntryRepository.createMailLogEntry({\n creationDate: new Date(Date.now()),\n from: mailContent.from,\n to: mailContent.to,\n subject: mailContent.subject,\n text: mailContent.text,\n html: mailContent.html,\n cc: mailContent.cc,\n bcc: mailContent.bcc,\n });\n }\n }\n}\n```\n\n**mail-log-entry.repository.ts**\n\n```\n@EntityRepository(MailLogEntry)\nexport class MailLogEntryRepository extends Repository {\n\n async createMailLogEntry(mailLogEntryDto: MailLogEntryDto): Promise {\n const mailLogEntry = MailLogEntryRepository.createMailLogEntryFromDto(mailLogEntryDto);\n return await mailLogEntry.save();\n }\n\n private static createMailLogEntryFromDto(mailLogEntryDto: MailLogEntryDto): MailLogEntry {\n const mailLogEntry = new MailLogEntry();\n mailLogEntry.from = mailLogEntryDto.from;\n mailLogEntry.to = mailLogEntryDto.to;\n mailLogEntry.subject = mailLogEntryDto.subject;\n mailLogEntry.text = mailLogEntryDto.text;\n mailLogEntry.html = mailLogEntryDto.html;\n mailLogEntry.cc = mailLogEntryDto.cc;\n mailLogEntry.bcc = mailLogEntryDto.bcc;\n\n return mailLogEntry;\n }\n}\n```\n\n========================================\n\nTop Answer:\nI had the same problem, I'll tell you what got me out of it if it helps someone else!\n\nIf your repository is handmade (not generated by an ORM) then you can't use the Repository injection :\n\nhttps://i.sstatic.net/klir6.png\n\nInstead just use the repository as you would for a service (just remove the @InjectRepository(People)):\n\nhttps://i.sstatic.net/duDXN.png\n\nI hope this will help!Happy coding !\n\nPS : Personnes is my entity and the helper has nothing to do with the issue\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class MailingService {\n\n    constructor(@InjectRepository(MailLogEntryRepository) private mailLogEntryRepository: MailLogEntryRepository) { }\n\n        // ...\n\n        if(transferResult) {\n            await this.mailLogEntryRepository.createMailLogEntry({\n                creationDate: new Date(Date.now()),\n                from: mailContent.from,\n                to: mailContent.to,\n                subject: mailContent.subject,\n                text: mailContent.text,\n                html: mailContent.html,\n                cc: mailContent.cc,\n                bcc: mailContent.bcc,\n            });\n        }\n    }\n}\n```\n\n```text\n@EntityRepository(MailLogEntry)\nexport class MailLogEntryRepository extends Repository<MailLogEntry> {\n\n    async createMailLogEntry(mailLogEntryDto: MailLogEntryDto): Promise<MailLogEntry> {\n        const mailLogEntry = MailLogEntryRepository.createMailLogEntryFromDto(mailLogEntryDto);\n        return await mailLogEntry.save();\n    }\n\n    private static createMailLogEntryFromDto(mailLogEntryDto: MailLogEntryDto): MailLogEntry {\n        const mailLogEntry = new MailLogEntry();\n        mailLogEntry.from = mailLogEntryDto.from;\n        mailLogEntry.to = mailLogEntryDto.to;\n        mailLogEntry.subject = mailLogEntryDto.subject;\n        mailLogEntry.text = mailLogEntryDto.text;\n        mailLogEntry.html = mailLogEntryDto.html;\n        mailLogEntry.cc = mailLogEntryDto.cc;\n        mailLogEntry.bcc = mailLogEntryDto.bcc;\n\n        return mailLogEntry;\n    }\n}\n```\n\n```text\nTypeError: this.mailLogEntryRepository.createMailLogEntry is not a function\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([TeamRepository])],\n  providers: [TeamService],\n  controllers: [TeamController]\n})\nexport class TeamModule {}\n```\n\n```text\n@Entity\nexport class Person { ... }\n\n@Injectable()\nexport class OtherPersonService { ... }  // Person !== OtherPerson\n\n@EntityRepository(Person)\nexport class OtherPersonRepository extends Repository<Person> { ... } // Same problem\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([\n  TeamRepository,\n  Team   // either the entity or the custom repository should be imported.\n  ])],\n  providers: [TeamService],\n  controllers: [TeamController]\n})\nexport class TeamModule {}\n```\n\n```text\n@Injectable()\nexport class ProductService {\n private logger = new Logger('ProductService');\n constructor(\n  @InjectRepository(Product)\n  private productRepository: Repository<Product>\n ) { }\n\n async getAllAsync(): Promise<Product[]> {\n  return await this.productRepository.find();\n }\n\n async getCountAsync(): Promise<number> {\n  return await this.productRepository.count();\n }\n}\n```\n\n```text\nconst mockUserRepository = {\n  register: jest.fn().mockResolvedValue('sampleResolvedValue')\n};\n```\n\n```js\nexampleQueryBuilder() {\n    return this.createQueryBuilder() ...\n}\n```\n\n```js\nexampleQueryBuilder() {\n    return this.dataSource\n          .getRepository(Person)\n          .createQueryBuilder() ...\n}\n```\n\n```js\n// account.repository.ts\n@Injectable()\nexport class AccountsRepository extends Repository<AccountsEntity> {\n    constructor(private dataSource: DataSource) {\n        super(AccountsEntity, dataSource.createEntityManager());\n    }\n\n    async getByUsername(username: string) {\n        return this.findOne({ where: { username } });\n    }\n    // ...\n}\n```\n\n```js\n// account.service.ts\nexport class AccountService {\n    constructor(private readonly accountRepository: AccountRepository) {}\n\n    async getByUsername(username: string): Promise<Account> {\n        return this.accountRepository.getByUsername(username);\n    }\n    // ...\n}\n```\n\n```js\n// account.module.ts\n@Module({\n    imports: [\n        TypeOrmModule.forFeature([AccountEntity])],\n    // ...\n  ],\n    providers: [AccountService, AccountRepository],\n    // ...\n})\nexport class AccountModule { }\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([\n      YourEntity\n    ])\n  ],\n  controllers: [],\n  providers: [YourRepository],\n  exports: [],\n})\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\n@Injectable()\nexport class TaskRepository extends Repository<Task> {\n    constructor(private readonly dataSource: DataSource) {\n        super(Task, dataSource.manager);\n      }\n    getTasks(filterDto: GetTasksFilterDto): Promise<Task[]> {}\n```\n\n```text\n@Injectable()\nexport class TasksService {\n\n  constructor (\n    @InjectRepository(Task)\n    private  taskRepository: TaskRepository\n  ) {}\n```\n\n```text\n@Module({\n  controllers: [TasksController],\n  providers: [TasksService, TaskRepository],\n  imports: [TypeOrmModule.forFeature([Task ])]\n})\nexport class TasksModule {}\n```\n\n========================================\n\nComments:\n- Probably you have some problem how you provide this custom repository and your mailing service gets undefined in place of mailLogEntryRepository\n- @Noniq, I'm currently having this same issue and none of these answers are fixing it for me. I don't know if you ever got yours fixed or if anyone has a fix for this. It's exactly the same issue saying **TypeError: this.userRepository.register is not a function**\n- @MSadiq Have you solved it?\n- Yes, I just added what fixed it for me to the answers, hopefully it helps someone someday\n- This should be an accepted answer. The custom extended repository you make has to be imported via Typeorm like in the answer.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but itโ€™d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who arenโ€™t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":298,"estimatedTokens":2021}}506{"id":"stack-66693362","source":"stackoverflow","questionId":66693362,"title":"How to excute Raw SQL Query on NestJS framework using typeorm","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to excute Raw SQL Query on NestJS framework using typeorm\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am going to execute such a long query on the NestJS framework using Typeform.\nPlease let me know how to execute this query.\n\n```\nselect user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'\n```\n\n========================================\n\nTop Answer:\nyou can use typeorm - DataSource module for execute raw SQL queries\n\nplease refer below example\n\n```\nimport { DataSource } from 'typeorm';\n\nexport class {\n constructor(\n @InjectDataSource() private dataSource: DataSource,\n) {}\n\n async function_name () {\n this.dataSource.query()\n }\n}\n```\n\n========================================\n\nCode:\n```text\nselect user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'\n```\n\n```js\nconst rawData = await connection.query(`SELECT * FROM USERS`);\n```\n\n```js\n@Injectable()\nexport class FooService {\n  constructor(@InjectConnection() private readonly connection: Connection) {}\n\n  async doSomeQuery() {\n    return this.connection.query('SELECT * FROM USERS;');\n  }\n}\n```\n\n```text\nTypeORM\n```\n\n```text\n@InjectConnection()\n```\n\n```text\nquery\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nthis.connection\n```\n\n```text\n@InjectConnection()\n```\n\n```text\n@InjectConnection()\n```\n\n```text\n@InjectDataSource()\n```\n\n```text\nreturn await getRepository(users)\n.createQueryBuilder(\"user\")\n.where(\"user.role = 'Admin'\")\n.select(\"user.id as userId\")\n.addSelect(\"user.fullName as fullName\")\n.addSelect(\"(select count(*) sendCnt from chat where senderId = user.id) as sendCnt\")\n.addSelect(\"(select count(*) recvCnt from chat where receiverId = user.id) as recvCnt\")\n.printSql()\n.getRawMany();\n```\n\n```text\nimport { getManager } from 'typeorm';\n\nconst entityManager = getManager();\nreturn entityManager.query(`SELECT * FROM users`)\n```\n\n```text\nreturn entityManager.query(`select user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'`)\n```\n\n```text\nimport { DataSource } from 'typeorm';\n\nexport class <class name> {\n  constructor(\n @InjectDataSource() private dataSource: DataSource,\n) {}\n\n  async function_name () {\n     this.dataSource.query(<QUERY>)\n  }\n}\n```\n\n========================================\n\nComments:\n- Currently, I am using PostgreSQL. Could you please let me know the detailed base code for this functionality?\n- I'm not sure I the question.\n- Please, provide a bit more information if you can, i.e: how you import connection and inject it in constructor or? Thanks.\n- @textoro just added a small example\n- @JayMcDoniel et al. `@InjectConnection()` decorator is now deprecated. Use `@InjectDataSource()` now.\n- After InjectConnection() is deprecated. This solution work for me.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":133,"estimatedTokens":776}}507{"id":"stack-64104169","source":"stackoverflow","questionId":64104169,"title":"How to inject the interface of a service in the constructor of a controller in Nestjs?","tags":["nestjs"],"text":"Title: How to inject the interface of a service in the constructor of a controller in Nestjs?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an app that receives a service as a dependency on the controller, so far so good, but I would like to find a way to instead of declaring the specific implementation of that service, to be able to \"ask\" from the controller for the interface that this service implements to decouple of the concrete implementation of that service. How is this done in nest js?\n\n========================================\n\nTop Answer:\nYou can achieve this decoupling with an interface + injection token string or use an abstract class.\n\nI prefer the abstract class approach due to the fact that you can avoid those injection tokens.\n\n### logger.interface.ts\n\n```\nexport abstract class ILogger {\n}\n```\n\n### logger.ts\n\n```\n@Injectable()\nexport class Logger implements ILogger { \n}\n```\n\n### example.module.ts\n\n```\n@Module({\n providers: [\n {\n provide: ILogger,\n useClass: Logger\n \n }\n ],\n controllers: [\n ExampleController\n ]\n})\nexport class GreetingModule {}\n```\n\n### example.controller.ts\n\n```\n@Controller('example')\nexport class ExampleController {\n constructor(\n private readonly logger: ILogger\n ) {}\n ...\n}\n```\n\n========================================\n\nCode:\n```text\n// This will be our injection token.\nexport const GREETING_SERVICE = 'GREETING SERVICE';\n\nexport interface IGreetingService {\n  greet(name: string): Promise<string>;\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { IGreetingService } from './greeting-service.interface';\n\n@Injectable()\nexport class ProfessionalGreetingService implements IGreetingService {\n  public async greet(name: string): Promise<string> {\n    return `Hello ${name}, how are you today?`;\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ProfessionalGreetingService } from './services/professional-greeting.service';\nimport { GREETING_SERVICE } from './services/greeting-service.interface';\nimport { GreetingController } from './controllers/greeting.controller';\n\n@Module({\n  providers: [\n    {\n      // You can switch useClass to different implementation\n      useClass: ProfessionalGreetingService,\n      provide: GREETING_SERVICE\n    }\n  ],\n  controllers: [\n    GreetingController\n  ]\n})\nexport class GreetingModule {}\n```\n\n```js\nimport { Controller, Get, Inject, Query } from '@nestjs/common';\nimport { GREETING_SERVICE, IGreetingService } from '../services/greeting-service.interface';\n\n@Controller('greeting')\nexport class GreetingController {\n  constructor(\n    @Inject(GREETING_SERVICE)\n    private readonly _greetingService: IGreetingService\n  ) {}\n\n  @Get()\n  public async getGreeting(@Query('name') name: string): Promise<string> {\n    return await this._greetingService.greet(name || 'John');\n  }\n}\n```\n\n```text\n@Inject()\n```\n\n```text\n@Inject()\n```\n\n```text\nuseClass\n```\n\n```text\nGreetingModule\n```\n\n```text\nexport abstract class ILogger {\n}\n```\n\n```text\n@Injectable()\nexport class Logger implements ILogger {  \n}\n```\n\n```text\n@Module({\n  providers: [\n  {\n    provide: ILogger,\n    useClass: Logger\n  \n  }\n  ],\n  controllers: [\n    ExampleController\n  ]\n})\nexport class GreetingModule {}\n```\n\n```text\n@Controller('example')\nexport class ExampleController {\n constructor(\n   private readonly logger: ILogger\n ) {}\n ...\n}\n```\n\n========================================\n\nComments:\n- This solves the problem but creates kind of a new one. How do you make sure that the used token corresponds to a matching interface? There is no built-in mechanism at type level that can check that and so it is vulnerabel to copypaste errors. A solution to this could be to use an abstract class in-place of the interface (so implement the class, not extend it!) and use the same class as the token.\n- Yes, this is an atrocity. Don't really understand why people think this is a good way to do things.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":180,"estimatedTokens":974}}508{"id":"stack-51707348","source":"stackoverflow","questionId":51707348,"title":"Nestjs Request and Application Lifecycle","tags":["nestjs"],"text":"Title: Nestjs Request and Application Lifecycle\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am looking for information about the request and application life-cycle for The NestJS framework. Specifically:\n\nWhat is the order of execution of the following processes in a request, for a route that implements: `middleware`, `pipes`, `guards`, `interceptors`, and any other potential request process\n\nWhat is the lifespan of modules and providers in a NestJS application? Do they last for the lifespan of a request, or the application, or something else?\n\nAre there any lifecycle hooks, in addition to `OnModuleInit` and `OnModuleDestroy`?\n\nWhat causes a Module to be destroyed (and trigger the `OnModuleDestroy` event)?\n\n========================================\n\nTop Answer:\nWhat is the order of execution of the following processes in a request, for a route that implements: middleware, pipes, guards, interceptors, and any other potential request process\n\nMiddleware -> Guards -> Interceptors (code before `next.handle()`) -> Pipes -> Route Handler -> Interceptors (eg: `next.handle().pipe( tap(() => changeResponse()) )` )-> Exception Filter (if exception is thrown)\n\nWith all three of them, you can inject other dependencies (like services,...) in their constructor.\n\n What is the lifespan of modules and providers in a NestJS application? Do they last for the lifespan of a request, or the application, or something else?\n\nA provider can have any of the following scopes:\n\n`SINGLETON` - A single instance of the provider is shared across the entire application. The instance lifetime is tied directly to the application lifecycle. Once the application has bootstrapped, all singleton providers have been instantiated. Singleton scope is used by default.\n\n`REQUEST` - A new instance of the provider is created exclusively for each incoming request. The instance is garbage-collected after the request has completed processing.\n\n`TRANSIENT` - Transient providers are not shared across consumers. Each consumer that injects a transient provider will receive a new, dedicated instance.\n\nUsing singleton scope is recommended for most use cases. Sharing providers across consumers and across requests means that an instance can be cached and its initialization occurs only once, during application startup.\n\nExample\n\n```\nimport { Injectable, Scope } from '@nestjs/common';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class CatsService {}\n```\n\n Are there any lifecycle hooks, in addition to OnModuleInit and OnModuleDestroy?\n\n`OnApplicationBootstrap` - Called once the application has fully started and is bootstrapped\n`OnApplicationShutdown` - Responds to the system signals (when application gets shutdown by e.g. SIGTERM). Use this hook to gracefully shutdown a Nest application. This feature is often used with Kubernetes, Heroku or similar services.\n\nBoth `OnModuleInit` and `OnApplicationBootstrap` hooks allow you to defer the application initialization process (return a Promise or mark the method as async).\n\n What causes a Module to be destroyed (and trigger the OnModuleDestroy event)?\n\nUsually shutdown signal from Kubernetes, Heroku or similar services.\n\n========================================\n\nCode:\n```text\nmiddleware\n```\n\n```text\npipes\n```\n\n```text\nguards\n```\n\n```text\ninterceptors\n```\n\n```text\nOnModuleInit\n```\n\n```text\nOnModuleDestroy\n```\n\n```text\nOnModuleDestroy\n```\n\n```text\nclose\n```\n\n```text\nINestApplication\n```\n\n```text\nimport { Injectable, Scope } from '@nestjs/common';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class CatsService {}\n```\n\n```text\nnext.handle()\n```\n\n```text\nnext.handle().pipe( tap(() => changeResponse()) )\n```\n\n```text\nSINGLETON\n```\n\n```text\nREQUEST\n```\n\n```text\nTRANSIENT\n```\n\n```text\nOnApplicationBootstrap\n```\n\n```text\nOnApplicationShutdown\n```\n\n```text\nOnModuleInit\n```\n\n```text\nOnApplicationBootstrap\n```\n\n========================================\n\nComments:\n- what is the best place to remove password data?\n- If you are talking about **input** data, you don't need to remove anything, but to be careful about how you store the data, and where you store it (I'd highly recommend to only store hashes using, for instance, `bcrypt` algorithm). If you are talking about **output** data, then Nest already proposes a way to do that, using Serialization. Please refer to the documentation: docs.nestjs.com/techniques/serialization. If you want to do it yourself, I'd recommend using reflection and decorators, combined with interceptors (but this is done by Serialization).","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":143,"estimatedTokens":1131}}509{"id":"stack-69435506","source":"stackoverflow","questionId":69435506,"title":"How to pass a dynamic port to the Websockets-gateway in NestJS?","tags":["websocket","configuration","nestjs","decorator"],"text":"Title: How to pass a dynamic port to the Websockets-gateway in NestJS?\nTags: websocket, configuration, nestjs, decorator\nSource: Stack Overflow\n\nQuestion:\nI wanted to dynamically set the Websockets-gateway port from config in NestJS. Below is my **websockets-gateway** code.\n\n```\nimport { WebSocketGateway } from '@nestjs/websockets';\n\nconst WS_PORT = parseInt(process.env.WS_PORT);\n\n@WebSocketGateway(WS_PORT)\nexport class WsGateway {\n constructor() {\n console.log(WS_PORT);\n }\n}\n```\n\nBut the WS_PORT is always NaN.\n\nThis is my **bootstrap** function insdie main.ts :\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule, { cors: false });\n const configService = app.get(ConfigService);\n initAdapters(app);\n await app.listen(configService.get(HTTP_PORT), () => {\n console.log('Listening on port ' + configService.get(HTTP_PORT));\n });\n}\n```\n\nBelow is my **app.module.ts** :\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({\n envFilePath: './src/config/dev.env',\n isGlobal: true,\n }),\n RedisModule,\n SocketStateModule,\n RedisPropagatorModule,\n JwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n secret: configService.get(JWT_SECRET_KEY),\n }),\n inject: [ConfigService],\n }),\n ],\n controllers: [AppController],\n providers: [WsGateway, AppService],\n})\nexport class AppModule {}\n```\n\nI put a console log in the Gateway constructor to print the value of 'WS_PORT' but it's always NaN.\n\n```\n[Nest] 13252 - 10/04/2021, 5:05:34 PM LOG [NestFactory] Starting Nest application...\nNaN\n```\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nYou can do it relatively straightforward if you decorate the `Gateway` before `app.init` is called:\n\n- Import the class in `main.ts`\n\n- Get an instance of your `ConfigurationService`\n\n- Manually call the decorator on the class with the config data\n\n```\nfunction decorateGateway(class_, config) {\n // Just calling the decorator as a function with the class\n // as argument does the same as `@WebSocketGateway`\n WebSocketGateway({\n cors: {\n origin: config.get(\"websocket.cors.origin\"),\n }\n })(class_)\n}\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule, {});\n const config = app.get(ConfigService);\n decorateGateway(ChatGateway, config);\n ...\n app.init();\n}\n```\n\nThe tricky part with a `Gateway` is that it starts up together with the server, and the decorator metadata needs to be applied to the class earlier than for other components. You can do this in `main.ts` before `app.init`.\n\n========================================\n\nCode:\n```text\nimport { WebSocketGateway } from '@nestjs/websockets';\n\nconst WS_PORT = parseInt(process.env.WS_PORT);\n\n@WebSocketGateway(WS_PORT)\nexport class WsGateway {\n  constructor() {\n    console.log(WS_PORT);\n  }\n}\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, { cors: false });\n  const configService = app.get(ConfigService);\n  initAdapters(app);\n  await app.listen(configService.get(HTTP_PORT), () => {\n    console.log('Listening on port ' + configService.get(HTTP_PORT));\n  });\n}\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      envFilePath: './src/config/dev.env',\n      isGlobal: true,\n    }),\n    RedisModule,\n    SocketStateModule,\n    RedisPropagatorModule,\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        secret: configService.get<string>(JWT_SECRET_KEY),\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n  controllers: [AppController],\n  providers: [WsGateway, AppService],\n})\nexport class AppModule {}\n```\n\n```text\n[Nest] 13252  - 10/04/2021, 5:05:34 PM     LOG [NestFactory] Starting Nest application...\nNaN\n```\n\n```js\nimport { INestApplicationContext } from '@nestjs/common';\nimport { IoAdapter } from '@nestjs/platform-socket.io';\nimport { ServerOptions } from 'socket.io';\nimport { ConfigService } from '@nestjs/config';\n\nexport class SocketIoAdapter extends IoAdapter {\nconstructor(\n  private app: INestApplicationContext,\n  private configService: ConfigService,\n) {\n  super(app);\n}\n\ncreateIOServer(port: number, options?: ServerOptions) {\n  port = this.configService.get<number>('SOCKETIO.SERVER.PORT');\n  const path = this.configService.get<string>('SOCKETIO.SERVER.PATH');\n  const origins = this.configService.get<string>(\n    'SOCKETIO.SERVER.CORS.ORIGIN',\n  );\n  const origin = origins.split(',');\n  options.path = path;\n  options.cors = { origin };\n  const server = super.createIOServer(port, options);\n  return server;\n}\n}\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\nimport { SocketIoAdapter } from './socket-io/socket-io.adapter';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const configService = app.get(ConfigService);\n  const hosts = configService.get<string>('CORS.HOST');\n  const hostsArray = hosts.split(',');\n  app.enableCors({\n    origin: hostsArray,\n    credentials: true,\n  });\n//Here you use the adapter and sent the config service\n  app.useWebSocketAdapter(new SocketIoAdapter(app, configService));\n  await app.listen(4300);\n}\nbootstrap();\n```\n\n```text\nSOCKETIO.SERVER.PORT=4101\nSOCKETIO.SERVER.PATH=\nSOCKETIO.SERVER.CORS.ORIGIN=http://localhost:4200,http://localhost.com:8080\n```\n\n```text\nSocketIoAdapter.ts\n```\n\n```text\nmain.ts\n```\n\n```text\nenv.local\n```\n\n```text\nport = this.configService.get<number>('SOCKETIO.SERVER.PORT');\n```\n\n```text\nparseInt(this.configService.get<number>('SOCKETIO.SERVER.PORT'), 10);\n```\n\n```js\nfunction decorateGateway(class_, config) {\n  // Just calling the decorator as a function with the class\n  // as argument does the same as `@WebSocketGateway`\n  WebSocketGateway({\n    cors: {\n      origin: config.get(\"websocket.cors.origin\"),\n    }\n  })(class_)\n}\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, {});\n  const config = app.get(ConfigService);\n  decorateGateway(ChatGateway, config);\n  ...\n  app.init();\n}\n```\n\n```text\nGateway\n```\n\n```text\napp.init\n```\n\n```text\nmain.ts\n```\n\n```text\nConfigurationService\n```\n\n```text\nGateway\n```\n\n```text\nmain.ts\n```\n\n```text\napp.init\n```\n\n```text\nimport * as dotenv from 'dotenv';\ndotenv.config();\n\nexport default () => {\n  return {\n    wsPort: parseInt(process.env.WS_PORT),\n  }\n}\n```\n\n```text\nimport envSetup from '../config/env';\n@WebSocketGateway(envSetup.wsPort)\n```\n\n```js\nimport { IoAdapter } from '@nestjs/platform-socket.io';\nimport { INestApplicationContext } from '@nestjs/common';\nimport { Server, ServerOptions } from 'socket.io';\nimport { CorsOptions } from 'cors';\n\nexport class Adapter extends IoAdapter {\n  constructor(\n    appOrHttpServer: INestApplicationContext,\n    private readonly corsOptions: CorsOptions,\n  ) {\n    super(appOrHttpServer);\n  }\n\n  create(port: number, options?: ServerOptions): Server {\n    return super.create(port, {\n      ...options,\n      cors: this.corsOptions,\n    });\n  }\n}\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\nimport { Adapter } from './chat/adapter';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const configService = app.get(ConfigService);\n\n  app.enableCors({\n    origin: configService.get('FRONTEND_URL'),\n  });\n\n  app.useWebSocketAdapter(\n    new Adapter(app, {\n      origin: configService.get('FRONTEND_URL'),\n    }),\n  );\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nFRONTEND_URL=http://localhost:5173\n```\n\n```text\nIoAdapter\n```\n\n```text\nbootstrap\n```\n\n```text\nFRONTEND_URL\n```\n\n========================================\n\nComments:\n- This is neat. Thanks you :)","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":369,"estimatedTokens":1951}}510{"id":"stack-54829935","source":"stackoverflow","questionId":54829935,"title":"NestJS - Mongoose @InjectConnection unit testing","tags":["node.js","typescript","mongoose","gridfs","nestjs"],"text":"Title: NestJS - Mongoose @InjectConnection unit testing\nTags: node.js, typescript, mongoose, gridfs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a service that uses the `@InjectConnection` decorator in it's constructor.\n\nI am unable to instantiate a testingModule for this service. The following error is thrown: `Nest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context.`\n\nService constructor:\n\n```\nconstructor(@InjectConnection() private readonly mongooseConnection: Mongoose,\n @Inject(Modules.Logger) private readonly logger: Logger) {\n this.attachmentGridFsRepository = gridfs({\n collection: 'attachments',\n model: Schemas.Attachment,\n mongooseConnection: this.mongooseConnection,\n });\n\n this.attachmentRepository = this.attachmentGridFsRepository.model;\n }\n```\n\nTest module constructor:\n\n```\nconst module: TestingModule = await Test.createTestingModule({\n imports: [\n WinstonModule.forRoot({\n transports: [\n new transports.Console({\n level: 'info',\n handleExceptions: false,\n format: format.combine(format.json()),\n }),\n ],\n }),\n ],\n providers: [AttachmentsService, {\n provide: getConnectionToken(''),\n useValue: {},\n }],\n}).compile();\n\nservice = module.get(AttachmentsService);\n```\n\nI realize that I will have to mock the connection object to be callable by GridFS, but right now I am unable to actually get the test module to build.\n\n========================================\n\nCode:\n```text\nconstructor(@InjectConnection() private readonly mongooseConnection: Mongoose,\n              @Inject(Modules.Logger) private readonly logger: Logger) {\n    this.attachmentGridFsRepository = gridfs({\n      collection: 'attachments',\n      model: Schemas.Attachment,\n      mongooseConnection: this.mongooseConnection,\n    });\n\n    this.attachmentRepository = this.attachmentGridFsRepository.model;\n  }\n```\n\n```text\nconst module: TestingModule = await Test.createTestingModule({\n  imports: [\n    WinstonModule.forRoot({\n      transports: [\n        new transports.Console({\n          level: 'info',\n          handleExceptions: false,\n          format: format.combine(format.json()),\n        }),\n      ],\n    }),\n  ],\n  providers: [AttachmentsService, {\n    provide: getConnectionToken(''),\n    useValue: {},\n  }],\n}).compile();\n\nservice = module.get<AttachmentsService>(AttachmentsService);\n```\n\n```text\n@InjectConnection\n```\n\n```text\nNest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context.\n```\n\n```text\nexport const DEFAULT_DB_CONNECTION = 'DatabaseConnection';\n```\n\n```text\nproviders: [AttachmentsService, {\n  provide: getConnectionToken('Database'),\n  useValue: {},\n}]\n```\n\n```text\nDatabaseConnection\n```\n\n```text\ngetConnectionToken('Database')\n```\n\n```text\ngetConnectionToken()\n```\n\n```text\ngetConnectionToken()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":122,"estimatedTokens":731}}511{"id":"stack-61434084","source":"stackoverflow","questionId":61434084,"title":"Saving files in file system in Nestjs","tags":["javascript","mysql","node.js","nestjs"],"text":"Title: Saving files in file system in Nestjs\nTags: javascript, mysql, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to store the `URL` of images sent from client using `multipart/form-data`in my `MySQL` database. I followed the docs but I can't really find out how I should save an image in server file system and return the URL back to the client.\n\nThis is my code:\n\n```\n@ApiTags('product-image')\n@Controller('product-image')\nexport class ProductImageController {\n constructor(public service: ProductImageService) {\n }\n\n @Post('upload')\n @UseInterceptors(FilesInterceptor('files'))\n uploadImage(@UploadedFiles() files) {\n console.log(files);\n // How can I save image files in\n // a custom path and return the path\n // back to the client?\n\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@ApiTags('product-image')\n@Controller('product-image')\nexport class ProductImageController {\n  constructor(public service: ProductImageService) {\n  }\n\n  @Post('upload')\n  @UseInterceptors(FilesInterceptor('files'))\n  uploadImage(@UploadedFiles() files) {\n    console.log(files);\n    // How can I save image files in\n    // a custom path and return the path\n    // back to the client?\n\n  }\n}\n```\n\n```text\nURL\n```\n\n```text\nmultipart/form-data\n```\n\n```text\nMySQL\n```\n\n```text\nimport { FilesInterceptor } from '@nestjs/platform-express';\nimport { diskStorage } from 'multer';\n\n@Post('upload')\n    @UseInterceptors(\n        FilesInterceptor('files', 20, {\n          storage: diskStorage({\n            destination: './uploads/',\n            filename: editFileName,\n          }),\n        //   fileFilter: imageFileFilter,\n        }),\n      )\n      uploadMultipleFiles(@UploadedFiles() files) {\n        const response = [];\n        files.forEach(file => {\n          const fileReponse = {\n            filename: file.filename,\n          };\n          response.push(fileReponse);\n        });\n        return response;\n      }\n```\n\n========================================\n\nComments:\n- Another question though: how can I return an image to the client? in express, we usually do `res.end()`, how can I return an image in nestjs?\n- @Get('image/:imgpath') seeUploadedFile(@Param('imgpath') image, @Res() res) { return res.sendFile(image, { root: './uploads' }); }\n- how can i move the save logic to service?","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":94,"estimatedTokens":577}}512{"id":"stack-60692331","source":"stackoverflow","questionId":60692331,"title":"Nestjs extend/combine decorators?","tags":["node.js","typescript","decorator","nestjs"],"text":"Title: Nestjs extend/combine decorators?\nTags: node.js, typescript, decorator, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have simple custom decorator:\n\n```\nexport const User: () => ParameterDecorator = createParamDecorator(\n (data: any, req): UserIdentity => {\n const user = getUser(req);\n return user;\n },\n);\n```\n\nAnd now, I need to validate if we have `email` in `user` object.\n\nThe problem is that I can't update my current decorator.\n\nCould I extend my current decorator?\n\nCreate a new decorator based on the previous one or create a new decorator and combine it?\n\n========================================\n\nCode:\n```text\nexport const User: () => ParameterDecorator = createParamDecorator(\n  (data: any, req): UserIdentity => {\n    const user = getUser(req);\n    return user;\n  },\n);\n```\n\n```text\nemail\n```\n\n```text\nuser\n```\n\n```js\nimport { applyDecorators } from '@nestjs/common';\n\nexport function Auth(...roles: Role[]) {\n  return applyDecorators(\n    SetMetadata('roles', roles),\n    UseGuards(AuthGuard, RolesGuard),\n    ApiBearerAuth(),\n    ApiUnauthorizedResponse({ description: 'Unauthorized\"' }),\n  );\n}\n```\n\n```js\n@Get()\nasync findOne(@User(new ValidationPipe()) user: UserEntity) {\n  console.log(user);\n}\n```\n\n```text\nuser\n```\n\n```text\nemail\n```\n\n```text\nAuth\n```\n\n```text\napplyDecorators\n```\n\n```text\nUser\n```\n\n```text\nValidationPipe\n```\n\n========================================\n\nComments:\n- Thx for answer. Unfortunatelly I can't extend the current decorator right now (it's in another project and we use it as an npm package). I used applyDecorators and it works like a charm.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":92,"estimatedTokens":399}}513{"id":"stack-59358741","source":"stackoverflow","questionId":59358741,"title":"Are there any differences between using `forRoot` or `register` when creating a Dynamic Module in NestJS?","tags":["nestjs"],"text":"Title: Are there any differences between using `forRoot` or `register` when creating a Dynamic Module in NestJS?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am new to NestJS and I would like to create a Dynamic Module for the injection of a metrics reporter provider. The documentation for NestJS says the following about Dynamic Modules:\n\n ...by convention we should call it either `forRoot()` or `register()` [when creating a Dynamic Module]\n\nUnfortunately, the documentation gives no clear guidance as to when you should implement `register` or `forRoot` or what the expectations in the implementation of the two functions should be. This leads me to believe that I could call the function `cheeseburger` and as long as it returns a `DynamicModule`.\n\n========================================\n\nCode:\n```text\nforRoot()\n```\n\n```text\nregister()\n```\n\n```text\nregister\n```\n\n```text\nforRoot\n```\n\n```text\ncheeseburger\n```\n\n```text\nDynamicModule\n```\n\n```text\nforRoot\n```\n\n```text\nforRootAsync\n```\n\n```text\nforFeature\n```\n\n```text\nAppModule\n```\n\n```text\nforFeature()\n```\n\n```text\ncheeseburger\n```\n\n========================================\n\nComments:\n- Thanks Jay. This explanation seems reasonable.\n- @Jay do you by chance have an example somewhere demonstrating this pattern?","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":67,"estimatedTokens":319}}514{"id":"stack-63002127","source":"stackoverflow","questionId":63002127,"title":"Parsing error \"parserOptions.project\" has been set for @typescript-eslint/parser","tags":["node.js","phpstorm","eslint","nestjs","prettier"],"text":"Title: Parsing error \"parserOptions.project\" has been set for @typescript-eslint/parser\nTags: node.js, phpstorm, eslint, nestjs, prettier\nSource: Stack Overflow\n\nQuestion:\nI created a new NestJS project which is a very popular NodeJS framework. But I have this error (see title) on my IDE (PhpStorm 2020.2-Beta) and ESLint doesn't work at all.\n\nI've used the NestJS CLI :\n\n```\nnest new nestjs-micro\n```\n\nI don't seem to be the only one with this problem, so it would be nice to find the cause of this problem and **fix it once and for all.**\n\nI already have an open issue but I haven't had an answer, this is really very problematic.\n\nIf anyone has an idea on how to fix the problem and **keeping an ESLint / Prettier integration with PhpStorm**, thanks.\n\n**Repro**\n\n```\n// .eslintrc.js\nmodule.exports = {\n parser: '@typescript-eslint/parser',\n parserOptions: {\n project: 'tsconfig.json',\n sourceType: 'module',\n },\n plugins: ['@typescript-eslint/eslint-plugin'],\n extends: [\n 'plugin:@typescript-eslint/eslint-recommended',\n 'plugin:@typescript-eslint/recommended',\n 'prettier',\n 'prettier/@typescript-eslint',\n ],\n root: true,\n env: {\n node: true,\n jest: true,\n },\n rules: {\n '@typescript-eslint/interface-name-prefix': 'off',\n '@typescript-eslint/explicit-function-return-type': 'off',\n '@typescript-eslint/no-explicit-any': 'off',\n },\n};\n```\n\n```\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n}\n```\n\n**Additional Info**\nhttps://user-images.githubusercontent.com/42717232/87725198-1d260a00-c7bd-11ea-9520-fd0d69fd7790.png\n\n**Versions**\n\n```\nTypescript: 3.7.4\nNode: 14.3.0\nESLint: 7.1.0\n@typescript-eslint/parser: 3.0.2\nYarn: 1.22.4\n```\n\n========================================\n\nTop Answer:\nFWIW what worked for me with this error was to add `ignorePatterns: ['.eslintrc.js'],` to the `.eslintrc.js` file. This line tells `eslint` to ignore the `.eslintrc.js` file (since it's not included in the `tsconfig` declared project `rootDir`).\n\n========================================\n\nCode:\n```text\nnest new nestjs-micro\n```\n\n```js\n// .eslintrc.js\nmodule.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceType: 'module',\n  },\n  plugins: ['@typescript-eslint/eslint-plugin'],\n  extends: [\n    'plugin:@typescript-eslint/eslint-recommended',\n    'plugin:@typescript-eslint/recommended',\n    'prettier',\n    'prettier/@typescript-eslint',\n  ],\n  root: true,\n  env: {\n    node: true,\n    jest: true,\n  },\n  rules: {\n    '@typescript-eslint/interface-name-prefix': 'off',\n    '@typescript-eslint/explicit-function-return-type': 'off',\n    '@typescript-eslint/no-explicit-any': 'off',\n  },\n};\n```\n\n```text\n// tsconfig.json\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true\n  }\n}\n```\n\n```text\nTypescript: 3.7.4\nNode: 14.3.0\nESLint: 7.1.0\n@typescript-eslint/parser: 3.0.2\nYarn: 1.22.4\n```\n\n```text\n{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"dist/**/*spec.ts\"],\n  \"include\": [\"src/**/*\", \".eslintrc.js\"]\n}\n```\n\n```text\n\"include\": [\n  \".eslintrc.js\",\n]\n```\n\n```text\nignorePatterns: ['.eslintrc.js'],\n```\n\n```text\n.eslintrc.js\n```\n\n```text\neslint\n```\n\n```text\n.eslintrc.js\n```\n\n```text\ntsconfig\n```\n\n```text\nrootDir\n```\n\n```text\n\"include\": [\n  ...\n  \"typings.d.ts\",\n  ...\n]\n```\n\n```text\ntypings.d.ts\n```\n\n```text\n\"allowJs\": true\n```\n\n```text\ntsconfig.json\n```\n\n```text\ncompilerOptions\n```\n\n========================================\n\nComments:\n- I needed to add `env: { browser: true, es6: true, jest: true, node: true, },` to .eslintrc.js after doing that.\n- This was also the solution to allow cascading eslintrc files, so that I can adjust linting rules in one subdirectory while still inheriting rules from the root config.\n- In my case I lint `js`, `cjs` and `ts`/`tsx` with the same eslint command and use override rules for several subsets of the checked files. I needed to add an `overrides` which disables rules requiring type config for all `*.cjs` and `*.js` files: `overrides: [{ files: ['*.js', '*.cjs'], rules: { '@typescript-eslint&#47;no-floating-promises': 'off' }}]`","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":216,"estimatedTokens":1156}}515{"id":"stack-62017504","source":"stackoverflow","questionId":62017504,"title":"Using an async method in a RxJS NextObserver","tags":["async-await","rxjs","nestjs"],"text":"Title: Using an async method in a RxJS NextObserver\nTags: async-await, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use an async function in a NestJS interceptor. These interceptors use RxJS Observables like this:\n\n```\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n async intercept(context: ExecutionContext, next: CallHandler): Promise> {\n await doBegin();\n return next\n .handle()\n .pipe(\n tap(\n () => console.log(\"Done\"),\n (e) => console.error(e)\n )\n );\n }\n}\n```\n\nThis works, but what if I want the methods in `tap` to be async? The method signature is:\n\n```\n(value: T) => void\n```\n\nCan I just put an async method in there? Or should I take a different approach?\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n    async intercept<T>(context: ExecutionContext, next: CallHandler): Promise<Observable<T>> {\n        await doBegin();\n        return next\n            .handle()\n            .pipe(\n                tap(\n                    () => console.log(\"Done\"),\n                    (e) => console.error(e)\n                )\n            );\n    }\n}\n```\n\n```text\n(value: T) => void\n```\n\n```text\ntap\n```\n\n```js\nconst myAsyncFunction = () => {\n  // a sample of promise.\n  return new Promise(resolve => {\n    setTimeout(() => {\n      console.log('Promise!');\n      resolve();\n    }, 1000);\n  });\n}\n```\n\n```js\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n    async intercept<T>(context: ExecutionContext, next: CallHandler): Promise<Observable<T>> {\n        await doBegin();\n        return next\n            .handle()\n            .pipe(\n                mergeMap(value => from(myAsyncFunction()).pipe(\n                  ignoreElements(),\n                  // catchError(() => EMPTY), // catching all errors.\n                  endWith(value),\n                )),\n                tap(\n                  () => {}, // nothing to do here, we need error.\n                  (e) => console.error(e), // or catchError if you wan't to handle it.\n                ),\n            );\n    }\n}\n```\n\n```js\n@Injectable()\nexport class MyInterceptor implements NestInterceptor {\n    async intercept<T>(context: ExecutionContext, next: CallHandler): Promise<Observable<T>> {\n        await doBegin();\n        return next\n            .handle()\n            .pipe(\n                tap(\n                  myAsyncFunction, // if it returns `new Promise` - it will work.\n                  (e) => console.error(e),\n                ),\n            );\n    }\n}\n```\n\n```text\nmergeMap\n```\n\n```text\ntap\n```\n\n```text\n.then\n```\n\n========================================\n\nComments:\n- I'm curious how adding the `then()` would help? Doesn't it just return a Promise? Why would it be different from `() => myAsyncFunction()`?\n- myAsyncFunction() returns a promise, myAsyncFunction().then() triggers its execution. Depends of course how the promise was written, but to ensure it was really triggered it's better to call `.then`, it's kind of `await Promise`. if it's a correct promise then `myAsyncFunction()` simply returns its pointer but doesn't trigger it.\n- Actually you are right and you don't need `.then` in case of `new Promise`. I was confused by my current project :) there we require a `.then` call to trigger original callback.\n- I tried this in a local project (without NestJS). Both techniques seem to work, but the mergemap works better IMO. In that case the async function is called before I log the result of the observable stream. In the second case, my async function is executed, but after logging the result of the stream. Because I'm working in AWS Lambda, and I'm not sure if the rest of the event loop will be executed, I'll try the mergeMap technique.\n- AWS Lambda will wait for it in both cases, I had with it experience in past. Node has an event loop that checks if there's something to do at some point: youtube.com/watch?v=8aGhZQkoFbQ, anyway I would vote for mergeMap too because it has better error handling.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":131,"estimatedTokens":1009}}516{"id":"stack-71548592","source":"stackoverflow","questionId":71548592,"title":"Nest JS & TypeORM cannot use findOne properly","tags":["javascript","nestjs","typeorm"],"text":"Title: Nest JS & TypeORM cannot use findOne properly\nTags: javascript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a user instance based on `id` (same happens for other attributes such as `email`. Inside the Service, this is my code:\n\n```\n@Injectable()\nexport class UserService {\n @InjectRepository(User)\n private readonly repository: Repository;\n\n async findOne(id: number): Promise {\n const user = await this.repository.findOne(id);\n return user;\n }\n}\n```\n\nand my User entity is:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ type: 'varchar', length: 120 })\n public name: string;\n\n @Column({ type: 'varchar', length: 120 })\n public email: string;\n}\n```\n\nThe problem is that I always get this error:\n`src/api/user/user.service.ts - error TS2559: Type 'number' has no properties in common with type 'FindOneOptions'.`\n\nOther methods such as `getAll` work just fine:\n\n```\npublic getAllUsers(): Promise {\n return this.repository.find();\n}\n```\n\n========================================\n\nTop Answer:\nThere are some breaking changes in `typeorm`. I wouldn't suggest downgrading, instead check the latest methods.\n\n`findOne(id);`\nis now changed to\n\n```\nfindOneBy({\nid: id // where id is your column name\n})\n```\n\nAnd `find()` is now\n\n```\nfind({\n select: {\n id: true,\n email: true,\n password: true,\n },\n});\n```\n\nPlease check this link for more information.\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class UserService {\n  @InjectRepository(User)\n  private readonly repository: Repository<User>;\n\n  async findOne(id: number): Promise<User> {\n    const user = await this.repository.findOne(id);\n    return user;\n  }\n}\n```\n\n```js\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  public id: number;\n\n  @Column({ type: 'varchar', length: 120 })\n  public name: string;\n\n  @Column({ type: 'varchar', length: 120 })\n  public email: string;\n}\n```\n\n```js\npublic getAllUsers(): Promise<User[]> {\n  return this.repository.find();\n}\n```\n\n```text\nid\n```\n\n```text\nemail\n```\n\n```text\nsrc/api/user/user.service.ts - error TS2559: Type 'number' has no properties in common with type 'FindOneOptions<User>'.\n```\n\n```text\ngetAll\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm@0.2\n```\n\n```text\n@nestjs/typeorm@8.0\n```\n\n```text\ntypeorm@0.3\n```\n\n```text\npackage.json\n```\n\n```text\n\"typeorm\": \"^0.2.34\"\n```\n\n```text\nfindOneBy({\nid: id // where id is your column name\n})\n```\n\n```text\nfind({\n  select: {\n    id: true,\n    email: true,\n    password: true,\n  },\n});\n```\n\n```text\ntypeorm\n```\n\n```text\nfindOne(id);\n```\n\n```text\nfind()\n```\n\n```text\nasync findOne(id: number): Promise<User> {\n    const user = await this.repository.findOne({\n           where: { id }\n    });\n    return user;\n}\n```\n\n```text\ntypeorm\n```\n\n```text\nfindOne\n```\n\n```text\nconst user = await userRepository.findOneBy({\n    id: id // where id is your column name\n})\n```\n\n========================================\n\nComments:\n- I think this should be the correct answer. The approach is mentioned in the change log typeorm.io/changelog#features-4\n- What if I have nested entity. Something like- `select: { client: { user: true } }` This thing does not work in latest version. Is there any solution?\n- @Srk95 I think you need to use the `where` in the docs github.com/typeorm/typeorm/releases/tag/0.3.0. For example `userRepository.find({ where: { photos: { album: { name: \"profile\" } } } })`\n- @SananAli `select` clause and `where` clause are different. I want to have the nested structure under `select` clause.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":209,"estimatedTokens":889}}517{"id":"stack-75581669","source":"stackoverflow","questionId":75581669,"title":"Customize error message in Nest js using class-validator","tags":["validation","nestjs","class-validator"],"text":"Title: Customize error message in Nest js using class-validator\nTags: validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI am working on a nest project, and using class-validator for validation.\n\nCurrently if there is any validation error, I am getting error response as\n\n```\n{\n \"statusCode\": 400,\n \"message\": [\n \"Title is too long. Maximal length is 50 characters, but actual is $value\",\n \"Title is too short. Minimal length is 10 characters, but actual is $value\"\n ],\n \"error\": \"Bad Request\"\n}\n```\n\nBut instead of message as array of string, can we have message as array of object. So, that FE can easy figure out which field is having the error, like\n\n```\n{\n \"message\": [\n { \"field\": \"title\", \"error\": \"Title is too long. Maximal length is 50 characters, but actual is $value\" },\n { \"field\": \"title\", \"error\": \"Title is too short. Minimal length is 10 characters, but actual is $value\" }\n ]\n}\n```\n\n========================================\n\nTop Answer:\nyou can achieve a similar error output as the default ValidationPipe by creating a custom pipe:\n\n```\nconst object = plainToInstance(metatype, value);\nconst errors = await validate(object); \nif (errors) {\n const errorMessages = [];\n errors.forEach((error) =>\n Object.entries(error.constraints).forEach((elt) =>\n errorMessages.push(elt[1]),\n ),\n );\n throw new BadRequestException(errorMessages);\n }\n```\n\nthe output looks like this:\n\n```\n{\n \"message\": [\n \"title should not be empty\",\n \"title must be a string\",\n \"ai_subject must be a string\"\n ],\n \"error\": \"Bad Request\",\n \"statusCode\": 400\n }\n```\n\nreference: https://docs.nestjs.com/pipes#class-validator\n\n========================================\n\nCode:\n```text\n{\n    \"statusCode\": 400,\n    \"message\": [\n        \"Title is too long. Maximal length is 50 characters, but actual is $value\",\n        \"Title is too short. Minimal length is 10 characters, but actual is $value\"\n    ],\n    \"error\": \"Bad Request\"\n}\n```\n\n```text\n{\n    \"message\": [\n        { \"field\": \"title\", \"error\": \"Title is too long. Maximal length is 50 characters, but actual is $value\" },\n        { \"field\": \"title\", \"error\": \"Title is too short. Minimal length is 10 characters, but actual is $value\" }\n    ]\n}\n```\n\n```js\napp.useGlobalPipes(\n  new ValidationPipe({\n    exceptionFactory: (validationErrors: ValidationError[] = []) => {\n      return new BadRequestException(\n        validationErrors.map((error) => ({\n          field: error.property,\n          error: Object.values(error.constraints).join(', '),\n        })),\n      );\n    },\n  }),\n);\n```\n\n```text\nconst object = plainToInstance(metatype, value);\nconst errors = await validate(object);    \nif (errors) {\n      const errorMessages = [];\n      errors.forEach((error) =>\n        Object.entries(error.constraints).forEach((elt) =>\n          errorMessages.push(elt[1]),\n        ),\n      );\n      throw new BadRequestException(errorMessages);\n    }\n```\n\n```text\n{\n      \"message\": [\n        \"title should not be empty\",\n        \"title must be a string\",\n        \"ai_subject must be a string\"\n      ],\n      \"error\": \"Bad Request\",\n      \"statusCode\": 400\n     }\n```\n\n========================================\n\nComments:\n- I used this code but it's not working for me in gql API. Can you please confirm or for gql","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":134,"estimatedTokens":815}}518{"id":"stack-72344455","source":"stackoverflow","questionId":72344455,"title":"Create repository when EntityRepository is deprecated typeorm","tags":["nestjs","typeorm"],"text":"Title: Create repository when EntityRepository is deprecated typeorm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI usually use this code to create a repository:\n\n```\nimport { EntityRepository, Repository } from 'typeorm'\nimport { User } from './user.entity'\n \n@EntityRepository(User)\nexport class UserRepository extends Repository {\n getInactiveUsers(): Promise {\n return this.createQueryBuilder()\n .where('isActive = :active', { active: false })\n .getMany()\n }\n}\n```\n\nHowever, now `EntityRepository` is deprecated. I found a reference but I think it's quite complex. I wonder if there is a simpler way to solve it?\n\n========================================\n\nTop Answer:\nfor the time being syntax below works for me:\n\n```\nconst queryBuilder = AppDataSource.getRepository(Post).createQueryBuilder(\"post\");\n```\n\nI hope this helps\n\nhttps://typeorm.io/select-query-builder#what-is-querybuilder\n\n========================================\n\nCode:\n```js\nimport { EntityRepository, Repository } from 'typeorm'\nimport { User } from './user.entity'\n    \n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n  getInactiveUsers(): Promise<User[]> {\n    return this.createQueryBuilder()\n      .where('isActive = :active', { active: false })\n      .getMany()\n  }\n}\n```\n\n```text\nEntityRepository\n```\n\n```text\n\"typeorm\": \"0.2.45\",\n\"@nestjs/typeorm\": \"8.0.3\",\n```\n\n```text\nnpm i @nestjs/typeorm@8.0.3 typeorm@0.2.45\n```\n\n```text\nconst queryBuilder = AppDataSource.getRepository(Post).createQueryBuilder(\"post\");\n```\n\n========================================\n\nComments:\n- not working \"Property 'getRepository' does not exist on type 'typeof DataSource'\"\n- This is not possible when you have @nestjs/common in version 9.X as a dependency.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":75,"estimatedTokens":439}}519{"id":"stack-70907953","source":"stackoverflow","questionId":70907953,"title":"Class-Validator (Node.js) Get another property value within custom validation","tags":["node.js","nestjs","class-validator"],"text":"Title: Class-Validator (Node.js) Get another property value within custom validation\nTags: node.js, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nAt the moment, I have a very simple class-validator file with a ValidationPipe in Nest.js as follows:\n\n```\nimport {\n IsDateString,\n IsEmail,\n IsOptional,\n IsString,\n Length,\n Max,\n} from 'class-validator';\n\nexport class UpdateUserDto {\n @IsString()\n id: string;\n\n @Length(2, 50)\n @IsString()\n firstName: string;\n\n @IsOptional()\n @Length(2, 50)\n @IsString()\n middleName?: string;\n\n @Length(2, 50)\n @IsString()\n lastName: string;\n\n @IsEmail()\n @Max(255)\n email: string;\n\n @Length(8, 50)\n password: string;\n\n @IsDateString()\n dateOfBirth: string | Date;\n}\n```\n\nLets say in the above \"UpdateUserDto,\" the user passes an \"email\" field. I want to build a custom validation rule through class-validator such that:\n\n- Check if email address is already taken by a user from the DB\n\n- If the email address is already in use, check if the current user (using the value of 'id' property) is using it, if so, validation passes, otherwise, if it is already in use by another user, the validation fails.\n\nWhile checking if the email address is already in use is a pretty simple task, how would you be able to pass the values of other properties within the DTO to a custom decorator `@IsEmailUsed`\n\n========================================\n\nTop Answer:\nLuckily for us, the **class-validator** provides a very handy **useContainer** function, which allows setting the container to be used by the class-validor library.\nSo add this code in your main.ts file (app variable is your Nest application instance):\n\n```\nuseContainer(app.select(AppModule), { fallbackOnErrors: true });\n```\n\nIt allows the **class-validator** to use the NestJS dependency injection container.\n\n```\n@ValidatorConstraint({ name: 'emailId', async: true })\n@Injectable()\nexport class CustomEmailvalidation implements ValidatorConstraintInterface {\n constructor(private readonly prisma: PrismaService) {}\n\n async validate(value: string, args: ValidationArguments): Promise {\n return this.prisma.user\n .findMany({ where: { email: value } })\n .then((user) => {\n if (user) return false;\n return true;\n });\n }\n defaultMessage(args: ValidationArguments) {\n return `Email already exist`;\n }\n}\n```\n\nDon't forget to declare your injectable classes as providers in the appropriate module.\nNow you can use your custom validation constraint. Simply decorate the class property with @Validate(CustomEmailValidation) decorator:\n\n```\nexport class CreateUserDto {\n @Validate(customEmailValidation)\n email: string;\n\n name: string;\n mobile: number;\n}\n```\n\nIf the email already exists in the database, you should get an error with the default message \"Email already exists\". Although using @Validate() is fine enough, you can write your own decorator, which will be much more convenient. Having written Validator Constraint is quick and easy. We need to just write decorator factory with registerDecorator() function.\n\n```\nexport function Unique(validationOptions?: ValidationOptions) {\n return function (object: any, propertyName: string) {\n registerDecorator({\n target: object.constructor,\n propertyName: propertyName,\n options: validationOptions,\n validator: CustomEmailvalidation,\n });\n };\n}\n```\n\nAs you can see, you can either write new validator logic or use written before validator constraint (in our caseโ€Š-โ€ŠUnique class).\nNow we can go back to our User class and use the @Unique validator instead of the @Validate(CustomEmailValidation) decorator.\n\n```\nexport class CreateUserDto {\n @Unique()\n email: string;\n\n name: string;\n mobile: number;\n}\n```\n\n========================================\n\nCode:\n```text\nimport {\n  IsDateString,\n  IsEmail,\n  IsOptional,\n  IsString,\n  Length,\n  Max,\n} from 'class-validator';\n\nexport class UpdateUserDto {\n  @IsString()\n  id: string;\n\n  @Length(2, 50)\n  @IsString()\n  firstName: string;\n\n  @IsOptional()\n  @Length(2, 50)\n  @IsString()\n  middleName?: string;\n\n  @Length(2, 50)\n  @IsString()\n  lastName: string;\n\n  @IsEmail()\n  @Max(255)\n  email: string;\n\n  @Length(8, 50)\n  password: string;\n\n  @IsDateString()\n  dateOfBirth: string | Date;\n}\n```\n\n```text\n@IsEmailUsed\n```\n\n```text\nimport { PrismaService } from '../../prisma/prisma.service';\nimport {\n  registerDecorator,\n  ValidationOptions,\n  ValidatorConstraint,\n  ValidatorConstraintInterface,\n  ValidationArguments,\n} from 'class-validator';\nimport { Injectable } from '@nestjs/common';\n\n@ValidatorConstraint({ name: 'Unique', async: true })\n@Injectable()\nexport class UniqueConstraint implements ValidatorConstraintInterface {\n  constructor(private readonly prisma: PrismaService) {}\n\n  async validate(value: any, args: ValidationArguments): Promise<boolean> {\n    const [model, property = 'id', exceptField = null] = args.constraints;\n\n    if (!value || !model) return false;\n\n    const record = await this.prisma[model].findUnique({\n      where: {\n        [property]: value,\n      },\n    });\n\n    if (record === null) return true;\n\n    if (!exceptField) return false;\n\n    const exceptFieldValue = (args.object as any)[exceptField];\n    if (!exceptFieldValue) return false;\n\n    return record[exceptField] === exceptFieldValue;\n  }\n\n  defaultMessage(args: ValidationArguments) {\n    return `${args.property} entered is not valid`;\n  }\n}\n\nexport function Unique(\n  model: string,\n  uniqueField: string,\n  exceptField: string = null,\n  validationOptions?: ValidationOptions,\n) {\n  return function (object: any, propertyName: string) {\n    registerDecorator({\n      target: object.constructor,\n      propertyName: propertyName,\n      options: validationOptions,\n      constraints: [model, uniqueField, exceptField],\n      validator: UniqueConstraint,\n    });\n  };\n}\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  ...\n  // Line below needs to be added.\n  useContainer(app.select(AppModule), { fallbackOnErrors: true });\n  ...\n}\n```\n\n```text\n@Module({\n  imports: ...,\n  controllers: [AppController],\n  providers: [\n    AppService,\n    PrismaService,\n    ...,\n    // Line below added\n    UniqueConstraint,\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nexport class UpdateUserDto {\n  @IsString()\n  id: string;\n\n  @IsEmail()\n  @Unique('user', 'email', 'id') // Adding this will check in the user table for a user with email entered, if it is already taken, it will check if it is taken by the same current user, and if so, no issues with validation, otherwise, validation fails.\n  email: string;\n}\n```\n\n```text\n@CurrentUser\n```\n\n```js\nuseContainer(app.select(AppModule), { fallbackOnErrors: true });\n```\n\n```js\n@ValidatorConstraint({ name: 'emailId', async: true })\n@Injectable()\nexport class CustomEmailvalidation implements ValidatorConstraintInterface {\n  constructor(private readonly prisma: PrismaService) {}\n\n  async validate(value: string, args: ValidationArguments): Promise<boolean> {\n    return this.prisma.user\n      .findMany({ where: { email: value } })\n      .then((user) => {\n        if (user) return false;\n        return true;\n      });\n  }\n  defaultMessage(args: ValidationArguments) {\n    return `Email already exist`;\n  }\n}\n```\n\n```js\nexport class CreateUserDto {\n  @Validate(customEmailValidation)\n  email: string;\n\n  name: string;\n  mobile: number;\n}\n```\n\n```js\nexport function Unique(validationOptions?: ValidationOptions) {\n  return function (object: any, propertyName: string) {\n    registerDecorator({\n      target: object.constructor,\n      propertyName: propertyName,\n      options: validationOptions,\n      validator: CustomEmailvalidation,\n    });\n  };\n}\n```\n\n```js\nexport class CreateUserDto {\n  @Unique()\n  email: string;\n\n  name: string;\n  mobile: number;\n}\n```\n\n========================================\n\nComments:\n- Pretty much the same thing I did, good stuff.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":335,"estimatedTokens":1958}}520{"id":"stack-53107886","source":"stackoverflow","questionId":53107886,"title":"Nest.js framework hot reload doesn't work","tags":["node.js","webpack-dev-server","nestjs"],"text":"Title: Nest.js framework hot reload doesn't work\nTags: node.js, webpack-dev-server, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've followed the steps of the documentation:\n\nhttps://docs.nestjs.com/techniques/hot-reload\n\nI'm running this command: `npm run webpack` but it closes, it returns me the prompt and it doesn't stay watching the files:\n\n```\ngabriel@roraima-tv:/var/www/studying/tera-ping-pong$ npm run webpack\n\n > tera-ping-pong@0.0.0 webpack /var/www/studying/tera-ping-pong\n > webpack --config webpack.config.js\n\n webpack is watching the filesโ€ฆ\n\n Hash: 6e13d56ba7d77331e5c2\n Version: webpack 4.23.1\n Time: 3014ms\n Built at: 11/01/2018 1:39:11 PM\n Asset Size Chunks Chunk Names\n dist/app.controller.d.ts 177 bytes [emitted] \n dist/app.module.d.ts 35 bytes [emitted] \n dist/app.service.d.ts 56 bytes [emitted] \n dist/main.d.ts 11 bytes [emitted] \n dist/main.hmr.d.ts 11 bytes [emitted] \n server.js 39 KiB main [emitted] main\n Entrypoint main = server.js\n [0] multi webpack/hot/poll?1000 ./src/main.hmr.ts 40 bytes {main} [built]\n [./node_modules/webpack/hot/log-apply-result.js] (webpack)/hot/log-apply-result.js 1.27 KiB {main} [built]\n [./node_modules/webpack/hot/log.js] (webpack)/hot/log.js 1.11 KiB {main} [built]\n [./node_modules/webpack/hot/poll.js?1000] (webpack)/hot/poll.js? 1000 1.15 KiB {main} [built]\n [./src/app.controller.ts] 1.44 KiB {main} [built]\n [./src/app.module.ts] 1.03 KiB {main} [built]\n [./src/app.service.ts] 883 bytes {main} [built]\n [./src/main.hmr.ts] 1.07 KiB {main} [built]\n [@nestjs/common] external \"@nestjs/common\" 42 bytes {main} [built]\n [@nestjs/core] external \"@nestjs/core\" 42 bytes {main} [built]\n gabriel@roraima-tv:/var/www/studying/tera-ping-pong$\n```\n\nTherefore, whenever I add my *.ts files changes and they aren't being reloaded until the server restarts.\n\n========================================\n\nTop Answer:\nyou can just use this command in the CLI, it comes by default :\n\n```\nnpm run start:dev\n```\n\n========================================\n\nCode:\n```text\ngabriel@roraima-tv:/var/www/studying/tera-ping-pong$ npm run webpack\n\n    > tera-ping-pong@0.0.0 webpack /var/www/studying/tera-ping-pong\n    > webpack --config webpack.config.js\n\n\n    webpack is watching the filesโ€ฆ\n\n    Hash: 6e13d56ba7d77331e5c2\n    Version: webpack 4.23.1\n    Time: 3014ms\n    Built at: 11/01/2018 1:39:11 PM\n                       Asset       Size  Chunks             Chunk         Names\n    dist/app.controller.d.ts  177 bytes          [emitted]  \n        dist/app.module.d.ts   35 bytes          [emitted]  \n       dist/app.service.d.ts   56 bytes          [emitted]  \n              dist/main.d.ts   11 bytes          [emitted]  \n          dist/main.hmr.d.ts   11 bytes          [emitted]  \n                   server.js     39 KiB    main  [emitted]  main\n    Entrypoint main = server.js\n    [0] multi webpack/hot/poll?1000 ./src/main.hmr.ts 40 bytes {main}         [built]\n    [./node_modules/webpack/hot/log-apply-result.js]         (webpack)/hot/log-apply-result.js 1.27 KiB {main} [built]\n    [./node_modules/webpack/hot/log.js] (webpack)/hot/log.js 1.11 KiB         {main} [built]\n    [./node_modules/webpack/hot/poll.js?1000] (webpack)/hot/poll.js?        1000 1.15 KiB {main} [built]\n    [./src/app.controller.ts] 1.44 KiB {main} [built]\n    [./src/app.module.ts] 1.03 KiB {main} [built]\n    [./src/app.service.ts] 883 bytes {main} [built]\n    [./src/main.hmr.ts] 1.07 KiB {main} [built]\n    [@nestjs/common] external \"@nestjs/common\" 42 bytes {main} [built]\n    [@nestjs/core] external \"@nestjs/core\" 42 bytes {main} [built]\n    gabriel@roraima-tv:/var/www/studying/tera-ping-pong$\n```\n\n```text\nnpm run webpack\n```\n\n```text\nnpm i --save-dev webpack-node-externals start-server-webpack-plugin\n```\n\n```text\nconst webpack = require('webpack');\nconst nodeExternals = require('webpack-node-externals');\nconst StartServerPlugin = require('start-server-webpack-plugin');\n\nmodule.exports = function(options) {\n  return {\n    ...options,\n    entry: ['webpack/hot/poll?100', options.entry],\n    watch: true,\n    externals: [\n      nodeExternals({\n        allowlist: ['webpack/hot/poll?100'],\n      }),\n    ],\n    plugins: [\n      ...options.plugins,\n      new webpack.HotModuleReplacementPlugin(),\n      new webpack.WatchIgnorePlugin([/\\.js$/, /\\.d\\.ts$/]),\n      new StartServerPlugin({ name: options.output.filename }),\n    ],\n  };\n};\n```\n\n```text\ndeclare const module: any;\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n\n  if (module.hot) {\n    module.hot.accept();\n    module.hot.dispose(() => app.close());\n  }\n}\nbootstrap();\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nnpm start\n```\n\n```text\nnpm start:dev\n```\n\n```text\nnest start --watch\n```\n\n========================================\n\nComments:\n- What platform are you using? Windows with Linux subsystem?\n- I followed the above instruction but got an ERROR Cannot read property 'HotModuleReplacementPlugin' of undefined\n- This should be the accepted answer!!\n- Correct me if I'm wrong but, although It works similarly to hot reloading, I believe this command line simply restarts the whole NestJS application, which works differently from a hot-reload, that reloads only the specific file you changed. It gets the job done and frankly it is more than enough for me, but it is not EXACTLY a hot-reload feature. This is why I believe this answer was not selected as the correct answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":163,"estimatedTokens":1359}}521{"id":"stack-50595647","source":"stackoverflow","questionId":50595647,"title":"Apply one Guard to multiple routes in Nestjs","tags":["nestjs"],"text":"Title: Apply one Guard to multiple routes in Nestjs\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nFor example: to apply one middleware to multiple routes we can use:\n\n```\nexport class UserModule {\n public configure(consumer: MiddlewaresConsumer) {\n consumer.apply(AuthMiddleware).forRoutes(\n { path: '/users', method: RequestMethod.GET },\n { path: '/users/:id', method: RequestMethod.GET },\n { path: '/users/:id', method: RequestMethod.PUT },\n { path: '/users/:id', method: RequestMethod.DELETE },\n );\n }\n}\n```\n\nI would like apply **AuthGuard** to multiple routes, ยฟ what is the best practice ? thanks ...\n\nCurrenly I use one by one decorator inside controller function like this, \n\n```\n@Get()\n@UseGuards(AuthGuard('jwt'))\nasync findAll(@Request() request): Promise {\n return await this.usersService.findAll();\n}\n```\n\nbut I'm looking for a masive implementation\n\n========================================\n\nCode:\n```text\nexport class UserModule {\n    public configure(consumer: MiddlewaresConsumer) {\n        consumer.apply(AuthMiddleware).forRoutes(\n            { path: '/users', method: RequestMethod.GET },\n            { path: '/users/:id', method: RequestMethod.GET },\n            { path: '/users/:id', method: RequestMethod.PUT },\n            { path: '/users/:id', method: RequestMethod.DELETE },\n        );\n    }\n}\n```\n\n```text\n@Get()\n@UseGuards(AuthGuard('jwt'))\nasync findAll(@Request() request): Promise<User[]> {\n      return await this.usersService.findAll();\n}\n```\n\n```text\n@Controller('cats')\n@UseGuards(RolesGuard)\nexport class CatsController {}\n```\n\n```text\nconst app = await NestFactory.create(ApplicationModule);\napp.useGlobalGuards(new RolesGuard());\n```\n\n========================================\n\nComments:\n- What version of NestJS do you use?\n- core version 5.0.0-beta.6\n- Also stable version 5.0.0 is already released, so I think it better, to switch, and it only few lines in package.json)\n- Thanks Vladyslav, your answer is very usefull.\n- it there a way to apply global guard and remove it for a particular controller\n- @DipanshuMahla unfortunately not github.com/nestjs/nest/issues/964\n- @DipanshuMahla you can use another decorator and logic into your guard to do so. For instance you could set a Public decorator and into your guard check for Public metadata and return directly if set to true. This way your guard will not run on routes with Public decorator","metadata":{"transformedAt":"2026-08-18T18:33:02.449Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":79,"estimatedTokens":597}}522{"id":"stack-67589835","source":"stackoverflow","questionId":67589835,"title":"TypeORM / NestJS - @BeforeUpdate hook not working","tags":["javascript","nestjs","typeorm","node.js-typeorm","nestjs-config"],"text":"Title: TypeORM / NestJS - @BeforeUpdate hook not working\nTags: javascript, nestjs, typeorm, node.js-typeorm, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI'm having problems using TypeOrm hook \"BeforeUpdate\"\n\nI'm trying to update the user entity password, by passing a simple string and calling the save method to trigger the beforeUpdate hook and then hash the password, but this hook is not working while calling the save method.\n\nThis is what i have\n\n**user.service.ts**\n\n```\nasync update(id: number, updateUserDto: UpdateUserDto) {\n const roles =\n updateUserDto.roles &&\n (await Promise.all(\n updateUserDto.roles.map((name) => this.preloadRoleByName(name))\n ));\n const user = await this.userRepository.findOneOrFail(id);\n if (!user) {\n throw new NotFoundException(`User with ID #${id} not found`);\n }\n const toSaveUser = {\n ...user,\n ...updateUserDto,\n roles,\n };\n return await this.userRepository.save(toSaveUser);\n}\n```\n\n**user.entity.ts**\n\n```\n.\n.\n.\n@Column()\n@Exclude()\npassword: string;\n\n@BeforeInsert()\n@BeforeUpdate()\nprivate async hashPassword() {\n const rounds = 10;\n const salt = await bcrypt.genSalt(rounds);\n this.password = await bcrypt.hash(this.password, salt);\n}\n```\n\n**user.controller.ts**\n\n```\n@Patch(\":id\")\n@UseInterceptors(ClassSerializerInterceptor)\nasync update(@Param(\"id\") id: string, @Body() updateUserDto: UpdateUserDto) {\n return await this.usersService.update(+id, updateUserDto);\n}\n```\n\nWhat I'm doing wrong?\n\n`BeforeInsert` hook works or if I call `userRepository.preload()` method to update it works but it doesn't replace the relationship of the role, that's why I take this approach.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nYou need to create DTO(Data Transfer Object) first and then update. this code is for update temporary password.\n\nHow create DTO:\n\n```\nthis..create()\n```\n\nExample:\n\n```\nasync updatePassword(id: number, tempPassword: string): Promise {\n let newUser = { tempPassword: tempPassword };\n const userDto = this.userAccountRepository.create(newUser)\n const userAccount = this.userAccountRepository.update(\n {\n userAccountId: id,\n },\n userDto \n );\n if (userAccount) {\n return true;\n } else {\n return false;\n }\n }\n```\n\nThis is my entity:\n\n```\nimport {\n BeforeInsert,\n BeforeUpdate,\n Column,\n Entity,\n JoinColumn,\n OneToMany,\n OneToOne,\n PrimaryColumn,\n } from 'typeorm';\nimport { Users } from '../users/users.entity';\nconst crypto = require('crypto');\n\n @Entity()\n export class UserAccount {\n @PrimaryColumn()\n userAccountId: number;\n @OneToOne(() => Users, { cascade: true })\n @JoinColumn({ name: 'userAccountId' })\n @Column({ nullable: true })\n tempPassword: string;\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise {\n if (!!this.password) {\n this.password = crypto.createHmac('sha256', this.password).digest('hex');\n }\n if (!!this.tempPassword) {\n this.tempPassword = crypto\n .createHmac('sha256', this.tempPassword)\n .digest('hex');\n }\n }\n }\n```\n\n========================================\n\nCode:\n```js\nasync update(id: number, updateUserDto: UpdateUserDto) {\n  const roles =\n    updateUserDto.roles &&\n    (await Promise.all(\n      updateUserDto.roles.map((name) => this.preloadRoleByName(name))\n    ));\n  const user = await this.userRepository.findOneOrFail(id);\n  if (!user) {\n    throw new NotFoundException(`User with ID #${id} not found`);\n  }\n  const toSaveUser = {\n    ...user,\n    ...updateUserDto,\n    roles,\n  };\n  return await this.userRepository.save(toSaveUser);\n}\n```\n\n```js\n.\n.\n.\n@Column()\n@Exclude()\npassword: string;\n\n@BeforeInsert()\n@BeforeUpdate()\nprivate async hashPassword() {\n  const rounds = 10;\n  const salt = await bcrypt.genSalt(rounds);\n  this.password = await bcrypt.hash(this.password, salt);\n}\n```\n\n```js\n@Patch(\":id\")\n@UseInterceptors(ClassSerializerInterceptor)\nasync update(@Param(\"id\") id: string, @Body() updateUserDto: UpdateUserDto) {\n return await this.usersService.update(+id, updateUserDto);\n}\n```\n\n```text\nBeforeInsert\n```\n\n```text\nuserRepository.preload()\n```\n\n```text\nconst user = await this.userRepository.findOneOrFail(id); // entity instance\nconst toSaveUser = { ...user, ...updateUserDto, roles }; // plain object\nreturn await this.userRepository.save(toSaveUser); // not running trigger\n```\n\n```text\nconst user = await this.userRepository.findOneOrFail(id); // entity instance\n// still entity instance\nconst toSaveUser = this.userRepository.create({\n  ...user,\n  ...updateUserDto,\n  roles,\n});\nreturn await this.userRepository.save(toSaveUser); // running trigger\n```\n\n```text\nProblem:\n```\n\n```text\nSolution:\n```\n\n```text\nrepository.save()\n```\n\n```text\nrepository.create()\n```\n\n```text\nrepository.preload()\n```\n\n```text\n@BeforeUpdate()\n  async hashPasswordBeforeUpdate() {\n    this.password = await bcrypt.hash(this.password, 10);\n  }\n```\n\n```text\nquery: UPDATE `users` SET `levelId` = ?, `updatedAt` = ?, `password` = ? WHERE `id` IN (?) -- PARAMETERS: [null,\"2021-05-07T07:27:47.198Z\",\"$2b$10$uQOMNv57BZLB/W/9SWPbke6/OMdIDWxv3i25A8rUhA0/vEMloWb2W\",1]\n```\n\n```text\nPUT\n```\n\n```text\nPATCH\n```\n\n```js\nthis.<YOUR_REPOSITORY_NAME>.create(<INPUT_OBJECT>)\n```\n\n```js\nasync updatePassword(id: number, tempPassword: string): Promise<boolean> {\n    let newUser = { tempPassword: tempPassword };\n    const userDto = this.userAccountRepository.create(newUser)\n    const userAccount = this.userAccountRepository.update(\n      {\n        userAccountId: id,\n      },\n      userDto \n    );\n    if (userAccount) {\n      return true;\n    } else {\n      return false;\n    }\n  }\n```\n\n```js\nimport {\n  BeforeInsert,\n  BeforeUpdate,\n  Column,\n  Entity,\n  JoinColumn,\n  OneToMany,\n  OneToOne,\n  PrimaryColumn,\n  } from 'typeorm';\nimport { Users } from '../users/users.entity';\nconst crypto = require('crypto');\n\n    @Entity()\n    export class UserAccount {\n      @PrimaryColumn()\n      userAccountId: number;\n      @OneToOne(() => Users, { cascade: true })\n      @JoinColumn({ name: 'userAccountId' })\n      @Column({ nullable: true })\n      tempPassword: string;\n      @BeforeInsert()\n      @BeforeUpdate()\n      async hashPassword(): Promise<void> {\n        if (!!this.password) {\n          this.password = crypto.createHmac('sha256', this.password).digest('hex');\n        }\n        if (!!this.tempPassword) {\n          this.tempPassword = crypto\n            .createHmac('sha256', this.tempPassword)\n            .digest('hex');\n        }\n      }\n    }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":308,"estimatedTokens":1596}}523{"id":"stack-61136081","source":"stackoverflow","questionId":61136081,"title":"How to catch error in nestjs when a query fails","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to catch error in nestjs when a query fails\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am new to `nestjs` and was trying to convert my backend from `nodejs` to `nestjs`. Hope that makes sense? I am using `typeorm. But I am not sure as what could be the best of way of catching errors.\n\n`entity.ts`\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, PrimaryColumn } from 'typeorm';\n\n@Entity()\nexport class Course {\n\n @PrimaryColumn()\n course: string;\n\n @Column(\"varchar\", { array: true })\n subject: string[];\n}\n```\n\n`controller.ts`\n\n```\nimport { Controller, Get, Post, Body } from '@nestjs/common';\nimport { CourseService } from './course.service';\nimport { Course } from './course.entity';\n\n@Controller('course')\nexport class CourseController {\n constructor(private courseService: CourseService) {}\n\n @Get()\n getCourses(): Promise {\n return this.courseService.findAll();\n }\n\n @Post()\n addCourse(@Body() courseDto: Course[]) {\n return this.courseService.create(courseDto);\n }\n}\n```\n\n`service.ts`\n\n```\nimport { Injectable, Catch, ExceptionFilter, ArgumentsHost, ConflictException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, QueryFailedError } from 'typeorm';\nimport { Course } from './course.entity';\n\n@Injectable()\nexport class CourseService {\n constructor(\n @InjectRepository(Course)\n private courseRepository: Repository,\n ) { }\n\n catch(exception: any, host: ArgumentsHost) {\n throw new Error(\"Error in course service.\" + exception.code);\n }\n\n findAll(): Promise {\n return this.courseRepository.find();\n }\n\n create(courseDto) {\n return this.courseRepository.insert(courseDto)\n .catch((err: any) => {\n // throw new ConflictException();\n\n switch (err.name) {\n case 'QueryFailedError':\n console.log(\"**++**\" + JSON.stringify(err));\n // throw new Error(\"Error\" + err.message + \"\" + err.detail);\n // throw new ConflictException();\n throw JSON.stringify(err); //\"Error creating a course\" + err.message + \"::: \" + err.detail;\n default:\n throw err; \n\n }\n });\n }\n}\n```\n\nNow, all I am able to throw is `throw new ConflictException();`. I wanted to throw different errors based on the result, like -\n1. For duplicate record\n2. Missing mandatory fields\n3. etc\n\nBut not sure how can we handle and customize the same and also make full use of nestjs.\n\nLike I see the below trace in console but `500, Internal server in postman` -\n\n```\n{\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]}\n[Nest] 12152 - 04/10/2020, 1:18:40 PM [ExceptionsHandler] {\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]} +190924ms\n```\n\n========================================\n\nTop Answer:\nDont return service function directly, nest will catch that exception and assume its from controller, another solution is wrap with try/catch\n\ncontroller.ts\n\n```\ntry {\n return await this.courseService.create(courseDto)\n} catch (error) {\n // handle error\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, PrimaryColumn } from 'typeorm';\n\n@Entity()\nexport class Course {\n\n  @PrimaryColumn()\n  course: string;\n\n  @Column(\"varchar\", { array: true })\n  subject: string[];\n}\n```\n\n```text\nimport { Controller, Get, Post, Body } from '@nestjs/common';\nimport { CourseService } from './course.service';\nimport { Course } from './course.entity';\n\n@Controller('course')\nexport class CourseController {\n    constructor(private courseService: CourseService) {}\n\n    @Get()\n    getCourses(): Promise<Course[]> {\n        return this.courseService.findAll();\n    }\n\n    @Post()\n    addCourse(@Body() courseDto: Course[]) {\n        return this.courseService.create(courseDto);\n    }\n}\n```\n\n```text\nimport { Injectable, Catch, ExceptionFilter, ArgumentsHost, ConflictException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, QueryFailedError } from 'typeorm';\nimport { Course } from './course.entity';\n\n@Injectable()\nexport class CourseService {\n    constructor(\n        @InjectRepository(Course)\n        private courseRepository: Repository<Course>,\n    ) { }\n\n    catch(exception: any, host: ArgumentsHost) {\n        throw new Error(\"Error in course service.\" + exception.code);\n    }\n\n    findAll(): Promise<Course[]> {\n        return this.courseRepository.find();\n    }\n\n    create(courseDto) {\n        return this.courseRepository.insert(courseDto)\n            .catch((err: any) => {\n                // throw new ConflictException();\n\n                switch (err.name) {\n                    case 'QueryFailedError':\n                        console.log(\"**++**\" + JSON.stringify(err));\n                        // throw new Error(\"Error\" + err.message + \"\" + err.detail);\n                        // throw new ConflictException();\n                        throw JSON.stringify(err); //\"Error creating a course\" + err.message + \"::: \" + err.detail;\n                    default:\n                        throw err; \n\n                }\n            });\n    }\n}\n```\n\n```text\n{\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]}\n[Nest] 12152   - 04/10/2020, 1:18:40 PM   [ExceptionsHandler] {\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]} +190924ms\n```\n\n```text\nnestjs\n```\n\n```text\nnodejs\n```\n\n```text\nnestjs\n```\n\n```text\nentity.ts\n```\n\n```text\ncontroller.ts\n```\n\n```text\nservice.ts\n```\n\n```text\nthrow new ConflictException();\n```\n\n```text\n500, Internal server in postman\n```\n\n```text\ncreate(courseDto) {\n  return this.courseRepository.insert(courseDto)\n}\n```\n\n```text\nimport {\n  Controller,\n  Get,\n  Post,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\n\n...\n\n@Post()\nasync addCourse(@Body() courseDto: Course[]) {\n    return await this.courseService.create(courseDto).catch(err => {\n      throw new HttpException({\n        message: err.message\n      }, HttpStatus.BAD_REQUEST);\n    })\n}\n```\n\n```text\ntry {\n  return await this.courseService.create(courseDto)\n} catch (error) {\n  // handle error\n}\n```\n\n========================================\n\nComments:\n- What would be best, to let service handle it and controller handle it like you mentioned above?\n- From a design perspective I wouldn't support this solution. In hexagonal architecture an endpoint (ie. controller) is only **one** way to access your business layer. If you add a CLI command for your service or (staying in web context) a GraphQL resolver you would need to re-build all that error handling for each entry point. Better let the service layer handle the exceptions when they are crucial to the business. I.e. when the service require an entity to fetch/persist and it fails, let it fail.\n- @agoldev Totally agree with your statement, except if it's to return an HTTP-specific error (with a HTTP status code for example). Then in that case I would be OK with it (it would be incorrect to return it from the service), even though in Nest.js I'd prefer to see an exception filter so the code doesn't end up duplicated in every controller.\n- Thanks your post helped me indirectly, my problem was I didn't have the `await`.","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":276,"estimatedTokens":2247}}524{"id":"stack-73067620","source":"stackoverflow","questionId":73067620,"title":"NestJs ParseEnumPipe can't be resolve","tags":["javascript","typescript","nestjs","nestjs-config"],"text":"Title: NestJs ParseEnumPipe can't be resolve\nTags: javascript, typescript, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI am using the NestJs framework (love it by the way) and I want to check the incoming data so it conforms with an Enum in Typscript. So I have the following:\n\n```\nenum ProductAction {\n PURCHASE = 'PURCHASE',\n}\n\n@Patch('products/:uuid')\nasync patchProducts(\n @Param('uuid', ParseUUIDPipe) uuid: string,\n @Body('action', ParseEnumPipe) action: ProductAction,\n ) {\n\n switch(action) {\n\n ... code \n }\n```\n\nThe weird thing is that when I run this code, the first pipe gets compiled\n\n```\n2022-07-21 16:53:51 [error] [ExceptionHandler] Nest can't resolve dependencies of the ParseEnumPipe (?, Object). Please make sure that the argument Object at index [0] is available in the FriendsModule context.\n```\n\nWhat I am doing wrong?\n\n========================================\n\nCode:\n```text\nenum ProductAction {\n  PURCHASE = 'PURCHASE',\n}\n\n@Patch('products/:uuid')\nasync patchProducts(\n    @Param('uuid', ParseUUIDPipe) uuid: string,\n    @Body('action', ParseEnumPipe) action: ProductAction,\n  ) {\n\n    switch(action) {\n\n    ... code \n  }\n```\n\n```text\n2022-07-21 16:53:51 [error] [ExceptionHandler] Nest can't resolve dependencies of the ParseEnumPipe (?, Object). Please make sure that the argument Object at index [0] is available in the FriendsModule context.\n```\n\n```text\n@Body('action', new ParseEnumPipe(ProductAction)) action: ProductAction\n```\n\n```text\nObject\n```\n\n========================================\n\nComments:\n- I guess we could improve the docs on that pipe","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":398}}525{"id":"stack-56583231","source":"stackoverflow","questionId":56583231,"title":"NestJS Request Scoped Multitenancy for Multiple Databases","tags":["multi-tenant","nestjs"],"text":"Title: NestJS Request Scoped Multitenancy for Multiple Databases\nTags: multi-tenant, nestjs\nSource: Stack Overflow\n\nQuestion:\nLooking to implement a multi-tenant NestJS solution using the new request injection scope feature of NestJS 6.\n\nFor any given service I assume I could do something like this:\n\n```\n@Injectable({scope: Scope.REQUEST})\nexport class ReportService implements OnModuleInit { ... }\n```\n\nthen, in the constructor, determine the tenant from the request, connect to the appropriate database, and instantiate repositories for the new connection.\n\nI'm wondering if this is the most straightforward way to go about it?\n\nInstead of updating each service, is it possible to override the connection provider and scope *that* to the request?\n\n========================================\n\nTop Answer:\nI would recommend to use the approach by @nurikabe with a request scoped factory provider and request scoped services. Nestjs itself has a similar factory example in the docs. \n\nBut for the sake of completenes, there is also another approach: You could also use a middleware and attach the connection to the request object as described in this answer to a similar question. However, attaching things like a connection to the request via a middleware is circumventing the DI mechanism and alienates the request object by making it behave like a service container that delivers the connection โ€“ therefore the factory approach should be preferred.\n\n========================================\n\nCode:\n```text\n@Injectable({scope: Scope.REQUEST})\nexport class ReportService implements OnModuleInit { ... }\n```\n\n```text\nimport { Global, Module, Scope } from '@nestjs/common';\nimport { REQUEST } from '@nestjs/core';\nimport { getConnection } from 'typeorm';\n\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  scope: Scope.REQUEST,\n  useFactory: (req) => {\n    const tenant = someMethodToDetermineTenantFromHost(req.headers.host);\n    return getConnection(tenant);\n  },\n  inject: [REQUEST],\n};\n\n@Global()\n@Module({\n  providers: [connectionFactory],\n  exports: ['CONNECTION'],\n})\nexport class TenancyModule {}\n```\n\n```text\n...\n@Injectable({scope: Scope.REQUEST})\nexport class UserService {\n  private readonly userRepository: Repository<User>;\n\n  constructor(@Inject('CONNECTION') connection) {\n    this.userRepository = connection.getRepository(User);\n  }\n```\n\n```text\nTenancyModule\n```\n\n```text\n'CONNECTION'\n```\n\n========================================\n\nComments:\n- This works for Multi-tenant with multiple databases, not for one database with multiple schemas\n- I am missing part about the connection itself, would you be able to provide example when do you pass database connection details? E.g. tenant = different database in the same host. @nurikabe\n- @jdnichollsc, it also works with multiple schemas as you can also change the schema when setting up a connection.\n- @WinterTime you pass all the database connection details when calling getConnection, see the TypeORM API docs. In the code by nurikabe, it seems he is just passing the tenant id \"string\", which would be wrong, he needs to pass the whole connection configuration here where e.g. the scheme or db name is set to the tenant..\n- Ohh you're right! I don't know the impact about performance updating the connection at runtime using Request scope, but it can works :)\n- Unless I remember incorrectly, the above *should* return the entire connection object. Note the factory: It returns `getConnection(tenant)`. `'CONNECTION'` is an alias that returns the result of `connectionFactory`.\n- Ah yes, sorry @nurikabe, you are right. I confused `getConnection` with `createConnection`. So for retrieving the connection by name your `getConnection(tenant)` is perfectly correct.\n- @jdnichollsc When using `createConnection` (to create a connection for a tenant) TypeORM behind the curtains stores the connection instance and subsequent calls to `getConnection` (and the factory) will return the same connection instance again, so you only create the connection once and not on every request. So you only create one connection per tenant and not one per request. However, you may experience memory problems with too many connections on a single server and unfortunately switching the schema for existing connections doesn't work (see stackoverflow.com/q/57459643/2477619)\n- @B12Toaster at what point do I have to have all connection settings loaded to call getConnection (tenat) to get the connection by name. I did not understand this part\n- @EdeGerSil I think you could create the multiple connections in the app module, look at this link, stackoverflow.com/a/51995362/11434648\n- This works but I am using class validators in the DTOs, how do we scope it to them as well\n- This is not working for me when I have passport integration, take a look here: stackoverflow.com/questions/78812051/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":92,"estimatedTokens":1215}}526{"id":"stack-61204434","source":"stackoverflow","questionId":61204434,"title":"Pass variable from configuration file to decorator","tags":["typescript","nestjs","typescript-decorator","class-validator"],"text":"Title: Pass variable from configuration file to decorator\nTags: typescript, nestjs, typescript-decorator, class-validator\nSource: Stack Overflow\n\nQuestion:\nI want to create a REST API with NestJs, TypeORM and class-validator. My database entity has a description field that currently has a maximum length of 3000. With TypeORM the code is\n\n```\n@Entity()\nexport class Location extends BaseEntity {\n @Column({ length: 3000 })\n public description: string;\n}\n```\n\nWhen creating a new entity I want to validate incoming requests for that maximum length using class-validator. The could would be\n\n```\nexport class AddLocationDTO {\n @IsString()\n @MaxLength(3000)\n public description: string;\n}\n```\n\nWhen updating that description field I would have to check for that maximum length in other DTOs too. I have a service class holding all my configuration fields for the API. Assuming this service class could also serve the maximum length, is there a way I could pass in a variable to the decorator?\n\nOtherwise, when changing the length from 3000 to 2000, I have to change multiple files.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Location extends BaseEntity {\n  @Column({ length: 3000 })\n  public description: string;\n}\n```\n\n```text\nexport class AddLocationDTO {\n  @IsString()\n  @MaxLength(3000)\n  public description: string;\n}\n```\n\n```js\n// constants.ts\n// you may need to import `dotenv` and run config(), but that could depend on how the server starts up\nexport const fieldLength = process.env.FIELD_LENGTH\n\n// location.entity.ts\n@Entity()\nexport class Location extends BaseEntity {\n  @Column({ length: fieldLength })\n  public description: string;\n}\n\n// add-location.dto.ts\nexport class AddLocationDTO {\n  @IsString()\n  @MaxLength(fieldLength)\n  public description: string;\n}\n```\n\n```text\n@nestjs/config\n```\n\n```text\nConfigService\n```\n\n```text\nprocess.env\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":473}}527{"id":"stack-54163467","source":"stackoverflow","questionId":54163467,"title":"How to access relationship ID from Parent's joined field in NestJS/TypeORM","tags":["node.js","graphql","nestjs","typeorm"],"text":"Title: How to access relationship ID from Parent's joined field in NestJS/TypeORM\nTags: node.js, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a NestJS GraphQL API that utilizes TypeORM, and am having trouble implementing relationships between entities.\n\nSpecifically, the TypeORM relationships are working great, and the entities are linking correctly in the database. However, the problem comes in when I try to query the API to get the results.\n\nRight now I have 2 entities, each with their own resolver: Users and Photos. Each User can have multiple Photos, while each Photo is only connected to one User (Many-to-One).\n\n### Here's how the entities are linked with TypeORM\n\n*Photo Entity, with a relationship to the User Entity*\n\n```\n@ManyToOne(type => User, user => user.photos, {\n onDelete: 'CASCADE',\n})\n@JoinColumn()\nuser: User;\n```\n\n*User Entity, completing connection to the Photo Entity*\n\n```\n@OneToMany(type => Photo, photo => photo.user, {\n eager: true,\n})\nphotos: Photo[];\n```\n\n### This code works, and let's us retrieve a User's Photos\n\n*User resolver*\n\n```\n@ResolveProperty('photos')\nasync photos(@Parent() user): Promise {\n return await this.service.readPhotos(user.id);\n}\n```\n\n*User service*\n\n```\nasync readPhotos(userId): Promise {\n return await this.photoRepository.find({\n where: {\n user: userId\n }\n });\n}\n```\n\n*** *Note that the photoRepository is able to be filtered by the 'user' field.* ***\n\n### This code, however, does not work. It should let us view which User is connected to the Photo, instead it returns null.\n\n*Photo resolver*\n\n```\n@ResolveProperty('user')\nasync user(@Parent() photo): Promise {\n console.log(photo);\n return await this.service.readUser(photo.user);\n}\n```\n\nThis Photo resolver seems to contain the problem; the photo object being output by the console indicates that while the @Parent photo object has all of its static fields available (like the ID, datePublished, URL), for some reason the actual 'user' field is not accessible here. So the 'photo.user' variable is null.\n*** *Note that this seems to indicated that the photoRepository is UNABLE to be filtered by/access the 'user' field.* ***\n\n*Photo service*\n\n```\nasync readUser(userId): Promise {\n return await this.userRepository.findOne({\n where: {\n user: userId\n }\n });\n}\n```\n\nThis returns null since the userId is blank, due to the previous Photo resolver not being able to access the 'user' field.\n\n### Conclusion\n\nWhy can't the Photo resolver access the @Parent photo 'user' field? The User service seems to be able to filter by the 'user' field just fine, yet I can't seem to be able to access the Photo 'user' field directly.\n\nThank you for any help on this! I've been stumped on this for the last two days...\n\n========================================\n\nTop Answer:\nI was struggling with a similar problem and although @bashleigh's solution works if you want the entire entity returned I only needed the id. So if that's your case you can pass the `loadRelationIds` option, and set it to `true`.\n\n```\nreturn await this.photoRepository.find({\n where: {\n id: photoId\n },\n loadRelationIds: true\n});\n```\n\nThis will return user as just the id (string or int).\n\n========================================\n\nCode:\n```text\n@ManyToOne(type => User, user => user.photos, {\n    onDelete: 'CASCADE',\n})\n@JoinColumn()\nuser: User;\n```\n\n```text\n@OneToMany(type => Photo, photo => photo.user, {\n    eager: true,\n})\nphotos: Photo[];\n```\n\n```text\n@ResolveProperty('photos')\nasync photos(@Parent() user): Promise<Photo[]> {\n    return await this.service.readPhotos(user.id);\n}\n```\n\n```text\nasync readPhotos(userId): Promise<Photo[]> {\n    return await this.photoRepository.find({\n        where: {\n            user: userId\n        }\n    });\n}\n```\n\n```text\n@ResolveProperty('user')\nasync user(@Parent() photo): Promise<User> {\n    console.log(photo);\n    return await this.service.readUser(photo.user);\n}\n```\n\n```text\nasync readUser(userId): Promise<User> {\n    return await this.userRepository.findOne({\n        where: {\n            user: userId\n        }\n    });\n}\n```\n\n```text\nasync readPhotos(userId): Promise<Photo[]> {\n    return await this.photoRepository.find({\n        where: {\n            user: userId\n        },\n        relations: ['user'],\n    });\n}\n```\n\n```text\nasync readUser(userId): Promise<User> {\n    return await this.userRepository.findOne({\n        where: {\n            user: userId\n        },\n        relations: ['photos'],\n    });\n}\n```\n\n```text\nphoto.user\n```\n\n```text\nFindOptions\n```\n\n```text\nphoto.user\n```\n\n```text\nuser.photos\n```\n\n```text\nPhoto\n```\n\n```text\nFindOptions\n```\n\n```text\nreturn await this.photoRepository.find({\n where: {\n  id: photoId\n },\n loadRelationIds: true\n});\n```\n\n```text\nloadRelationIds\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Can you your GraphQL schema as well? Specifically the definitions for your Photo and User","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":228,"estimatedTokens":1229}}528{"id":"stack-71785164","source":"stackoverflow","questionId":71785164,"title":"Is it possible to have multiple local strategies in passport implemented with NestJS","tags":["nestjs","passport.js","passport-local"],"text":"Title: Is it possible to have multiple local strategies in passport implemented with NestJS\nTags: nestjs, passport.js, passport-local\nSource: Stack Overflow\n\nQuestion:\nI have a scenario where I need to implement an authentication mechanism for admin and for normal users in my application using the Passport local strategy. I implemented the strategy for the normal users as described here. It is working perfectly fine.\n\nHowever, now I need to implement the same local strategy for Admin login. I feel like it would have been much easier if both the type of users(admin and normal user) are on the same entity/table because a single validate function would be capable enough to handle the case but my application design has separate entities for Admins and normal users and hence are the separate services.\n\nMy local strategy looks something like this:\n\n```\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private userService: UserService) {\n super();\n }\n\n async validate(username: string, password: string): Promise {\n const user = await this.userService.validateUser(username, password);\n if (!user) {\n throw new UnauthorizedException(\"Incorrect credentials!\");\n }\n return user;\n }\n}\n```\n\nAs I went through the documentation, it is said that a Local Strategy can have only one validate function(that works as a verify callback), if this is the case how do I differentiate a logic inside this single validate function to behave differently for the requests coming in from the normal user controller and from the admin controller? Because in the admin login case, I'll be using a different route something like(admin/login), and for the user, it could be something like(user/login).\n\nWhat's the best approach for this? Do I need to create a separate local strategy for admin? If yes, any hints will be appreciated. Otherwise, how can I incorporate logic inside this single validate function?\n\nOne of the alternatives could be checking if data exists in both the tables for every login payload each time. This approach doesn't look quite right to me.\n\nIf this provides more insight, the auth guard is simple as this:\n\n```\n@Injectable()\nexport class LocalAuthGuard extends AuthGuard('local') { \n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n    constructor(private userService: UserService) {\n        super();\n    }\n\n    async validate(username: string, password: string): Promise<any> {\n        const user = await this.userService.validateUser(username, password);\n        if (!user) {\n            throw new UnauthorizedException(\"Incorrect credentials!\");\n        }\n        return user;\n    }\n}\n```\n\n```text\n@Injectable()\nexport class LocalAuthGuard extends AuthGuard('local') { \n}\n```\n\n```js\n@Injectable()\nexport class LocalAdminStrategy extends PassportStrategy(Strategy, 'admin') {\n  validate(username: string, password: string) {\n    return validateAdminInfo({ username, password });\n  }\n}\n```\n\n```text\n@UseGuards(AuthGuard(['admin', 'user']))\n```\n\n```text\npassport-local\n```\n\n```text\nadmin\n```\n\n```text\n@UseGuards(AuthGuard('admin'))\n```\n\n========================================\n\nComments:\n- How do I differentiate JWT strategies in this case? Do I have to create named JWT strategies similarly for two different strategies? Do I have to care about any other things to get these all work in auth module?\n- I'm not sure I your question. You can have as many custom named strategies that options as you want\n- Don't forget to import LocalAdminStrategy in the associated (probably auth) module. :)","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":99,"estimatedTokens":910}}529{"id":"stack-69798092","source":"stackoverflow","questionId":69798092,"title":"PayloadTooLargeError: request entity too large. How solve it in NestJS?","tags":["javascript","node.js","express","nestjs"],"text":"Title: PayloadTooLargeError: request entity too large. How solve it in NestJS?\nTags: javascript, node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to send the request which contains a base64 string and it's too large (probable, around 2 mb).\n\nBut server throw next exeption, how to avoid this error:\n\n```\n[Nest] 1666 - 11/01/2021, 1:50:58 PM ERROR [ExceptionsHandler] request entity too large\ngateway-client | PayloadTooLargeError: request entity too large\ngateway-client | at readStream (/srv/app/node_modules/raw-body/index.js:155:17)\ngateway-client | at getRawBody (/srv/app/node_modules/raw-body/index.js:108:12)\ngateway-client | at read (/srv/app/node_modules/body-parser/lib/read.js:77:3)\ngateway-client | at jsonParser (/srv/app/node_modules/body-parser/lib/types/json.js:135:5)\ngateway-client | at Layer.handle [as handle_request] (/srv/app/node_modules/express/lib/router/layer.js:95:5)\ngateway-client | at trim_prefix (/srv/app/node_modules/express/lib/router/index.js:317:13)\ngateway-client | at /srv/app/node_modules/express/lib/router/index.js:284:7\ngateway-client | at Function.process_params (/srv/app/node_modules/express/lib/router/index.js:335:12)\ngateway-client | at next (/srv/app/node_modules/express/lib/router/index.js:275:10)\ngateway-client | at expressInit (/srv/app/node_modules/express/lib/middleware/init.js:40:5)\n```\n\nMy main.ts includes:\n\n```\nasync function bootstrap() { \n const app = await NestFactory.create(AppModule);\n \n // app.enableCors({\n // origin: '*',\n // });\n\n const config = new DocumentBuilder()\n .setTitle('API client gateway')\n .setDescription('API client gateway full documentation')\n .setVersion('v0.0.1')\n .addTag('')\n .addBearerAuth(\n {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n name: 'JWT',\n description: 'Enter JWT token',\n in: 'header',\n },\n 'jwt-token',\n )\n .build();\n\n const document = SwaggerModule.createDocument(app, config);\n\n SwaggerModule.setup('/api/docs', app, document);\n\n await app.init();\n\n app.use(express.json({limit: \"50mb\"})) //For JSON requests\n app.use(express.urlencoded({\n limit: \"50mb\",\n extended: false\n }));\n\n await app.listen(AppConfig.Port);\n}\n\nbootstrap();\n```\n\n========================================\n\nTop Answer:\nif you want to use a more idiomatic version of `body-parser` (after disabling it in your `bootstrap` function):\n\n```\n// json-body-parser.middleware.ts\nimport { NestMiddleware } from '@nestjs/common';\nimport bodyParser from 'body-parser';\n\ntype JsonBodyParserOpts = bodyParser.OptionsJson;\n\n// As we're not using DI, we don't need to mark this as Injectable\nexport class JsonBodyParserMiddleware implements NestMiddleware {\n private readonly options: JsonBodyParserOpts = {\n limit: '5mb',\n };\n\n use = bodyParser.json(this.options);\n}\n```\n\n```\n// in your main/root module\n// ...\nexport class AppModule implements NestModule {\n configure(middlewareConsumer: MiddlewareConsumer): void {\n middlewareConsumer\n .apply(JsonBodyParserMiddleware)\n .forRoutes({\n path: '*',\n method: RequestMethod.ALL,\n });\n }\n}\n```\n\nI prefer avoiding `app.use` as much I can to let `bootstrap` function cleaner.\n\nOr you could make it dynamic configurable from outside, doing something like this.\n\nLearn more about Nestjs middlewares here: https://docs.nestjs.com/middleware\n\n========================================\n\nCode:\n```text\n[Nest] 1666  - 11/01/2021, 1:50:58 PM   ERROR [ExceptionsHandler] request entity too large\ngateway-client  | PayloadTooLargeError: request entity too large\ngateway-client  |     at readStream (/srv/app/node_modules/raw-body/index.js:155:17)\ngateway-client  |     at getRawBody (/srv/app/node_modules/raw-body/index.js:108:12)\ngateway-client  |     at read (/srv/app/node_modules/body-parser/lib/read.js:77:3)\ngateway-client  |     at jsonParser (/srv/app/node_modules/body-parser/lib/types/json.js:135:5)\ngateway-client  |     at Layer.handle [as handle_request] (/srv/app/node_modules/express/lib/router/layer.js:95:5)\ngateway-client  |     at trim_prefix (/srv/app/node_modules/express/lib/router/index.js:317:13)\ngateway-client  |     at /srv/app/node_modules/express/lib/router/index.js:284:7\ngateway-client  |     at Function.process_params (/srv/app/node_modules/express/lib/router/index.js:335:12)\ngateway-client  |     at next (/srv/app/node_modules/express/lib/router/index.js:275:10)\ngateway-client  |     at expressInit (/srv/app/node_modules/express/lib/middleware/init.js:40:5)\n```\n\n```text\nasync function bootstrap() {  \n  const app = await NestFactory.create<NestExpressApplication>(AppModule);\n  \n  // app.enableCors({\n  //   origin: '*',\n  // });\n\n  const config = new DocumentBuilder()\n    .setTitle('API client gateway')\n    .setDescription('API client gateway full documentation')\n    .setVersion('v0.0.1')\n    .addTag('')\n    .addBearerAuth(\n      {\n        type: 'http',\n        scheme: 'bearer',\n        bearerFormat: 'JWT',\n        name: 'JWT',\n        description: 'Enter JWT token',\n        in: 'header',\n      },\n      'jwt-token',\n    )\n    .build();\n\n  const document = SwaggerModule.createDocument(app, config);\n\n  SwaggerModule.setup('/api/docs', app, document);\n\n\n  await app.init();\n\n  app.use(express.json({limit: \"50mb\"})) //For JSON requests\n  app.use(express.urlencoded({\n    limit: \"50mb\",\n    extended: false\n  }));\n\n  await app.listen(AppConfig.Port);\n}\n\nbootstrap();\n```\n\n```js\nimport { json } from 'body-parser';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(AppModule,\n    { bodyParser: false });\n\n  app.use(json({ limit: '5mb' }));\n\n  ...\n}\n```\n\n```text\nmain.ts\n```\n\n```text\nbootstrap()\n```\n\n```text\n// json-body-parser.middleware.ts\nimport { NestMiddleware } from '@nestjs/common';\nimport bodyParser from 'body-parser';\n\ntype JsonBodyParserOpts = bodyParser.OptionsJson;\n\n// As we're not using DI, we don't need to mark this as Injectable\nexport class JsonBodyParserMiddleware implements NestMiddleware {\n  private readonly options: JsonBodyParserOpts = {\n    limit: '5mb',\n  };\n\n  use = bodyParser.json(this.options);\n}\n```\n\n```text\n// in your main/root module\n// ...\nexport class AppModule implements NestModule {\n  configure(middlewareConsumer: MiddlewareConsumer): void {\n    middlewareConsumer\n      .apply(JsonBodyParserMiddleware)\n      .forRoutes({\n        path: '*',\n        method: RequestMethod.ALL,\n      });\n  }\n}\n```\n\n```text\nbody-parser\n```\n\n```text\nbootstrap\n```\n\n```text\napp.use\n```\n\n```text\nbootstrap\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":244,"estimatedTokens":1612}}530{"id":"stack-75203608","source":"stackoverflow","questionId":75203608,"title":"Nest could not find PrismaService element (this provider does not exist in the current context)","tags":["nestjs","prisma"],"text":"Title: Nest could not find PrismaService element (this provider does not exist in the current context)\nTags: nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get PrismaService on my main.ts, but it's keep crashing. I'm new on this, can anyone help me to solve it?\nMy prisma.service.ts:\n\n```\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n async onModuleInit() {\n await this.$connect();\n }\n\n async enableShutdownHooks(app: INestApplication) {\n this.$on('beforeExit', async () => {\n await app.close();\n });\n }\n}\n```\n\nMy main.ts:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { PrismaService } from './prisma.service';\nimport { ValidationPipe } from '@nestjs/common';\nimport helmet from 'helmet';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n app.enableCors({\n allowedHeaders: '*',\n origin: '*',\n });\n app.use(helmet());\n app.use(helmet.hidePoweredBy());\n app.use(helmet.contentSecurityPolicy());\n\n const prismaService = app.get(PrismaService);\n await prismaService.enableShutdownHooks(app);\n\n app.useGlobalPipes(\n new ValidationPipe({\n transform: true,\n whitelist: true,\n forbidNonWhitelisted: true,\n }),\n );\n\n await app.listen(process.env.PORT, () => console.log('runing...'));\n}\nbootstrap();\n```\n\nThe error message:\n\n```\nError: Nest could not find PrismaService element (this provider does not exist in the current context)\n at InstanceLinksHost.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/instance-links-host.js:15:19)\n at NestApplication.find (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/abstract-instance-resolver.js:8:60)\n at NestApplication.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-application-context.js:64:20)\n at /home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:133:40\n at Function.run (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/errors/exceptions-zone.js:10:13)\n at Proxy. (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:132:46)\n at Proxy. (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:181:54)\n at bootstrap (/home/rafittu/wophi/alma/back/src/main.ts:18:29)\n```\n\nWhen I delete PrismaService from main.ts, server start normaly\n\n========================================\n\nTop Answer:\nAfter setting up the `PrismaService` in `prisma.service.ts` and enabling shutdown hooks in the `main.ts` file, you also need to do the following:\n\nIn the `app.module.ts` you need to add `PrismaService` as one of the providers:\n\n```\n...\nimport { PrismaService } from './prisma/prisma.service';\n\n@Module({\n imports: [],\n controllers: [AppController],\n providers: [AppService, PrismaService], // add PrismaService here\n})\nexport class AppModule {}\n```\n\n========================================\n\nCode:\n```text\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { PrismaService } from './prisma.service';\nimport { ValidationPipe } from '@nestjs/common';\nimport helmet from 'helmet';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  app.enableCors({\n    allowedHeaders: '*',\n    origin: '*',\n  });\n  app.use(helmet());\n  app.use(helmet.hidePoweredBy());\n  app.use(helmet.contentSecurityPolicy());\n\n  const prismaService = app.get(PrismaService);\n  await prismaService.enableShutdownHooks(app);\n\n  app.useGlobalPipes(\n    new ValidationPipe({\n      transform: true,\n      whitelist: true,\n      forbidNonWhitelisted: true,\n    }),\n  );\n\n  await app.listen(process.env.PORT, () => console.log('runing...'));\n}\nbootstrap();\n```\n\n```text\nError: Nest could not find PrismaService element (this provider does not exist in the current context)\n    at InstanceLinksHost.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/instance-links-host.js:15:19)\n    at NestApplication.find (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/abstract-instance-resolver.js:8:60)\n    at NestApplication.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-application-context.js:64:20)\n    at /home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:133:40\n    at Function.run (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/errors/exceptions-zone.js:10:13)\n    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:132:46)\n    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:181:54)\n    at bootstrap (/home/rafittu/wophi/alma/back/src/main.ts:18:29)\n```\n\n```text\napp.get(PrismaService, { strict: false })\n```\n\n```text\nstrict: false\n```\n\n```text\nAppModule\n```\n\n```js\n...\nimport { PrismaService } from './prisma/prisma.service';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService, PrismaService], // add PrismaService here\n})\nexport class AppModule {}\n```\n\n```text\nPrismaService\n```\n\n```text\nprisma.service.ts\n```\n\n```text\nmain.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nPrismaService\n```\n\n========================================\n\nComments:\n- Using strict: false didn't work, same error message\n- Do you have a module that has `providers: [PrimsaService]` imported by the `AppModule`?\n- Sorted out!!! I have an users module and PrismaService was not imported. As I imported it, server started normaly! Thanks a lot!!","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":214,"estimatedTokens":1497}}531{"id":"stack-69433044","source":"stackoverflow","questionId":69433044,"title":"Winston with AWS Cloudwatch on Nestjs","tags":["node.js","amazon-web-services","nestjs","amazon-cloudwatch","winston"],"text":"Title: Winston with AWS Cloudwatch on Nestjs\nTags: node.js, amazon-web-services, nestjs, amazon-cloudwatch, winston\nSource: Stack Overflow\n\nQuestion:\nAll the articles and documentation I have read so far talk about the integration of Cloudwatch and Winston on a vanilla Node app, but nothing on Nestjs\n\nSo far I have on my **app.module.ts**:\n\n```\nimports: [\n ConfigModule.forRoot({ isGlobal: true }),\n MongooseModule.forRoot(\n `mongodb://${environment.MONGO_INITDB_ROOT_USERNAME}:${environment.MONGO_INITDB_ROOT_PASSWORD}@${environment.MONGODB_HOST}/${environment.MONGO_INITDB_DATABASE}`,\n ),\n VoucherModule,\n ApiKeyModule,\n WinstonModule.forRoot(loggerConfig),\n ],\n```\n\nwhere loggerConfig are the basic Winston configs depending on the env.\n\nUsing winston-cloudwatch package I need to create a new Transporter and add it add it to winston, but can't seem to find a way to do this.\n\n========================================\n\nCode:\n```text\nimports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    MongooseModule.forRoot(\n      `mongodb://${environment.MONGO_INITDB_ROOT_USERNAME}:${environment.MONGO_INITDB_ROOT_PASSWORD}@${environment.MONGODB_HOST}/${environment.MONGO_INITDB_DATABASE}`,\n    ),\n    VoucherModule,\n    ApiKeyModule,\n    WinstonModule.forRoot(loggerConfig),\n  ],\n```\n\n```text\n//main.ts\nimport {\n  utilities as nestWinstonModuleUtilities,\n  WinstonModule,\n} from 'nest-winston';\nimport * as winston from 'winston';\nimport CloudWatchTransport from 'winston-cloudwatch';\n\nconst app = await NestFactory.create(AppModule, {\n  logger: WinstonModule.createLogger({\n    format: winston.format.uncolorize(), //Uncolorize logs as weird character encoding appears when logs are colorized in cloudwatch.\n    transports: [\n      new winston.transports.Console({\n        format: winston.format.combine(\n          winston.format.timestamp(),\n          winston.format.ms(),\n          nestWinstonModuleUtilities.format.nestLike()\n        ),\n      }),\n      new CloudWatchTransport({\n        name: \"Cloudwatch Logs\",\n        logGroupName: process.env.CLOUDWATCH_GROUP_NAME,\n        logStreamName: process.env.CLOUDWATCH_STREAM_NAME,\n        awsAccessKeyId: process.env.AWS_ACCESS_KEY,\n        awsSecretKey: process.env.AWS_KEY_SECRET,\n        awsRegion: process.env.CLOUDWATCH_AWS_REGION,\n        messageFormatter: function (item) {\n          return (\n            item.level + \": \" + item.message + \" \" + JSON.stringify(item.meta)\n          );\n        },\n      }),\n    ],\n  }),\n});\n```\n\n```text\n//main.js\nimport {\n  utilities as nestWinstonModuleUtilities,\n  WinstonModule,\n} from 'nest-winston';\nimport * as winston from 'winston';\nimport CloudWatchTransport from 'winston-cloudwatch';\nimport { ConfigService } from '@nestjs/config';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const configService = app.get(ConfigService);\n\n  app.useLogger(\n    WinstonModule.createLogger({\n      format: winston.format.uncolorize(),\n      transports: [\n        new winston.transports.Console({\n          format: winston.format.combine(\n            winston.format.timestamp(),\n            winston.format.ms(),\n            nestWinstonModuleUtilities.format.nestLike(),\n          ),\n        }),\n        new CloudWatchTransport({\n          name: 'Cloudwatch Logs',\n          logGroupName: configService.get('CLOUDWATCH_GROUP_NAME'),\n          logStreamName: configService.get('CLOUDWATCH_STREAM_NAME'),\n          awsAccessKeyId: configService.get('AWS_ACCESS_KEY'),\n          awsSecretKey: configService.get('AWS_KEY_SECRET'),\n          awsRegion: configService.get('CLOUDWATCH_AWS_REGION'),\n          messageFormatter: function (item) {\n            return (\n              item.level + ': ' + item.message + ' ' + JSON.stringify(item.meta)\n            );\n          },\n        }),\n      ],\n    }),\n  );\n\n  await app.listen(configService.get('PORT') || 3000);\n}\n```\n\n========================================\n\nComments:\n- thank you, how would you use configService in this case to get the env variables? your solution works great but I would rather create a config file to pass on the createLogger method.\n- I have edited my answer. This should work.\n- Thanks for your answer. I did the same thing by following your example on aliyun/alibaba clound's logging service of SLS, which is equivalent of aws's cloudwatch. And I used this package to replace the CloudWatchTransport: github.com/chylvina/winston-sls\n- More about logging service please see wanago.io/2021/10/04/api-nestjs-logging-typeorm\n- @FrankGuo Thank you. I'm glad that you found my blog useful.","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":132,"estimatedTokens":1145}}532{"id":"stack-58896932","source":"stackoverflow","questionId":58896932,"title":"Nest can't resolve dependencies of the UserModel (?)","tags":["javascript","node.js","typescript","mongoose","nestjs"],"text":"Title: Nest can't resolve dependencies of the UserModel (?)\nTags: javascript, node.js, typescript, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen I try to use `MongooseModel` on `Users` I am getting the following error\n\n Nest can't resolve dependencies of the UserModel (?). Please make sure\n that the argument DatabaseConnection at index [0] is available in the\n MongooseModule context.\n\n**/src/database/database.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\nimport { ConfigModule } from '../config/config.module';\n\n@Module({\n imports: [ConfigModule],\n providers: [...databaseProviders],\n exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\n**/src/database/database.provider.ts**\n\n```\n// NPM Packages\nimport * as mongoose from 'mongoose';\nimport { Provider } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n// Custom Packages\nimport { ConfigService } from '../config/config.service';\n\nexport const databaseProviders: Provider[] = [\n {\n inject: [ConfigService],\n provide: 'DATABASE_CONNECTION',\n useFactory: async (\n configService: ConfigService,\n ): Promise =>\n await mongoose.connect(configService.get('MONGODB_URI'), {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n useCreateIndex: true,\n useFindAndModify: false,\n }),\n },\n];\n```\n\n**/src/app.module.ts**\n\n```\n// Core Packages\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n// NPM Packages\n\n// Custom Packages\nimport { ConfigModule } from './config/config.module';\nimport { DatabaseModule } from './database/database.module';\nimport { AuthModule } from './auth/auth.module';\nimport { UsersModule } from './users/users.module';\n\n@Module({\n imports: [ConfigModule, DatabaseModule, AuthModule, UsersModule],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n**/src/auth/auth.module.ts**\n\n```\n// Core Packages\nimport { Module } from '@nestjs/common';\n\n// NPM Packages\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\n\n// Custom Packages\nimport { AuthService } from './auth.service';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtStrategy } from './jwt.strategy';\nimport { UsersModule } from '../users/users.module';\nimport { jwtConstants } from './constants';\nimport { AuthController } from './auth.controller';\nimport { ConfigService } from 'src/config/config.service';\nimport { ConfigModule } from 'src/config/config.module';\nimport { DatabaseModule } from 'src/database/database.module';\n\n@Module({\n imports: [\n ConfigModule,\n DatabaseModule,\n UsersModule,\n PassportModule,\n JwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n secret: configService.get('JWT_SECRET'),\n signOptions: { expiresIn: configService.get('JWT_EXPIRE') },\n }),\n inject: [ConfigService],\n }),\n ],\n providers: [AuthService, LocalStrategy, JwtStrategy],\n exports: [AuthService],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n**/src/users/user.module.ts**\n\n```\n// Core Packages\nimport { Module } from '@nestjs/common';\n\n// NPM Packages\nimport { MongooseModule } from '@nestjs/mongoose';\n\n// Custom Packages\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\nimport { UserSchema } from './schemas/user.schema';\nimport { DatabaseModule } from 'src/database/database.module';\n\n@Module({\n providers: [UsersService],\n exports: [UsersService],\n controllers: [UsersController],\n imports: [\n DatabaseModule,\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n ],\n})\nexport class UsersModule {}\n```\n\n========================================\n\nTop Answer:\nIn my case, *main.ts* was erroneously calling `NestFactory.create(UsersModule)` instead of `NestFactory.create(AppModule)`\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\nimport { ConfigModule } from '../config/config.module';\n\n@Module({\n  imports: [ConfigModule],\n  providers: [...databaseProviders],\n  exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\n```text\n// NPM Packages\nimport * as mongoose from 'mongoose';\nimport { Provider } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n// Custom Packages\nimport { ConfigService } from '../config/config.service';\n\nexport const databaseProviders: Provider[] = [\n  {\n    inject: [ConfigService],\n    provide: 'DATABASE_CONNECTION',\n    useFactory: async (\n      configService: ConfigService,\n    ): Promise<typeof mongoose> =>\n      await mongoose.connect(configService.get('MONGODB_URI'), {\n        useNewUrlParser: true,\n        useUnifiedTopology: true,\n        useCreateIndex: true,\n        useFindAndModify: false,\n      }),\n  },\n];\n```\n\n```text\n// Core Packages\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n// NPM Packages\n\n// Custom Packages\nimport { ConfigModule } from './config/config.module';\nimport { DatabaseModule } from './database/database.module';\nimport { AuthModule } from './auth/auth.module';\nimport { UsersModule } from './users/users.module';\n\n@Module({\n  imports: [ConfigModule, DatabaseModule, AuthModule, UsersModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n// Core Packages\nimport { Module } from '@nestjs/common';\n\n// NPM Packages\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\n\n// Custom Packages\nimport { AuthService } from './auth.service';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtStrategy } from './jwt.strategy';\nimport { UsersModule } from '../users/users.module';\nimport { jwtConstants } from './constants';\nimport { AuthController } from './auth.controller';\nimport { ConfigService } from 'src/config/config.service';\nimport { ConfigModule } from 'src/config/config.module';\nimport { DatabaseModule } from 'src/database/database.module';\n\n@Module({\n  imports: [\n    ConfigModule,\n    DatabaseModule,\n    UsersModule,\n    PassportModule,\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        secret: configService.get('JWT_SECRET'),\n        signOptions: { expiresIn: configService.get('JWT_EXPIRE') },\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n  providers: [AuthService, LocalStrategy, JwtStrategy],\n  exports: [AuthService],\n  controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n```text\n// Core Packages\nimport { Module } from '@nestjs/common';\n\n// NPM Packages\nimport { MongooseModule } from '@nestjs/mongoose';\n\n// Custom Packages\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\nimport { UserSchema } from './schemas/user.schema';\nimport { DatabaseModule } from 'src/database/database.module';\n\n@Module({\n  providers: [UsersService],\n  exports: [UsersService],\n  controllers: [UsersController],\n  imports: [\n    DatabaseModule,\n    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n  ],\n})\nexport class UsersModule {}\n```\n\n```text\nMongooseModel\n```\n\n```text\nUsers\n```\n\n```text\nMongooseModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    uri: configService.getString('MONGODB_URI'),\n    useNewUrlParser: true,\n    useUnifiedTopology: true,\n    useCreateIndex: true,\n    useFindAndModify: false,\n  }),\n  inject: [ConfigService],\n});\n```\n\n```text\ndatabase.provider.ts\n```\n\n```text\nMongooseModule.forRootAsync\n```\n\n```text\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({\n  imports: [\n    MongooseModule.forRootAsync({\n      useFactory: () => ({\n        uri: 'mongodb://xxxxx',\n      }),\n    }),\n   \n  ],\n})\nexport class AppModule {}\n```\n\n```text\nNestFactory.create(UsersModule)\n```\n\n```text\nNestFactory.create(AppModule)\n```\n\n========================================\n\nComments:\n- Is there a way I can seperate out the configuration part into a new file and just import it on the `app.module.ts`\n- Yes, with `useClass`, see docs.nestjs.com/techniques/mongodb#async-configuration\n- tried it but not able to get it to work. Any suggestions? github.com/harshamv/nestjs-starter/blob/master/src/database/&zwnj;&#8203;&hellip;\n- Maybe open a new question about it including the error message you receive. I'd say the problem of this thread is solved; this seems to be a new problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":344,"estimatedTokens":2178}}533{"id":"stack-58747303","source":"stackoverflow","questionId":58747303,"title":"How to cover TypeORM @Column decorator with Jest unit testing?","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: How to cover TypeORM @Column decorator with Jest unit testing?\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to Unit and e2e test my applications as much as possible and my goal is a coverage of 101%. Problem right now with my setup is, that the @Column decorator from typeorm uses an arrow function to set a default value like the current timestamp on a database update. This arrow function is not covered with jest test coverage. Message is: `statement not covered`\n\nI run the code coverage with: `jest --coverage`.\nMy versions:\n\n```\n\"jest\": \"^24.9.0\",\n\"typeorm\": \"^0.2.20\"\n```\n\nJest configuration within package.json:\n\n```\n{\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"../build/coverage\",\n \"testEnvironment\": \"node\",\n \"coverageThreshold\": {\n \"global\": {\n \"branches\": 80,\n \"functions\": 80,\n \"lines\": 80,\n \"statements\": -10\n }\n }\n },\n}\n```\n\nMy entity looks like this:\n\n```\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Role {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n tenantId: number;\n\n @Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' })\n createdAt: Date;\n\n @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' })\n updatedAt: Date;\n}\n```\n\nCoverage for this entity:\n\nhttps://i.sstatic.net/XSr5J.png\n\n========================================\n\nTop Answer:\nThis is the solution that worked for me, based off of @JayMcDoniel's answer.\n\n- database type: `postgreSQl`\n\n- testing: `jest/chai`\n\nFunctions class:\n\n```\nexport abstract class EntityDefaultFunctions {\n public static defaultNull = (): string => 'NULL';\n public static defaultZero = (): string => '0';\n }\n```\n\nTests:\n\n```\nexpect(EntityDefaultFunctions.defaultNull()).to.equal('NULL');\n expect(EntityDefaultFunctions.defaultZero()).to.equal('0');\n```\n\nExample Entity Column definition:\n\n```\n@Column('text', {\n default: EntityDefaultFunctions.defaultNull,\n name: 'somePropertyName'\n })\n```\n\n========================================\n\nCode:\n```text\n\"jest\": \"^24.9.0\",\n\"typeorm\": \"^0.2.20\"\n```\n\n```json\n{\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".spec.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"coverageDirectory\": \"../build/coverage\",\n    \"testEnvironment\": \"node\",\n    \"coverageThreshold\": {\n      \"global\": {\n        \"branches\": 80,\n        \"functions\": 80,\n        \"lines\": 80,\n        \"statements\": -10\n      }\n    }\n  },\n}\n```\n\n```js\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Role {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    tenantId: number;\n\n    @Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' })\n    createdAt: Date;\n\n    @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' })\n    updatedAt: Date;\n}\n```\n\n```text\nstatement not covered\n```\n\n```text\njest --coverage\n```\n\n```js\nexport const returnString = () => String;\n\n@Query(returnString)\n```\n\n```js\nexpect(returnString()).toBe(String);\n```\n\n```text\nexpect(namedFunction).toBe('CURRENT_TIMESTAMP()')\n```\n\n```text\nexport abstract class EntityDefaultFunctions {\n    public static defaultNull = (): string => 'NULL';\n    public static defaultZero = (): string => '0';\n  }\n```\n\n```text\nexpect(EntityDefaultFunctions.defaultNull()).to.equal('NULL');\n  expect(EntityDefaultFunctions.defaultZero()).to.equal('0');\n```\n\n```text\n@Column('text', {\n    default: EntityDefaultFunctions.defaultNull,\n    name: 'somePropertyName'\n  })\n```\n\n```text\npostgreSQl\n```\n\n```text\njest/chai\n```\n\n========================================\n\nComments:\n- You are the hero we need in these dark times.\n- Amazing. Coverage is 100% now without those annoying \"ignore\" comments <3\n- Only problem left is the missing return type of those newly created functions. E.g.: `export const returnString = () => String;` I can't provide `: String` as return type because it moans about missing methods of type *StringConstructor*\n- You should still be able to do something like `expect(returnString()).toBe(String)`. I've got that running in my test classes without a problem\n- Thanks for the updates @JayMcDoniel. This was enough to get me to a solution that worked for my case.","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":214,"estimatedTokens":1135}}534{"id":"stack-59090942","source":"stackoverflow","questionId":59090942,"title":"Nestjs: How to generate \"spec.ts\" files if --no-spec used to disable spec files generation","tags":["nestjs"],"text":"Title: Nestjs: How to generate \"spec.ts\" files if --no-spec used to disable spec files generation\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nNestjs: How to generate \"spec.ts\" files if --no-spec used to disable spec files generation. I need to test the complete module but i do not have spec.ts files. Is there any mechanism to generate these files for existing modules.\n\n========================================\n\nTop Answer:\nif you use vs-code plugin nestjs snippets\n\nuse prefix : `n-test` or `n-test-service` will quickly generate template code for test\n\n========================================\n\nCode:\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { MyService } from './my.service';\n\ndescribe('MyService', () => {\n  let service: MyService;\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [MyService],\n    }).compile();\n    service = module.get<MyService>(MyService);\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n});\n```\n\n```text\nn-test\n```\n\n```text\nn-test-service\n```\n\n========================================\n\nComments:\n- there are typos like `ascyn`, `moudle` need to be correct :)","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":48,"estimatedTokens":303}}535{"id":"stack-67081931","source":"stackoverflow","questionId":67081931,"title":"How to configure NestJS TypeOrm with URI instead of host, port, username and password fields?","tags":["database","postgresql","heroku","nestjs","typeorm"],"text":"Title: How to configure NestJS TypeOrm with URI instead of host, port, username and password fields?\nTags: database, postgresql, heroku, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe Heroku Postgres addon provides DB connection details as `postgres://user:pw@host:port` in the `DATABASE_URL` env var.\n\nI'm wondering how to configure a NestJS app using TypeOrm, because all the examples look like this:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: '...',\n port: 5432,\n username: '...',\n password: '...',\n }),\n ],\n})\n```\n\n========================================\n\nTop Answer:\nI also had problem with `postgres://` protocol and I had change to `postgresql://` to have database connection fully working.\n\n========================================\n\nCode:\n```js\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n        type: 'postgres',\n        host: '...',\n        port: 5432,\n        username: '...',\n        password: '...',\n    }),\n  ],\n})\n```\n\n```text\npostgres://user:pw@host:port\n```\n\n```text\nDATABASE_URL\n```\n\n```js\nTypeOrmModule.forRoot({\n  type: 'postgres',\n  url: process.env.DATABASE_URL,\n}),\n```\n\n```text\npostgres://postgres:@<db_service_name>:5432\n```\n\n```text\nurl\n```\n\n```text\npostgres\n```\n\n```text\npostgres://\n```\n\n```text\npostgresql://\n```\n\n========================================\n\nComments:\n- you saved my time as well. i wrote `mysql:&#47;&#47;~~` text using mysql. thanks\n- options like synchronize how to paass that?","metadata":{"transformedAt":"2026-08-18T18:33:02.450Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":85,"estimatedTokens":369}}536{"id":"stack-68497436","source":"stackoverflow","questionId":68497436,"title":"NestJS Mapped Types and DTO usage","tags":["nestjs","nestjs-swagger"],"text":"Title: NestJS Mapped Types and DTO usage\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI'm confused about the mapped types in NestJS.\n\nThe documentation says that `PartialType` create a new class making its validation decorators optional.\n\nSo, we use it in our validation pipes as we do with the original classes.\n\nI'm wondering if it's the normal usage of the derived classes.\nI mean, to make it easy to create a partial update DTO.\n\nAnd if so, why is it in a swagger package (or graphql) and not in a utils of the core?\n\n========================================\n\nCode:\n```text\nPartialType\n```\n\n```text\nmapped-types\n```\n\n```text\n@nestjs/mapped-types\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\npassword\n```\n\n```text\nUser\n```\n\n```text\n@nestjs/mapped-types\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nmapped-types\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\nmapped-types\n```\n\n========================================\n\nComments:\n- Thanks Jay, I really didnt find this information elsewhere.\n- Hi Jay, thanks for info. But how do I use both PartialType from @nestjs/mapped-types and @nestjs/swagger in one definition? Or do I have to create 2 different class. If create 2 different class is the only way then do I have to add the Partial class that use @nestjs/swagger to extraModels, for it to show up properly?\n- Why do you need both `@nestjs&#47;swagger`'s mapped types and `@nestjs&#47;mapped-types`' mapped types?\n- if I use @nestjs/mapped-types then my OpenApi docs is doom and if I use @nestjs/swagger then my class-transform wont work. I mean I can just define my PartialDto with all the fields but optional, just thought if I could use both PartialType from both lib then it would improve my dev experience\n- `@nestjs&#47;swagger`'s mapped types build *on top of* the original `@nestjs&#47;mapped-types`, so I don't see why your class-transformer config won't keep working\n- I have a `@Type(() -> Date)` on one of the attribute and nestjs keep throwing me errors but if i use PartialType from `@nestjs&#47;mapped-types` then it works just fine\n- @JayMcDoniel I have the same issue actually, using `@nestjs&#47;mapped-types` works but does not get picked by my openapi, `@nestjs&#47;swagger` makes openapi correct but does not pick transformers correctly.\n- @ManNguyen did you find a workaround for this?","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":86,"estimatedTokens":603}}537{"id":"stack-64872626","source":"stackoverflow","questionId":64872626,"title":"How can I use ParseIntPipe and Dto together?","tags":["nestjs","dto"],"text":"Title: How can I use ParseIntPipe and Dto together?\nTags: nestjs, dto\nSource: Stack Overflow\n\nQuestion:\nFrom query I get limit param.\nHow to transform into number and check by Dto ?\n\n```\n@Get('currency/:type')\n getCurrency(\n @Param() params: CurrencyTypeDto,\n @Query('limit', ParseIntPipe) limit: number,\n @Query() query: PaginationLimitDto\n ) {\n```\n\nPaginationLimitDto\n\n```\nexport class PaginationLimitDto {\n @IsOptional()\n @IsInt()\n limit: number;\n}\n```\n\n========================================\n\nTop Answer:\nThe updated syntax for `@Transorm` decorator.\n\n```\nimport { Transform } from 'class-transformer';\n\nexport class Photo {\n id: number;\n\n @Transform(({ value }) => parseInt(value))\n index: number;\n}\n```\n\n========================================\n\nCode:\n```text\n@Get('currency/:type')\n  getCurrency(\n    @Param() params: CurrencyTypeDto,\n    @Query('limit', ParseIntPipe) limit: number,\n    @Query() query: PaginationLimitDto\n  ) {\n```\n\n```text\nexport class PaginationLimitDto {\n    @IsOptional()\n    @IsInt()\n    limit: number;\n}\n```\n\n```js\nexport class PaginationLimitDto {\n  @IsOptional()\n  @IsInt()\n  // pre 0.3.2 syntax\n  @Transform(val => Number.parseInt(val))\n  // after 0.3.2 syntax*\n  @Transform({ value } => Number.parseInt(value))\n  limit: number;\n}\n```\n\n```text\n@Transform()\n```\n\n```text\n@Query() query: PaginationLimitDto\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\nimport { Transform } from 'class-transformer';\n\nexport class Photo {\n  id: number;\n\n  @Transform(({ value }) => parseInt(value))\n  index: number;\n}\n```\n\n```text\n@Transorm\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({\n    transform: true\n  }))\n```\n\n========================================\n\nComments:\n- By \"check by Dto\", do you mean use Nest's `ValdiationPipe`?\n- transform to int from string and check by dto\n- This is the current correct answer as of 9/25/22. Ignore the accepted answer since it has been updated.","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":122,"estimatedTokens":491}}538{"id":"stack-62094995","source":"stackoverflow","questionId":62094995,"title":"Deploying NestJS to Azure DevOps: Error: Cannot find module '../commands'","tags":["node.js","azure-devops","azure-pipelines","nestjs","azure-pipelines-release-pipeline"],"text":"Title: Deploying NestJS to Azure DevOps: Error: Cannot find module '../commands'\nTags: node.js, azure-devops, azure-pipelines, nestjs, azure-pipelines-release-pipeline\nSource: Stack Overflow\n\nQuestion:\nI have a very basic \"Hello World\" NestJS app that I'm trying to get deployed to an Azure Web App instance in Azure DevOps.\n\nI have set up a build pipeline using a YAML file which outputs a build artifact with the `dist` and `node_modules` directories.\n\nThen, in my release pipeline, I have a continuous deployment set up to download that artifact and deploy it. The release pipeline consists of a single step to Deploy Azure App Service. Furthermore, after this step, I entered some Post-Deployment Actions which are `npm install`, `npm update`, and `npm run start:prod` to get the NestJS server started.\n\nhttps://i.sstatic.net/FkhVO.png\n\nHowever, when running the pipeline, that step takes an inordinate amount of time eventually erroring with:\n\nhttps://i.sstatic.net/kv5ka.png\n\nWhen I visit the web app instance that I have set up (`https://.azurewebsites.net/`), I see: \n\nhttps://i.sstatic.net/8qndb.png\n\nSo, I click on \"Diagnostic Resources\" to try to figure out why my release is failing and eventually discover this error:\n\n```\n2020-05-29T20:01:30.864090341Z _____ \n2020-05-29T20:01:30.864143041Z / _ \\ __________ _________ ____ \n2020-05-29T20:01:30.864149941Z / /_\\ \\___ / | \\_ __ \\_/ __ \\ \n2020-05-29T20:01:30.864153741Z / | \\/ /| | /| | \\/\\ ___/ \n2020-05-29T20:01:30.864157341Z \\____|__ /_____ \\____/ |__| \\___ >\n2020-05-29T20:01:30.864161141Z \\/ \\/ \\/ \n2020-05-29T20:01:30.864164541Z A P P S E R V I C E O N L I N U X\n2020-05-29T20:01:30.864167941Z \n2020-05-29T20:01:30.864171141Z Documentation: http://aka.ms/webapp-linux\n2020-05-29T20:01:30.864174441Z NodeJS quickstart: https://aka.ms/node-qs\n2020-05-29T20:01:30.864177741Z NodeJS Version : v12.13.0\n2020-05-29T20:01:30.864181041Z Note: Any data outside '/home' is not persisted\n2020-05-29T20:01:30.864184441Z \n2020-05-29T20:01:30.951441760Z Oryx Version: 0.2.20191105.2, Commit: 67e159d71419415435cb5d10c05a0f0758ee8809, ReleaseTagName: 20191105.2\n2020-05-29T20:01:30.951840160Z Cound not find build manifest file at '/home/site/wwwroot/oryx-manifest.toml'\n2020-05-29T20:01:30.951915661Z Could not find operation ID in manifest. Generating an operation id...\n2020-05-29T20:01:30.952061661Z Build Operation ID: dfd18989-3b7b-4e2e-a64e-cf7310361e99\n2020-05-29T20:01:32.750738663Z Writing output script to '/opt/startup/startup.sh'\n2020-05-29T20:01:33.355033998Z Running #!/bin/sh\n2020-05-29T20:01:33.359017599Z \n2020-05-29T20:01:33.359033399Z # Enter the source directory to make sure the script runs where the user expects\n2020-05-29T20:01:33.359644199Z cd \"/home/site/wwwroot\"\n2020-05-29T20:01:33.359658399Z \n2020-05-29T20:01:33.359664799Z export NODE_PATH=$(npm root --quiet -g):$NODE_PATH\n2020-05-29T20:01:33.360538899Z if [ -z \"$PORT\" ]; then\n2020-05-29T20:01:33.360552699Z export PORT=8080\n2020-05-29T20:01:33.360557899Z fi\n2020-05-29T20:01:33.360561499Z \n2020-05-29T20:01:33.361582699Z npm start\n2020-05-29T20:01:35.698639821Z \n2020-05-29T20:01:35.698668521Z > @0.0.1 start /home/site/wwwroot\n2020-05-29T20:01:35.698675121Z > nest start\n2020-05-29T20:01:35.698679221Z \n2020-05-29T20:01:35.930729770Z internal/modules/cjs/loader.js:797\n2020-05-29T20:01:35.930766970Z throw err;\n2020-05-29T20:01:35.930772870Z ^\n2020-05-29T20:01:35.930776770Z \n2020-05-29T20:01:35.930780670Z Error: Cannot find module '../commands'\n2020-05-29T20:01:35.930784670Z Require stack:\n2020-05-29T20:01:35.930788470Z - /home/site/wwwroot/node_modules/.bin/nest\n2020-05-29T20:01:35.930792370Z at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)\n2020-05-29T20:01:35.930803370Z at Function.Module._load (internal/modules/cjs/loader.js:687:27)\n2020-05-29T20:01:35.930807770Z at Module.require (internal/modules/cjs/loader.js:849:19)\n2020-05-29T20:01:35.930811570Z at require (internal/modules/cjs/helpers.js:74:18)\n2020-05-29T20:01:35.930815370Z at Object. (/home/site/wwwroot/node_modules/.bin/nest:5:20)\n2020-05-29T20:01:35.930819770Z at Module._compile (internal/modules/cjs/loader.js:956:30)\n2020-05-29T20:01:35.930823570Z at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)\n2020-05-29T20:01:35.930827470Z at Module.load (internal/modules/cjs/loader.js:812:32)\n2020-05-29T20:01:35.930831270Z at Function.Module._load (internal/modules/cjs/loader.js:724:14)\n2020-05-29T20:01:35.930835070Z at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) {\n2020-05-29T20:01:35.930838970Z code: 'MODULE_NOT_FOUND',\n2020-05-29T20:01:35.930842770Z requireStack: [ '/home/site/wwwroot/node_modules/.bin/nest' ]\n2020-05-29T20:01:35.930846670Z }\n2020-05-29T20:01:35.970252977Z npm ERR! code ELIFECYCLE\n2020-05-29T20:01:35.979824678Z npm ERR! errno 1\n2020-05-29T20:01:35.981324478Z npm ERR! @0.0.1 start: `nest start`\n2020-05-29T20:01:35.982002178Z npm ERR! Exit status 1\n2020-05-29T20:01:35.982641778Z npm ERR! \n2020-05-29T20:01:35.991823280Z npm ERR! Failed at the @0.0.1 start script.\n2020-05-29T20:01:35.991838780Z npm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n2020-05-29T20:01:36.118651500Z \n2020-05-29T20:01:36.119439400Z npm ERR! A complete log of this run can be found in:\n2020-05-29T20:01:36.128548002Z npm ERR! /root/.npm/_logs/2020-05-29T20_01_35_990Z-debug.log\n```\n\nAt this point I can't figure out what is wrong. Any help would be greatly appreciated.\n\n========================================\n\nCode:\n```text\n2020-05-29T20:01:30.864090341Z   _____                               \n2020-05-29T20:01:30.864143041Z   /  _  \\ __________ _________   ____  \n2020-05-29T20:01:30.864149941Z  /  /_\\  \\___   /  |  \\_  __ \\_/ __ \\ \n2020-05-29T20:01:30.864153741Z /    |    \\/    /|  |  /|  | \\/\\  ___/ \n2020-05-29T20:01:30.864157341Z \\____|__  /_____ \\____/ |__|    \\___  >\n2020-05-29T20:01:30.864161141Z         \\/      \\/                  \\/ \n2020-05-29T20:01:30.864164541Z A P P   S E R V I C E   O N   L I N U X\n2020-05-29T20:01:30.864167941Z \n2020-05-29T20:01:30.864171141Z Documentation: http://aka.ms/webapp-linux\n2020-05-29T20:01:30.864174441Z NodeJS quickstart: https://aka.ms/node-qs\n2020-05-29T20:01:30.864177741Z NodeJS Version : v12.13.0\n2020-05-29T20:01:30.864181041Z Note: Any data outside '/home' is not persisted\n2020-05-29T20:01:30.864184441Z \n2020-05-29T20:01:30.951441760Z Oryx Version: 0.2.20191105.2, Commit: 67e159d71419415435cb5d10c05a0f0758ee8809, ReleaseTagName: 20191105.2\n2020-05-29T20:01:30.951840160Z Cound not find build manifest file at '/home/site/wwwroot/oryx-manifest.toml'\n2020-05-29T20:01:30.951915661Z Could not find operation ID in manifest. Generating an operation id...\n2020-05-29T20:01:30.952061661Z Build Operation ID: dfd18989-3b7b-4e2e-a64e-cf7310361e99\n2020-05-29T20:01:32.750738663Z Writing output script to '/opt/startup/startup.sh'\n2020-05-29T20:01:33.355033998Z Running #!/bin/sh\n2020-05-29T20:01:33.359017599Z \n2020-05-29T20:01:33.359033399Z # Enter the source directory to make sure the script runs where the user expects\n2020-05-29T20:01:33.359644199Z cd \"/home/site/wwwroot\"\n2020-05-29T20:01:33.359658399Z \n2020-05-29T20:01:33.359664799Z export NODE_PATH=$(npm root --quiet -g):$NODE_PATH\n2020-05-29T20:01:33.360538899Z if [ -z \"$PORT\" ]; then\n2020-05-29T20:01:33.360552699Z         export PORT=8080\n2020-05-29T20:01:33.360557899Z fi\n2020-05-29T20:01:33.360561499Z \n2020-05-29T20:01:33.361582699Z npm start\n2020-05-29T20:01:35.698639821Z \n2020-05-29T20:01:35.698668521Z > <project-name>@0.0.1 start /home/site/wwwroot\n2020-05-29T20:01:35.698675121Z > nest start\n2020-05-29T20:01:35.698679221Z \n2020-05-29T20:01:35.930729770Z internal/modules/cjs/loader.js:797\n2020-05-29T20:01:35.930766970Z     throw err;\n2020-05-29T20:01:35.930772870Z     ^\n2020-05-29T20:01:35.930776770Z \n2020-05-29T20:01:35.930780670Z Error: Cannot find module '../commands'\n2020-05-29T20:01:35.930784670Z Require stack:\n2020-05-29T20:01:35.930788470Z - /home/site/wwwroot/node_modules/.bin/nest\n2020-05-29T20:01:35.930792370Z     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)\n2020-05-29T20:01:35.930803370Z     at Function.Module._load (internal/modules/cjs/loader.js:687:27)\n2020-05-29T20:01:35.930807770Z     at Module.require (internal/modules/cjs/loader.js:849:19)\n2020-05-29T20:01:35.930811570Z     at require (internal/modules/cjs/helpers.js:74:18)\n2020-05-29T20:01:35.930815370Z     at Object. (/home/site/wwwroot/node_modules/.bin/nest:5:20)\n2020-05-29T20:01:35.930819770Z     at Module._compile (internal/modules/cjs/loader.js:956:30)\n2020-05-29T20:01:35.930823570Z     at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)\n2020-05-29T20:01:35.930827470Z     at Module.load (internal/modules/cjs/loader.js:812:32)\n2020-05-29T20:01:35.930831270Z     at Function.Module._load (internal/modules/cjs/loader.js:724:14)\n2020-05-29T20:01:35.930835070Z     at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) {\n2020-05-29T20:01:35.930838970Z   code: 'MODULE_NOT_FOUND',\n2020-05-29T20:01:35.930842770Z   requireStack: [ '/home/site/wwwroot/node_modules/.bin/nest' ]\n2020-05-29T20:01:35.930846670Z }\n2020-05-29T20:01:35.970252977Z npm ERR! code ELIFECYCLE\n2020-05-29T20:01:35.979824678Z npm ERR! errno 1\n2020-05-29T20:01:35.981324478Z npm ERR! <project-name>@0.0.1 start: `nest start`\n2020-05-29T20:01:35.982002178Z npm ERR! Exit status 1\n2020-05-29T20:01:35.982641778Z npm ERR! \n2020-05-29T20:01:35.991823280Z npm ERR! Failed at the <project-name>@0.0.1 start script.\n2020-05-29T20:01:35.991838780Z npm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n2020-05-29T20:01:36.118651500Z \n2020-05-29T20:01:36.119439400Z npm ERR! A complete log of this run can be found in:\n2020-05-29T20:01:36.128548002Z npm ERR!     /root/.npm/_logs/2020-05-29T20_01_35_990Z-debug.log\n```\n\n```text\ndist\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install\n```\n\n```text\nnpm update\n```\n\n```text\nnpm run start:prod\n```\n\n```text\nhttps://<project-name>.azurewebsites.net/\n```\n\n```text\nnpm start\n```\n\n```text\nnest start\n```\n\n```text\n@nestjs/cli\n```\n\n```text\nnest\n```\n\n```text\ndevDependencies\n```\n\n```text\ndevDeps\n```\n\n```text\nnode dist/main\n```\n\n```text\n@nestjs/cli\n```\n\n```text\ndependencies\n```\n\n========================================\n\nComments:\n- Hi @noblerare, Error: Cannot find module '../commands' i think you don't copy commands in build\n- This is what I needed. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":225,"estimatedTokens":2632}}539{"id":"stack-77020350","source":"stackoverflow","questionId":77020350,"title":"nestjs swc Error: Cannot find module 'path-to-project/src/app.module'","tags":["node.js","nestjs","swc"],"text":"Title: nestjs swc Error: Cannot find module 'path-to-project/src/app.module'\nTags: node.js, nestjs, swc\nSource: Stack Overflow\n\nQuestion:\nWhen I installed the swc, I get this Error: Cannot find module 'path-to-project/src/app.module'\n\nI'm using:\n\n- nodejs: 18.17.1\n\n- nestjs: 10.1.16\n\n- @swc/cli: 0.1.62\n\n- @swc/core: 1.3.81\n\n\"**dist/main.js**\"\n\n```\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true,\n});\nconst _cors = /*#__PURE__*/ _interop_require_default(require(\"@fastify/cors\"));\nconst _csrfprotection = /*#__PURE__*/ _interop_require_default(\n require(\"@fastify/csrf-protection\"),\n);\nconst _helmet = /*#__PURE__*/ _interop_require_default(\n require(\"@fastify/helmet\"),\n);\nconst _common = require(\"@nestjs/common\");\nconst _config = require(\"@nestjs/config\");\nconst _core = require(\"@nestjs/core\");\nconst _platformfastify = require(\"@nestjs/platform-fastify\");\nconst _swagger = require(\"@nestjs/swagger\");\nconst _appmodule = require(\"path-to-projects/src/app.module\");\nfunction _interop_require_default(obj) {\n return obj && obj.__esModule\n ? obj\n : {\n default: obj,\n };\n}\nasync function bootstrap() {\n const app = await _core.NestFactory.create(\n _appmodule.AppModule,\n new _platformfastify.FastifyAdapter(),\n );\n app.useGlobalPipes(\n new _common.ValidationPipe({\n transform: true,\n whitelist: true,\n }),\n );\n const config = app.get(_config.ConfigService);\n {\n const options = new _swagger.DocumentBuilder()\n .setTitle(config.get(\"API_TITLE\"))\n .setDescription(config.get(\"API_DESCRIPTION\"))\n .setVersion(config.get(\"API_VERSION\"))\n .build();\n const document = _swagger.SwaggerModule.createDocument(app, options);\n _swagger.SwaggerModule.setup(\"docs\", app, document);\n }\n await app.register(_cors.default);\n await app.register(_csrfprotection.default);\n await app.register(_helmet.default);\n await app.listen(config.get(\"API_PORT\"), \"0.0.0.0\");\n console.log(`๐Ÿš€ Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n\"**src/main.ts**\"\n\n```\nimport fastifyCors from \"@fastify/cors\";\nimport fastifyCsrf from \"@fastify/csrf-protection\";\nimport fastifyHelmet from \"@fastify/helmet\";\nimport { ValidationPipe } from \"@nestjs/common\";\nimport { ConfigService } from \"@nestjs/config\";\nimport { NestFactory } from \"@nestjs/core\";\nimport {\n FastifyAdapter,\n NestFastifyApplication,\n} from \"@nestjs/platform-fastify\";\nimport { DocumentBuilder, SwaggerModule } from \"@nestjs/swagger\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap() {\n const app = await NestFactory.create(\n AppModule,\n new FastifyAdapter(),\n );\n app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));\n const config = app.get(ConfigService);\n\n {\n const options = new DocumentBuilder()\n .setTitle(config.get(\"API_TITLE\"))\n .setDescription(config.get(\"API_DESCRIPTION\"))\n .setVersion(config.get(\"API_VERSION\"))\n .build();\n const document = SwaggerModule.createDocument(app, options);\n SwaggerModule.setup(\"docs\", app, document);\n }\n\n await app.register(fastifyCors);\n await app.register(fastifyCsrf);\n await app.register(fastifyHelmet);\n await app.listen(config.get(\"API_PORT\"), \"0.0.0.0\");\n console.log(`๐Ÿš€ Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n\"**package.json**\"\n\n```\n{\n \"name\": \"test\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"prebuild\": \"rimraf dist\",\n \"build\": \"nest build\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"nest start\",\n \"start:dev\": \"nest start --watch\",\n \"start:debug\": \"nest start --debug --watch\",\n \"start:prod\": \"node dist/main\",\n \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@fastify/cors\": \"^8.3.0\",\n \"@fastify/csrf-protection\": \"^6.3.0\",\n \"@fastify/helmet\": \"^11.0.0\",\n \"@fastify/static\": \"^6.10.2\",\n \"@nestjs/common\": \"^10.0.0\",\n \"@nestjs/config\": \"^3.0.1\",\n \"@nestjs/core\": \"^10.0.0\",\n \"@nestjs/platform-express\": \"^10.0.0\",\n \"@nestjs/platform-fastify\": \"^10.2.4\",\n \"@nestjs/swagger\": \"^7.1.10\",\n \"@prisma/client\": \"^5.2.0\",\n \"bcrypt\": \"^5.1.1\",\n \"class-transformer\": \"^0.5.1\",\n \"class-validator\": \"^0.14.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^5.0.1\",\n \"rxjs\": \"^7.8.1\"\n },\n \"devDependencies\": {\n \"@nestjs/cli\": \"^10.0.0\",\n \"@nestjs/schematics\": \"^10.0.0\",\n \"@nestjs/testing\": \"^10.0.0\",\n \"@swc/cli\": \"^0.1.62\",\n \"@swc/core\": \"^1.3.81\",\n \"@types/bcrypt\": \"^5.0.0\",\n \"@types/express\": \"^4.17.17\",\n \"@types/jest\": \"^29.5.2\",\n \"@types/node\": \"^20.3.1\",\n \"@types/supertest\": \"^2.0.12\",\n \"@typescript-eslint/eslint-plugin\": \"^6.0.0\",\n \"@typescript-eslint/parser\": \"^6.0.0\",\n \"eslint\": \"^8.42.0\",\n \"eslint-config-prettier\": \"^9.0.0\",\n \"eslint-plugin-prettier\": \"^5.0.0\",\n \"jest\": \"^29.5.0\",\n \"prettier\": \"^3.0.0\",\n \"prisma\": \"^5.2.0\",\n \"source-map-support\": \"^0.5.21\",\n \"supertest\": \"^6.3.3\",\n \"ts-jest\": \"^29.1.0\",\n \"ts-loader\": \"^9.4.3\",\n \"ts-node\": \"^10.9.1\",\n \"tsconfig-paths\": \"^4.2.0\",\n \"typescript\": \"^5.1.3\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"collectCoverageFrom\": [\n \"**/*.(t|j)s\"\n ],\n \"coverageDirectory\": \"../coverage\",\n \"testEnvironment\": \"node\"\n },\n \"prisma\": {\n \"schema\": \"src/database/prisma/schema.prisma\"\n }\n}\n```\n\n\"**tsconfig.json**\"\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"ES2021\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"skipLibCheck\": true,\n \"strictNullChecks\": false,\n \"noImplicitAny\": false,\n \"strictBindCallApply\": false,\n \"forceConsistentCasingInFileNames\": false,\n \"noFallthroughCasesInSwitch\": false\n }\n}\n```\n\n\"**tsconfig.build.json**\"\n\n```\n{\n \"extends\": \"./tsconfig.json\",\n \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n```\n\n\"**nest-cli.json**\"\n\n```\n{\n \"$schema\": \"https://json.schemastore.org/nest-cli\",\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"deleteOutDir\": true,\n \"builder\": \"swc\",\n \"typeCheck\": true\n }\n}\n```\n\nstructure\n\nI tried to change the base Url, create .swcrc\n\n========================================\n\nTop Answer:\nDowngrading to `@swc/core@1.3.78` worked for me\n\n========================================\n\nCode:\n```text\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n  value: true,\n});\nconst _cors = /*#__PURE__*/ _interop_require_default(require(\"@fastify/cors\"));\nconst _csrfprotection = /*#__PURE__*/ _interop_require_default(\n  require(\"@fastify/csrf-protection\"),\n);\nconst _helmet = /*#__PURE__*/ _interop_require_default(\n  require(\"@fastify/helmet\"),\n);\nconst _common = require(\"@nestjs/common\");\nconst _config = require(\"@nestjs/config\");\nconst _core = require(\"@nestjs/core\");\nconst _platformfastify = require(\"@nestjs/platform-fastify\");\nconst _swagger = require(\"@nestjs/swagger\");\nconst _appmodule = require(\"path-to-projects/src/app.module\");\nfunction _interop_require_default(obj) {\n  return obj && obj.__esModule\n    ? obj\n    : {\n        default: obj,\n      };\n}\nasync function bootstrap() {\n  const app = await _core.NestFactory.create(\n    _appmodule.AppModule,\n    new _platformfastify.FastifyAdapter(),\n  );\n  app.useGlobalPipes(\n    new _common.ValidationPipe({\n      transform: true,\n      whitelist: true,\n    }),\n  );\n  const config = app.get(_config.ConfigService);\n  {\n    const options = new _swagger.DocumentBuilder()\n      .setTitle(config.get(\"API_TITLE\"))\n      .setDescription(config.get(\"API_DESCRIPTION\"))\n      .setVersion(config.get(\"API_VERSION\"))\n      .build();\n    const document = _swagger.SwaggerModule.createDocument(app, options);\n    _swagger.SwaggerModule.setup(\"docs\", app, document);\n  }\n  await app.register(_cors.default);\n  await app.register(_csrfprotection.default);\n  await app.register(_helmet.default);\n  await app.listen(config.get(\"API_PORT\"), \"0.0.0.0\");\n  console.log(`๐Ÿš€ Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n```text\nimport fastifyCors from \"@fastify/cors\";\nimport fastifyCsrf from \"@fastify/csrf-protection\";\nimport fastifyHelmet from \"@fastify/helmet\";\nimport { ValidationPipe } from \"@nestjs/common\";\nimport { ConfigService } from \"@nestjs/config\";\nimport { NestFactory } from \"@nestjs/core\";\nimport {\n  FastifyAdapter,\n  NestFastifyApplication,\n} from \"@nestjs/platform-fastify\";\nimport { DocumentBuilder, SwaggerModule } from \"@nestjs/swagger\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter(),\n  );\n  app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));\n  const config = app.get(ConfigService);\n\n  {\n    const options = new DocumentBuilder()\n      .setTitle(config.get(\"API_TITLE\"))\n      .setDescription(config.get(\"API_DESCRIPTION\"))\n      .setVersion(config.get(\"API_VERSION\"))\n      .build();\n    const document = SwaggerModule.createDocument(app, options);\n    SwaggerModule.setup(\"docs\", app, document);\n  }\n\n  await app.register(fastifyCors);\n  await app.register(fastifyCsrf);\n  await app.register(fastifyHelmet);\n  await app.listen(config.get(\"API_PORT\"), \"0.0.0.0\");\n  console.log(`๐Ÿš€ Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n```text\n{\n  \"name\": \"test\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@fastify/cors\": \"^8.3.0\",\n    \"@fastify/csrf-protection\": \"^6.3.0\",\n    \"@fastify/helmet\": \"^11.0.0\",\n    \"@fastify/static\": \"^6.10.2\",\n    \"@nestjs/common\": \"^10.0.0\",\n    \"@nestjs/config\": \"^3.0.1\",\n    \"@nestjs/core\": \"^10.0.0\",\n    \"@nestjs/platform-express\": \"^10.0.0\",\n    \"@nestjs/platform-fastify\": \"^10.2.4\",\n    \"@nestjs/swagger\": \"^7.1.10\",\n    \"@prisma/client\": \"^5.2.0\",\n    \"bcrypt\": \"^5.1.1\",\n    \"class-transformer\": \"^0.5.1\",\n    \"class-validator\": \"^0.14.0\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^5.0.1\",\n    \"rxjs\": \"^7.8.1\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^10.0.0\",\n    \"@nestjs/schematics\": \"^10.0.0\",\n    \"@nestjs/testing\": \"^10.0.0\",\n    \"@swc/cli\": \"^0.1.62\",\n    \"@swc/core\": \"^1.3.81\",\n    \"@types/bcrypt\": \"^5.0.0\",\n    \"@types/express\": \"^4.17.17\",\n    \"@types/jest\": \"^29.5.2\",\n    \"@types/node\": \"^20.3.1\",\n    \"@types/supertest\": \"^2.0.12\",\n    \"@typescript-eslint/eslint-plugin\": \"^6.0.0\",\n    \"@typescript-eslint/parser\": \"^6.0.0\",\n    \"eslint\": \"^8.42.0\",\n    \"eslint-config-prettier\": \"^9.0.0\",\n    \"eslint-plugin-prettier\": \"^5.0.0\",\n    \"jest\": \"^29.5.0\",\n    \"prettier\": \"^3.0.0\",\n    \"prisma\": \"^5.2.0\",\n    \"source-map-support\": \"^0.5.21\",\n    \"supertest\": \"^6.3.3\",\n    \"ts-jest\": \"^29.1.0\",\n    \"ts-loader\": \"^9.4.3\",\n    \"ts-node\": \"^10.9.1\",\n    \"tsconfig-paths\": \"^4.2.0\",\n    \"typescript\": \"^5.1.3\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"collectCoverageFrom\": [\n      \"**/*.(t|j)s\"\n    ],\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  },\n  \"prisma\": {\n    \"schema\": \"src/database/prisma/schema.prisma\"\n  }\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"ES2021\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": false,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false\n  }\n}\n```\n\n```text\n{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n```\n\n```text\n{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"deleteOutDir\": true,\n    \"builder\": \"swc\",\n    \"typeCheck\": true\n  }\n}\n```\n\n```text\n@swc/core@1.3.78\n```\n\n```text\n@swc/cli\n```\n\n```text\n@swc/core@1.3.78\n```\n\n```text\n../../app.module\n```\n\n```text\npath-to-project/src/app.module\n```\n\n```text\npath-to-project\n```\n\n```text\napp.module\n```\n\n```json\n{\n  \"$schema\": \"https://json.schemastore.org/swcrc\",\n  \"sourceMaps\": true,\n  \"jsc\": {\n    \"parser\": {\n      \"syntax\": \"typescript\",\n      \"decorators\": true,\n      \"dynamicImport\": true\n    },\n    \"baseUrl\": \"./\"\n  },\n  \"minify\": false\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"tsConfigPath\": \"tsconfig.build.json\",\n    \"builder\": \"swc\",\n    \"deleteOutDir\": true\n  }\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"paths\": {\n      \"@src/*\": [\"src/*\"]\n    },\n  }\n}\n```\n\n```text\nnest-cli.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nsrc/**\n```\n\n```text\n@src/**\n```\n\n========================================\n\nComments:\n- I have the same issue but your solution didn't worked in my case\n- Worked for me, thx! Do you know if there's a related issue on Nest or SWC repositories?\n- OK, finally I add to open a new issue as they didn't want to reopen an existing one: github.com/swc-project/swc/issues/7990\n- Drama: kdy1 commented 4 hours ago Closing as this is not about the latest version @kdy1 kdy1 closed this as completed 4 hours ago @kdy1 kdy1 reopened this 4 hours ago @kdy1 kdy1 added this to the Planned milestone 2 hours ago ------ At least, `tsc` works good, just remove ` -b swc` from scripts....","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":592,"estimatedTokens":3642}}540{"id":"stack-62824276","source":"stackoverflow","questionId":62824276,"title":"Auto Increment Sequence in NestJs/Mongoose","tags":["node.js","mongodb","mongoose","nestjs","mongoose-sequence"],"text":"Title: Auto Increment Sequence in NestJs/Mongoose\nTags: node.js, mongodb, mongoose, nestjs, mongoose-sequence\nSource: Stack Overflow\n\nQuestion:\nI'm migrating a NodeJs project to NestJs, this project uses MongoDB as back-end database and Mongoose as ODM. I was using the mongoose-sequence plugin to handle autoincrement sequences, however I'm facing troubles requiring the library under NestJs.\n\nThe mongoose-sequence documentation explains how to import the library using CommonJS syntax as follows:\n\n```\nconst mongoose = require('mongoose')\nconst AutoIncrementFactory = require('mongoose-sequence');\n\nconst connection = await mongoose.createConnection('mongodb://...');\n\nconst AutoIncrement = AutoIncrementFactory(connection);\n```\n\nUsing ES6 import syntax it would be something like:\n\n```\nimport * as mongoose from 'mongoose';\nimport * as AutoIncrementFactory from 'mongoose-sequence';\n\nconst connection = ...;\n\nconst AutoIncrement = AutoIncrementFactory(connection);\n```\n\nHowever since NestJs uses Dependency Injection, accessing the native connection is not so direct. According to the documentation to integrate MongoDB using Mongoose accessing the native Mongoose Connection object can be done using the `@InjectConnection()` decorator as follows:\n\n```\n@Injectable()\nexport class CatsService {\n constructor(@InjectConnection() private connection: Connection) {}\n}\n```\n\nBut since TypeScript decorators can only be attached to a class declaration, method, accessor, property, or parameter I don't see how to inject the connection, require the plugin and initialize it on my Schema classes.\n\n========================================\n\nTop Answer:\nI faced the same problem but this worked for me:\n\n```\nMongooseModule.forFeatureAsync([\n {\n name: Cats.name,\n useFactory: async (connection: Connection) => {\n const schema = CatsSchema;\n const AutoIncrement = require('mongoose-sequence')(connection);\n schema.plugin(AutoIncrement, {inc_field: 'id'});\n return schema;\n },\n inject: [getConnectionToken()],\n },\n]),\n```\n\n========================================\n\nCode:\n```text\nconst mongoose = require('mongoose')\nconst AutoIncrementFactory = require('mongoose-sequence');\n\nconst connection = await mongoose.createConnection('mongodb://...');\n\nconst AutoIncrement = AutoIncrementFactory(connection);\n```\n\n```text\nimport * as mongoose from 'mongoose';\nimport * as AutoIncrementFactory from 'mongoose-sequence';\n\nconst connection = ...;\n\nconst AutoIncrement = AutoIncrementFactory(connection);\n```\n\n```text\n@Injectable()\nexport class CatsService {\n  constructor(@InjectConnection() private connection: Connection) {}\n}\n```\n\n```text\n@InjectConnection()\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forFeatureAsync([\n      {\n        name: Cat.name,\n        useFactory: () => {\n          const schema = CatsSchema;\n          schema.plugin(require('mongoose-autopopulate'));\n          return schema;\n        },\n      },\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nimport {getConnectionToken, MongooseModule} from '@nestjs/mongoose';\nimport * as AutoIncrementFactory from 'mongoose-sequence';\n\n@Module({\n  imports: [\n    MongooseModule.forFeatureAsync([\n      {\n        name: Cat.name,\n        useFactory: async (connection: Connection) => {\n          const schema = CatsSchema;\n          const AutoIncrement = AutoIncrementFactory(connection);\n          schema.plugin(AutoIncrement, {inc_field: 'id'});\n          return schema;\n        },\n        inject: [getConnectionToken('YOUR_CONNECTION_NAME')],\n      },\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nforFeatureAsync()\n```\n\n```text\nMongooseModule\n```\n\n```text\nuseFactory\n```\n\n```text\nmongoose-sequence\n```\n\n```text\ngetConnectionToken\n```\n\n```text\nMongooseModule.forFeatureAsync([\n  {\n    name: Cats.name,\n    useFactory: async (connection: Connection) => {\n      const schema = CatsSchema;\n      const AutoIncrement = require('mongoose-sequence')(connection);\n      schema.plugin(AutoIncrement, {inc_field: 'id'});\n      return schema;\n    },\n    inject: [getConnectionToken()],\n  },\n]),\n```\n\n```text\n@Module({\n    imports: [MongooseModule.forFeatureAsync([\n        {\n            name: Supplier.name,\n            useFactory: async (connection: Connection) =>{\n                const schema = SupplierSchema;\n                const AutoIncrement = require('mongoose-sequence')(connection)\n                 schema.plugin(AutoIncrement, {inc_field: 'code'});\n                 return schema;\n            },\n            inject: [getConnectionToken(process.env.DATA_BASE_URI)]\n        }\n    ])],\n    controllers: [SupplierController],\n    providers: [SupplierService]\n\n})\n```\n\n```bash\nnpm i @typegoose/auto-increment\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule, getConnectionToken } from '@nestjs/mongoose';\nimport { User, UserSchema } from './model/user.model';\nimport { UsersController } from './controller/users.controller';\nimport { UsersService } from './service/Users.service';\nimport {\n  AutoIncrementID,\n  AutoIncrementIDOptions,\n} from '@typegoose/auto-increment';\n\n@Module({\n  imports: [\n    MongooseModule.forFeatureAsync([\n      {\n        name: User.name,\n        useFactory: async () => {\n          const schema = UserSchema;\n\n          schema.plugin(AutoIncrementID, {\n            field: 'numbering',\n            startAt: 1,\n          } satisfies AutoIncrementIDOptions);\n\n          return schema;\n        },\n        inject: [getConnectionToken()],\n      },\n    ]),\n  ],\n  controllers: [UsersController],\n  providers: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\nmongoose-sequence\n```\n\n```text\n@typegoose/auto-increment\n```\n\n========================================\n\nComments:\n- Thank you for this answer. I'm trying to use this but I'm getting typscript errors from AutoIncrementFactory(connection). \"Argument of type Connection is not assignable to parameter of type 'Schema'. Did you run into this as well?\n- Hi @Todd, no I didn't encounter that problem, it seems to me you are assigning the connection to something that is not a Connection, but without more context it's difficult to tell.\n- thanks Andres. My module looks just like yours above. Maybe underlying libraries differ between our installations.\n- I did the same implementation explained in this answer, however when I generate a new orderModel, the orderId field doesn't populate.\n- Ok I fixed by doing this forFeatureAsync import on the main AppModule and not on the OrderModule. It's finally working.\n- @AndresFelipe Getting this error any idea? `Cannot read property 'modelNames' of undefined`\n- @HenonoaH Same here, did you solve it?\n- const AutoIncrement = AutoIncrementFactory(connection as any); i will fix the above issues\n- can you guys a complete example? I'm following the sample in the database `counter` collection automatically created, but the user collection doesn't have id automatically generated, and no error Thanks! @AndresFelipe @Todd","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":248,"estimatedTokens":1738}}541{"id":"stack-56790476","source":"stackoverflow","questionId":56790476,"title":"How to use keycloak with NestJS properly","tags":["node.js","authentication","keycloak","nestjs"],"text":"Title: How to use keycloak with NestJS properly\nTags: node.js, authentication, keycloak, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to use keycloak with NestJS and GrapphQL (type-graphql). There are some guides for using it with pure Express, but I'd prefer using with NestJS auth pattern. Can someboby give any suggestion?\n\n========================================\n\nTop Answer:\nI never tried it myself, but i guess i will soon. What i would do:\n\n- Check out the Authentication Technique again, and especially learn how to implement the different strategies of passport in nest: https://docs.nestjs.com/techniques/authentication\n\n- Take a look at the npm-package and it's documentation. The guys from passport have dedicated a whole section to OpenID: http://www.passportjs.org/docs/openid/\n\n- Implement the OpenID-Strategy in nestjs - here i would just the docs, since they are pretty good\n\nI hope this will maybe help you out. At the end of the day, you will have an OpenID implementation of passport with KeyCloak and can use a guard to protect your Routes / Schemes.\n\n========================================\n\nCode:\n```text\nasync authenticate(accessToken: string): Promise<User> {\n    const url = `${this.baseURL}/realms/${this.realm}/protocol/openid-connect/userinfo`;\n\n    try {\n        const response = await this.httpService.get<KeycloakUserInfoResponse>(url, {\n            headers: {\n                authorization: `Bearer ${accessToken}`,\n            },\n        }).toPromise();\n\n        return {\n            id: response.data.sub,\n            username: response.data.preferred_username,\n        };\n    } catch (e) {\n        throw new AuthenticationError(e.message);\n    }\n}\n```\n\n```text\npassport\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":47,"estimatedTokens":429}}542{"id":"stack-69564787","source":"stackoverflow","questionId":69564787,"title":"NestJS Postgres Prisma - Error type 'string' is not assignable to parameter type 'TemplateStringsArray | Sql'","tags":["node.js","typescript","postgresql","nestjs","prisma"],"text":"Title: NestJS Postgres Prisma - Error type 'string' is not assignable to parameter type 'TemplateStringsArray | Sql'\nTags: node.js, typescript, postgresql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a NestJS Monorepo service using Microservices architecture with PostgreSQL as a database, Prisma as ORM and TypeScript as primary language.\nBut I keep getting the error below when I try executing a Postgres query.\n\nsrc/infrastructure/persistence/work.repository.postgres.ts:188:7 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray | Sql'.\n\nI checked the data types and they seem to be compatible.\n\nPlease help me fix this.\n\nStack: TypeScript, PostgreSQL, Node.JS, Express and NestJS.\n\nThanks in advance!\n\n```\nasync findWriterNumber(writerAddress: string): Promise {\n const maxNumber = await this.prismaService.$queryRaw(\n `SELECT coalesce(max('writerNumber') + 1, 0) as max\n FROM \"Work\"\n LEFT OUTER JOIN \"WriterID\"\n ON \"Work\".\"id\" = \"WorkID\".\"workId\" AND \"WorkID\".\"address\" = '${writerAddress}'`,\n );\n return maxNumber[0].max;\n }\n```\n\n========================================\n\nTop Answer:\nAnother solution is to use the `Prisma.sql` helper:\n\n```\nconst maxNumber = await this.prismaService.$queryRaw(\n Prisma.sql`SELECT coalesce(max('writerNumber') + 1, 0) as max\n FROM \"Work\"\n LEFT OUTER JOIN \"WriterID\"\n ON \"Work\".\"id\" = \"WorkID\".\"workId\"\n AND \"WorkID\".\"address\" = '${writerAddress}'`,\n);\nreturn maxNumber[0].max;\n```\n\n========================================\n\nCode:\n```js\nasync findWriterNumber(writerAddress: string): Promise<number> {\n    const maxNumber = await this.prismaService.$queryRaw<{\n      max: number;\n    }>(\n      `SELECT coalesce(max('writerNumber') + 1, 0) as max\n       FROM \"Work\"\n                LEFT OUTER JOIN \"WriterID\"\n                                ON \"Work\".\"id\" = \"WorkID\".\"workId\" AND \"WorkID\".\"address\" = '${writerAddress}'`,\n    );\n    return maxNumber[0].max;\n  }\n```\n\n```js\nasync findWriterNumber(writerAddress: string): Promise<number> {\n    const maxNumber = await this.prismaService.$queryRaw<{\n      max: number;\n    }>\n      `SELECT coalesce(max('writerNumber') + 1, 0) as max\n       FROM \"Work\"\n                LEFT OUTER JOIN \"WriterID\"\n                                ON \"Work\".\"id\" = \"WorkID\".\"workId\" AND \"WorkID\".\"address\" = '${writerAddress}'`;\n    return maxNumber[0].max;\n  }\n```\n\n```text\nconst maxNumber = await this.prismaService.$queryRaw<{ max: number; }>(\n  Prisma.sql`SELECT coalesce(max('writerNumber') + 1, 0) as max\n   FROM \"Work\"\n   LEFT OUTER JOIN \"WriterID\"\n   ON \"Work\".\"id\" = \"WorkID\".\"workId\"\n   AND \"WorkID\".\"address\" = '${writerAddress}'`,\n);\nreturn maxNumber[0].max;\n```\n\n```text\nPrisma.sql\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":685}}543{"id":"stack-55376098","source":"stackoverflow","questionId":55376098,"title":"How to access the request url in the validate method of the http strategy?","tags":["javascript","node.js","typescript","passport.js","nestjs"],"text":"Title: How to access the request url in the validate method of the http strategy?\nTags: javascript, node.js, typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to access the context object that exists in guards, inside my bearer strategy validate method. Can I pass it as an argument alongside with the token?\n\nbearer-auth.guard.ts:\n\n```\n@Injectable()\nexport class BearerAuthGuard extends AuthGuard('bearer') {\n canActivate(context: ExecutionContext): boolean | Promise | Observable {\n return super.canActivate(context);\n }\n}\n```\n\nhttp.strategy.ts:\n\n```\n@Injectable()\nexport class HttpStrategy extends PassportStrategy(Strategy) {\n constructor(private globalService: GlobalService) {\n super();\n }\n\n async validate(token: string) {\n const customer = await this.globalService.validateCustomer(token);\n if (!customer) {\n throw new UnauthorizedException();\n }\n return customer;\n }\n}\n```\n\nI want something like this:\n\n```\nasync validate(token: string, context) { // <-- context object as argument\n const customer = await this.globalService.validateCustomer(token);\n if (!customer) {\n throw new UnauthorizedException();\n }\n return customer;\n}\n```\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class BearerAuthGuard extends AuthGuard('bearer') {\n    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {\n        return super.canActivate(context);\n    }\n}\n```\n\n```js\n@Injectable()\nexport class HttpStrategy extends PassportStrategy(Strategy) {\n    constructor(private globalService: GlobalService) {\n        super();\n    }\n\n    async validate(token: string) {\n        const customer = await this.globalService.validateCustomer(token);\n        if (!customer) {\n            throw new UnauthorizedException();\n        }\n        return customer;\n    }\n}\n```\n\n```js\nasync validate(token: string, context) { // <-- context object as argument\n    const customer = await this.globalService.validateCustomer(token);\n    if (!customer) {\n        throw new UnauthorizedException();\n    }\n    return customer;\n}\n```\n\n```text\n@Injectable()\nexport class HttpStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    // Add the option here\n    super({ passReqToCallback: true });\n  }\n\n  async validate(request: Request, token: string) {\n    // Now you have access to the request url\n    console.log(request.url);\n    const user = await this.authService.validateUser(token);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\n```text\nrequest\n```\n\n```text\npassReqToCallback: true\n```\n\n```text\npassport-http-bearer\n```\n\n```text\nrequest\n```\n\n========================================\n\nComments:\n- What do you need the context for? The `request`?\n- @KimKern Yes, I need the url","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":129,"estimatedTokens":708}}544{"id":"stack-55628093","source":"stackoverflow","questionId":55628093,"title":"Use socket client with NestJs microservice","tags":["javascript","node.js","sockets","microservices","nestjs"],"text":"Title: Use socket client with NestJs microservice\nTags: javascript, node.js, sockets, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI started working with NestJs recently and got stock while trying to test my NestJs microservices app using a TCP client\n\nIs it possible to trigger an `@EventPattern` or `@MessagePattern()` using a non-nest app?\n\nWhen trying this method the the socket client just stuck on `trying to connect`.\n\nAny ideas?\n\nThanks.\n\n========================================\n\nCode:\n```text\n@EventPattern\n```\n\n```text\n@MessagePattern()\n```\n\n```text\ntrying to connect\n```\n\n```text\n<json-length>#{\"pattern\": <pattern-name>, \"data\": <your-data>[, \"id\": <message-id>]}\n```\n\n```text\n76#{\"pattern\":\"sum\",\"data\":[0,3,3],\"id\":\"ce51ebd3-32b1-4ae6-b7ef-e018126c4cc4\"}\n```\n\n```text\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.TCP,\n  options: { host: 'localhost', port: 3005 },\n  //                            ^^^^^^^^^^\n});\n```\n\n```text\n@Client({\n  transport: Transport.TCP,\n  options: { host: 'localhost', port: 52079 },\n  //                            ^^^^^^^^^^^  \n})\nprivate client: ClientTCP;\n```\n\n```text\nasync onModuleInit() {\n  await this.client.connect();\n}\n```\n\n```text\n@MessagePattern('sum')\nsum(data: number[]): number {\n  console.log(data);\n  return data.reduce((a, b) => a + b, 0);\n}\n```\n\n```text\nid\n```\n\n```text\n@MessagePattern\n```\n\n```text\n@EventPattern\n```\n\n```text\nmain.ts\n```\n\n```text\n@Client\n```\n\n```text\n@MessagePattern\n```\n\n```text\n[0,3,3]\n```\n\n```text\n6\n```\n\n========================================\n\nComments:\n- Yes, it is possible to connect a nest app to a non-nest client but you have to pay attention to the special handling of nest, see this answer: stackoverflow.com/a/54294325/4694994 It's hard to tell what the connection issue is without seeing your setup. Can you post the relevant parts of your code?\n- @kernkim the message structure was exactly what I needed. by creating a massage `[MSG_LEN]#{ pattern: \"[PATTERN_STRING]\", data: \"[DATA]\" }` I'm able to send custom messages. Thenks\n- I have checked this - it is exactly what I want it to do , but I can't get it to work. HTTP/1.1 400 Bad Request\\r\\nConnection: close\\r\\n\\r\\n . I am using this sample github.com/nestjs/nest/tree/master/sample/03-microservices - which seems to work for internal communication - but I can't connect with the service through packet sender.\n- @MartinThompson I don't have time to look into this atm, but there have been changes that should make it easier to integrate external services. Have a look at this pr: github.com/nestjs/nest/pull/2653 If your problem persists, maybe open a new question so someone can have a look at it. :)\n- Thanks @KimKern . It was actually easier than I thought. I just wasn't putting the correct pattern in:\n- It is: 89#{\"pattern\": { \"cmd\": \"sum\" },\"data\":[0,3,3],\"id\":\"ce51ebd3-32b1-4ae6-b7ef-e018126c4cc4\"&zwnj;&#8203;}\n- @KimKern Could you please elaborate more on your update? The PR is huge, and I don't quite grasp the idea.","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":111,"estimatedTokens":758}}545{"id":"stack-66707441","source":"stackoverflow","questionId":66707441,"title":"Dto to entity and dto from entity","tags":["node.js","rest","mapping","nestjs"],"text":"Title: Dto to entity and dto from entity\nTags: node.js, rest, mapping, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my app I need multi times map from the Entity (Database model) to DTO (local object)\n\nMost times, Dto have the same names as the entity\n\nFor example The Entity\n\n```\nexport class CompanyModel extends BaseEntity {\n constructor(init?: Partial) {\n }\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ length: 500 })\n name: string;\n\n @Column({ length: 500, unique: true })\n email: string;\n\n ....\n\n}\n```\n\nThe DTO\n\n```\nexport class Company {\n @ApiProperty()\n id: string;\n\n @ApiProperty()\n email: string;\n\n @ApiProperty()\n name: string;\n...\n}\n```\n\nNow I add static function `toModel` and `fromModel`\n\n```\nstatic toModel(companyDto :CreateCompanyDto ) : CompanyModel {\n const companyModel = new CompanyModel();\n\n const {name, email,..... } = companyDto;\n companyModel.name = name;\n companyModel.email =email\n \n.....\n return companyModel;\n}\n```\n\nWhat is the best solution for mapping DTO to ENTITY in nestjs / node\n\n========================================\n\nCode:\n```text\nexport class CompanyModel extends BaseEntity {\n  constructor(init?: Partial<CompanyModel>) {\n  }\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column({ length: 500 })\n  name: string;\n\n  @Column({ length: 500, unique: true })\n  email: string;\n\n\n\n\n  ....\n\n}\n```\n\n```text\nexport class Company {\n  @ApiProperty()\n  id: string;\n\n\n  @ApiProperty()\n  email: string;\n\n  @ApiProperty()\n  name: string;\n...\n}\n```\n\n```text\nstatic toModel(companyDto :CreateCompanyDto ) : CompanyModel {\n    const companyModel =  new CompanyModel();\n\n    const {name, email,..... } = companyDto;\n    companyModel.name = name;\n    companyModel.email =email\n   \n.....\n    return companyModel;\n}\n```\n\n```text\ntoModel\n```\n\n```text\nfromModel\n```\n\n```js\nexport class Company {\n  @ApiProperty()\n  id: string;\n\n  @ApiProperty()\n  @Transform(value => value.toLowerCase())\n  email: string;\n\n  @ApiProperty()\n  name: string;\n...\n}\n```\n\n```js\nstatic toModel(companyDto: CreateCompanyDto ): CompanyModel {\n  const data = classToPlain(companyDto);\n  return plainToClass(CompanyModel, data);\n}\n```\n\n```text\nclassToPlain\n```\n\n```text\nplainToClass\n```\n\n========================================\n\nComments:\n- If my entity has 3 properties {a,b,c}, and my dto contain 2 propretis {a,b}, and i wrote {const data = classToPlain(entity); return plainToClass(Dto,data); I got the all 3 properties {a,b,c}, so how does it works? thanks\n- You have to expose properties explicitely and skip non-whitelisted properties. You can read more here: github.com/typestack/&hellip;\n- Using plainToClass is the best solution to use in NestJS @24sharon\n- PlainToClass is now deprecated, use PlainToInstance instead","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":685}}546{"id":"stack-63608615","source":"stackoverflow","questionId":63608615,"title":"Nest js upload is not saving file","tags":["nestjs","multer"],"text":"Title: Nest js upload is not saving file\nTags: nestjs, multer\nSource: Stack Overflow\n\nQuestion:\nI'm following the `nestjs` documentation for File upload, my endpoint is getting the file, but the file is not stored.\n\nI'm using the same configuration than NesJS\n\n```\n@Post('upload')\n@UseInterceptors(FileInterceptor('file'))\nuploadFile(@UploadedFile() file) {\n console.log(file);\n}\n```\n\nMy `app.module` file, I added the import for:\n\n```\nMulterModule.register({\n dest: './uploads'\n })\n```\n\nBut the file is not stored in the directory `uploads`. The complete log is:\n\n```\nundefined\n{\n fieldname: 'file',\n originalname: 'nopornimage.png',\n encoding: '7bit',\n mimetype: 'image/png',\n buffer: ,\n size: 20137\n}\n```\n\n(Yes, including the `undefined`)\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nyou should register `multer` module in your domain module not in app\nmodule(unless app module is the only module in your project ) for\nexample if your controller belongs to task domain you should\nregister `multer` in task module not in app module\n\n```\nimports: [\n TypeOrmModule.forFeature([TaskRepository]),\n MulterModule.register({ dest: './upload' }),\n ],\n controllers: [TaskController],\n providers: [TaskService],\n })\n export class TaskModule {}\n```\n\ncreate `upload` directory and determine it's path in `multer`\nregistration\n\n========================================\n\nCode:\n```text\n@Post('upload')\n@UseInterceptors(FileInterceptor('file'))\nuploadFile(@UploadedFile() file) {\n  console.log(file);\n}\n```\n\n```text\nMulterModule.register({\n      dest: './uploads'\n    })\n```\n\n```text\nundefined\n{\n  fieldname: 'file',\n  originalname: 'nopornimage.png',\n  encoding: '7bit',\n  mimetype: 'image/png',\n  buffer: <Buffer 89 50 4e 47 0d 0a 1a 04 d00 01 73 52 47 42 00 ae ce 04 ... 20087 more bytes>,\n  size: 20137\n}\n```\n\n```text\nnestjs\n```\n\n```text\napp.module\n```\n\n```text\nuploads\n```\n\n```text\nundefined\n```\n\n```js\n@Post('upload')\n@UseInterceptors(FileInterceptor('file', {\n  dest: 'uploads/'\n}))\nuploadFile(@UploadedFile() file) {\n  console.log(file);\n}\n```\n\n```js\nimport {createWriteStream} from 'fs'\n\n@Post('upload')\n@UseInterceptors(FileInterceptor('file'))\nuploadFile(@UploadedFile() file) {\n  const ws = createWriteStream('custom_filename')\n  ws.write(file.buffer)\n  console.log(file);\n}\n```\n\n```text\nfs\n```\n\n```text\nimports: [\n     TypeOrmModule.forFeature([TaskRepository]),\n     MulterModule.register({ dest: './upload' }),\n   ],\n   controllers: [TaskController],\n   providers: [TaskService],\n })\n export class TaskModule {}\n```\n\n```text\nmulter\n```\n\n```text\nmulter\n```\n\n```text\nupload\n```\n\n```text\nmulter\n```\n\n```js\n@Post('upload')\n@UseInterceptors(FileInterceptor('file', {dest: 'uploads/'}))\nuploadFile(@UploadedFile() file: Express.Multer.File) {\n    console.log(file);\n}\n```\n\n```text\nMulterModule\n```\n\n```text\n@Global\n```\n\n```text\nforRoot\n```\n\n```text\nFileStorageModule\n```\n\n========================================\n\nComments:\n- The problem here is that MulterModule is not a global module. So we need to add it to the imports array of the module where we are doing the upload. I think the NestJS documentation should highlight this aspect.\n- While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":192,"estimatedTokens":832}}547{"id":"stack-52964076","source":"stackoverflow","questionId":52964076,"title":"What's a valid @MessagePattern for NestJS MQTT microservice?","tags":["node.js","typescript","microservices","mqtt","nestjs"],"text":"Title: What's a valid @MessagePattern for NestJS MQTT microservice?\nTags: node.js, typescript, microservices, mqtt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to setup a MQTT Microservice using NestJS according to the docs.\n\nI've started a working Mosquitto Broker using Docker and verified it's operability using various MQTT clients. Now, when I start the NestJS service it seems to be connecting correctly (mqqt.fx shows new client), yet I am unable to receive any messages in my controllers.\nThis is my bootstrapping, just like in the docs:\n\n**main.ts**\n\n```\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(AppModule, {\n transport: Transport.MQTT,\n options: {\n host: 'localhost',\n port: 1883,\n protocol: 'tcp'\n }\n });\n app.listen(() => console.log('Microservice is listening'));\n}\nbootstrap();\n```\n\n**app.controller.ts**\n\n```\n@Controller()\nexport class AppController {\n\n @MessagePattern('mytopic') // tried {cmd:'mytopic'} or {topic:'mytopic'}\n root(msg: Buffer) {\n console.log('received: ', msg)\n }\n}\n```\n\nAm I using the message-pattern decorator wrongly or is my concept wrong of what a NestJS MQTT microservice even is supposed to do? I thought it might subscribe to the topic I pass to the decorator. My only other source of information being the corresponding unit tests\n\n========================================\n\nTop Answer:\nThe documentation is not very clear, but it seem that for mqtt if you have `@MessagePattern('mytopic')` you can publish a command on the topic `mytopic_ack` and you will get response on `mytopic_res`. I am still trying to find out how to publish to the mqtt broker from a service. \n\nSee https://github.com/nestjs/nest/blob/e019afa472c432ffe9e7330dc786539221652412/packages/microservices/server/server-mqtt.ts#L99\n\n```\npublic getAckQueueName(pattern: string): string {\n return `${pattern}_ack`;\n }\n\n public getResQueueName(pattern: string): string {\n return `${pattern}_res`;\n }\n```\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n    const app = await NestFactory.createMicroservice(AppModule, {\n        transport: Transport.MQTT,\n        options: {\n            host: 'localhost',\n            port: 1883,\n            protocol: 'tcp'\n        }\n    });\n    app.listen(() => console.log('Microservice is listening'));\n}\nbootstrap();\n```\n\n```text\n@Controller()\nexport class AppController {\n\n    @MessagePattern('mytopic') // tried {cmd:'mytopic'} or {topic:'mytopic'}\n    root(msg: Buffer) {\n        console.log('received: ', msg)\n    }\n}\n```\n\n```text\n@MessagePattern('sum')\nsum(data: number[]): number {\n  return data.reduce((a, b) => a + b, 0);\n}\n```\n\n```text\nvar mqtt = require('mqtt')\nvar client  = mqtt.connect('mqtt://localhost:1883')\n\nclient.on('connect', function () {\n  client.subscribe('sum_res', function (err) {\n    if (!err) {\n      client.publish('sum_ack', '{\"data\": [2, 3]}');\n    }\n  })\n})\n\nclient.on('message', function (topic, message) {\n  console.log(message.toString())\n  client.end()\n})\n```\n\n```text\n// Log:\n{\"err\":null,\"response\":5} // This is the response from sum()\n{\"isDisposed\":true} // Internal \"complete event\" (according to unit test)\n```\n\n```text\nasync onModuleInit() {\n  await this.client.connect();\n  // no 'sum_ack' or {data: [0, 2, 3]} needed\n  this.client.send('sum', [0, 2, 3]).toPromise();\n}\n```\n\n```text\nsum_ack\n```\n\n```text\nnpm install mqtt\n```\n\n```text\nnode client.js\n```\n\n```text\nsum_ack\n```\n\n```text\nsum_res\n```\n\n```text\nsum_res\n```\n\n```text\n{data: myData}\n```\n\n```text\nsum(myData)\n```\n\n```text\npublic getAckQueueName(pattern: string): string {\n    return `${pattern}_ack`;\n  }\n\n  public getResQueueName(pattern: string): string {\n    return `${pattern}_res`;\n  }\n```\n\n```text\n@MessagePattern('mytopic')\n```\n\n```text\nmytopic_ack\n```\n\n```text\nmytopic_res\n```\n\n```js\nconst app = await NestFactory.createMicroservice(AppModule, {\n    transport: Transport.MQTT,\n    options: {\n      host: 'test.mosquitto.org',\n      port: 1883,\n      protocol: 'tcp',\n    },\n  });\n  await app.listenAsync();\n```\n\n```js\nconst app = await NestFactory.createMicroservice(AppModule, {\n    transport: Transport.MQTT,\n    options: {\n      url: 'mqtt://test.mosquitto.org:1883',\n    },\n  });\n  await app.listenAsync();\n```\n\n```js\n@MessagePattern('sum')\n  sum(data: number[]): number {\n    return data.reduce((a, b) => a + b, 0);\n  }\n\n  @MessagePattern('sum_ack')\n  sumAck(data: number[]): number {\n    return data.reduce((a, b) => a + b, 0);\n  }\n```\n\n```js\n@MessagePattern('sum')\n  sum(data: number[]): number {\n    return data.reduce((a, b) => a + b, 0);\n  }\n```\n\n```text\nurl\n```\n\n```text\n'mqtt://localhost:1883'\n```\n\n```text\napp.listenAsync()\n```\n\n```text\nurl\n```\n\n```text\nid\n```\n\n```text\nsum\n```\n\n```text\nsum_ack\n```\n\n```text\nconsole.log\n```\n\n```text\nmqtt pub -t 'sum_ack' -h 'test.mosquitto.org' -m '{\"data\":[1,2]}'\n```\n\n```text\nid\n```\n\n```text\nmqtt pub -t 'sum_ack' -h 'test.mosquitto.org' -m '{\"data\":[1,2], \"id\":\"any-id\"}'\n```\n\n```text\nhandleMessage\n```\n\n```text\nid\n```\n\n```text\nurl\n```\n\n```text\nid\n```\n\n```text\n@MessagePattern('helloWorld')\n  getHello(): string {\n    console.log(\"hello world\")\n    return this.appService.getHello();\n  }\n```\n\n```text\n{\"data\":\"foo\",\"id\":\"bar\"}\n```\n\n```text\n{\"response\":\"Hello World!\",\"isDisposed\":true,\"id\":\"bar\"}\n```\n\n```text\n{\"data\":\"foo\"} or {}\n```\n\n========================================\n\nComments:\n- This strange behavior was fixed in Nest 7.0. You can directly subscribe topic without any suffix.\n- I have created an example on how to publish messages as a client in this answer: stackoverflow.com/a/54293468/4694994 Is this what you were looking for?\n- As you say it's not very convinient and a bit confusing. At first I was happy to see this build-in interface with MQTT or AMQP, but then I understood that it use request-response paradigm, and this is a bit strange for this kind of protocole.\n- Thanks very much for the clarification, like Alexandre pointed out, it kinda defeats the purpose when there's such a coupling to a specific client paradigm. Just glad I now know how it's supposed to be used\n- Does somebody use the clientMqtt class for publishing? I have the problem, that is publish not just the data - also the pattern and id. But I just need the data. I use the ClientMqtt.send function.","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":310,"estimatedTokens":1570}}548{"id":"stack-75010411","source":"stackoverflow","questionId":75010411,"title":"Float number saves as integer in MySQL using TypeORM","tags":["mysql","node.js","orm","nestjs","typeorm"],"text":"Title: Float number saves as integer in MySQL using TypeORM\nTags: mysql, node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM for my Nest.js backend app. When I try to save entity in database:\n\n```\nawait this.dayRepository.save({\n price: item.price,\n ... other columns\n});\n```\n\nAnd my price is float, that float saves in database as integer - always truncated (3.99 round to 3, 5.56 round to 5 etc.). I even try this:\n\n```\nawait this.dayRepository.save({\n price: 3.99,\n ... other columns\n});\n```\n\nAnd it also saves price column in database as 3. I tried to declare my price column in database as float and double - none of that worked. What I'm doing wrong? Or it could be some issue with database?\n\n========================================\n\nCode:\n```text\nawait this.dayRepository.save({\n   price: item.price,\n   ... other columns\n});\n```\n\n```text\nawait this.dayRepository.save({\n   price: 3.99,\n   ... other columns\n});\n```\n\n```js\n@Column('decimal', { precision: 6, scale: 2 })\nprice: number\n```\n\n```text\nmysql\n```\n\n```text\nprecision\n```\n\n```text\nscale\n```\n\n```text\nscale\n```\n\n========================================\n\nComments:\n- can you please your entity information, which has information about the price column? Also, did you check your column type on the SQL?","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":67,"estimatedTokens":324}}549{"id":"stack-68423743","source":"stackoverflow","questionId":68423743,"title":"How do I setup Nestjs to host a React site?","tags":["reactjs","nestjs"],"text":"Title: How do I setup Nestjs to host a React site?\nTags: reactjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nAll the examples I've seen are with React running in one server and Nestjs running on another. I know Nestjs can host a site, but how do I set it up to host a React site?\n\n========================================\n\nComments:\n- @ZEE please explain.\n- Thank you Ray! That helps a lot. Do you know if there is an example of using the static module with web sockets?\n- Hi @Heath I do not see any documentation for that. If I get some time over the weekend I will try dig a little deeper to see if they have any.\n- Is there any example that I can refer to so that I can get the configuration exactly correct?","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":14,"estimatedTokens":178}}550{"id":"stack-59104427","source":"stackoverflow","questionId":59104427,"title":"nestjs global pubsub instance and dependency injection","tags":["dependency-injection","publish-subscribe","nestjs"],"text":"Title: nestjs global pubsub instance and dependency injection\nTags: dependency-injection, publish-subscribe, nestjs\nSource: Stack Overflow\n\nQuestion:\nI followed the Nestjs DOCS regarding pubsub/subsciprtions:\n\nAccording to the examples, pubsub is initialized at the top of a given resolver with:\n\n```\nconst pubSub = new PubSub();\n```\n\nlater the docs say:\n\n\"We used a local PubSub instance here. Instead, we should define PubSub as a provider, inject it through the constructor (using @Inject() decorator), and reuse it among the whole application\"\n\n```\n{\n provide: 'PUB_SUB',\n useValue: new PubSub(),\n}\n```\n\nwhere does this go though?\n\nI.e. what's the syntax/approach for how to provide this in my main app.module so it's available in all other modules?\n\nif i try to provide this as a dependency in a different module i'm getting dependency resolution issues. \napp.module\n\n```\nproviders: [\n AppService,\n {\n provide: APP_FILTER,\n useClass: AllExceptionsFilter,\n },\n {\n provide: 'PUB_SUB',\n useValue: new PubSub(),\n },\n```\n\nsome-resolver.js\n\n```\nconstructor(\n @Inject('PUB_SUB')\n private pubSub: PubSub,\n```\n\ngives: \nNest can't resolve dependencies of the MyResolver (\nMyResolver is provided by MyModule\n\nI can't import appmodule into MyModule or i'll create a circular depenency.\n\nDo i define a new module which just provides a pub_sub instance?\n\n========================================\n\nTop Answer:\nUsing with async/await init pubSub:\n\n```\n// pubSub.module.ts\n@Module({\n providers: [\n {\n provide: PubSub,\n // if you need init with async/await\n useFactory: async () => {\n return await getPubSub();\n },\n },\n ],\n exports: [PubSub],\n})\nexport class PubSubModule {}\n\n// test.module.ts\n@Module({\n imports: [PubSubModule],\n providers: [TestService]\n})\nexport class TestModule {}\n\n// test.service.ts\nexport class TestService {\n constructor(private pubSub: PubSub) {}\n\n @Subscription(() => any)\n testAdded() {\n return this.pubSub.asyncIterator('TEST_ADDED');\n }\n}\n```\n\n========================================\n\nCode:\n```text\nconst pubSub = new PubSub();\n```\n\n```text\n{\n  provide: 'PUB_SUB',\n  useValue: new PubSub(),\n}\n```\n\n```text\nproviders: [\n    AppService,\n    {\n      provide: APP_FILTER,\n      useClass: AllExceptionsFilter,\n    },\n    {\n      provide: 'PUB_SUB',\n      useValue: new PubSub(),\n    },\n```\n\n```text\nconstructor(\n    @Inject('PUB_SUB')\n    private pubSub: PubSub,\n```\n\n```js\n@Module({\n  providers: [\n    {\n      provide: 'PUB_SUB',\n      useClass: PubSub,\n      // useValue: new PubSub(),\n      // useFactory: () => {\n      //  return new PubSub();\n      // }\n    }\n  ],\n  exports: ['PUB_SUB'],\n})\nexport class PubSubModule {}\n```\n\n```js\n@Global()\n@Module({\n  providers: [\n    {\n      provide: 'PUB_SUB',\n      useClass: PubSub,\n      // useValue: new PubSub(),\n      // useFactory: () => {\n      //  return new PubSub();\n      // }\n    }\n  ],\n})\nexport class PubSubModule {}\n```\n\n```text\nPubSubModule\n```\n\n```text\nPubSub\n```\n\n```text\n@Global()\n```\n\n```js\n// pubSub.module.ts\n@Module({\n  providers: [\n    {\n      provide: PubSub,\n      // if you need init with async/await\n      useFactory: async () => {\n        return await getPubSub();\n      },\n    },\n  ],\n  exports: [PubSub],\n})\nexport class PubSubModule {}\n\n// test.module.ts\n@Module({\n  imports: [PubSubModule],\n  providers: [TestService]\n})\nexport class TestModule {}\n\n// test.service.ts\nexport class TestService {\n  constructor(private pubSub: PubSub) {}\n\n  @Subscription(() => any)\n  testAdded() {\n    return this.pubSub.asyncIterator('TEST_ADDED');\n  }\n}\n```\n\n========================================\n\nComments:\n- thanks a lot, this is indeed where i landed. what is the disadvantage of using the global decorator? other module instantiations done in appmodule, like typeorm, graphql, etc don't seem to this pattern. And again in the docs, nest team does not mention using this for say, custom logger. Still hazy on how some features are 'magically' available after being configured in main app.module. So far this is the only instance where i'm using the 'global' decorator\n- I don't really see drawbacks to it, other than like you said, it \"magically\" being available. I actually worked with a contributor recently to figure out a way around using Global but still only working with configurations once. I like to not use `@global()` just because it makes me think about what is really available in the current scope of things","metadata":{"transformedAt":"2026-08-18T18:33:02.451Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":217,"estimatedTokens":1101}}551{"id":"stack-55665343","source":"stackoverflow","questionId":55665343,"title":"NestJS WebSocketGateway does not initialize","tags":["javascript","node.js","typescript","websocket","nestjs"],"text":"Title: NestJS WebSocketGateway does not initialize\nTags: javascript, node.js, typescript, websocket, nestjs\nSource: Stack Overflow\n\nQuestion:\nAccording to the NestJS docs I've implemented the websockets gateway and providing it inside of the `AppModule`. The server is starting properly and I can serve static assets via http successfully. But I can't get the websockets running at all, the ws server is not available at `ws://localhost:3333` and the `afterInit` function is not executed at all. Even not when I am defining the `@SubscribeMessage`.\n\nThe gateway is implemented as\n\n```\n@WebSocketGateway()\nexport class SocketGateway implements OnGatewayInit {\n afterInit() {\n console.log('Gateway initialized');\n }\n}\n```\n\nThe AppModule provides the gateway properly\n\n```\n@Module({\n providers: [SocketGateway]\n})\nexport class AppModule {}\n```\n\nAnd this is the bootstrap implementation\n\n```\nexport async function bootstrap() {\n let app = await NestFactory.create(AppModule);\n\n await app.listen(process.env.port || 3333, () => {\n console.log(`Listening at http://localhost:${port}`);\n });\n}\n\nbootstrap();\n```\n\nMy dependecies are\n\n```\n\"socket.io-client\": \"^2.2.0\",\n\"@nestjs/common\": \"5.5.0\",\n\"@nestjs/core\": \"5.5.0\",\n\"@nestjs/platform-socket.io\": \"^6.1.0\",\n\"@nestjs/websockets\": \"^6.1.0\"\n```\n\nMaybe you see the problem directly. Thanks for your help, cheers!\n\n========================================\n\nCode:\n```js\n@WebSocketGateway()\nexport class SocketGateway implements OnGatewayInit {\n  afterInit() {\n    console.log('Gateway initialized');\n  }\n}\n```\n\n```js\n@Module({\n  providers: [SocketGateway]\n})\nexport class AppModule {}\n```\n\n```js\nexport async function bootstrap() {\n  let app = await NestFactory.create(AppModule);\n\n  await app.listen(process.env.port || 3333, () => {\n    console.log(`Listening at http://localhost:${port}`);\n  });\n}\n\nbootstrap();\n```\n\n```text\n\"socket.io-client\": \"^2.2.0\",\n\"@nestjs/common\": \"5.5.0\",\n\"@nestjs/core\": \"5.5.0\",\n\"@nestjs/platform-socket.io\": \"^6.1.0\",\n\"@nestjs/websockets\": \"^6.1.0\"\n```\n\n```text\nAppModule\n```\n\n```text\nws://localhost:3333\n```\n\n```text\nafterInit\n```\n\n```text\n@SubscribeMessage\n```\n\n```text\nnpm WARN @nestjs/websockets@6.1.0 requires a peer of @nestjs/common@^6.0.0 but none is installed.\nYou must install peer dependencies yourself.\n```\n\n```text\n$ npm i @nestjs/core@latest @nestjs/common@latest\n```\n\n========================================\n\nComments:\n- You are mixing nest v5 and nest v6. Different major versions are not guaranteed to interoperate properly. Please update all your nest dependencies to v6, see docs.nestjs.com/migration-guide\n- This starts the gateway properly :) it is an nrwl/nx workspace including the 5.5.0 deps. Adding additional packages via npm installed 6.1.0.\n- apparently this is also true for minors. In my case in different packages for nest I had ^9.0 and ^9.4. bumped all and it started :/\n- this was very time consuming stupid bug to fix, thank you!!!","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":124,"estimatedTokens":735}}552{"id":"stack-76234811","source":"stackoverflow","questionId":76234811,"title":"Error: Only URLs with a scheme in: file and data are supported by the default ESM loader in NestJS app generated with NX in a monorepo","tags":["nestjs","nrwl-nx","nomachine-nx"],"text":"Title: Error: Only URLs with a scheme in: file and data are supported by the default ESM loader in NestJS app generated with NX in a monorepo\nTags: nestjs, nrwl-nx, nomachine-nx\nSource: Stack Overflow\n\nQuestion:\nI have a Monorepo generated with NX v16. I have working React app inside. I generated NestJS app with the nx generator command coming from the NX VS Code plugin, but the moment I start the nest app with `nx run :serve` I receive this error: `Error: Only URLs with a scheme in: file and data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'`. I don't have this issue with my React app, only with the NestJS one.\nI am on Windows 11, my Node version is 18.16.0. This most likely is Windows related issue but I have no clue how to overcome it, neither I understood something from the internet while searching for such fix.\nThis is my package.json content:\n\n```\n{\n \"name\": \"my-nx-monorepo\",\n \"version\": \"0.1.0\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"graph\": \"npx nx graph\",\n \"dashboard\": \"npx nx run dashboard:serve\",\n \"dashboard:lint\": \"npx nx run dashboard:lint\",\n \"dashboard:test\": \"npx nx run dashboard:test\",\n \"dashboard:build\": \"npx nx run dashboard:build\",\n \"connect-to-nx-cloud\": \"npx nx connect-to-nx-cloud\"\n },\n \"private\": true,\n \"dependencies\": {\n \"@nestjs/common\": \"^9.1.1\",\n \"@nestjs/core\": \"^9.1.1\",\n \"@nestjs/platform-express\": \"^9.1.1\",\n \"@swc/helpers\": \"~0.5.0\",\n \"@tanstack/react-query\": \"^4.29.5\",\n \"@tanstack/react-query-devtools\": \"^4.29.6\",\n \"@xstate/react\": \"^3.2.2\",\n \"axios\": \"^1.4.0\",\n \"clsx\": \"^1.2.1\",\n \"i18next\": \"^22.4.15\",\n \"i18next-browser-languagedetector\": \"^7.0.1\",\n \"normalize.css\": \"^8.0.1\",\n \"react\": \"18.2.0\",\n \"react-aria\": \"^3.24.0\",\n \"react-dom\": \"18.2.0\",\n \"react-i18next\": \"^12.2.2\",\n \"react-router-dom\": \"^6.11.1\",\n \"react-stately\": \"^3.22.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rxjs\": \"^7.8.0\",\n \"tslib\": \"^2.3.0\",\n \"xstate\": \"^4.37.2\"\n },\n \"devDependencies\": {\n \"@babel/preset-react\": \"^7.14.5\",\n \"@nestjs/schematics\": \"^9.1.0\",\n \"@nestjs/testing\": \"^9.1.1\",\n \"@nx/cypress\": \"16.1.0\",\n \"@nx/eslint-plugin\": \"16.1.0\",\n \"@nx/jest\": \"16.1.4\",\n \"@nx/js\": \"16.1.4\",\n \"@nx/linter\": \"16.1.0\",\n \"@nx/nest\": \"16.1.4\",\n \"@nx/node\": \"16.1.4\",\n \"@nx/react\": \"16.1.0\",\n \"@nx/vite\": \"16.1.0\",\n \"@nx/webpack\": \"16.1.4\",\n \"@nx/workspace\": \"16.1.0\",\n \"@swc/cli\": \"~0.1.62\",\n \"@swc/core\": \"~1.3.51\",\n \"@tanstack/eslint-plugin-query\": \"^4.29.4\",\n \"@testing-library/react\": \"14.0.0\",\n \"@total-typescript/ts-reset\": \"^0.4.2\",\n \"@types/jest\": \"^29.4.0\",\n \"@types/node\": \"18.14.2\",\n \"@types/react\": \"18.0.28\",\n \"@types/react-dom\": \"18.0.11\",\n \"@typescript-eslint/eslint-plugin\": \"^5.58.0\",\n \"@typescript-eslint/parser\": \"^5.58.0\",\n \"@vitejs/plugin-react\": \"^3.0.0\",\n \"@vitest/coverage-c8\": \"^0.31.0\",\n \"@vitest/ui\": \"^0.31.0\",\n \"cypress\": \"^12.11.0\",\n \"eslint\": \"~8.15.0\",\n \"eslint-config-prettier\": \"8.1.0\",\n \"eslint-plugin-cypress\": \"^2.10.3\",\n \"eslint-plugin-import\": \"2.27.5\",\n \"eslint-plugin-jsx-a11y\": \"6.7.1\",\n \"eslint-plugin-react\": \"7.32.2\",\n \"eslint-plugin-react-hooks\": \"4.6.0\",\n \"jest\": \"^29.4.1\",\n \"jest-environment-node\": \"^29.4.1\",\n \"jsdom\": \"~20.0.3\",\n \"nx\": \"16.1.0\",\n \"nx-cloud\": \"latest\",\n \"prettier\": \"^2.6.2\",\n \"react-test-renderer\": \"18.2.0\",\n \"sass\": \"^1.55.0\",\n \"ts-jest\": \"^29.1.0\",\n \"ts-node\": \"10.9.1\",\n \"typescript\": \"~5.0.2\",\n \"vite\": \"^4.3.4\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"vite-tsconfig-paths\": \"^4.0.2\",\n \"vitest\": \"^0.31.0\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nI also tried just updated all nx & nrwl packages from v16.1.4 to v16.1.0, it's working for me.\nNode Version - 16.20\nNPM - 8.19.4\nTypeScript - 4.8.2\n\n========================================\n\nCode:\n```text\n{\n  \"name\": \"my-nx-monorepo\",\n  \"version\": \"0.1.0\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"graph\": \"npx nx graph\",\n    \"dashboard\": \"npx nx run dashboard:serve\",\n    \"dashboard:lint\": \"npx nx run dashboard:lint\",\n    \"dashboard:test\": \"npx nx run dashboard:test\",\n    \"dashboard:build\": \"npx nx run dashboard:build\",\n    \"connect-to-nx-cloud\": \"npx nx connect-to-nx-cloud\"\n  },\n  \"private\": true,\n  \"dependencies\": {\n    \"@nestjs/common\": \"^9.1.1\",\n    \"@nestjs/core\": \"^9.1.1\",\n    \"@nestjs/platform-express\": \"^9.1.1\",\n    \"@swc/helpers\": \"~0.5.0\",\n    \"@tanstack/react-query\": \"^4.29.5\",\n    \"@tanstack/react-query-devtools\": \"^4.29.6\",\n    \"@xstate/react\": \"^3.2.2\",\n    \"axios\": \"^1.4.0\",\n    \"clsx\": \"^1.2.1\",\n    \"i18next\": \"^22.4.15\",\n    \"i18next-browser-languagedetector\": \"^7.0.1\",\n    \"normalize.css\": \"^8.0.1\",\n    \"react\": \"18.2.0\",\n    \"react-aria\": \"^3.24.0\",\n    \"react-dom\": \"18.2.0\",\n    \"react-i18next\": \"^12.2.2\",\n    \"react-router-dom\": \"^6.11.1\",\n    \"react-stately\": \"^3.22.0\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rxjs\": \"^7.8.0\",\n    \"tslib\": \"^2.3.0\",\n    \"xstate\": \"^4.37.2\"\n  },\n  \"devDependencies\": {\n    \"@babel/preset-react\": \"^7.14.5\",\n    \"@nestjs/schematics\": \"^9.1.0\",\n    \"@nestjs/testing\": \"^9.1.1\",\n    \"@nx/cypress\": \"16.1.0\",\n    \"@nx/eslint-plugin\": \"16.1.0\",\n    \"@nx/jest\": \"16.1.4\",\n    \"@nx/js\": \"16.1.4\",\n    \"@nx/linter\": \"16.1.0\",\n    \"@nx/nest\": \"16.1.4\",\n    \"@nx/node\": \"16.1.4\",\n    \"@nx/react\": \"16.1.0\",\n    \"@nx/vite\": \"16.1.0\",\n    \"@nx/webpack\": \"16.1.4\",\n    \"@nx/workspace\": \"16.1.0\",\n    \"@swc/cli\": \"~0.1.62\",\n    \"@swc/core\": \"~1.3.51\",\n    \"@tanstack/eslint-plugin-query\": \"^4.29.4\",\n    \"@testing-library/react\": \"14.0.0\",\n    \"@total-typescript/ts-reset\": \"^0.4.2\",\n    \"@types/jest\": \"^29.4.0\",\n    \"@types/node\": \"18.14.2\",\n    \"@types/react\": \"18.0.28\",\n    \"@types/react-dom\": \"18.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.58.0\",\n    \"@typescript-eslint/parser\": \"^5.58.0\",\n    \"@vitejs/plugin-react\": \"^3.0.0\",\n    \"@vitest/coverage-c8\": \"^0.31.0\",\n    \"@vitest/ui\": \"^0.31.0\",\n    \"cypress\": \"^12.11.0\",\n    \"eslint\": \"~8.15.0\",\n    \"eslint-config-prettier\": \"8.1.0\",\n    \"eslint-plugin-cypress\": \"^2.10.3\",\n    \"eslint-plugin-import\": \"2.27.5\",\n    \"eslint-plugin-jsx-a11y\": \"6.7.1\",\n    \"eslint-plugin-react\": \"7.32.2\",\n    \"eslint-plugin-react-hooks\": \"4.6.0\",\n    \"jest\": \"^29.4.1\",\n    \"jest-environment-node\": \"^29.4.1\",\n    \"jsdom\": \"~20.0.3\",\n    \"nx\": \"16.1.0\",\n    \"nx-cloud\": \"latest\",\n    \"prettier\": \"^2.6.2\",\n    \"react-test-renderer\": \"18.2.0\",\n    \"sass\": \"^1.55.0\",\n    \"ts-jest\": \"^29.1.0\",\n    \"ts-node\": \"10.9.1\",\n    \"typescript\": \"~5.0.2\",\n    \"vite\": \"^4.3.4\",\n    \"vite-plugin-eslint\": \"^1.8.1\",\n    \"vite-tsconfig-paths\": \"^4.0.2\",\n    \"vitest\": \"^0.31.0\"\n  }\n}\n```\n\n```text\nnx run <ny-app-name>:serve\n```\n\n```text\nError: Only URLs with a scheme in: file and data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'\n```\n\n```text\nnx list [tag-name] --project=[project-name]\n```\n\n```text\nnx build [tag-name] --with-deps\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":223,"estimatedTokens":1707}}553{"id":"stack-63496404","source":"stackoverflow","questionId":63496404,"title":"In NestJS, how to get execution context or request instance in custom method decorator?","tags":["decorator","nestjs"],"text":"Title: In NestJS, how to get execution context or request instance in custom method decorator?\nTags: decorator, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a custom method decorator like this.\n\n```\nexport function CustomDecorator() {\n\n return applyDecorators(\n UseGuards(JwtAuthGuard)\n );\n}\n```\n\nInside the Custom Decorator, I want to get the Request Header but not sure how to get the Request Instance?\n\n========================================\n\nTop Answer:\nI managed to access the execution context within decorator using `Inject` inside decorator's factory.\nHere is my decorator that swallows errors produced by method and returns predefined value in case of exception.\n\n```\nimport { Injectable, Scope, Inject, ExecutionContext } from '@nestjs/common';\nimport { CONTEXT } from '@nestjs/graphql';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class ExceptionsHandler {\n public constructor(@Inject(CONTEXT) private readonly context: ExecutionContext) {}\n\n private integrationsRequestErrors: unknown[] = [];\n\n public handle(error: unknown): void {\n // ADD error to context if necessary\n this.integrationsRequestErrors.push(error);\n }\n}\n\nexport const ErrorSwallower = (options: {\n serviceImplementation: string;\n defaultValue: unknown;\n errorMessage?: string;\n}): MethodDecorator => {\n const { defaultValue, integration } = options;\n const Injector = Inject(ExceptionsHandler);\n return (target: object, _propertyKey: string, descriptor: PropertyDescriptor) => {\n Injector(target, 'exceptionsHandler');\n const originalMethod = descriptor.value;\n descriptor.value = function (...args: unknown[]) {\n const exceptionHandler = this.experiment as ExceptionsHandler;\n try {\n const result = originalMethod.apply(this, args);\n if (result && result instanceof Promise) {\n return result.catch((error: unknown) => {\n exceptionHandler.handle({ error, integration });\n return defaultValue;\n });\n }\n return result;\n } catch (error) {\n exceptionHandler.handle({ error, integration });\n return defaultValue;\n }\n };\n };\n};\n```\n\nand here is the code above put into action:\n\n```\n@Injectable()\nexport class ExampleService {\n @ErrorSwallower({ serviceImplementation: 'ExampleClass', defaultValue: [] })\n private async getSomeData(args: IGetSomeDataArgs): Promise {\n throw new Error('Oops');\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport function CustomDecorator() {\n\n    return applyDecorators(\n        UseGuards(JwtAuthGuard)\n    );\n}\n```\n\n```js\n@Injectable()\nexport class SuperGuard implements CanActivate {\n  constructor(\n    private readonly jwtAuthGuard: JwtAuthGuard,\n    private readonly googleAuthGuard: GoogleAuthGuard,\n  ) {}\n\n  canActivate(context: ExecutionContext) {\n    const req = context.switchToHttp().getRequest();\n    if (req.headers['whatever'] === 'google') {\n      return this.googleAuthGuard.canActivate(context);\n    } else {\n      return this.jwtAuthGuard.canActivate(context);\n    }\n  }\n}\n```\n\n```text\nExectuionContext\n```\n\n```text\nRequest\n```\n\n```text\nSuperGuard\n```\n\n```text\nExecutionContext\n```\n\n```text\nSuperGuard\n```\n\n```text\nconstructor\n```\n\n```js\nimport { Injectable, Scope, Inject, ExecutionContext } from '@nestjs/common';\nimport { CONTEXT } from '@nestjs/graphql';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class ExceptionsHandler {\n  public constructor(@Inject(CONTEXT) private readonly context: ExecutionContext) {}\n\n  private integrationsRequestErrors: unknown[] = [];\n\n  public handle(error: unknown): void {\n    // ADD error to context if necessary\n    this.integrationsRequestErrors.push(error);\n  }\n}\n\nexport const ErrorSwallower = (options: {\n  serviceImplementation: string;\n  defaultValue: unknown;\n  errorMessage?: string;\n}): MethodDecorator => {\n  const { defaultValue, integration } = options;\n  const Injector = Inject(ExceptionsHandler);\n  return (target: object, _propertyKey: string, descriptor: PropertyDescriptor) => {\n    Injector(target, 'exceptionsHandler');\n    const originalMethod = descriptor.value;\n    descriptor.value = function (...args: unknown[]) {\n      const exceptionHandler = this.experiment as ExceptionsHandler;\n      try {\n        const result = originalMethod.apply(this, args);\n        if (result && result instanceof Promise) {\n          return result.catch((error: unknown) => {\n            exceptionHandler.handle({ error, integration });\n            return defaultValue;\n          });\n        }\n        return result;\n      } catch (error) {\n        exceptionHandler.handle({ error, integration });\n        return defaultValue;\n      }\n    };\n  };\n};\n```\n\n```js\n@Injectable()\nexport class ExampleService {\n  @ErrorSwallower({ serviceImplementation: 'ExampleClass', defaultValue: [] })\n  private async getSomeData(args: IGetSomeDataArgs): Promise<ISomeData[]> {\n    throw new Error('Oops');\n  }\n}\n```\n\n```text\nInject\n```\n\n```js\nconstructor(@Inject(CONTEXT) private readonly context: ExecutionContext) {}\n```\n\n```js\nexport function CustomDecorator() {\n    return applyDecorators(\n        UseGuards(JwtAuthGuard)\n        const context = this.context;\n    );\n}\n```\n\n========================================\n\nComments:\n- Could add more info about what do you wanna do, please? I got it that you want to access headers but with what purpose?\n- We have a shared auth module in which we can have JWT or GoogleAuth. I want to implement a custom decorator which applies different guards based on the request headers.\n- Hi Jay, I get this error. Error: Nest can't resolve dependencies of the RomeGuard (?). Please make sure that the argument JwtAuthGuard at index [0] is available in the AuthModule context. Potential solutions: - If JwtAuthGuard is a provider, is it part of the current AuthModule? - If JwtAuthGuard is exported from a separate @Module, is that module imported within AuthModule? @Module({ imports: [ /* the Module containing JwtAuthGuard */ ] }) at Injector.lookupComponentInParentModules\n- You'll need to make sure that wherever you use `SuperGuard` you have `JwtAuthGuard` and `GoogleAuthGuard` added as `providers`. This can be done from a `GuardModule` if you so choose\n- Hi Jay, I added it like this `providers: [SharedDataAuthService, JwtStrategy, JwtAuthGuard],` but it's showing that error.\n- All good Jay. I need to add it into exports as well. Thanks for your help.\n- Hi Jay, I have a question... If the Guard decorator run immediately at the moment of import, how could it catch the request in executionContext ? ^^","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":220,"estimatedTokens":1607}}554{"id":"stack-55423823","source":"stackoverflow","questionId":55423823,"title":"ValidationPipe() does not work on override @Query in Nestjs/Crud","tags":["javascript","node.js","typescript","nestjs","class-validator"],"text":"Title: ValidationPipe() does not work on override @Query in Nestjs/Crud\nTags: javascript, node.js, typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to validate the parameters that come in the query of a get request, but for some reason, the validation pipe is unable to identify the elements of the query.\n\n```\nimport {\n Controller,\n Post,\n Query,\n Body,\n UseInterceptors,\n Param,\n Res,\n Logger,\n} from '@nestjs/common';\nimport { Crud, CrudController, Override } from '@nestjsx/crud';\n\nimport { OpenScheduleDto } from './open-schedule.dto';\n@Crud(Schedule)\nexport class ScheduleController\n implements CrudController {\n constructor(public service: ScheduleService) {}\n\n get base(): CrudController {\n return this;\n }\n\n @Override()\n async getMany(@Query() query: OpenScheduleDto) { \n return query; \n } \n }\n```\n\n**OpenSchedule.dto**\n\n```\nimport { IsNumber, IsOptional, IsString } from 'class-validator';\nexport class OpenScheduleDto {\n\n @IsNumber()\n companyId: number;\n\n @IsNumber()\n @IsOptional()\n professionalId: number;\n\n @IsString()\n @IsOptional()\n scheduleDate: string;\n}\n```\n\nWhen I make a get request to http://localhost:3000/schedules?companyId=3&professionalId=1\n\nI get unexpected errors:\n\n```\n{\n \"statusCode\": 400,\n \"error\": \"Bad Request\",\n \"message\": [\n {\n \"target\": {\n \"companyId\": \"3\",\n \"professionalId\": \"1\"\n },\n \"value\": \"3\",\n \"property\": \"companyId\",\n \"children\": [],\n \"constraints\": {\n \"isNumber\": \"companyId must be a number\"\n }\n },\n {\n \"target\": {\n \"companyId\": \"3\",\n \"professionalId\": \"1\"\n },\n \"value\": \"1\",\n \"property\": \"professionalId\",\n \"children\": [],\n \"constraints\": {\n \"isNumber\": \"professionalId must be a number\"\n }\n }\n ]\n}\n```\n\n========================================\n\nTop Answer:\nYou could also try setting `enableImplicitConversion` as `true` in your `ValidationPipe`.\n\n```\napp.useGlobalPipes(new ValidationPipe({\n transform: true,\n transformOptions: {\n enableImplicitConversion: true, // This should work locally e.g., in a `Controller` or method as well.\n\n========================================\n\nCode:\n```text\nimport {\n  Controller,\n  Post,\n  Query,\n  Body,\n  UseInterceptors,\n  Param,\n  Res,\n  Logger,\n} from '@nestjs/common';\nimport { Crud, CrudController, Override } from '@nestjsx/crud';\n\nimport { OpenScheduleDto } from './open-schedule.dto';\n@Crud(Schedule)\nexport class ScheduleController\n          implements CrudController<ScheduleService, Schedule> {\n          constructor(public service: ScheduleService) {}\n\n          get base(): CrudController<ScheduleService, Schedule> {\n            return this;\n          }\n\n          @Override()\n          async getMany(@Query() query: OpenScheduleDto) { \n             return query; \n         } \n    }\n```\n\n```text\nimport { IsNumber, IsOptional, IsString } from 'class-validator';\nexport class OpenScheduleDto {\n\n  @IsNumber()\n  companyId: number;\n\n  @IsNumber()\n  @IsOptional()\n  professionalId: number;\n\n  @IsString()\n  @IsOptional()\n  scheduleDate: string;\n}\n```\n\n```text\n{\n    \"statusCode\": 400,\n    \"error\": \"Bad Request\",\n    \"message\": [\n        {\n            \"target\": {\n                \"companyId\": \"3\",\n                \"professionalId\": \"1\"\n            },\n            \"value\": \"3\",\n            \"property\": \"companyId\",\n            \"children\": [],\n            \"constraints\": {\n                \"isNumber\": \"companyId must be a number\"\n            }\n        },\n        {\n            \"target\": {\n                \"companyId\": \"3\",\n                \"professionalId\": \"1\"\n            },\n            \"value\": \"1\",\n            \"property\": \"professionalId\",\n            \"children\": [],\n            \"constraints\": {\n                \"isNumber\": \"professionalId must be a number\"\n            }\n        }\n    ]\n}\n```\n\n```text\nimport { IsNumber, IsOptional, IsString } from 'class-validator';\nimport { Transform } from 'class-transformer';\nexport class OpenScheduleDto {\n\n  @Transform(id => parseInt(id))\n  @IsNumber()\n  companyId: number;\n\n  @Transform(id => id ? parseInt(id) : id)\n  @IsNumber()\n  @IsOptional()\n  professionalId?: number;\n\n  @IsString()\n  @IsOptional()\n  scheduleDate?: string;\n}\n```\n\n```text\n@Query\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Transform\n```\n\n```text\nparseInt('5abc010')\n```\n\n```text\n5\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({\n  transform: true,\n  transformOptions: {\n    enableImplicitConversion: true, // <- This line here\n  },\n}));\n```\n\n```text\nenableImplicitConversion\n```\n\n```text\ntrue\n```\n\n```text\nValidationPipe\n```\n\n```text\nController\n```\n\n========================================\n\nComments:\n- Would it be safer to check if the string is numeric before doing the transformation? I guess the package has a IsNumberString decorator.\n- @EliseuMonardosSantos You can for example check `!isNan(id)` and return the untransformed id otherwise. The `@IsNumber` validator will reject the untransformed string.","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":257,"estimatedTokens":1216}}555{"id":"stack-55448050","source":"stackoverflow","questionId":55448050,"title":"NestJs: How to have Body input shape different from entity's DTO?","tags":["javascript","node.js","typescript","serialization","nestjs"],"text":"Title: NestJs: How to have Body input shape different from entity's DTO?\nTags: javascript, node.js, typescript, serialization, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have DTOs for my Photo and Tag objects that look like this:\n\n```\nexport class PhotoDto {\n readonly title: string\n readonly file: string\n readonly tags: TagDto[]\n}\n\nexport class TagDto {\n readonly name: string\n}\n```\n\nI use the `PhotoDto` in my `photo.service.ts` and eventually in the `photo.controller.ts` for the creation of Photo:\n\n```\n// In photo.service.ts\nasync create(createPhotoDto: PhotoDto): Promise {\n // ...\n return await this.photoRepo.create(createPhotoDto)\n}\n\n// In photo.controller.ts\n@Post()\nasync create(@Body() createPhotoDto: PhotoDto): Promise {\n // ...\n}\n```\n\nHowever, the input in the Body of the API is expected to have this structure:\n\n```\n{\n \"title\": \"Photo Title\",\n \"file\": \"/some/path/file.jpg\",\n \"tags\": [\n {\n \"name\": \"holiday\"\n },\n {\n \"name\": \"memories\"\n }\n ]\n}\n```\n\nHow can I change the input shape of the `Body` to accept this structure instead?\n\n```\n{\n \"title\": \"Photo Title\",\n \"file\": \"/some/path/file.jpg\",\n \"tags\": [\"holiday\", \"memories\"]\n}\n```\n\nI have tried creating 2 different DTOs, a `CreatePhotoDto` and an `InputPhotoDto`, one for the desired input shape in the controller and one for use with the service and entity, but this ends up very messy because there is a lot of work with converting between the 2 DTOs.\n\nWhat is the correct way to have a different input shape from the `Body` of a `Post` request and then have it turned into the DTO required for use by the entity?\n\n========================================\n\nTop Answer:\nUpdate DTO to\n\n`export class PhotoDto {\n readonly title: string\n readonly file: string\n readonly tags: Array\n}`\n\nIt will change the API structure to\n\n`{\n \"title\": \"Photo Title\",\n \"file\": \"/some/path/file.jpg\",\n \"tags\": [\"holiday\", \"memories\"]\n}`\n\ncurrently your tags property is an array of object of type **TagDto**, change tags property to just array of string.\n\n========================================\n\nCode:\n```text\nexport class PhotoDto {\n    readonly title: string\n    readonly file: string\n    readonly tags: TagDto[]\n}\n\nexport class TagDto {\n    readonly name: string\n}\n```\n\n```text\n// In photo.service.ts\nasync create(createPhotoDto: PhotoDto): Promise<PhotoEntity> {\n   // ...\n   return await this.photoRepo.create(createPhotoDto)\n}\n\n// In photo.controller.ts\n@Post()\nasync create(@Body() createPhotoDto: PhotoDto): Promise<PhotoEntity> {\n   // ...\n}\n```\n\n```text\n{\n   \"title\": \"Photo Title\",\n   \"file\": \"/some/path/file.jpg\",\n   \"tags\": [\n      {\n         \"name\": \"holiday\"\n      },\n      {\n         \"name\": \"memories\"\n      }\n   ]\n}\n```\n\n```text\n{\n   \"title\": \"Photo Title\",\n   \"file\": \"/some/path/file.jpg\",\n   \"tags\": [\"holiday\", \"memories\"]\n}\n```\n\n```text\nPhotoDto\n```\n\n```text\nphoto.service.ts\n```\n\n```text\nphoto.controller.ts\n```\n\n```text\nBody\n```\n\n```text\nCreatePhotoDto\n```\n\n```text\nInputPhotoDto\n```\n\n```text\nBody\n```\n\n```text\nPost\n```\n\n```text\n@UsePipes(new ValidationPipe({ transform: true }))\n@Post()\nasync create(@Body() createPhotoDto: PhotoDto): Promise<PhotoEntity> {\n   // ...\n}\n```\n\n```text\n// Transforms string[] to TagDto[]\nconst transformTags = tags => {\n  if (Array.isArray(tags)) {\n    return tags.map(tag => ({name: tag}))\n  } else {\n    return tags;\n  }\n}\n\n\nimport { Transform } from 'class-transformer';\nexport class PhotoDto {\n    readonly title: string\n    readonly file: string\n    @Transform(transformTags, {toClassOnly: true})\n    readonly tags: TagDto[]\n}\n```\n\n```text\nValidationPipe()\n```\n\n```text\nValidationPipe\n```\n\n```text\n@Transform\n```\n\n```text\nPhotoDto\n```\n\n```text\nexport class PhotoDto {\n    readonly title: string\n    readonly file: string\n    readonly tags: Array<string>\n}\n```\n\n```text\n{\n   \"title\": \"Photo Title\",\n   \"file\": \"/some/path/file.jpg\",\n   \"tags\": [\"holiday\", \"memories\"]\n}\n```\n\n```text\nexport const ConvertToCreateCatDto = createRouteParamDecorator((data, req): CreateCatDto => { // `createParamDecorator` for nest old version\n    if (req.body.tags.every(value => typeof value === \"string\")) { // if input tags is a string[]\n        req.body.tags = (req.body.tags as string[]).map<TagDto>((tag) => {\n            return { // convert to TagDto\n                name: tag + \"\"\n            }\n        });\n    }\n    let result = new CreateCatDto(req.body);\n    // TODO: validate `result` object\n    return result;\n});\n```\n\n```text\nexport class CreateCatDto {\n    readonly title: string;\n    readonly file: number;\n    readonly tags: TagDto[];\n\n    constructor(obj: any) {\n        this.title = obj.title;\n        this.file = obj.file;\n        this.tags = obj.tags;\n    }\n}\n```\n\n```text\n// In photo.controller.ts\n@Post()\nasync create(@ConvertToCreateCatDto() createPhotoDto: PhotoDto): Promise<PhotoEntity> {\n   //...\n}\n```\n\n```text\nnest\n```\n\n```text\n@ConvertToCreateCatDto\n```\n\n```text\n@Body\n```\n\n========================================\n\nComments:\n- For some reason, my nested dto passed as POST body becomes to string instead of Class contains another Class. The seconds `@Transform` solution really saved me! Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":284,"estimatedTokens":1281}}556{"id":"stack-57391545","source":"stackoverflow","questionId":57391545,"title":"\"QueryFailedError: invalid input syntax for integer:\" when querying on type float","tags":["postgresql","nestjs","typeorm"],"text":"Title: \"QueryFailedError: invalid input syntax for integer:\" when querying on type float\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen querying the database using the TypeORM QueryBuilder() I get: \n\n```\nQueryFailedError: invalid input syntax for integer: \"X\"\n```\n\nWith X being the value stored in the DB.\n\nOriginally my entity was of type;\n\n```\n{type: 'decimal', precision: 5, scale: 2 }\nvalue: number\n```\n\nSince I have changed it to: \n\n```\n{type: 'real'}\nvalue: string\n```\n\nand tried: \n\n```\n'float'\nvalue: string\n```\n\nAll three types throw the same error. However, if the value in the DB doesn't have any decimal places - it works fine. \n\nI am running Postgres v11.4, TypeORM v0.2.18 and Nest.js v6.5.3\n\nThe entity definition: \n\n```\nexport class Entity extends BaseEntity {\n\n @Column('float')\n value: string;\n}\n```\n\nThe query:\n\n```\nconst current = await this.entityRepo\n .createQueryBuilder('uL')\n .leftJoin('uL.user', 'user')\n .leftJoinAndSelect('uL.currentLevel', 'cL')\n .where('user.id = :id', { id: userId })\n .getOne();\n```\n\nI am expecting the entity to be returned with the value being of correct decimal spacing.\n\n========================================\n\nCode:\n```text\nQueryFailedError: invalid input syntax for integer: \"X\"\n```\n\n```text\n{type: 'decimal', precision: 5, scale: 2 }\nvalue: number\n```\n\n```text\n{type: 'real'}\nvalue: string\n```\n\n```text\n'float'\nvalue: string\n```\n\n```text\nexport class Entity extends BaseEntity {\n\n    @Column('float')\n    value: string;\n}\n```\n\n```text\nconst current = await this.entityRepo\n            .createQueryBuilder('uL')\n            .leftJoin('uL.user', 'user')\n            .leftJoinAndSelect('uL.currentLevel', 'cL')\n            .where('user.id = :id', { id: userId })\n            .getOne();\n```\n\n```js\n@Column()\nvalue: number;\n```\n\n```js\n@Column({type: 'real'})\nvalue: string;\n```\n\n```sh\nnpm run typeorm:migrate ChangedNumbersTypeToReal\nnpm run build; npm run typeorm:run\n```\n\n========================================\n\nComments:\n- Thanks, it helped me, the only observation is that here I had to clean up the changed column before running the migration","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":532}}557{"id":"stack-66086508","source":"stackoverflow","questionId":66086508,"title":"NestJS [TypeOrmModule] Unable to connect to the database","tags":["postgresql","nestjs","typeorm"],"text":"Title: NestJS [TypeOrmModule] Unable to connect to the database\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to connect to a remote PostgreSQL database (which is being hosted on Heroku) and getting this error:\n\n```\nerror: no pg_hba.conf entry for host \"\", user \"\", database \"\", SSL off\n```\n\nHere's my `app.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nconst cfg: TypeOrmModuleOptions = {\n type: 'postgres',\n host: process.env.DB_HOST,\n database: process.env.DB_NAME,\n username: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n port: Number(process.env.DB_PORT),\n};\n\n@Module({\n imports: [TypeOrmModule.forRoot(cfg)],\n})\nexport class AppModule {}\n```\n\nEvery `DB_*` variable matches corresponding values in Heroku's `Database Credentials`\n\nI think that the problem is somewhere in `TypeORM`, because connecting to the same DB with the same `.env` file values worked in my other application (written in different programming language)\n\nAny ideas on what could be wrong?\n\n========================================\n\nTop Answer:\nI got the same error and looks like the same dev environment as you.\n\nin my case, I resolved the error from this Heloku Postgres Connecting in Node.js\n\nI chose the alternative way to omit the ssl configuration as the link says.\n\non the console of your project path, type the following command.\n\nheroku config:set PGSSLMODE=no-verify\n\nabove command is the same as this.\nhttps://i.sstatic.net/5FpJ1.png\n\n========================================\n\nCode:\n```text\nerror: no pg_hba.conf entry for host \"<My public IP address>\", user \"<username>\", database \"<dbname>\", SSL off\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nconst cfg: TypeOrmModuleOptions = {\n  type: 'postgres',\n  host: process.env.DB_HOST,\n  database: process.env.DB_NAME,\n  username: process.env.DB_USER,\n  password: process.env.DB_PASSWORD,\n  port: Number(process.env.DB_PORT),\n};\n\n@Module({\n  imports: [TypeOrmModule.forRoot(cfg)],\n})\nexport class AppModule {}\n```\n\n```text\napp.module.ts\n```\n\n```text\nDB_*\n```\n\n```text\nDatabase Credentials\n```\n\n```text\nTypeORM\n```\n\n```text\n.env\n```\n\n```text\nssl: true,\nextra: {\n  ssl: {\n    rejectUnauthorized: false,\n  },\n},\n```\n\n```text\nssl: true\n```\n\n```js\nimport { DynamicModule, Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport * as fs from 'fs';\n\n@Module({})\nexport class DatabaseModule {\n  static async forRoot(): Promise<DynamicModule> {\n    const creds = JSON.parse(process.env.VCAP_SERVICES || '{}')[\"postgresql-db\"][0].credentials;\n    await new Promise(resolve => setTimeout(resolve, 1000));\n    return {\n      module: DatabaseModule,\n      imports: [\n        TypeOrmModule.forRoot({\n          // type: 'postgres',\n          // host: process.env.PG_HOST,\n          // port: Number(process.env.PG_PORT),\n          // username: process.env.POSTGRES_USER,\n          // password: process.env.POSTGRES_PASSWORD,\n          // database: process.env.POSTGRES_DB,\n          // // ssl: {\n          // //   rejectUnauthorized: false, // quick fix\n          // // },\n\n          type: 'postgres',\n          host: creds.hostname,\n          port: Number(creds.port),\n          username: creds.username,\n          password: creds.password,\n          database: creds.dbname,\n          ssl: {\n            rejectUnauthorized: true,\n            ca: creds.sslrootcert.replace(/\\\\n/g, '\\n'),\n            cert: creds.sslcert.replace(/\\\\n/g, '\\n'),\n            // key: creds.sslkey?.replace(/\\\\n/g, '\\n'), // not provided in your binding\n          },\n\n          entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n          synchronize: true,\n          logging: ['query', 'error', 'log', 'warn', 'info'],\n          autoLoadEntities: true,\n        }),\n      ],\n    };\n  }\n}\n```\n\n========================================\n\nComments:\n- Man!!! I spent hours struggling with this issue, and this solution finally helped!","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":165,"estimatedTokens":1016}}558{"id":"stack-57143174","source":"stackoverflow","questionId":57143174,"title":"How can we implement a registration by invitation in existing application?","tags":["javascript","node.js","typescript","jwt","nestjs"],"text":"Title: How can we implement a registration by invitation in existing application?\nTags: javascript, node.js, typescript, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy application supports normal registration for admin roles and registration by invite for team members. Admins can successfully register themselves. Login functionality is also working fine. I am using jwt for token generation and `AuthGuards` to protect private routes.\n\nNeed some help on how I can send an invitation url to users? (nodemailer already configured and working). More concerned about url generation.\n\nCan someone help me?\nThe application backend is in nestjs and frontend is in angular 8.\nCurrently I am testing apis through postman.\n\nThanks in advance,\nAjinkya\n\n========================================\n\nCode:\n```text\nAuthGuards\n```\n\n```text\ninvitation-token\n```\n\n```text\ntoken\n```\n\n```text\ninvitation-token\n```\n\n```text\n/registration?invitation-token=Usa67Nsus78\n```\n\n```text\ninvite\n```\n\n```text\ninvitation-token\n```\n\n========================================\n\nComments:\n- It's better to send an email field on params at step 2 because you can check if the email exists and then redirect him to the registering page. If an email exists just update the database to make sure he is invited and has access. It is important when the user receives multi-invitation links. You can also do this process by saving the email address on the invitation-token entity!","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":51,"estimatedTokens":360}}559{"id":"stack-68434502","source":"stackoverflow","questionId":68434502,"title":"Unit testing a service with many dependencies in NestJS","tags":["unit-testing","nestjs"],"text":"Title: Unit testing a service with many dependencies in NestJS\nTags: unit-testing, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen building API's in Nest, I often come across an issue where a particular API might need to make use of several Nest modules to do it's job. I'd like to know if there's a better way to structure my modules so that unit testing them is easier.\n\nFor example, imagine we have an `OrderService`. The `OrderService` makes use of a few different dependencies in order to do it's job:\n\n- It uses the `ProductsService` in order to look up product details and prices.\n\n- It uses the `UsersService` in order to look up customer information, such as a Stripe customer ID.\n\n- It uses a Typeorm to handle writing the `Order` into the database\n\n- And finally, let's say it uses a `CouponsService` in order to look up and validate coupon details for the `Order`.\n\nFor the sake of this example, let's just imagine each of these 4 dependencies to be it's own Nest module.\n\nWhen it comes to unit testing the `OrdersService`, I'd then need to stub out 4 different dependencies. This seems like a lot more work than it should be, and so I realized there must be a better way.\n\nOne thing that I've tried doing is creating separate helper files for setting up each services mocks. This cuts down on the amount of boilerplate for each service that uses a particular dependency, but you still end up in a situation where 1 service might have 4 different dependencies.\n\nIdeally, I'd like to implement some pattern or structure so that when I test a file, the dependencies are either really simple or automatic to mock, or a particular file only has 1 dependency at a time, without oversimplifying the system.\n\nMy question really boils down to:\n\nHow do you handle many dependencies like this in a Service, without ending up in a situation where testing a function requires you to mock 4+ methods. I'd love to hear a Nest specific way to do this, but I'd also appreciate any generic software engineering examples or patterns to look into as well.\n\n========================================\n\nCode:\n```text\nOrderService\n```\n\n```text\nOrderService\n```\n\n```text\nProductsService\n```\n\n```text\nUsersService\n```\n\n```text\nOrder\n```\n\n```text\nCouponsService\n```\n\n```text\nOrder\n```\n\n```text\nOrdersService\n```\n\n```js\nconst modFixture = await Test.createTestingModule({\n  providers: [\n    OrderService,\n    {\n      provide: ProductService,\n      useValue: createMock<ProductService>(),\n    },\n    {\n      provide: UserService,\n      useValue: createMock<UserService>(),\n    },\n    ...etc\n  ]\n}).compile();\n```\n\n```text\n@nestjs/testing\n```\n\n```text\n@golevelup/ts-jest\n```\n\n```text\n{ get: jest.fn(), create: jest.fn(), ...etc }\n```\n\n```text\nuseValue\n```\n\n```text\njest.fn()\n```\n\n========================================\n\nComments:\n- This is fantastic news, really looking forward to seeing this in the main testing package.\n- Hey Jay, I took a look at the package and it looks fantastic, but I noticed that the Github links don't point to a repo. I'm assuming it's currently private? Just wanted to point that out in case it's a mistake! Otherwise, looks very easy to use. Thanks for all your work with Nest!\n- I'm not sure which links you're talking about\n- Specifically github.com/golevelup/nestjs/blob/HEAD/src/mocks.spec.ts on this page (at the bottom) npmjs.com/package/@golevelup/ts-jest. However, the sidebar links to the repo and homepage on the NPM package just lead to the main golevelup repo, which doesn't seem to include this project.","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":108,"estimatedTokens":882}}560{"id":"stack-54607278","source":"stackoverflow","questionId":54607278,"title":"NestJS return a file from GridFS","tags":["get","http-headers","zip","httpresponse","nestjs"],"text":"Title: NestJS return a file from GridFS\nTags: get, http-headers, zip, httpresponse, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to return a file from GridFS using my Nest controller. As far as I can tell nest is not respecting my custom `content-type` header which i set to `application/zip`, as I am receiving a text content type upon return (see screenshot).\n\nresponse data image, wrong content-type header\n\nMy nest controller looks like this\n\n```\n@Get(':owner/:name/v/:version/download')\n @Header('Content-Type', 'application/zip')\n async downloadByVersion(@Param('owner') owner: string, @Param('name') name: string, @Param('version') version: string, @Res() res): Promise {\n let bundleData = await this.service.getSwimbundleByVersion(owner, name, version);\n let downloadFile = await this.service.downloadSwimbundle(bundleData['meta']['fileData']['_id']); \n return res.pipe(downloadFile);\n }\n```\n\nHere is the service call\n\n```\ndownloadSwimbundle(fileId: string): Promise {\n return this.repository.getFile(fileId)\n }\n```\n\nwhich is essentially a pass-through to this.\n\n```\nasync getFile(fileId: string): Promise {\n const db = await this.dbSource.db;\n const bucket = new GridFSBucket(db, { bucketName: this.collectionName });\n const downloadStream = bucket.openDownloadStream(new ObjectID(fileId));\n\n return new Promise(resolve => {\n resolve(downloadStream)\n });\n }\n```\n\nMy end goal is to call the `download` endpoint and have a browser register that it is a zip file and download it instead of seeing the binary in the browser. Any guidance on what needs to be done to get there would be greatly appreciated. Thanks for reading\n\n========================================\n\nCode:\n```text\n@Get(':owner/:name/v/:version/download')\n  @Header('Content-Type', 'application/zip')\n  async downloadByVersion(@Param('owner') owner: string, @Param('name') name: string, @Param('version') version: string, @Res() res): Promise<any> {\n    let bundleData = await this.service.getSwimbundleByVersion(owner, name, version);\n    let downloadFile = await this.service.downloadSwimbundle(bundleData['meta']['fileData']['_id']);   \n    return res.pipe(downloadFile);\n  }\n```\n\n```text\ndownloadSwimbundle(fileId: string): Promise<GridFSBucketReadStream> {\n      return this.repository.getFile(fileId)\n    }\n```\n\n```text\nasync getFile(fileId: string): Promise<GridFSBucketReadStream> {\n    const db = await this.dbSource.db;\n    const bucket = new GridFSBucket(db, { bucketName: this.collectionName });\n    const downloadStream = bucket.openDownloadStream(new ObjectID(fileId));\n\n    return new Promise<GridFSBucketReadStream>(resolve => {\n        resolve(downloadStream)\n      });\n  }\n```\n\n```text\ncontent-type\n```\n\n```text\napplication/zip\n```\n\n```text\ndownload\n```\n\n```js\n@Get('/test')\n@Header('Content-Type', 'application/pdf')\n@Header('Content-Disposition', 'attachment; filename=something.pdf')\ngetTest(@Res() response: Response) {\n   const data = createReadStream(path.join(__dirname, 'test.pdf'));\n   data.pipe(response);\n}\n\n@Get('/test')\n@Header('Content-Type', 'application/pdf')\ngetTest(@Res() response: Response) {\n   const data = createReadStream(path.join(__dirname, 'test.pdf'));\n\n   response.setHeader(\n     'Content-Disposition',\n     'attachment; filename=another.pdf',\n   );\n\n   data.pipe(response);\n}\n```\n\n```text\nContent-Disposition\n```\n\n```text\n@Header()\n```\n\n```text\nsetHeader\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":122,"estimatedTokens":847}}561{"id":"stack-51845556","source":"stackoverflow","questionId":51845556,"title":"How to set up a default layout in nest.js using Handlebars.js?","tags":["javascript","node.js","typescript","handlebars.js","nestjs"],"text":"Title: How to set up a default layout in nest.js using Handlebars.js?\nTags: javascript, node.js, typescript, handlebars.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm just starting with nest.js having some previous experience with node and express. \n\nI'm trying to set up a default layout for my partials and response renders. Here's my `main.ts`: \n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as hbs from 'hbs';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n app.setBaseViewsDir(__dirname + '/views');\n hbs.registerPartials(__dirname + '/views/partials');\n app.setViewEngine('hbs');\n\n await app.listen(3000);\n}\nbootstrap();\n```\n\nI have a feeling that there should be a default layout defined somewhere in that code but I have no idea how to proceed. My Google-fu has failed me, so can anyone give me a hand with this?\n\n========================================\n\nTop Answer:\nThis worked on a NestExpressApplication:\n\nImport handlebars:\n\n```\nimport * as hbs from 'hbs';\nimport { join } from 'path';\n```\n\nsetting hbs as viewEngine a\n\n```\napp.setBaseViewsDir(join(__dirname, '..', 'views'));\napp.setViewEngine('hbs');\nhbs.registerPartials(join(__dirname, '..', '/views/partials'));\n```\n\nWorked also with helpers:\n\n```\nhbs.handlebars.helpers = {\n...require('handlebars-helpers')()\n};\n```\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport * as hbs from 'hbs';\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n\n    app.setBaseViewsDir(__dirname + '/views');\n    hbs.registerPartials(__dirname + '/views/partials');\n    app.setViewEngine('hbs');\n\n    await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nmain.ts\n```\n\n```text\napp.set('view options', { layout: 'index' });\n```\n\n```text\n@Render('valid-layout')\n```\n\n```text\nimport * as hbs from 'hbs';\nimport { join } from 'path';\n```\n\n```text\napp.setBaseViewsDir(join(__dirname, '..', 'views'));\napp.setViewEngine('hbs');\nhbs.registerPartials(join(__dirname, '..', '/views/partials'));\n```\n\n```text\nhbs.handlebars.helpers = {\n...require('handlebars-helpers')()\n};\n```\n\n========================================\n\nComments:\n- For anyone running a newer NestJS version do as: app.setLocal('view options', { layout: 'layout' });","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":597}}562{"id":"stack-55406194","source":"stackoverflow","questionId":55406194,"title":"NestJS set HttpStatus in interceptor","tags":["javascript","node.js","typescript","nestjs","fastify"],"text":"Title: NestJS set HttpStatus in interceptor\nTags: javascript, node.js, typescript, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm using an interceptor to transform my response. I want to set the `HttpStatus` inside but the code I'm using now doesn't work.\n\n```\nimport { CallHandler, ExecutionContext, NestInterceptor, SetMetadata } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { classToPlain } from 'class-transformer';\nimport { ApiResponse } from '../models/apiResponse';\n\nexport class TransformInterceptor implements NestInterceptor {\n intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable {\n return next.handle().pipe(\n map(data => {\n const http = context.switchToHttp();\n const res = http.getResponse();\n\n if(data instanceof ApiResponse) {\n if(data.status !== undefined) {\n res.status(data.status);\n }\n }\n\n return classToPlain(data);\n }),\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { CallHandler, ExecutionContext, NestInterceptor, SetMetadata } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { classToPlain } from 'class-transformer';\nimport { ApiResponse } from '../models/apiResponse';\n\nexport class TransformInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    next: CallHandler<ApiResponse | any>,\n  ): Observable<ApiResponse | any> {\n    return next.handle().pipe(\n      map(data => {\n        const http = context.switchToHttp();\n        const res = http.getResponse();\n\n        if(data instanceof ApiResponse) {\n          if(data.status !== undefined) {\n            res.status(data.status);\n          }\n        }\n\n        return classToPlain(data);\n      }),\n    );\n  }\n}\n```\n\n```text\nHttpStatus\n```\n\n```text\ncontext.switchToHttp()\n      .getResponse()\n      .status(205);\n```\n\n```text\nexport class StatusException extends HttpException {\n  constructor(data, status: HttpStatus) {\n    super(data, status);\n  }\n}\n```\n\n```text\n@Catch(StatusException)\nexport class StatusFilter implements ExceptionFilter {\n  catch(exception: StatusException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const status = exception.getStatus();\n    console.log(`Setting status to ${status}`);\n    response.status(status).json(exception.message);\n  }\n}\n```\n\n```text\n@Injectable()\nexport class StatusInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next): Observable<any> {\n    return next.handle().pipe(\n      map((data: any) => {\n        if (data.text === 'created') {\n          throw new StatusException(data, HttpStatus.CREATED);\n        } else {\n          throw new StatusException(data, HttpStatus.ACCEPTED);\n        }\n      }),\n    );\n  }\n}\n```\n\n```text\n@UseFilters(StatusFilter)\n@UseInterceptors(StatusInterceptor)\n@Controller()\nexport class AppController {\n  @Get(':param')\n  async get(@Param('param') param) {\n    return { text: param };\n  }\n}\n```\n\n```text\nHttpException\n```\n\n```text\n@Res()\n```\n\n========================================\n\nComments:\n- Please see my update. This is now possible.\n- thanks. This will do it for now, but still itโ€™s not a good solution since the middleware/interceptors provided later on wonโ€™t run anymore. Think Iโ€™ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.\n- According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.\n- I'm the creator of the PR ;) but thanks for your work around! :D\n- Haha, sorry, didn't see that. Thanks for the PR! :-)","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":146,"estimatedTokens":953}}563{"id":"stack-71764270","source":"stackoverflow","questionId":71764270,"title":"NestJs @Sse - event is consumed only by one client","tags":["nestjs","server-sent-events"],"text":"Title: NestJs @Sse - event is consumed only by one client\nTags: nestjs, server-sent-events\nSource: Stack Overflow\n\nQuestion:\nI tried the sample SSE application provided with nest.js (28-SSE), and modified the sse endpoint to send a counter:\n\n```\n@Sse('sse')\n sse(): Observable {\n return interval(5000).pipe(\n map((_) => ({ data: { hello: `world - ${this.c++}` }} as MessageEvent)),\n );\n }\n```\n\nI expect that **each** client that is listening to this SSE will receive the message, but when opening multiple browser tabs I can see that each message is consumed only by one browser, so if I have three browsers open I get the following:\n\nhttps://i.sstatic.net/f6oNe.png\n\nHow can I get the expected behavior?\n\n========================================\n\nTop Answer:\nyou just have to generate a new observable for each sse connection of the same subject\n\n```\nprivate events: Subject = new Subject();\n\n constuctor(){\n timer(0, 1000).pipe(takeUntil(this.destroy)).subscribe(async (index: any)=>{\n let event: MessageEvent = { \n id: index, \n type: 'test', \n retry: 30000, \n data: {index: index}\n } as MessageEvent;\n this.events.next(event);\n });\n }\n\n @Sse('sse')\n public sse(): Observable {\n return this.events.asObservable();\n }\n```\n\nNote: I'm skipping the rest of the controller code.\n\nRegards,\n\n========================================\n\nCode:\n```text\n@Sse('sse')\n  sse(): Observable<MessageEvent> {\n    return interval(5000).pipe(\n      map((_) => ({ data: { hello: `world - ${this.c++}` }} as MessageEvent)),\n    );\n  }\n```\n\n```js\nimport { Controller, Get, MessageEvent, OnModuleDestroy, OnModuleInit, Res, Sse } from '@nestjs/common';\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\nimport { Observable, ReplaySubject } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { Response } from 'express';\n\n@Controller()\nexport class AppController implements OnModuleInit, OnModuleDestroy {\n  private stream: {\n    id: string;\n    subject: ReplaySubject<unknown>;\n    observer: Observable<unknown>;\n  }[] = [];\n  private timer: NodeJS.Timeout;\n  private id = 0;\n\n  public onModuleInit(): void {\n    this.timer = setInterval(() => {\n      this.id += 1;\n      this.stream.forEach(({ subject }) => subject.next(this.id));\n    }, 1000);\n  }\n\n  public onModuleDestroy(): void {\n    clearInterval(this.timer);\n  }\n\n  @Get()\n  public index(): string {\n    return readFileSync(join(__dirname, 'index.html'), 'utf-8').toString();\n  }\n\n  @Sse('sse')\n  public sse(@Res() response: Response): Observable<MessageEvent> {\n    const id = AppController.genStreamId();\n    // Clean up the stream when the client disconnects\n    response.on('close', () => this.removeStream(id));\n    // Create a new stream\n    const subject = new ReplaySubject();\n    const observer = subject.asObservable();\n    this.addStream(subject, observer, id);\n\n    return observer.pipe(map((data) => ({\n      id: `my-stream-id:${id}`,\n      data: `Hello world ${data}`,\n      event: 'my-event-name',\n    }) as MessageEvent));\n  }\n\n  private addStream(subject: ReplaySubject<unknown>, observer: Observable<unknown>, id: string): void {\n    this.stream.push({\n      id,\n      subject,\n      observer,\n    });\n  }\n\n  private removeStream(id: string): void {\n    this.stream = this.stream.filter(stream => stream.id !== id);\n  }\n\n  private static genStreamId(): string {\n    return Math.random().toString(36).substring(2, 15);\n  }\n}\n```\n\n```text\nprivate events: Subject<MessageEvent> = new Subject();\n\n constuctor(){\n   timer(0, 1000).pipe(takeUntil(this.destroy)).subscribe(async (index: any)=>{\n            let event: MessageEvent = { \n                id: index, \n                type: 'test', \n                retry: 30000, \n                data: {index: index}\n            } as MessageEvent;\n            this.events.next(event);\n   });\n }\n\n @Sse('sse')\n public sse(): Observable<MessageEvent> {\n   return this.events.asObservable();\n }\n```\n\n========================================\n\nComments:\n- Are the same browser(profile) tabs in your screenshot?\n- Same behavior even in two different browsers (chrome / edge).\n- \"This behaviour is correct. Each SSE connection is a dedicated socket and handled by a dedicated server process. So each client can receive different data. It is not a broadcast-same-thing-to-many technology.\" Doesn't it contradict the SSE concept of one-to-many broadcasting ?\n- @sharon.biren SSE is not a one-to-many broadcast technology. (Neither are websockets.) If you've seen it described like that somewhere you were looking at an unreliable reference.\n- So actually if there are multiple clients who are registered to the same SSE endpoint (in NestJS) , then when the server returns a message event it will get just to one client ?\n- @sharon.biren Each client to the SSE endpoint is a dedicated socket, and the server can send a different message to each client, and at different times. However a server could maintain a list of all those connections, and loop through them and send each the same message. So you can build a broadcast-same-thing-to-many technology *on top of* SSE.\n- that's weird, because when i'm emitting some event , the 2 Chrome tabs that subscribed to this endpoint gets the same message. without maintaining a list of all clients connections. I'm using EventEmitter in NestJS\n- Why is it important to use reply subject in that case ?\n- The only requirement for SSE to work in NestJS is to return an Observable stream. Technically you can return `new Observable(...)` with the static data in it but in a real-world scenario, you do not wish to return static data, it would be dynamic. When you want to inject data into the stream you can use `Subject` or `ReplaySubject` they are almost the same. The thing is that with Subject/ReplaySubject you can return it as an observable and push data into the stream with `next` method while in `new Observable()` you can't. *(at least that's how I know it)*","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":166,"estimatedTokens":1479}}564{"id":"stack-56092791","source":"stackoverflow","questionId":56092791,"title":"instantiate service Class inside Interceptor in Nestjs","tags":["typescript","nestjs"],"text":"Title: instantiate service Class inside Interceptor in Nestjs\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would call a service inside interceptor in NestJS (see doc) , here's how I made\n\n```\nexport class HttpInterceptor implements NestInterceptor {\n constructor(private configService:ConfigService){}\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n let request = context.switchToHttp().getRequest();\n const apikey= this.configService.get('apikey');\n const hash=this.configService.get('hash');\n request.params= {apikey:apikey ,hash:hash,ts:Date.now()}\n return next\n }\n}\n```\n\nHers's ConfigService\n\n```\nexport class ConfigService {\n private readonly envConfig: { [key: string]: string };\n\n constructor(filePath: string) { \n this.envConfig = dotenv.parse(fs.readFileSync(path.join(__dirname, filePath)));\n }\n\n get(key: string): string {\n return this.envConfig[key];\n }\n}\n```\n\nI get an error that configService is undefined\n\n Cannot read property 'get' of undefined\n\nBut I have instantiated `ConfigService` correctly \n\nI don't know why I can't use `ConfigService` inside the interceptor\n\n========================================\n\nCode:\n```text\nexport class HttpInterceptor implements NestInterceptor {\n    constructor(private configService:ConfigService){}\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    let request = context.switchToHttp().getRequest();\n    const apikey= this.configService.get('apikey');\n    const hash=this.configService.get('hash');\n    request.params= {apikey:apikey ,hash:hash,ts:Date.now()}\n    return next\n  }\n}\n```\n\n```text\nexport class ConfigService {\n  private readonly envConfig: { [key: string]: string };\n\n  constructor(filePath: string) {    \n    this.envConfig = dotenv.parse(fs.readFileSync(path.join(__dirname, filePath)));\n  }\n\n  get(key: string): string {\n    return this.envConfig[key];\n  }\n}\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n@Module({\n  providers: [\n    ConfigService,\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: HttpInterceptor,\n    },\n  ],\n})\nexport class YourModule {}\n```\n\n```text\n@UseInterceptors(HttpInterceptor)\nexport class YourController {}\n```\n\n```text\nmain.ts\n```\n\n```text\napp.useGlobalInterceptors(new HttpInterceptor());\n```\n\n```text\napp.useGlobalInterceptors(new HttpInterceptor(new ConfigService()));\n```\n\n========================================\n\nComments:\n- *But I have instantiated ConfigService correctly* - I am not so soure: it seems that `ConfigService`is not injected - so you should post the relevant Module definition so that we can see the providers\n- Could you a bit of your code\n- I got response here I have imported theinterceptor inside module instead of calling it inside `main.ts`","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":704}}565{"id":"stack-69235867","source":"stackoverflow","questionId":69235867,"title":"Typeorm migration not detecting changes properly","tags":["typescript","postgresql","nestjs","typeorm"],"text":"Title: Typeorm migration not detecting changes properly\nTags: typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using typeorm in my nestjs application using a postgresql database. When I try to create a migration to synchronize my database to apply application changes the following query is always existed in generated migration file (I removed some unnecessary queries for extra readability):\n\n```\nexport class portal1631976435381 implements MigrationInterface {\n name = 'portal1631976435381'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"isTransporter\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"crmId\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"telephoneNumber\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"crmId\" character varying`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"telephoneNumber\" character varying`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"isTransporter\" boolean NOT NULL DEFAULT false`);\n await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableC`);\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableB`);\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n await queryRunner.query(`CREATE VIEW \"receipt_item_transaction_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableA`)\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",...]);\n }\n public async down(queryRunner: QueryRunner): Promise { ... }\n}\n```\n\nNo matter what changes are applied to the application all viewEntities are Dropped and recreated.\n\nAnother problem is that `inventory_based_on_receipt_item_view` is being created two times in the query with 2 slightly different queries although I only have one viewEntity with that name (I don't really know where it is coming from).\nAnother problem is that the 3 columns of organization table (`crmId`, `telephoneNumber` and `isTransporter`) are dropped and recreated with the same detail.\n\nI wanted to know that is there any better way for migrating database tables, maybe with another package (I couldn't find anything useful myself) or any workaround that can optimize my workflow? Cause I need to regenerate the migration file whenever any changes happen to the entities and make sure I remove every single wrong query that is generated.\n\n========================================\n\nCode:\n```js\nexport class portal1631976435381 implements MigrationInterface {\n    name = 'portal1631976435381'\n\n    public async up(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"isTransporter\"`);\n        await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"crmId\"`);\n        await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"telephoneNumber\"`);\n        await queryRunner.query(`ALTER TABLE \"organization\" ADD \"crmId\" character varying`);\n        await queryRunner.query(`ALTER TABLE \"organization\" ADD \"telephoneNumber\" character varying`);\n        await queryRunner.query(`ALTER TABLE \"organization\" ADD \"isTransporter\" boolean NOT NULL DEFAULT false`);\n        await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableC`);\n        await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n        await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableB`);\n        await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n        await queryRunner.query(`CREATE VIEW \"receipt_item_transaction_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableA`)\n        await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",...]);\n    }\n    public async down(queryRunner: QueryRunner): Promise<void> { ... }\n}\n```\n\n```text\ninventory_based_on_receipt_item_view\n```\n\n```text\ncrmId\n```\n\n```text\ntelephoneNumber\n```\n\n```text\nisTransporter\n```\n\n```text\nmigration:generate\n```\n\n========================================\n\nComments:\n- That's not help. :(","metadata":{"transformedAt":"2026-08-18T18:33:02.452Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":85,"estimatedTokens":1242}}566{"id":"stack-54838260","source":"stackoverflow","questionId":54838260,"title":"How to redirect all routes to index.html (Angular) in nest.js?","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: How to redirect all routes to index.html (Angular) in nest.js?\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am making Angular + NestJS app, and I want to send `index.html` file for all routes.\n\n**main.ts**\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useStaticAssets(join(__dirname, '..', 'frontend', 'dist', 'my-app'));\n app.setBaseViewsDir(join(__dirname, '..', 'frontend', 'dist', 'my-app'));\n await app.listen(port);\n}\n```\n\n**app.controller.ts**\n\n```\n@Controller('*')\nexport class AppController {\n\n @Get()\n @Render('index.html')\n root() {\n return {};\n }\n}\n```\n\nIt works fine while I open `localhost:3000/`, but if I open `localhost:3000/some_route` the server falls with `500 internal error` and says `Can not find html module`.\nI was searching why I am getting this error and everyone says `set default view engine like ejs or pug`, but I don't want to use some engines, I just want to send plain html built by angular without hacking like `res.sendFile('path_to_file')`. Please help\n\n========================================\n\nTop Answer:\n**Updated Answer for December 10, 2019**\n\n*You need to create middleware for sending the react index.html*\n\nCreate middleware file \n\n**frontend.middleware.ts**\n\n```\nimport { NestMiddleware, Injectable } from '@nestjs/common';\nimport {Request, Response} from \"express\"\nimport { resolve } from 'path';\n\n@Injectable()\nexport class FrontendMiddleware implements NestMiddleware {\n use(req: Request, res: Response, next: Function) {\n res.sendFile(resolve('../../react/build/index.html'));\n }\n}\n```\n\nInclude middleware in\n\n**app.module.ts**\n\n```\nimport { FrontendMiddleware } from './frontend.middleware';\nimport {\n Module,\n MiddlewareConsumer,\n RequestMethod,\n} from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n imports: [],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {\n configure(frontEnd: MiddlewareConsumer) {\n frontEnd.apply(FrontendMiddleware).forRoutes({\n path: '/**', // For all routes\n method: RequestMethod.ALL, // For all methods\n });\n }\n}\n```\n\n**App Structure for Reference:**\n\nenter image description here\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useStaticAssets(join(__dirname, '..', 'frontend', 'dist', 'my-app'));\n  app.setBaseViewsDir(join(__dirname, '..', 'frontend', 'dist', 'my-app'));\n  await app.listen(port);\n}\n```\n\n```text\n@Controller('*')\nexport class AppController {\n\n  @Get()\n  @Render('index.html')\n  root() {\n    return {};\n  }\n}\n```\n\n```text\nindex.html\n```\n\n```text\nlocalhost:3000/\n```\n\n```text\nlocalhost:3000/some_route\n```\n\n```text\n500 internal error\n```\n\n```text\nCan not find html module\n```\n\n```text\nset default view engine like ejs or pug\n```\n\n```text\nres.sendFile('path_to_file')\n```\n\n```text\n@Injectable()\nexport class FrontendMiddleware implements NestMiddleware {\n  resolve(...args: any[]): ExpressMiddleware {\n    return (req, res, next) => {\n      res.sendFile(path.resolve('../frontend/dist/my-app/index.html')));\n    };\n  }\n}\n```\n\n```text\nexport class ApplicationModule implements NestModule {\n  configure(consumer: MiddlewaresConsumer): void {\n    consumer.apply(FrontendMiddleware).forRoutes(\n      {\n        path: '/**', // For all routes\n        method: RequestMethod.ALL, // For all methods\n      },\n    );\n  }\n}\n```\n\n```text\n@Catch(NotFoundException)\nexport class NotFoundExceptionFilter implements ExceptionFilter {\n  catch(exception: HttpException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse();\n    response.sendFile(path.resolve('../frontend/dist/my-app/index.html')));\n  }\n}\n```\n\n```text\napp.useGlobalFilters(new NotFoundExceptionFilter());\n```\n\n```text\nsetBaseViewsDir\n```\n\n```text\n@Render()\n```\n\n```text\nuseStaticAssets\n```\n\n```text\nresponse.sendFile\n```\n\n```text\nindex.html\n```\n\n```text\nNotFoundExceptions\n```\n\n```text\nindex.html\n```\n\n```text\nmain.ts\n```\n\n```text\n@Module({\n  imports: [\n    AngularUniversalModule.forRoot({\n      bundle: require('./path/to/server/main'), // Bundle is created dynamically during build process.\n      liveReload: true,\n      templatePath: join(BROWSER_DIR, 'index2.html'),\n      viewsPath: BROWSER_DIR\n    })\n  ]\n})\n```\n\n```text\n{\n  \"hosting\": {\n    \"ignore\": [\"firebase.json\", \"**/.*\", \"**/node_modules/**\"],\n    \"public\": \"functions/dist/apps/path/to/browser\",\n    \"rewrites\": [\n      {\n        \"function\": \"angularUniversalFunction\",\n        \"source\": \"**\"\n      }\n    ]\n  }\n}\n```\n\n```text\nimport * as admin from 'firebase-admin';\nimport * as functions from 'firebase-functions';\n\nadmin.initializeApp(); // Initialize Firebase SDK.\nconst expressApp: Express = express(); // Create Express instance.\n\n// Create and init NestJS application based on Express instance.\n(async () => {\n  const nestApp = await NestFactory.create<NestExpressApplication>(\n    ApplicationModule,\n    new ExpressAdapter(expressApp)\n  );\n  nestApp.init();\n})().catch(err => console.error(err));\n\n// Firebase Cloud Function for Server Side Rendering (SSR).\nexports.angularUniversalFunction = functions.https.onRequest(expressApp);\n```\n\n```text\nindex.html\n```\n\n```text\nindex2.html\n```\n\n```text\n/\n```\n\n```text\nangular.json\n```\n\n```text\n\"index\": \"apps/myapp/src/index2.html\",\n```\n\n```text\nindex.html\n```\n\n```text\nindex2.html\n```\n\n```text\ntemplatePath: join(BROWSER_DIR, 'index2.html'),\n```\n\n```text\nApplicationModule\n```\n\n```text\nhosting\n```\n\n```text\nindex.html\n```\n\n```text\nindex2.html\n```\n\n```text\nimport { NestMiddleware, Injectable } from '@nestjs/common';\nimport {Request, Response} from \"express\"\nimport { resolve } from 'path';\n\n@Injectable()\nexport class FrontendMiddleware implements NestMiddleware {\n  use(req: Request, res: Response, next: Function) {\n    res.sendFile(resolve('../../react/build/index.html'));\n  }\n}\n```\n\n```text\nimport { FrontendMiddleware } from './frontend.middleware';\nimport {\n  Module,\n  MiddlewareConsumer,\n  RequestMethod,\n} from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {\n  configure(frontEnd: MiddlewareConsumer) {\n    frontEnd.apply(FrontendMiddleware).forRoutes({\n      path: '/**', // For all routes\n      method: RequestMethod.ALL, // For all methods\n    });\n  }\n}\n```\n\n========================================\n\nComments:\n- Thanks a lot! I thought it could be easy if I could just set `useStaticAssets` and return files from `@Render()`. But it seems more complex than I thought.\n- Thanks for the info, but from where did you import the decorator @Middleware()?\n- @StefanKlocke A long, long time ago... docs.nestjs.com/v4/middlewares ;-) Nowadays it's just `@Injectable()`\n- Ok Alan, but OP ask for Angular. I agree it's same.","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":356,"estimatedTokens":1755}}567{"id":"stack-54021714","source":"stackoverflow","questionId":54021714,"title":"Handling third party dependencies in nest.js","tags":["typescript","dependency-injection","nestjs"],"text":"Title: Handling third party dependencies in nest.js\nTags: typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhat is the best practice on how to handle third-party dependencies (i.e. dependencies that don't come in the form of a nest-module) in nest?\n\nFor example, I'm using `morgan` in my own logging module directly by importing it in the respective file:\n\n```\nimport { Injectable, MiddlewareFunction, NestMiddleware } from '@nestjs/common';\nimport * as morgan from 'morgan';\n\n@Injectable()\nexport class NestLoggingMiddleware implements NestMiddleware {\n\n resolve(...args: any[]): MiddlewareFunction {\n /** use morgan here, e.g. wrap it in a custom middleware ... */\n }\n}\n```\n\nNow I know nest's architecture is heavily influenced by Angular, and I found this article explaining how to deal with 3rd party dependencies in angular. Does the same idea apply to nest? Should I create a custom provider for `morgan` and inject that? And do I inject just the `morgan` import, or an already configured `morgan` instance?\n\n========================================\n\nCode:\n```text\nimport { Injectable, MiddlewareFunction, NestMiddleware } from '@nestjs/common';\nimport * as morgan from 'morgan';\n\n@Injectable()\nexport class NestLoggingMiddleware implements NestMiddleware {\n\n    resolve(...args: any[]): MiddlewareFunction {\n        /** use morgan here, e.g. wrap it in a custom middleware ... */\n    }\n}\n```\n\n```text\nmorgan\n```\n\n```text\nmorgan\n```\n\n```text\nmorgan\n```\n\n```text\nmorgan\n```\n\n```text\nimport { Telegraf } from 'telegraf';\n\n// ...\n\nproviders: [\n  {\n    provide: Telegraf,\n    useFactory: async (configService: ConfigService) => {\n      return new Telegraf(configService.telegramToken);\n    },\n    inject: [ConfigService],\n  },\n]\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":71,"estimatedTokens":440}}568{"id":"stack-64940682","source":"stackoverflow","questionId":64940682,"title":"How can a NestJS app listen on the same port as a connected microservice?","tags":["node.js","nestjs"],"text":"Title: How can a NestJS app listen on the same port as a connected microservice?\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to understand how Nest microservices work.\n\nLet's start with this example from the docs (https://docs.nestjs.com/faq/hybrid-application)\n\n```\nconst app = await NestFactory.create(AppModule);\n// microservice #1\nconst microserviceTcp = app.connectMicroservice({\n transport: Transport.TCP,\n options: {\n port: 3001,\n },\n});\n// microservice #2\nconst microserviceRedis = app.connectMicroservice({\n transport: Transport.REDIS,\n options: {\n url: 'redis://localhost:6379',\n },\n});\n\nawait app.startAllMicroservicesAsync();\nawait app.listen(3001);\n```\n\nAfter going through the source (https://github.com/nestjs/nest) , I understand `connectMicroservice` creates a `net.Server` when using `TCP` and the server starts listening when `startAllMicroservicesAsync` is called.\nBut then `app.listen` should initialize the listening of the base Nest webserver.\n\nWhy doesn't that cause an error?\n\nI checked what happens if I have two microservices connected on the port. It sure does throw an error. What am I missing here?\n\n```\n// CODE CAUSES ERROR AS EXPECTED\n\nconst app = await NestFactory.create(AppModule);\n// microservice #1\nconst microserviceTcp = app.connectMicroservice({\n transport: Transport.TCP,\n options: {\n port: 3001,\n },\n});\n\n// microservice #2 ({\n transport: Transport.TCP,\n options: {\n port: 3001,\n },\n});\n\nawait app.startAllMicroservicesAsync();\nawait app.listen(3001);\n```\n\n========================================\n\nCode:\n```text\nconst app = await NestFactory.create(AppModule);\n// microservice #1\nconst microserviceTcp = app.connectMicroservice<MicroserviceOptions>({\n  transport: Transport.TCP,\n  options: {\n    port: 3001,\n  },\n});\n// microservice #2\nconst microserviceRedis = app.connectMicroservice<MicroserviceOptions>({\n  transport: Transport.REDIS,\n  options: {\n    url: 'redis://localhost:6379',\n  },\n});\n\nawait app.startAllMicroservicesAsync();\nawait app.listen(3001);\n```\n\n```text\n// CODE CAUSES ERROR AS EXPECTED\n\nconst app = await NestFactory.create(AppModule);\n// microservice #1\nconst microserviceTcp = app.connectMicroservice<MicroserviceOptions>({\n  transport: Transport.TCP,\n  options: {\n    port: 3001,\n  },\n});\n\n// microservice #2  <--- THIS WILL CAUSE AN ERROR AS EXPECTED\nconst microserviceTcp = app.connectMicroservice<MicroserviceOptions>({\n  transport: Transport.TCP,\n  options: {\n    port: 3001,\n  },\n});\n\nawait app.startAllMicroservicesAsync();\nawait app.listen(3001);\n```\n\n```text\nconnectMicroservice\n```\n\n```text\nnet.Server\n```\n\n```text\nTCP\n```\n\n```text\nstartAllMicroservicesAsync\n```\n\n```text\napp.listen\n```\n\n```text\nlocalhost:3000 (LISTEN). // microservice\n*:3000 (LISTEN)          // http app\n```\n\n```text\nlsof\n```\n\n```text\nhostname\n```\n\n```text\nlocalhost\n```\n\n```text\napp.listen\n```\n\n```text\nmain.ts\n```\n\n========================================\n\nComments:\n- i think docs example is slightly confusing, here is an issue related github.com/nestjs/nest/issues/10205","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":157,"estimatedTokens":761}}569{"id":"stack-62822943","source":"stackoverflow","questionId":62822943,"title":"NestJS/TypeORM unit testing: Can't resolve dependencies of JwtService","tags":["jestjs","nestjs","typeorm","nestjs-jwt"],"text":"Title: NestJS/TypeORM unit testing: Can't resolve dependencies of JwtService\nTags: jestjs, nestjs, typeorm, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI'm trying to unit test this controller and mock away the services/repositories that it needs.\n\n```\n@Controller('auth')\nexport class AuthController {\n constructor(\n private readonly authService: AuthService,\n private readonly usersService: UsersService,\n ) {}\n\n @Post('register')\n public async registerAsync(@Body() createUserModel: CreateUserModel) {\n const result = await this.authenticationService.registerUserAsync(createUserModel);\n\n // more code here\n }\n\n @Post('login')\n public async loginAsync(@Body() login: LoginModel): Promise {\n const user = await this.usersService.getUserByUsernameAsync(login.username);\n\n // more code here\n }\n}\n```\n\nHere is my unit test file:\n\n```\ndescribe('AuthController', () => {\n let authController: AuthController;\n let authService: AuthService;\n\n beforeEach(async () => {\n const moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n AuthService,\n UsersService,\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n ],\n }).compile();\n\n authController = moduleRef.get(AuthenticationController);\n authService = moduleRef.get(AuthenticationService);\n });\n\n describe('registerAsync', () => {\n it('Returns registration status when user registration succeeds', async () => {\n let createUserModel: CreateUserModel = {...}\n\n let registrationStatus: RegistrationStatus = {\n success: true,\n message: 'User registered successfully',\n };\n\n jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n Promise.resolve(registrationStatus),\n );\n\n expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);\n });\n });\n});\n```\n\nBut when running this, I get the following error(s):\n\n```\nโ— AuthController โ€บ registerAsync โ€บ Returns registration status when user registration succeeds\n\n Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.\n\n Potential solutions:\n - If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?\n - If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?\n @Module({\n imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]\n })\n\n at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)\n at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)\n at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)\n at async Promise.all (index 0)\n at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)\n at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)\n at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)\n at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)\n at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)\n\n โ— AuthController โ€บ registerAsync โ€บ Returns registration status when user registration succeeds\n\n Cannot spyOn on a primitive value; undefined given\n\n 48 | };\n 49 |\n > 50 | jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n | ^\n 51 | Promise.resolve(registrationStatus),\n 52 | );\n 53 |\n\n at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)\n at Object. (Authentication/authentication.controller.spec.ts:50:18)\n```\n\nI'm not quite sure how to proceed so I'd like some help.\n\n========================================\n\nTop Answer:\nSince you are registering `AuthService` in the dependency injection container and just spying on `registerUserAsync`, it requires `JWTService` to be registered as well.\n\nYou need to register dependencies that are injected in `AuthService`:\n\n```\nconst moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n AuthService,\n UsersService,\n JWTService, // or register a fully mocked `AuthService` that doesn't need any other dependency:\n\n```\nconst moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n {\n provide: AuthService,\n useValue: {\n registerUserAsync: jest.fn(), // <--here\n }\n },\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n],\n}).compile();\n```\n\n========================================\n\nCode:\n```text\n@Controller('auth')\nexport class AuthController {\n    constructor(\n        private readonly authService: AuthService,\n        private readonly usersService: UsersService,\n    ) {}\n\n    @Post('register')\n    public async registerAsync(@Body() createUserModel: CreateUserModel) {\n        const result = await this.authenticationService.registerUserAsync(createUserModel);\n\n        // more code here\n    }\n\n    @Post('login')\n    public async loginAsync(@Body() login: LoginModel): Promise<{ accessToken: string }> {\n        const user = await this.usersService.getUserByUsernameAsync(login.username);\n\n        // more code here\n    }\n}\n```\n\n```text\ndescribe('AuthController', () => {\n    let authController: AuthController;\n    let authService: AuthService;\n\n    beforeEach(async () => {\n        const moduleRef: TestingModule = await Test.createTestingModule({\n            imports: [JwtModule],\n            controllers: [AuthController],\n            providers: [\n                AuthService,\n                UsersService,\n                {\n                    provide: getRepositoryToken(User),\n                    useClass: Repository,\n                },\n            ],\n        }).compile();\n\n        authController = moduleRef.get<AuthenticationController>(AuthenticationController);\n        authService = moduleRef.get<AuthenticationService>(AuthenticationService);\n    });\n\n    describe('registerAsync', () => {\n        it('Returns registration status when user registration succeeds', async () => {\n            let createUserModel: CreateUserModel = {...}\n\n            let registrationStatus: RegistrationStatus = {\n                success: true,\n                message: 'User registered successfully',\n            };\n\n            jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n                Promise.resolve(registrationStatus),\n            );\n\n            expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);\n        });\n    });\n});\n```\n\n```text\nโ— AuthController โ€บ registerAsync โ€บ Returns registration status when user registration succeeds\n\n    Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.\n\n    Potential solutions:\n    - If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?\n    - If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?\n      @Module({\n        imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]\n      })\n\n      at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)\n      at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)\n      at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)\n          at async Promise.all (index 0)\n      at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)\n      at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)\n      at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)\n      at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)\n      at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)\n\n  โ— AuthController โ€บ registerAsync โ€บ Returns registration status when user registration succeeds\n\n    Cannot spyOn on a primitive value; undefined given\n\n      48 |             };\n      49 |\n    > 50 |             jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n         |                  ^\n      51 |                 Promise.resolve(registrationStatus),\n      52 |             );\n      53 |\n\n      at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)\n      at Object.<anonymous> (Authentication/authentication.controller.spec.ts:50:18)\n```\n\n```js\nbeforeEach(async () => {\n  const modRef = await Test.createTestingModule({\n    controllers: [AuthController],\n    providers: [\n      {\n        provide: AuthService,\n        useValue: {\n          registerUserAsync: jest.fn(),\n        }\n\n      },\n      {\n        provide: UserService,\n        useValue: {\n          getUserByUsernameAsync: jest.fn(),\n        }\n      }\n    ]\n  }).compile();\n});\n```\n\n```text\nimports\n```\n\n```text\nmodRef.get()\n```\n\n```ts\nconst moduleRef: TestingModule = await Test.createTestingModule({\n  imports: [JwtModule],\n  controllers: [AuthController],\n  providers: [\n    AuthService,\n    UsersService,\n    JWTService, // <--here\n    {\n      provide: getRepositoryToken(User),\n      useClass: Repository,\n    },\n],\n}).compile();\n```\n\n```ts\nconst moduleRef: TestingModule = await Test.createTestingModule({\n  imports: [JwtModule],\n  controllers: [AuthController],\n  providers: [\n    {\n      provide: AuthService,\n      useValue: {\n        registerUserAsync: jest.fn(), // <--here\n      }\n     },\n    {\n      provide: getRepositoryToken(User),\n      useClass: Repository,\n    },\n],\n}).compile();\n```\n\n```text\nAuthService\n```\n\n```text\nregisterUserAsync\n```\n\n```text\nJWTService\n```\n\n```text\nAuthService\n```\n\n```text\nAuthService\n```\n\n```text\nJwtModule.registerAsync({\n                    imports: [ConfigModule],\n                    inject: [ConfigService],\n                    useFactory: async (configService: ConfigService) => ({\n                        secret: configService.get('JWT_SECRET'),\n                        signOptions: { expiresIn: '1d' }\n                    })\n                }),\n```\n\n```text\nmodule\n```\n\n```text\nAuthService\n```\n\n```text\nJwtService\n```\n\n```text\nNest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the RootTestModule context.\n```\n\n```text\nimports: []\n```\n\n```text\nawait Test.createTestingModule({\n```\n\n```text\nJwtService\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtService\n```\n\n========================================\n\nComments:\n- I spent over an hour trying to figure out how to solve my problem with unit testing, and this was the only solution that worked for me. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":396,"estimatedTokens":2713}}570{"id":"stack-66911356","source":"stackoverflow","questionId":66911356,"title":"Create a Header Custom Validation with NestJS and class-validator","tags":["typescript","nestjs","class-validator"],"text":"Title: Create a Header Custom Validation with NestJS and class-validator\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI have been working to validate a request using the class-validator, and NestJS validation plus trying to validate the header contents.\n\nMy basic interfaces are all working, but now I am trying to compare some header field data the same way.\n\nI had this question about the custom decorator to try to handle the headers, but the solution to that question, will return the one header. I want to be able to handle them all, similar to how all the body() data is processed.\n\nI need to be able to create a custom decorator for extracting the header fields, and being able to pass them into the class-validator DTO.\n\nFor Instance, I want to validate three header fields, such as:\n\n```\nUser-Agent = 'Our Client Apps'\nContent-Type = 'application/json'\ntraceabilityId = uuid\n```\n\nThere are more fields, but if I can get this going, then I can extrapolate out the rest. I have a simple controller example:\n\n```\n@Controller(/rest/package)\nexport class PackageController {\n\n constructor(\n private PackageData_:PackageService\n )\n { }\n\n ...\n\n @Post('inquiry')\n @HttpCode(HttpStatus.OK) // Not creating data, but need body, so return 200 OK\n async StatusInquiry(\n @RequestHeader() HeaderInfo:HeadersDTO, // This should be the Headers validation using the decorator from the question above.\n```\n\nI am trying to validate that the headers of the request contain some specific data, and I am using NestJS. I found this information. While this is what I want to do, and it looks proper, the ClassType reference does not exist, and I am not sure what to use instead.\n\nFrom the example, the decorator is referring to.\n\nrequest-header.decorator.ts\n\n```\nexport interface iError {\n statusCode:number;\n messages:string[];\n error:string;\n}\n\nexport const RequestHeader = createParamDecorator(\nasync (value: any, ctx: ExecutionContext) => {\n\n // extract headers\n const headers = ctx.switchToHttp().getRequest().headers;\n\n // Convert headers to DTO object\n const dto = plainToClass(value, headers, { excludeExtraneousValues: true });\n\n // Validate\n const errors: ValidationError[] = await validate(dto);\n\n if (errors.length > 0) {\n let ErrorInfo:IError = {\n statusCode: HttpStatus.BAD_REQUEST,\n error: 'Bad Request',\n message: new Array()\n };\n \n errors.map(obj => { \n AllErrors = Object.values(obj.constraints); \n AllErrors.forEach( (OneError) => {\n OneError.forEach( (Key) => {\n ErrorInfo.message.push(Key);\n });\n });\n\n // Your example, but wanted to return closer to how the body looks, for common error parsing\n //Get the errors and push to custom array\n // let validationErrors = errors.map(obj => Object.values(obj.constraints));\n throw new HttpException(`${ErrorInfo}`, HttpStatus.BAD_REQUEST);\n }\n\n // return header dto object\n return dto;\n},\n```\n\nI am having trouble generically mapping the constraints into a string array.\n\nMy HeadersDTO.ts:\n\n```\nimport { Expose } from 'class-transformer';\nimport { Equals, IsIn, IsString } from 'class-validator';\nexport class HeadersDTO {\n\n @IsString()\n @Equals('OurApp')\n @Expose({ name: 'user-agent' })\n public readonly 'user-agent':string;\n\n @IsString() \n @IsIn(['PRODUCTION', 'TEST'])\n public readonly operationMode:string;\n}\n```\n\nHeaders being sent via Postman for the request:\n\n```\nContent-Type:application/json\noperationMode:PRODUCTION\nAccept-Language:en\n```\n\n========================================\n\nTop Answer:\nAs mentioned in the issue you referenced, you need to create a DTO class and pass it to `RequestHeader` decorator.\n\ne.g\n\n```\nexport class MyHeaderDTO {\n @IsString()\n @IsDefined()\n @Expose({ name: 'myheader1' }) // required as headers are case insensitive\n myHeader1: string;\n}\n\n...\n\n@Get('/hello')\ngetHello(@RequestHeader(MyHeaderDTO) headers: MyHeaderDTO) {\n console.log(headers);\n}\n```\n\n========================================\n\nCode:\n```text\nUser-Agent = 'Our Client Apps'\nContent-Type = 'application/json'\ntraceabilityId = uuid\n```\n\n```text\n@Controller(/rest/package)\nexport class PackageController {\n\n    constructor(\n        private PackageData_:PackageService\n    )\n    { }\n\n    ...\n\n    @Post('inquiry')\n    @HttpCode(HttpStatus.OK)        // Not creating data, but need body, so return 200 OK\n    async StatusInquiry(\n        @RequestHeader() HeaderInfo:HeadersDTO,     // This should be the Headers validation using the decorator from the question above.\n```\n\n```text\nexport interface iError {\n    statusCode:number;\n    messages:string[];\n    error:string;\n}\n\nexport const RequestHeader = createParamDecorator(\nasync (value:  any, ctx: ExecutionContext) => {\n\n    // extract headers\n    const headers = ctx.switchToHttp().getRequest().headers;\n\n    // Convert headers to DTO object\n    const dto = plainToClass(value, headers, { excludeExtraneousValues: true });\n\n    // Validate\n    const errors: ValidationError[] = await validate(dto);\n\n    if (errors.length > 0) {\n        let ErrorInfo:IError = {\n            statusCode: HttpStatus.BAD_REQUEST,\n            error: 'Bad Request',\n            message: new Array<string>()\n        };\n        \n        errors.map(obj => { \n            AllErrors = Object.values(obj.constraints);    \n            AllErrors.forEach( (OneError) => {\n            OneError.forEach( (Key) => {\n                ErrorInfo.message.push(Key);\n            });\n        });\n\n        // Your example, but wanted to return closer to how the body looks, for common error parsing\n        //Get the errors and push to custom array\n        // let validationErrors = errors.map(obj => Object.values(obj.constraints));\n        throw new HttpException(`${ErrorInfo}`, HttpStatus.BAD_REQUEST);\n    }\n\n    // return header dto object\n    return dto;\n},\n```\n\n```text\nimport { Expose } from 'class-transformer';\nimport { Equals, IsIn, IsString } from 'class-validator';\nexport class HeadersDTO {\n\n    @IsString()\n    @Equals('OurApp')\n    @Expose({ name: 'user-agent' })\n    public readonly 'user-agent':string;\n\n    @IsString() \n    @IsIn(['PRODUCTION', 'TEST'])\n    public readonly operationMode:string;\n}\n```\n\n```text\nContent-Type:application/json\noperationMode:PRODUCTION\nAccept-Language:en\n```\n\n```js\nasync StatusInquiry(\n        @RequestHeader() HeaderInfo:HeadersDTO,\n```\n\n```js\nexport const RequestHeader = createParamDecorator(\n    //Removed ClassType<unknown>,, I don't think you need this here\n    async (value:  any, ctx: ExecutionContext) => {\n\n        // extract headers\n        const headers = ctx.switchToHttp().getRequest().headers;\n\n        // Convert headers to DTO object\n        const dto = plainToClass(value, headers, { excludeExtraneousValues: true });\n\n        // Validate\n        const errors: ValidationError[] = await validate(dto);\n        \n        if (errors.length > 0) {\n            //Get the errors and push to custom array\n            let validationErrors = errors.map(obj => Object.values(obj.constraints));\n            throw new HttpException(`Validation failed with following Errors: ${validationErrors}`, HttpStatus.BAD_REQUEST);\n        }\n\n        // return header dto object\n        return dto;\n    },\n);\n```\n\n```js\nexport class HeadersDTO \n    {\n      @IsDefined()\n      @Expose({ name: 'custom-header' })\n      \"custom-header\": string; // note the param here is in double quotes\n    }\n\nThe reason i found this when I looked compiled TS file, it looks like this,\n\n    class HeadersDTO {\n    }\n    tslib_1.__decorate([\n        class_validator_1.IsDefined(),\n        class_transformer_1.Expose({ name: 'custom-header' }),\n        tslib_1.__metadata(\"design:type\", String)\n    ], HeadersDTO.prototype, \"custom-header\", void 0);\n    exports.HeadersDTO = HeadersDTO;\n\nI get following error when i do not pass the header ,\n\n    [\n      ValidationError {\n        target: HeadersDTO { 'custom-header': undefined },\n        value: undefined,\n        property: 'custom-header',\n        children: [],\n        constraints: { isDefined: 'custom-header should not be null or undefined' }\n      }\n    ]\n```\n\n```text\n@RequestHeader(HeadersDTO) HeaderInfo:HeadersDTO,\n```\n\n```text\nHeadersDTO.ts\n```\n\n```text\nexport class MyHeaderDTO {\n    @IsString()\n    @IsDefined()\n    @Expose({ name: 'myheader1' })        // required as headers are case insensitive\n    myHeader1: string;\n}\n\n...\n\n@Get('/hello')\ngetHello(@RequestHeader(MyHeaderDTO) headers: MyHeaderDTO) {\n    console.log(headers);\n}\n```\n\n```text\nRequestHeader\n```\n\n========================================\n\nComments:\n- I believe you followed this link - github.com/nestjs/nest/issues/4798. if yes please cross check if anything is missing\n- Yes, except the issue with ClassType not being found is still there, it will not compile. `import { ClassType } from 'class-transformer&#47;ClassTransformer';`\n- The error is `Cannot find module 'class-transformer&#47;ClassTransformer' or its corresponding type declarations.ts(2307)`\n- I have tested below code I posted and it is working for me\n- Sorry, did not see you changed the ClassType to simply be an any.\n- I do that, as you can see in the controller. However, I am not sending the headers and it is not failing. Also, in the request-headers.decorator.ts, that code does not run, as the ClassType is undefined. The answer that does get the headers returned, does not call the validation, which is still my main issue.\n- @StevenScott In your example you do `@RequestHeader() HeaderInfo: HeadersDTO`, it should be `@RequestHeader(HeadersDTO) headers: HeadersDTO`\n- I added the `@RequestHeader(HeadersDTO) headers: HeadersDTO` but that does not get the failures to occur. For instance, using Postman to post the request, I disable the User-Agent from being sent. My code has the check that it is a client of ours. I updated the question with the example DTO.\n- This does give me a server error, 500 now, not the normal 400 Bad Request. Is there a way to get the default handling to kick in?\n- You can add your custom validation and throw exception around `await validateOrReject(dto);` function. I did same thing, Also note i have used `validate(obj)` method now. Updated answer\n- That did fix the issue, and I can reformat these. Was hoping to get the internal call for consistency, but can work with this.\n- I am not getting the header values passed in though. So while the validation is running, it is not truly validating as the header fields in quotes, are not getting populated, so their value is undefined.\n- I was able to see the header values i passed... I just monitored them and could see it. Are you saying you are unable to get header values ? Where are you trying to access those values?\n- Sorry, found them working. They are all lower case, without dashes. I had the custom headers getting populated, but the standard HTTP headers (User-Agent, etc.) would not work without all lower case and the @Expose() decorator. I only needed the quotes you had though on headers with a dash in the name.\n- Trying to create the same return as the normal validation, so working to change the `errors.map(obj => Object.values(obj.constraints));` to be the message:string[] return type. Would be nice to be able to simply send the errors into a function to get the same results as the standard validation of the payload, to allow the app receiving the errors to have a common error parsing routine.\n- okay... glad it is working ... it was not easy trace. :)\n- Added the example of trying to work out the response, but they do not come back as different array entries like the body, just one long string.\n- nestjs will convert all headers to lowercase, then the dto should match with this, for example property name in dto should be `x-app-name`","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":347,"estimatedTokens":2919}}571{"id":"stack-66680945","source":"stackoverflow","questionId":66680945,"title":"Testing NestJS Validation Pipe not working","tags":["jestjs","automated-tests","nestjs"],"text":"Title: Testing NestJS Validation Pipe not working\nTags: jestjs, automated-tests, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a simple class I am trying to get to work with NestJS and End To End testing to ensure I can get the validations working properly, but I cannot get the validations to work. If I send the data with Postman, or a normal client, the application does respond with the proper error.\n\nAPI.dto.ts\n\n```\nimport { IsNumber, IsPositive, IsString } from 'class-validator';\nexport class ApiDTO {\n @IsString() public readonly FileName:string;\n @IsNumber() @IsPositive() public readonly StatusCode:number;\n @IsNumber() @IsPositive() public readonly TimeOut:number;\n}\n```\n\nE2E Test File\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport * as request from 'supertest';\n\nimport { INestApplication, ValidationPipe } from '@nestjs/common';\n\nimport { AppModule } from '@APP/app.module';\nimport { ApiDTO } from './../../src/api/api.dto';\n\ndescribe('ApiController (e2e)', () => {\n let app: INestApplication;\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n app.useGlobalPipes(new ValidationPipe());\n await app.init();\n });\n\n it('/api/test/ (POST) test to see data validation works', async done => {\n const RequestBody:ApiDTO = {\n FileName : 'README.md',\n StatusCode: 111,\n TimeOut: -25\n };\n const Expected:string = `${RequestBody.FileName} = ${RequestBody.StatusCode.toString()} after ${RequestBody.TimeOut.toString()}`;\n\n const ResponseData = await request(app.getHttpServer())\n .post('/api/test')\n .send(RequestBody)\n .set('Accept', 'application/json');\n\n // All of these will fail as the code returns a 200 OK, as it does not do the validation (TimeOut -25 should fail IsPositive())\n expect(ResponseData.status).toBe(400);\n expect(ResponseData.headers['content-type']).toContain('application/json');\n\n // This line caused the problem as body is an object\n //expect(ResponseData.body.length).toBeGreaterThan(2);\n\n expect(ResponseData.body.statusCode).toBe(400);\n expect(ResponseData.body.message[0]).toBe('TimeOut must be a positive number');\n expect(ResponseData.body.error).toBe('Bad Request');\n done(); \n });\n\n});\n```\n\nI get a successful return, 200, when making this call. My code should be failing, due to the TimeOut with a negative number, where it needs to be `IsPositive()`. The service and other code all runs, just not the validations. I have added the global pipes in the beforeEach() so not sure what else to check.\n\n========================================\n\nTop Answer:\nRemoving my node_modules folder and reinstalling it worked for me.\n\nSteps:\n\nRemove `/node_modules`\n\nRe run `npm install`\n\n========================================\n\nCode:\n```text\nimport { IsNumber, IsPositive, IsString } from 'class-validator';\nexport class ApiDTO {\n    @IsString() public readonly FileName:string;\n    @IsNumber() @IsPositive() public readonly StatusCode:number;\n    @IsNumber() @IsPositive() public readonly TimeOut:number;\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport * as request from 'supertest';\n\nimport { INestApplication, ValidationPipe } from '@nestjs/common';\n\nimport { AppModule } from '@APP/app.module';\nimport { ApiDTO } from './../../src/api/api.dto';\n\ndescribe('ApiController (e2e)', () => {\n    let app: INestApplication;\n\n    beforeEach(async () => {\n        const moduleFixture: TestingModule = await Test.createTestingModule({\n            imports: [AppModule],\n        }).compile();\n\n        app = moduleFixture.createNestApplication();\n        app.useGlobalPipes(new ValidationPipe());\n        await app.init();\n    });\n\n    it('/api/test/ (POST) test to see data validation works', async done => {\n        const RequestBody:ApiDTO = {\n            FileName : 'README.md',\n            StatusCode: 111,\n            TimeOut: -25\n        };\n        const Expected:string = `${RequestBody.FileName} = ${RequestBody.StatusCode.toString()} after ${RequestBody.TimeOut.toString()}`;\n\n        const ResponseData = await request(app.getHttpServer())\n            .post('/api/test')\n            .send(RequestBody)\n            .set('Accept', 'application/json');\n\n        // All of these will fail as the code returns a 200 OK, as it does not do the validation (TimeOut -25 should fail IsPositive())\n        expect(ResponseData.status).toBe(400);\n        expect(ResponseData.headers['content-type']).toContain('application/json');\n\n        // This line caused the problem as body is an object\n        //expect(ResponseData.body.length).toBeGreaterThan(2);\n\n        expect(ResponseData.body.statusCode).toBe(400);\n        expect(ResponseData.body.message[0]).toBe('TimeOut must be a positive number');\n        expect(ResponseData.body.error).toBe('Bad Request');\n        done();         \n    });\n\n});\n```\n\n```text\nIsPositive()\n```\n\n```text\napp = moduleFixture.createNestApplication();\napp.useGlobalPipes(new ValidationPipe());   // <- This addition\nawait app.init();\n```\n\n```text\nit('/api/test/ (POST) test to see data validation works', async done => {\n    ...\n    expect(ResponseData.body.length).toBeGreaterThan(10);\n    ...\n    done();         \n});\n```\n\n```text\nit('/api/test/ (POST) test to see data validation works', async done => {\n    const RequestBody:ApiDTO = {\n        FileName : 'README.md',\n        StatusCode: 111,\n        TimeOut: -25\n    };\n    const Expected:string = `${RequestBody.FileName} = ${RequestBody.StatusCode.toString()} after ${RequestBody.TimeOut.toString()}`;\n\n    const ResponseData = await request(app.getHttpServer())\n        .post('/api/test')\n        .send(RequestBody)\n        .set('Accept', 'application/json');\n\n    expect(ResponseData.status).toBe(400);\n    expect(ResponseData.headers['content-type']).toContain('application/json');\n    \n    expect(ResponseData.body.statusCode).toBe(400);\n    expect(ResponseData.body.message[0]).toBe('TimeOut must be a positive number');\n    expect(ResponseData.body.error).toBe('Bad Request');\n    done();         \n});\n```\n\n```text\n.length\n```\n\n```text\n/node_modules\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- Cannot we get it to work with `ValidationPipe`s applied at the controller level and not global? Did you try that?\n- @MohammadJawadBarati My answer is quite old, March 2021. I did use a ValidationPipe, it was my code not working with the object, which I then corrected.\n- Don't think it will solve the problem for other folks","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":208,"estimatedTokens":1638}}572{"id":"stack-66442223","source":"stackoverflow","questionId":66442223,"title":"NestJS: Set @Param and body values to DTO in POST request","tags":["parameters","request","nestjs","dto"],"text":"Title: NestJS: Set @Param and body values to DTO in POST request\nTags: parameters, request, nestjs, dto\nSource: Stack Overflow\n\nQuestion:\nI have a POST request entry where I specify an \"account\" parameter as a path parameter, and a boolean in the body to set validation state, like:\n\n`POST /users/authorized/USER_ACCOUNT1`\n\nThe body would carry:\n\n```\nvalid=1\n```\n\nI have the following controller entry:\n\n```\n@ApiTags('users')\n @ApiOperation( { summary: 'Set user account status. '} )\n @Post('authorized/:account')\n async setAuthStatus(params: SetUserAuthDto) {\n return this.userService.setUserAuthDto(params);\n }\n```\n\nHow I can feed both the \"account\" and the request body \"status\" parameter to the same DTO? I assume I cannot use both decorators @Param and @Body there.\nShould I use pipes?\n\nI'm new in NestJS so excuse my ignorance.\n\nThanks.\n\n========================================\n\nCode:\n```text\nvalid=1\n```\n\n```text\n@ApiTags('users')\n    @ApiOperation( { summary: 'Set user account status.  '} )\n    @Post('authorized/:account')\n    async setAuthStatus(params: SetUserAuthDto) {\n        return this.userService.setUserAuthDto(params);\n    }\n```\n\n```text\nPOST /users/authorized/USER_ACCOUNT1\n```\n\n```js\n@Post('authorized/:account')\nasync setAuthStatus(@Param('account') accountValue: string, @Body() body: SetUserAuthDto) {\n  // do your thing here\n}\n```\n\n```text\n@Params()\n```\n\n```text\n@Body()\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nreq.params\n```\n\n```text\nreq.body\n```\n\n```text\n@ParamAndBody()\n```\n\n========================================\n\nComments:\n- Thank you! I'm still thinking where DTOs are useful and where they are a little excess.","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":88,"estimatedTokens":414}}573{"id":"stack-70284761","source":"stackoverflow","questionId":70284761,"title":"UnauthorizedException is deliver as Internal Server Error","tags":["nestjs","nestjs-passport","nestjs-jwt"],"text":"Title: UnauthorizedException is deliver as Internal Server Error\nTags: nestjs, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI'm trying a create a shared Guard as an external library in order to be imported and used across services. I'm not doing anything special that what is described in some guides but with the particularity that the code will reside in a shared library. Everything is working but the Exception to return a 401 error.\n\nMy guard looks something like this:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class MainGuard extends AuthGuard('jwt') {}\n```\n\nNothing else. If I use that in a service folder it works, but at the time that I move as in their own library, the response changes.\n\nThe way that I'm using in the service has nothing special:\n\n```\nimport { MainGuard } from 'shared-guard-library';\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { SomeService } from './some.service';\n\n@Controller()\nexport class SomeController {\n constructor(private someService: SomeService) {}\n\n @Get('/foo')\n @UseGuards(MainGuard)\n async getSomething(): Promise {\n return this.someService.getSomething();\n }\n}\n```\n\nThe client receives an error 500:\n\n```\nhttp :3010/foo\nHTTP/1.1 500 Internal Server Error\nConnection: keep-alive\nContent-Length: 52\nContent-Type: application/json; charset=utf-8\nDate: Thu, 09 Dec 2021 04:11:42 GMT\nETag: W/\"34-rlKccw1E+/fV8niQk4oFitDfPro\"\nKeep-Alive: timeout=5\nVary: Origin\nX-Powered-By: Express\n\n{\n \"message\": \"Internal server error\",\n \"statusCode\": 500\n}\n```\n\nAnd in the logs shows:\n\n```\n[Nest] 93664 - 12/08/2021, 10:11:42 PM ERROR [ExceptionsHandler] Unauthorized\nUnauthorizedException: Unauthorized\n at MainGuard.handleRequest (/sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:68:30)\n at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:49:128\n at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:86:24\n at allFailed (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:101:18)\n at attempt (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:174:28)\n at Object.strategy.fail (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:296:9)\n at Object.JwtStrategy.authenticate (/sharedGuardLibrary/node_modules/passport-jwt/lib/strategy.js:96:21)\n at attempt (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:360:16)\n at authenticate (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:361:7)\n at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:91:3\n```\n\nThe logs are telling me that the correct exception was thrown, but is ignored at some point and I don't know the reason. Again: the same code in the same project works.\n\nI took a look at the original class and I don't see any particular way to treat the exception\n\nAny clue or guide it will appreciate.\n\n========================================\n\nTop Answer:\nI had a similar problem with a custom auth package inside a monorepo.\n\nMy auth-library exposed AuthModule, JwtAuthGuard, and some utility functions. All needed packages were installed under my library so any other projects that were using it had not installed other versions of dependencies. Unfortunately using a custom guard caused Internal Server Error.\n\nI've solved this issue by adding a global custom exception filter. It looks for a workaround but at least solves this issue.\n\nThis filter is exported from auth-library, so `UnauthorizedException` indicates on the same object as AuthGuard.\n\n```\nimport { ArgumentsHost, Catch, ExceptionFilter, UnauthorizedException } from '@nestjs/common';\nimport { Response } from 'express'\n\n@Catch(UnauthorizedException)\nexport class UnauthorizedExceptionFilter implements ExceptionFilter {\n public catch(exception: UnauthorizedException, host: ArgumentsHost): Response {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n\n return response.status(401).json({ statusCode: 401 });\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class MainGuard extends AuthGuard('jwt') {}\n```\n\n```js\nimport { MainGuard } from 'shared-guard-library';\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { SomeService } from './some.service';\n\n@Controller()\nexport class SomeController {\n  constructor(private someService: SomeService) {}\n\n  @Get('/foo')\n  @UseGuards(MainGuard)\n  async getSomething(): Promise<any> {\n    return this.someService.getSomething();\n  }\n}\n```\n\n```text\nhttp :3010/foo\nHTTP/1.1 500 Internal Server Error\nConnection: keep-alive\nContent-Length: 52\nContent-Type: application/json; charset=utf-8\nDate: Thu, 09 Dec 2021 04:11:42 GMT\nETag: W/\"34-rlKccw1E+/fV8niQk4oFitDfPro\"\nKeep-Alive: timeout=5\nVary: Origin\nX-Powered-By: Express\n\n{\n    \"message\": \"Internal server error\",\n    \"statusCode\": 500\n}\n```\n\n```text\n[Nest] 93664  - 12/08/2021, 10:11:42 PM   ERROR [ExceptionsHandler] Unauthorized\nUnauthorizedException: Unauthorized\n    at MainGuard.handleRequest (/sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:68:30)\n    at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:49:128\n    at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:86:24\n    at allFailed (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:101:18)\n    at attempt (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:174:28)\n    at Object.strategy.fail (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:296:9)\n    at Object.JwtStrategy.authenticate (/sharedGuardLibrary/node_modules/passport-jwt/lib/strategy.js:96:21)\n    at attempt (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:360:16)\n    at authenticate (/sharedGuardLibrary/node_modules/passport/lib/middleware/authenticate.js:361:7)\n    at /sharedGuardLibrary/node_modules/@nestjs/passport/dist/auth.guard.js:91:3\n```\n\n```text\nBaseExceptionFilter\n```\n\n```text\nexception instanceof HttpException\n```\n\n```text\nUnauthorizedException\n```\n\n```text\npeerDependencies\n```\n\n```text\n@nestjs/*\n```\n\n```text\n{  hello: 'world' } === { hello: 'world' } // false\n```\n\n```text\nnpm/yarn/pnpm link\n```\n\n```text\ndist\n```\n\n```text\npackage.json\n```\n\n```text\nnode_modules/<package_name>\n```\n\n```js\nimport { ArgumentsHost, Catch, ExceptionFilter, UnauthorizedException } from '@nestjs/common';\nimport { Response } from 'express'\n\n@Catch(UnauthorizedException)\nexport class UnauthorizedExceptionFilter implements ExceptionFilter {\n  public catch(exception: UnauthorizedException, host: ArgumentsHost): Response {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n\n    return response.status(401).json({ statusCode: 401 });\n  }\n}\n```\n\n```text\nUnauthorizedException\n```\n\n```text\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n      \n  handleRequest(err, user, info) {\n    // You can throw an exception based on either \"info\" or \"err\" arguments\n    if (err || !user) {\n      throw err || new UnauthorizedException();\n    }\n    return user;\n  }\n\n}\n```\n\n```text\nhandleRequest(err, user, info)\n```\n\n```js\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  canActivate(context: ExecutionContext) {\n    // Add your custom authentication logic here\n    // for example, call super.logIn(request) to establish a session.\n    return super.canActivate(context);\n  }\n\n  handleRequest(err: unknown, user: any, info: unknown) {\n    // You can throw an exception based on either \"info\" or \"err\" arguments\n    if (err || !user) {\n      throw err || new MyException();\n    }\n    return user;\n  }\n}\n\n\nclass MyException extends UnauthorizedException {\n  statusCode = 401\n  constructor() {\n    super()\n  }\n}\n```\n\n========================================\n\nComments:\n- if the same code in the same project works, try `rm -rf node_modules` and install it again (without touching the lock file)\n- Already tried that and similar related things like cleaning npm cache with the service and the library; Same result\n- I would never have come up with the explanation without your help. Thank you so much!\n- How did you solve this? I have the same problem, I have a Rust monorepo with a pnpm, after updating nestjs to 8.2.0 it responds with 500 error instead of 401. Any suggestion?\n- Why is this answer being accepterd if does not answer the question?\n- @GabrielLlamas But it does answer the question. The `UnauthorizedExcepotion` is being treated as an `Internal Server Error` because the `instanceof HttpException` check is failing due to how JavaScript treats object equality.\n- Using \"chokidar\" and \"fs-extra\", I was able to fix the issue and replicate the \"npm link\" developer experience. Thanks!\n- Where should I place this global custom exception filter?","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":284,"estimatedTokens":2256}}574{"id":"stack-74652818","source":"stackoverflow","questionId":74652818,"title":"Nestjs swagger array of strings with one parameter","tags":["swagger","nestjs","swagger-ui"],"text":"Title: Nestjs swagger array of strings with one parameter\nTags: swagger, nestjs, swagger-ui\nSource: Stack Overflow\n\nQuestion:\nWhen I send only one parameter, I got query result like string, not like string[]. This happened only from UI swagger, if I send from Postman - it works good.\n\nI just want send from swagger-ui one parameter and got array of strings, not a single string.\n\nHow I can fix it? Help me please.\n\nExample1: send one parameter and in my controller I got string like '25'\n\nExample2: when I send 2 parameters in controller I can see array of strings ('25', '21')\n\n```\nexport class List {\n @ApiProperty({ isArray: true, type: String, required: false })\n @IsOptional()\n public categories?: string[];\n}\n```\n\n========================================\n\nTop Answer:\nYou should try to spread your parameter in a const in services\nedit:\n\nI don't know how to explain in formal words, but a array of strings of one item, for JAVASCRIPT, seems with the same thing as one string value.\n\nBecause array is not a type, but a form of a type....\n\nSo, if you, in your controller, before do anything with it, you redeclare as:\n\n```\n@Get(\":id\")\n findManybyId(@Param(\"id\") id: string[]) {\n const idArray = [...id];\n return await this.service.findManyById(idArray);\n }\n```\n\nIt will solve your problem about being an array\n\nold answer:\n\nYou should try to change in your controller where you make your input decorator.\n\nin your case, i don't know if you are using ID to get, but you must to do as the example:\n\n```\n@ApiOperation({\n summary: \"Get many categories by ID\",\n })\n async getMany(\n @Param(\"id\") ids: string[],\n ) {\n return await this.categoriesService.getMany(id);\n }\n```\n\n========================================\n\nCode:\n```text\nexport class List {\n  @ApiProperty({ isArray: true, type: String, required: false })\n  @IsOptional()\n  public categories?: string[];\n}\n```\n\n```text\n@Transform(({ value }) => (Array.isArray(value) ? value : Array(value)))\n```\n\n```text\n@Get(\":id\")\n    findManybyId(@Param(\"id\") id: string[]) {\n        const idArray = [...id];\n        return await this.service.findManyById(idArray);\n    }\n```\n\n```text\n@ApiOperation({\n       summary: \"Get many categories by ID\",\n   })\n   async getMany(\n       @Param(\"id\") ids: string[],\n   ) {\n       return await this.categoriesService.getMany(id);\n   }\n```\n\n```text\nexport function ToArray(): (target: any, key: string) => void {\n    return Transform((params: TransformFnParams) => {\n          const { value } = params;\n\n          if (Array.isArray(value)) {\n              return value;\n           }\n\n          if (typeof value === 'string') {\n              return value.split(',').map(item => item.trim());\n          }\n       \n          return [];\n         });\n      }\n```\n\n```text\n@ApiProperty({ description: 'List of category IDs', example: ['47b32970-4997-4364-91b6-4b5533941307', '620b7c84-6d63-492e-8abb-7606e04a375c'], required: false })\n    @ToArray()\n    @IsArray()\n    categories?: string[];\n```\n\n========================================\n\nComments:\n- Have you tried using the type like this `@ApiProperty({ type: [String] })`?\n- @Farista Latuconsina I just tried, but got the same result. `@ApiProperty({ type: [String] })` `@ApiProperty({ type: () => [String] })` `@ApiProperty({ type: () => [String], isArray: true })`\n- can you write an example or explain more please?\n- I don't want write some logic in controller. Thanks\n- If you do [,,,id] where id is a string and not an array (E.g. \"hello\"), you'll get the value of the string split ([\"h\",\"e\",\"l\",\"l\",\"o\"])\n- As I understood swagger library can't fix that, so your answer good for me. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":130,"estimatedTokens":907}}575{"id":"stack-71880907","source":"stackoverflow","questionId":71880907,"title":"MongoDB transaction with @NestJs/mongoose not working","tags":["mongodb","mongoose","nestjs"],"text":"Title: MongoDB transaction with @NestJs/mongoose not working\nTags: mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI really need your help. My MongoDB transaction with @NestJs/mongoose not working...When My stripe payment fails rollback is not working... Still, my order collection saved the data...How can I fix this issue..?\n\n```\nasync create(orderData: CreateOrderServiceDto): Promise {\n const session = await this.connection.startSession();\n session.startTransaction();\n try {\n const createOrder = new this.orderModel(orderData);\n const order = await createOrder.save();\n\n await this.stripeService.charge(\n orderData.amount,\n orderData.paymentMethodId,\n orderData.stripeCustomerId,\n );\n await session.commitTransaction();\n return order;\n } catch (error) {\n await session.abortTransaction();\n throw error;\n } finally {\n await session.endSession();\n }\n }\n```\n\n========================================\n\nCode:\n```text\nasync create(orderData: CreateOrderServiceDto): Promise<any> {\n    const session = await this.connection.startSession();\n    session.startTransaction();\n    try {\n      const createOrder = new this.orderModel(orderData);\n      const order = await createOrder.save();\n\n      await this.stripeService.charge(\n        orderData.amount,\n        orderData.paymentMethodId,\n        orderData.stripeCustomerId,\n      );\n      await session.commitTransaction();\n      return order;\n    } catch (error) {\n      await session.abortTransaction();\n      throw error;\n    } finally {\n      await session.endSession();\n    }\n  }\n```\n\n```text\nconst order = await this.orderModel.create(orderData, { session });\n```\n\n```text\ncreate(docs: (AnyKeys<T> | AnyObject)[], options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;\n```\n\n```text\ninterface SaveOptions {\n  checkKeys?: boolean;\n  j?: boolean;\n  safe?: boolean | WriteConcern;\n  session?: ClientSession | null;\n  timestamps?: boolean;\n  validateBeforeSave?: boolean;\n  validateModifiedOnly?: boolean;\n  w?: number | string;\n  wtimeout?: number;\n}\n```\n\n```text\nconst createOrder = new this.orderModel(orderData);\nconst order = await createOrder.save({ session });\n```\n\n```text\nimport { InternalServerErrorException } from \"@nestjs/common\"\nimport { Connection, ClientSession } from \"mongoose\"\n\nexport const mongooseTransactionHandler = async <T = any>(\n  method: (session: ClientSession) => Promise<T>,\n  onError: (error: any) => any,\n  connection: Connection, session?: ClientSession\n): Promise<T> => {\n  const isSessionFurnished = session === undefined ? false : true\n  if (isSessionFurnished === false) {\n    session = await connection.startSession()\n    session.startTransaction()\n  }\n\n  let error\n  let result: T\n  try {\n    result = await method(session)\n\n    if (isSessionFurnished === false) {\n      await session.commitTransaction()\n    }\n  } catch (err) {\n    error = err\n    if (isSessionFurnished === false) {\n      await session.abortTransaction()\n    }\n  } finally {\n    if (isSessionFurnished === false) {\n      await session.endSession()\n    }\n\n    if (error) {\n      onError(error)\n    }\n\n    return result\n  }\n}\n```\n\n```text\n/** UserService **/\nasync deleteById(id: string): Promise<void> {\n  const transactionHandlerMethod = async (session: ClientSession): Promise<void> => {\n    const user = await this.userModel.findOneAndDelete(id, { session })\n    await this.fileService.deleteById(user.avatar._id.toString(), session)\n  }\n\n  const onError = (error: any) => {\n    throw error\n  }\n\n  await mongooseTransactionHandler<void>(\n    transactionHandlerMethod,\n    onError,\n    this.connection\n  )\n}\n\n/** FileService **/\nasync deleteById(id: string, session?: ClientSession): Promise<void> {\n  const transactionHandlerMethod = async (session: ClientSession): Promise<void> => {\n    await this.fileModel.findOneAndRemove(id, { session })\n  }\n\n  const onError = (error: any) => {\n    throw error\n  }\n\n  await mongooseTransactionHandler<void>(\n    transactionHandlerMethod,\n    onError,\n    this.connection,\n    session\n  )\n}\n```\n\n```text\nasync create(orderData: CreateOrderServiceDto): Promise<any> {\n  const transactionHandlerMethod = async (session: ClientSession): Promise<Order> => {\n    const createOrder = new this.orderModel(orderData);\n    const order = await createOrder.save({ session });\n\n    await this.stripeService.charge(\n      orderData.amount,\n      orderData.paymentMethodId,\n      orderData.stripeCustomerId,\n    );\n\n    return order\n  }\n\n  const onError = (error: any): void => {\n    throw error\n  }\n\n  const order = await mongooseTransactionHandler<Order>(\n    transactionHandlerMethod,\n    onError,\n    this.connection\n  )\n\n  return order\n}\n```\n\n```text\ncreate\n```\n\n```text\nModel.create\n```\n\n```text\nSaveOptions\n```\n\n```text\nSaveOptions\n```\n\n```text\nModel.save()\n```\n\n```text\nSaveOptions\n```\n\n```text\nsession\n```\n\n```text\nUser\n```\n\n```text\nFile\n```\n\n```text\nmodel.save({ session })\n```\n\n```text\nmodel.findOneAndUpdate\n```\n\n========================================\n\nComments:\n- Best explanation I ever had... Thank you.โค๏ธ๐Ÿ˜Š Thank you very much for your time... This really helped me.โค๏ธ\n- I'm glad i could help you ! Have fun with NestJS ๐Ÿ˜Ž\n- This was explanatory and wild to read <3","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":244,"estimatedTokens":1304}}576{"id":"stack-64185541","source":"stackoverflow","questionId":64185541,"title":"How to use ConfigService in Nestjs DatabaseModule","tags":["nestjs","typeorm","nestjs-config"],"text":"Title: How to use ConfigService in Nestjs DatabaseModule\nTags: nestjs, typeorm, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI have created a DatabaseModule using the nestjs typeorm\n\n```\nimport { createConnection } from 'typeorm';\nimport { ConfigService } from '@nestjs/config';\n\nexport const databaseConnection = [\n {\n provide: 'DATABASE_CONNECTION',\n useFactory: async (configService: ConfigService) => await createConnection({\n type: configService.get('DBTYPE'),\n host: configService.get('DBHOST'),\n port: configService.get('DBPORT'),\n username: configService.get('DBUSERNAME'),\n password: configService.get('DBPASSWORD'),\n database: configService.get('DBNAME'),\n synchronize: true,\n entities: [\n __dirname + '/../**/*.entity.ts'\n ]\n })\n }\n];\n```\n\nWhile starting the rest service I am getting the following error\n\n```\nCannot read property 'get' of undefined - {\"stack\":[\"TypeError: Cannot read property 'get' of undefined\n\n at InstanceWrapper.useFactory [as metatype] (../database/database.provider.js:9:33)\n at Injector.instantiateClass (../node_modules/@nestjs/core/injector/injector.js:293:55)\n at callback (../node_modules/@nestjs/core/injector/injector.js:77:41)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n at startup (internal/bootstrap/node.js:283:19)\n at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\"]}\n```\n\nI have imported the `ConfigModule` inside `DatabaseModule`.\n\nCan someone help me out with this?\n\n**EDIT**\n\nMy database config\n\n```\nimport { registerAs } from '@nestjs/config';\n\n// Configuration factory class for database configuration.\nconst DatabaseConfig = registerAs('DBConfig', () => ({\n DBTYPE: process.env.DATABASE_TYPE,\n DBHOST: process.env.DATABASE_HOST || 'localhost',\n DBPORT: process.env.DATABASE_PORT || 5432,\n DBUSERNAME: process.env.DATABASE_USERNAME,\n DBPASSWORD: process.env.DATABASE_PASSWORD,\n DBNAME: process.env.DATABASE_NAME\n}));\n```\n\nIn app.module.ts imports\n\n```\nConfigModule.forRoot({\n isGlobal: true,\n expandVariables: true,\n load: [AppConfig, DatabaseConfig]\n}),\n```\n\n========================================\n\nCode:\n```text\nimport { createConnection } from 'typeorm';\nimport { ConfigService } from '@nestjs/config';\n\n\nexport const databaseConnection = [\n    {\n        provide: 'DATABASE_CONNECTION',\n        useFactory: async (configService: ConfigService) => await createConnection({\n            type: configService.get('DBTYPE'),\n            host: configService.get('DBHOST'),\n            port: configService.get('DBPORT'),\n            username: configService.get('DBUSERNAME'),\n            password: configService.get('DBPASSWORD'),\n            database: configService.get('DBNAME'),\n            synchronize: true,\n            entities: [\n                __dirname + '/../**/*.entity.ts'\n            ]\n        })\n    }\n];\n```\n\n```text\nCannot read property 'get' of undefined - {\"stack\":[\"TypeError: Cannot read property 'get' of undefined\n\n    at InstanceWrapper.useFactory [as metatype] (../database/database.provider.js:9:33)\n    at Injector.instantiateClass (../node_modules/@nestjs/core/injector/injector.js:293:55)\n    at callback (../node_modules/@nestjs/core/injector/injector.js:77:41)\n    at process._tickCallback (internal/process/next_tick.js:68:7)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n    at startup (internal/bootstrap/node.js:283:19)\n    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\"]}\n```\n\n```text\nimport { registerAs } from '@nestjs/config';\n\n// Configuration factory class for database configuration.\nconst DatabaseConfig = registerAs('DBConfig', () => ({\n    DBTYPE: process.env.DATABASE_TYPE,\n    DBHOST: process.env.DATABASE_HOST || 'localhost',\n    DBPORT: process.env.DATABASE_PORT || 5432,\n    DBUSERNAME: process.env.DATABASE_USERNAME,\n    DBPASSWORD: process.env.DATABASE_PASSWORD,\n    DBNAME: process.env.DATABASE_NAME\n}));\n```\n\n```text\nConfigModule.forRoot({\n        isGlobal: true,\n        expandVariables: true,\n        load: [AppConfig, DatabaseConfig]\n}),\n```\n\n```text\nConfigModule\n```\n\n```text\nDatabaseModule\n```\n\n```js\nexport const databaseConnection = [\n    {\n        provide: 'DATABASE_CONNECTION',\n        inject: [ConfigService],\n        useFactory: async (configService: ConfigService) => await createConnection({\n            type: configService.get('DBConfig.DBTYPE'),\n            host: configService.get('DBConfig.DBHOST'),\n            port: configService.get('DBConfig.DBPORT'),\n            username: configService.get('DBConfig.DBUSERNAME'),\n            password: configService.get('DBConfig.DBPASSWORD'),\n            database: configService.get('DBConfig.DBNAME'),\n            synchronize: true,\n            entities: [\n                __dirname + '/../**/*.entity.ts'\n            ]\n        })\n    }\n];\n```\n\n```text\nConfigService\n```\n\n```text\ninject\n```\n\n```text\nDBConfig.DBTYPE\n```\n\n```text\nConfigService\n```\n\n```text\ninject: [ConfigService]\n```\n\n```text\nimports: [ConfigModule]\n```\n\n========================================\n\nComments:\n- The config service does come from the global module. After adding `inject` the `configService.get('DBTYPE')` returns `undefined`\n- Well, how is the `ConfigModule` registered? Do you have `DBTYPE` in a `.env` file? You can see the `ConfigService` is working as expected\n- I have updated my question. I have invoked the `AppConfig` inside main.ts and it works\n- You're using a config namesapce. You need to do `configService.get(namespace.value)`. In this case `configService.get('DBConfig.DBTYPE')`","metadata":{"transformedAt":"2026-08-18T18:33:02.453Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":197,"estimatedTokens":1394}}577{"id":"stack-70563784","source":"stackoverflow","questionId":70563784,"title":"Mocking Bull queues in NestJS","tags":["testing","mocking","nestjs","bullmq"],"text":"Title: Mocking Bull queues in NestJS\nTags: testing, mocking, nestjs, bullmq\nSource: Stack Overflow\n\nQuestion:\nI am trying to test that after sending a request to one of my controllers, the queue pushes a job. The implementation itself works as expected.\n\nThis is my **app.module.ts**\n\n```\n@Module({\n imports: [\n HttpModule,\n TypeOrmModule.forRoot(typeOrmConfig),\n BullModule.forRoot({\n redis: {\n host: redisConfig.host,\n port: redisConfig.port,\n },\n }),\n // Bunch of unrelated modules\n ],\n providers: [\n {\n provide: APP_FILTER,\n useClass: AllExceptionsFilter,\n },\n ],\n controllers: [SomeControllers],\n })\n export class AppModule {}\n```\n\nAnd this is how my **import.module.ts** (module using queues) looks like:\n\n```\n@Module({\n imports: [\n BullModule.registerQueue({\n name: importQueueName.value,\n }),\n //More unrelated modules,\n ],\n providers: [\n //More services, and bull consumer and producer,\n ImportDataProducer,\n ImportDataConsumer,\n ImportDataService,\n ],\n controllers: [ImportDataController],\n })\n export class ImportDataModule {}\n```\n\nI tried to this approach\n\nWhich does not register the queue in the beforeAll hook, and I'm getting\n\n```\nDriver not Connected\n```\n\nAnd this approach\n\nWhich registers a queue in the beforeAll hook in the test suite, and I am getting:\n\n```\nTypeError: Cannot read properties of undefined (reading 'call')\n \n at BullExplorer.handleProcessor (node_modules/@nestjs/bull/dist/bull.explorer.js:95:23)\n at MapIterator.iteratee (node_modules/@nestjs/bull/dist/bull.explorer.js:59:26)\n at MapIterator.next (node_modules/iterare/src/map.ts:9:39)\n at FilterIterator.next (node_modules/iterare/src/filter.ts:11:34)\n at IteratorWithOperators.next (node_modules/iterare/src/iterate.ts:19:28)\n at Function.from ()\n at IteratorWithOperators.toArray (node_modules/iterare/src/iterate.ts:227:22)\n at MetadataScanner.scanFromPrototype (node_modules/@nestjs/core/metadata-scanner.js:12:14)\n at node_modules/@nestjs/bull/dist/bull.explorer.js:56:34\n at Array.forEach ()\n```\n\nThis is my 'base test suite':\n\n```\ndescribe('Queue test suite', () => {\n let app: INestApplication;\n const importQueue: any = { add: jest.fn() };\n beforeAll(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule, ImportDataModule],\n })\n .overrideProvider(importQueueName.value)\n .useValue(importQueue)\n .compile();\n \n app = moduleFixture.createNestApplication();\n app.useGlobalPipes(\n new ValidationPipe({\n transform: true,\n whitelist: true,\n forbidNonWhitelisted: true,\n }),\n );\n await app.init();\n });\n \n afterAll(async () => {\n \n await app.close();\n \n });\n \n test('A job should be pushed', async () => {\n await request(app.getHttpServer())\n .post('/some/route')\n .attach('file', __dirname + '/some.file')\n .expect(HttpStatus.CREATED);\n \n \n expect(importQueue.add).toHaveBeenCalled();\n });\n });\n```\n\nAny idea what could be wrong here?\n\n========================================\n\nTop Answer:\nI found a simple way to deep mock a class or an interface using `createMock` function from the package `@golevelup/ts-jest`, which works well with NestJS dependency injection.\n\n```\nlet someController: SomeController;\n let someService: DeepMocked;\n\n beforeEach(async () => {\n const moduleRef = await Test.createTestingModule({\n imports: [SomeModule],\n controllers: [SomeController],\n providers: [\n {\n provide: SomeService,\n useValue: createMock(),\n },\n { provide: getConnectionToken(), useValue: createMock() },\n { provide: getQueueToken('queueName'), useValue: createMock() },\n ],\n }).compile();\n\n someController = moduleRef.get(SomeController);\n someService = moduleRef.get(SomeService);\n });\n```\n\n========================================\n\nCode:\n```js\n@Module({\n        imports: [\n        HttpModule,\n        TypeOrmModule.forRoot(typeOrmConfig),\n        BullModule.forRoot({\n          redis: {\n            host: redisConfig.host,\n            port: redisConfig.port,\n          },\n        }),\n        // Bunch of unrelated modules\n         ],\n         providers: [\n        {\n          provide: APP_FILTER,\n          useClass: AllExceptionsFilter,\n        },\n        ],\n         controllers: [SomeControllers],\n        })\n        export class AppModule {}\n```\n\n```js\n@Module({\n      imports: [\n        BullModule.registerQueue({\n          name: importQueueName.value,\n        }),\n       //More unrelated modules,\n      ],\n      providers: [\n        //More services, and bull consumer and producer,\n        ImportDataProducer,\n        ImportDataConsumer,\n        ImportDataService,\n      ],\n      controllers: [ImportDataController],\n    })\n    export class ImportDataModule {}\n```\n\n```text\nDriver not Connected\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'call')\n    \n          at BullExplorer.handleProcessor (node_modules/@nestjs/bull/dist/bull.explorer.js:95:23)\n          at MapIterator.iteratee (node_modules/@nestjs/bull/dist/bull.explorer.js:59:26)\n          at MapIterator.next (node_modules/iterare/src/map.ts:9:39)\n          at FilterIterator.next (node_modules/iterare/src/filter.ts:11:34)\n          at IteratorWithOperators.next (node_modules/iterare/src/iterate.ts:19:28)\n              at Function.from (<anonymous>)\n          at IteratorWithOperators.toArray (node_modules/iterare/src/iterate.ts:227:22)\n          at MetadataScanner.scanFromPrototype (node_modules/@nestjs/core/metadata-scanner.js:12:14)\n          at node_modules/@nestjs/bull/dist/bull.explorer.js:56:34\n              at Array.forEach (<anonymous>)\n```\n\n```js\ndescribe('Queue test suite', () => {\n      let app: INestApplication;\n      const importQueue: any = { add: jest.fn() };\n      beforeAll(async () => {\n        const moduleFixture: TestingModule = await Test.createTestingModule({\n          imports: [AppModule, ImportDataModule],\n        })\n          .overrideProvider(importQueueName.value)\n          .useValue(importQueue)\n          .compile();\n    \n        app = moduleFixture.createNestApplication();\n        app.useGlobalPipes(\n          new ValidationPipe({\n            transform: true,\n            whitelist: true,\n            forbidNonWhitelisted: true,\n          }),\n        );\n        await app.init();\n      });\n    \n      afterAll(async () => {\n       \n        await app.close();\n     \n      });\n    \n      test('A job should be pushed', async () => {\n        await request(app.getHttpServer())\n          .post('/some/route')\n          .attach('file', __dirname + '/some.file')\n          .expect(HttpStatus.CREATED);\n       \n    \n        expect(importQueue.add).toHaveBeenCalled();\n      });\n    });\n```\n\n```text\nconst importQueue: any = { \n  add: jest.fn(),\n  process: jest.fn(),\n};\n```\n\n```text\nexpect(mockQueue.add).toBeCalledTimes(1);\n      expect(mockQueue.add).nthCalledWith(\n        1,\n        PendoJobNames.SCR,\n        {\n          ...mockJobDto,\n        },\n        {\n          jobId: mockDto.visitorId,\n          removeOnComplete: true,\n          removeOnFail: true,\n        },\n      );\n    ```\n```\n\n```text\nmockQueue\n```\n\n```text\nprocess\n```\n\n```js\nconst queueMock = {\n  add: jest.fn(),\n  process: jest.fn(),\n  on: jest.fn()\n};\n```\n\n```text\non\n```\n\n```js\nlet someController: SomeController;\n  let someService: DeepMocked<SomeService>;\n\n  beforeEach(async () => {\n    const moduleRef = await Test.createTestingModule({\n      imports: [SomeModule],\n      controllers: [SomeController],\n      providers: [\n        {\n          provide: SomeService,\n          useValue: createMock<SomeService>(),\n        },\n        { provide: getConnectionToken(), useValue: createMock<Connection>() },\n        { provide: getQueueToken('queueName'), useValue: createMock<Queue>() },\n      ],\n    }).compile();\n\n    someController = moduleRef.get<SomeController>(SomeController);\n    someService = moduleRef.get(SomeService);\n  });\n```\n\n```text\ncreateMock\n```\n\n```text\n@golevelup/ts-jest\n```\n\n```text\nimport { createMock } from \"@golevelup/ts-jest\";\nimport { getQueueOptionsToken, getQueueToken } from \"@nestjs/bullmq\";\nimport { Test } from \"@nestjs/testing\";\nimport { Queue, QueueOptions } from \"bullmq\";\n\ndescribe(\"SomeModule\", () => {\n  let module: SomeModule;\n\n  beforeEach(async () => {\n    const testingModule = await Test.createTestingModule({\n      imports: [\n        /* ... */\n      ],\n    })\n      .overrideProvider(getQueueOptionsToken())\n      .useValue(createMock<QueueOptions>())\n      .overrideProvider(getQueueToken(\"yourQueueName\"))\n      .useValue(createMock<Queue>())\n      .compile();\n\n    module = testingModule.get(SomeModule);\n  });\n\n  it(\"can be instantiated by Nest\", () => {\n    expect(module).toBeDefined();\n  });\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.454Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":364,"estimatedTokens":2150}}578{"id":"stack-61835295","source":"stackoverflow","questionId":61835295,"title":"How to add multiple Nestjs RoleGuards in controllers","tags":["angular","typescript","nestjs","roles","guard"],"text":"Title: How to add multiple Nestjs RoleGuards in controllers\nTags: angular, typescript, nestjs, roles, guard\nSource: Stack Overflow\n\nQuestion:\nI have role guard for ADMIN, SUPERADMIN, USER, MODERATORS,\n\nThis is an example of one of the guards. An Admin guard in the case. They are working as I expected but I can't add multiple guards in the controller\n\n```\nimportย {ย Injectable,ย CanActivate,ย ExecutionContext,ย HttpException,ย HttpStatusย }ย from '@nestjs/common';\n\n@/Injectable()\nexport class AdminGuard implements CanActivateย {\n constructor()ย {ย }\n\n canActivate(context:ย ExecutionContext)ย {\n const requestย =ย context.switchToHttp().getRequest();\n const userย =ย request.user;\n\n ifย (user.usertypeย ==ย 'Admin')ย {\n return true;\nย ย ย ย ย ย ย ย }\n throw new HttpException('Unauthorizedย access',ย HttpStatus.BAD_REQUEST);\nย ย ย ย }\n}\n```\n\nin my controllers, I have this decorator\n\n```\n@UseGuards(AuthGuard('jwt'),ย AdminGuard)\n```\n\nI want to be able to do something like this\n\n```\n@UseGuards(AuthGuard('jwt'),ย AdminGuard, SuperAdminGuard)\n```\n\nor\n\n```\n@UseGuards(AuthGuard('jwt'), [AdminGuard, SuperAdminGuard, UserGuard])\n```\n\nor\n\n```\n@UseGuards(AuthGuard('jwt'), AdminGuard || SuperAdminGuard || UserGuard])\n```\n\nNone of the above implementations worked. Is there a better way to go about it? Maybe there is something I am not doing right. I have checked the docs but I can't seem to make it work\n\n========================================\n\nTop Answer:\nAnother approach rather than what Kim has answered is to use `Mixin`. The mixin concept is used by the `AuthGuard` itself.\n\n```\nexport const UserTypeGuard: (...types: string[]) => CanActivate = createUserTypeGuard;\n\nfunction createUserTypeGuard(...types: string[]) {\n class MixinUserTypeGuard implements CanActivate {\n canActivate(context: ExecutionContext) {\n const user = context.switchToHttp().getRequest().user;\n return types.some(type => user.userType === type);\n }\n }\n}\n```\n\nUsage:\n\n```\n@UseGuards(AuthGuard('jwt'), UserTypeGuard('SuperAdmin', 'Admin'))\n```\n\n========================================\n\nCode:\n```text\nimportย {ย Injectable,ย CanActivate,ย ExecutionContext,ย HttpException,ย HttpStatusย }ย from '@nestjs/common';\n\n@/Injectable()\nexport class AdminGuard implements CanActivateย {\n constructor()ย {ย }\n\n canActivate(context:ย ExecutionContext)ย {\n const requestย =ย context.switchToHttp().getRequest();\n const userย =ย request.user;\n\n ifย (user.usertypeย ==ย 'Admin')ย {\n return true;\nย ย ย ย ย ย ย ย }\n throw new HttpException('Unauthorizedย access',ย HttpStatus.BAD_REQUEST);\nย ย ย ย }\n}\n```\n\n```text\n@UseGuards(AuthGuard('jwt'),ย AdminGuard)\n```\n\n```text\n@UseGuards(AuthGuard('jwt'),ย AdminGuard, SuperAdminGuard)\n```\n\n```text\n@UseGuards(AuthGuard('jwt'), [AdminGuard, SuperAdminGuard, UserGuard])\n```\n\n```text\n@UseGuards(AuthGuard('jwt'), AdminGuard || SuperAdminGuard || UserGuard])\n```\n\n```text\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const roles = this.reflector.get<string[]>('roles', context.getHandler());\n    if (!roles) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const userType = request.user.userType;\n    return roles.some(r => r === userType);\n\n  }\n}\n```\n\n```text\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n```\n\n```text\n// For this route you need either Superadmin or Admin privileges\n@Roles('Superadmin', 'Admin')\n@UseGuards(AuthGuard('jwt'), RolesGuard)\n```\n\n```text\nRolesGuard\n```\n\n```js\nexport const UserTypeGuard: (...types: string[]) => CanActivate = createUserTypeGuard;\n\nfunction createUserTypeGuard(...types: string[]) {\n    class MixinUserTypeGuard implements CanActivate {\n        canActivate(context: ExecutionContext) {\n            const user = context.switchToHttp().getRequest().user;\n            return types.some(type => user.userType === type);\n        }\n    }\n}\n```\n\n```js\n@UseGuards(AuthGuard('jwt'), UserTypeGuard('SuperAdmin', 'Admin'))\n```\n\n```text\nMixin\n```\n\n```text\nAuthGuard\n```\n\n========================================\n\nComments:\n- In `@UseGuards(A, B, C)`, if `A` returns false, it won't go to `B`. So in order to proceed, all must return true. You may want to handle like this: `if (user.usertype === 'Admin' || user.usertype) { return true }` so the next guard can be invoked.\n- Your suggestion worked. I tried it out. But I will go for @kim-kern","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":178,"estimatedTokens":1103}}579{"id":"stack-61840299","source":"stackoverflow","questionId":61840299,"title":"NestJS .env file doesn't get built","tags":["node.js","nestjs","dotenv"],"text":"Title: NestJS .env file doesn't get built\nTags: node.js, nestjs, dotenv\nSource: Stack Overflow\n\nQuestion:\nI'm using dotenv v8.2.0 in my NestJS project, and it has always worked in my production environment. I cloned the project on my new pc, made a .env file with the right variables in the root folder, but the .env file now doesn't get built into the dist folder. \n\nThe .env file: \n\n```\ndatabaseHost=database-di... \ndatabasePassword=a3^U...\n```\n\nThe setup of my main.ts file (only relevant parts):\n\n```\nimport { config } from 'dotenv';\nimport * as path from 'path';`\n\nconst ENV_FILE = path.join(__dirname, '..', '.env');\nconfig({ path: ENV_FILE });\n```\n\nWhen I log the dotenv config function, i get the following:\n\n```\n{\n error: Error: ENOENT: no such file or directory, open 'C:\\Users\\Jasper\\***\\dist\\.env'\n at Object.openSync (fs.js:461:3)\n at Object.readFileSync (fs.js:364:35)\n at Object.config (C:\\Users\\Jasper\\***\\node_modules\\dotenv\\lib\\main.js:96:29)\n at Object. (C:\\Users\\Jasper\\***\\dist\\src\\main.js:21:22)\n at Module._compile (internal/modules/cjs/loader.js:1176:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)\n at Module.load (internal/modules/cjs/loader.js:1040:32)\n at Function.Module._load (internal/modules/cjs/loader.js:929:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)\n at internal/main/run_main_module.js:17:47 {\n errno: -4058,\n syscall: 'open',\n code: 'ENOENT',\n path: 'C:\\\\Users\\\\Jasper\\\\***\\\\dist\\\\.env'\n }\n```\n\nWhen I look at the dist folder, the .env file does indeed not get ported over, while it used to always work. Logging the variables in the .env folder returns `undefined`.\n\nDoes anyone know what I'm doing wrong?\n\n========================================\n\nCode:\n```text\ndatabaseHost=database-di... \ndatabasePassword=a3^U...\n```\n\n```text\nimport { config } from 'dotenv';\nimport * as path from 'path';`\n\nconst ENV_FILE = path.join(__dirname, '..', '.env');\nconfig({ path: ENV_FILE });\n```\n\n```text\n{\n  error: Error: ENOENT: no such file or directory, open 'C:\\Users\\Jasper\\***\\dist\\.env'\n      at Object.openSync (fs.js:461:3)\n      at Object.readFileSync (fs.js:364:35)\n      at Object.config (C:\\Users\\Jasper\\***\\node_modules\\dotenv\\lib\\main.js:96:29)\n      at Object.<anonymous> (C:\\Users\\Jasper\\***\\dist\\src\\main.js:21:22)\n      at Module._compile (internal/modules/cjs/loader.js:1176:30)\n      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)\n      at Module.load (internal/modules/cjs/loader.js:1040:32)\n      at Function.Module._load (internal/modules/cjs/loader.js:929:14)\n      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)\n      at internal/main/run_main_module.js:17:47 {\n    errno: -4058,\n    syscall: 'open',\n    code: 'ENOENT',\n    path: 'C:\\\\Users\\\\Jasper\\\\***\\\\dist\\\\.env'\n  }\n```\n\n```text\nundefined\n```\n\n```text\n.env\n```\n\n```text\nassets\n```\n\n```text\nnest-cli.json\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\npackage.json\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- All right thanks! I had no idea, since I'm rather new to TS & JS. I now configured it to pull them from the root folder and that does work. We work with Kubernetes Secrets to hold the secrets in the .env file for CI/CD, so no need to commit the file :)\n- Jay McDoniel I have a problem where my Config Service does not take into account what's in my .env file","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":862}}580{"id":"stack-58140891","source":"stackoverflow","questionId":58140891,"title":"Nest JS GraphQL โ€œCannot return null for non-nullableโ€","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: Nest JS GraphQL โ€œCannot return null for non-nullableโ€\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI tried to resolve one error in my study code, but failed. Then I just try to launch this code...\n\nhttps://github.com/nestjs/nest/tree/master/sample/23-type-graphql\n\nand the same situation...\n\nError looks like\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field Recipe.id.\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"recipe\",\n \"id\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Cannot return null for non-nullable field Recipe.id.\",\n \" at completeValue (/home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:560:13)\",\n \" at /home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:492:16\",\n \" at process._tickCallback (internal/process/next_tick.js:68:7)\"\n ]\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\nHas someone ideas?\n\n========================================\n\nCode:\n```text\n{\n  \"errors\": [\n    {\n      \"message\": \"Cannot return null for non-nullable field Recipe.id.\",\n      \"locations\": [\n        {\n          \"line\": 3,\n          \"column\": 5\n        }\n      ],\n      \"path\": [\n        \"recipe\",\n        \"id\"\n      ],\n      \"extensions\": {\n        \"code\": \"INTERNAL_SERVER_ERROR\",\n        \"exception\": {\n          \"stacktrace\": [\n            \"Error: Cannot return null for non-nullable field Recipe.id.\",\n            \"    at completeValue (/home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:560:13)\",\n            \"    at /home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:492:16\",\n            \"    at process._tickCallback (internal/process/next_tick.js:68:7)\"\n          ]\n        }\n      }\n    }\n  ],\n  \"data\": null\n}\n```\n\n```text\nimport { Field, ID, ObjectType } from 'type-graphql';\n\n@ObjectType()\nexport class Recipe {\n  @Field(type => ID, { nullable: true })\n  id?: string;\n\n  @Field({ nullable: true })\n  title?: string;\n\n  @Field({ nullable: true })\n  description?: string;\n\n  @Field({ nullable: true })\n  creationDate?: Date;\n\n  @Field(type => [String], { nullable: true })\n  ingredients?: string[];\n}\n```\n\n========================================\n\nComments:\n- If you have the same issue and reached this page as I did, I added an answer on this page. stackoverflow.com/questions/56319137/&hellip; I cannot add an answer on this page because this question is marked as a duplicated question.\n- Not a good way to solve it. Making the field nullable should be done intentionally, not to bypass a bug.\n- I had the exact same error message. It happened because I used a partial fixture in my test where I didn't filled all the necessary field in my entity. One should be looking for that kind of misuse instead of this quick fix workaround.\n- I believe it's much simpler if you go into the entity definition and append ? to the field name. This means that the property may or may not be present in instances of the class. That way; you wouldn't need to specify @Field({ nullable: true }) above all the properties; @Entity() @ObjectType() export class StoreProfile { fieldName?: string; }","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":111,"estimatedTokens":833}}581{"id":"stack-61328438","source":"stackoverflow","questionId":61328438,"title":"How to pass reflector to Nest.js global guard?","tags":["dependency-injection","nestjs","guard"],"text":"Title: How to pass reflector to Nest.js global guard?\nTags: dependency-injection, nestjs, guard\nSource: Stack Overflow\n\nQuestion:\nI am new to nest.js and I have a question.\nI have a Roles Guard like this\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private readonly reflector: Reflector) {\n }\n\n canActivate(context: ExecutionContext): boolean | Promise | Observable {\n const roles = this.reflector.get('roles', context.getHandler());\n if (!roles) {\n return true;\n }\n const request = context.switchToHttp().getRequest();\n const user = request.user;\n return user.role.some(role => !!roles.find(item => item === role));\n }\n\n}\n```\n\nNow I want to use this guard as a global guard like this\n\n```\napp.useGlobalGuards(new RolesGuard())\n```\n\nBut it says that I need to pass argument(the reflector) to the guard as I mentioned in the constructor, now will it be okay to initialize the reflector like this?\n\n```\nconst reflector:Reflector = new Reflector();\napp.useGlobalGuards(new RolesGuard(reflector))\n```\n\nOr is there a better way to do this?\n\n========================================\n\nTop Answer:\n```\napp.useGlobalGuards(new RolesGuard(new Reflector()));\n```\n\nIt is working also. Could not find any better solution.\n\n========================================\n\nCode:\n```text\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector) {\n  }\n\n  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {\n    const roles = this.reflector.get<string[]>('roles', context.getHandler());\n    if (!roles) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const user = request.user;\n    return user.role.some(role => !!roles.find(item => item === role));\n  }\n\n}\n```\n\n```text\napp.useGlobalGuards(new RolesGuard())\n```\n\n```text\nconst reflector:Reflector = new Reflector();\napp.useGlobalGuards(new RolesGuard(reflector))\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { APP_GUARD } from '@nestjs/core';\nimport { AuthTokenGuard } from './guards/auth-token.guard';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule],\n  providers: [\n    {\n      provide: APP_GUARD,\n      useClass: AuthTokenGuard,\n    },\n  ],\n})\nexport class CommonModule {}\n```\n\n```text\napp.useGlobalGuards(new RolesGuard(new Reflector()));\n```\n\n```js\nnew RoleGuard(new Reflector());\n```\n\n```ts\nconst req = context.switchToHttp().getRequest();\nconst contextId = ContextIdFactory.getByRequest(req);\nthis.moduleRef.registerRequestByContextId(req, contextId);\nthis.authorizationService = await this.moduleRef.resolve(\n  RequestScopedService,\n  contextId\n);\n```\n\n```text\nContextIdFactory\n```\n\n```text\nmoduleRef.resolve()\n```\n\n```text\n@nestjs/core\n```\n\n```text\nnpm ls @nestjs/core\n```\n\n========================================\n\nComments:\n- SulsDotK's answer is the best practice now which is in the official guide. Another way is `app.useGlobalGuards(new AuthGuard(app.get(Reflector)));`\n- For this one, my fix is to also specify the `AuthGuard` provision scope as Scope.REQUEST.","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":147,"estimatedTokens":859}}582{"id":"stack-61868153","source":"stackoverflow","questionId":61868153,"title":"Jest: Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases","tags":["javascript","node.js","jestjs","nestjs"],"text":"Title: Jest: Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases\nTags: javascript, node.js, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nThis is my controller class(usercontoller.ts) i am trying to write junit test cases for this class \n\n import { UpsertUserDto } from '../shared/interfaces/dto/upsert-user.dto';\n import { UserDto } from '../shared/interfaces/dto/user.dto';\n import { UserService } from './user.service';\n async updateUser(@BodyToClass() user: UpsertUserDto): Promise {\n try {\n if (!user.id) {\n throw new BadRequestException('User Id is Required');\n }\n return await this.userService.updateUser(user);\n } catch (e) {\n throw e;\n }\n }\n```\n\nThis is my TestClass(UserContollerspec.ts)\nwhile running my test classes getting error \" Cannot spy the updateUser property because it is not a function; undefined given instead.\ngetting error.\nHowever, when I use spyOn method, I keep getting TypeError: Cannot read property 'updateuser' of undefined: \n\n*it seems jest.spyOn() not working properly where i am doing mistake.\n could some one please help me.the argument which I am passing ? \n\n```\njest.mock('./user.service');\n\n describe('User Controller', () => {\n let usercontroller: UserController;\n let userservice: UserService;\n // let fireBaseAuthService: FireBaseAuthService;\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [UserController],\n providers: [UserService]\n }).compile();\n\n usercontroller = module.get(UserController);\n\n userservice = module.get(UserService);\n });\n\n afterEach(() => {\n jest.resetAllMocks();\n });\n\n describe('update user', () => {\n it('should return a user', async () => {\n //const result = new UpsertUserDto();\n const testuser = new UpsertUserDto();\n const mockDevice = mock >();\n const mockNumberToSatisfyParameters = 0;\n //const userservice =new UserService();\n //let userservice: UserService;\n jest.spyOn(userservice, 'updateUser').mockImplementation(() => mockDevice);\n expect(await usercontroller.updateUser(testuser)).toBe(mockDevice);\n\n it('should throw internal error if user not found', async (done) => {\n const expectedResult = undefined;\n ****jest.spyOn(userservice, 'updateUser').mockResolvedValue(expectedResult);****\n await usercontroller.updateUser(testuser)\n .then(() => done.fail('Client controller should return NotFoundException error of 404 but did not'))\n .catch((error) => {\n expect(error.status).toBe(503);\n expect(error.message).toMatchObject({error: 'Not Found', statusCode: 503}); done();\n });\n });\n });\n });\n```\n\n========================================\n\nCode:\n```text\nThis is my controller class(usercontoller.ts) i am trying to write junit test cases for this class  \n\n            import { UpsertUserDto } from '../shared/interfaces/dto/upsert-user.dto';\n            import { UserDto } from '../shared/interfaces/dto/user.dto';\n            import { UserService } from './user.service';\n                async updateUser(@BodyToClass() user: UpsertUserDto): Promise<UpsertUserDto> {\n                    try {\n                        if (!user.id) {\n                            throw new BadRequestException('User Id is Required');\n                        }\n                        return await this.userService.updateUser(user);\n                    } catch (e) {\n                        throw e;\n                    }\n                }\n```\n\n```text\njest.mock('./user.service');\n\n        describe('User Controller', () => {\n            let usercontroller: UserController;\n            let userservice: UserService;\n            // let fireBaseAuthService: FireBaseAuthService;\n            beforeEach(async () => {\n                const module: TestingModule = await Test.createTestingModule({\n                    controllers: [UserController],\n                    providers: [UserService]\n                }).compile();\n\n                usercontroller = module.get<UserController>(UserController);\n\n                userservice = module.get<UserService>(UserService);\n            });\n\n            afterEach(() => {\n                jest.resetAllMocks();\n            });\n\n         describe('update user', () => {\n             it('should return a user', async () => {\n               //const result = new  UpsertUserDto();\n               const testuser =  new  UpsertUserDto();\n               const mockDevice = mock <Promise<UpsertUserDto>>();\n               const mockNumberToSatisfyParameters = 0;\n               //const userservice =new UserService();\n               //let userservice: UserService;\n                jest.spyOn(userservice, 'updateUser').mockImplementation(() => mockDevice);\n              expect(await usercontroller.updateUser(testuser)).toBe(mockDevice);\n\n          it('should throw internal  error if user not found', async (done) => {\n            const expectedResult = undefined;\n             ****jest.spyOn(userservice, 'updateUser').mockResolvedValue(expectedResult);****\n             await usercontroller.updateUser(testuser)\n              .then(() => done.fail('Client controller should return NotFoundException error of 404 but did not'))\n              .catch((error) => {\n                expect(error.status).toBe(503);\n                expect(error.message).toMatchObject({error: 'Not Found', statusCode: 503});  done();\n            });\n        });\n        });\n        });\n```\n\n```js\ndescribe(\"User Controller\", () => {\n  let usercontroller: UserController;\n  let userservice: UserService;\n  // let fireBaseAuthService: FireBaseAuthService;\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      controllers: [UserController],\n      providers: [\n        {\n          provide: UserService,\n          useValue: {\n            updateUser: jest.fn(),\n            // other UserService methods\n          }\n        }\n      ],\n    }).compile();\n\n    usercontroller = module.get<UserController>(UserController);\n\n    userservice = module.get<UserService>(UserService);\n  });\n  // rest of tests\n});\n```\n\n```text\nUserService\n```\n\n```text\nUserService\n```\n\n```text\nuserService = module.get(UserService)\n```\n\n```text\nundefined\n```\n\n```text\njest.spyOn()\n```\n\n```text\nUserService\n```\n\n```text\njest.spyOn\n```\n\n========================================\n\nComments:\n- Hi Jay, when I am running testcases as changed suggestd by you. showing error with message 'userId required' with same method \"updateUser\" of my controller class.\n- Are you passing in a user object with an `id` property? I see you are passing a `new UpsertUserDto()` but does anything create the `id` property and value in the constructor?","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":206,"estimatedTokens":1662}}583{"id":"stack-63753467","source":"stackoverflow","questionId":63753467,"title":"How to close database connection in nestjs service?","tags":["javascript","testing","jestjs","nestjs"],"text":"Title: How to close database connection in nestjs service?\nTags: javascript, testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my database module I'm creating a connection to my database. With this setup I do get the error\n\n**A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --runInBand --detectOpenHandles to find leaks.**\n\nin my e2e tests.\n\nI think I have to close the connection. But how do I run `client.close` in the `onModuleDestroy()` in my Databasemodule?\n\n**database.module.ts**\n\n```\nimport { Module } from '@nestjs/common'\nimport { MongoClient, Db, Logger } from 'mongodb'\n\n@Module({\n providers: [\n {\n provide: 'DATABASE_CONNECTION',\n useFactory: async (): Promise => {\n const mongo = 'mongodb://localhost:27017'\n const database = 'testing'\n\n try {\n Logger.setLevel('debug')\n\n const client = await MongoClient.connect(mongo, {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n });\n\n const db = client.db(database)\n return db\n } catch (error) {\n throw error\n }\n }\n },\n {\n provide: 'DATABASE_CLIENT',\n useFactory: () => true // how do I get client of the above provider?\n }\n ],\n exports: ['DATABASE_CONNECTION', 'DATABASE_CLIENT']\n})\n\nexport class DatabaseModule {\n constructor(\n @Inject('DATABASE_CLIENT')\n private client: Db\n ) {}\n\n async onModuleDestroy() {\n console.log(this.client);\n // await this.client.close()\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common'\nimport { MongoClient, Db, Logger } from 'mongodb'\n\n@Module({\n    providers: [\n        {\n            provide: 'DATABASE_CONNECTION',\n            useFactory: async (): Promise<Db> => {\n                const mongo = 'mongodb://localhost:27017'\n                const database = 'testing'\n\n                try {\n                    Logger.setLevel('debug')\n\n                    const client = await MongoClient.connect(mongo, {\n                        useNewUrlParser: true,\n                        useUnifiedTopology: true,\n                    });\n\n                    const db = client.db(database)\n                    return db\n                } catch (error) {\n                    throw error\n                }\n            }\n        },\n        {\n            provide: 'DATABASE_CLIENT',\n            useFactory: () => true // how do I get client of the above provider?\n        }\n    ],\n    exports: ['DATABASE_CONNECTION', 'DATABASE_CLIENT']\n})\n\nexport class DatabaseModule {\n    constructor(\n        @Inject('DATABASE_CLIENT')\n        private client: Db\n    ) {}\n\n    async onModuleDestroy() {\n        console.log(this.client);\n        // await this.client.close()\n    }\n}\n```\n\n```text\nclient.close\n```\n\n```text\nonModuleDestroy()\n```\n\n```text\n@Injectable()\nclass DatabaseConnection {\n  async onModuleInit() {\n    // ...same as DATABASE_CONNECTION factory\n    this.client = client;\n    this.db = client.db(database);\n  }\n  async onModuleDestroy() {\n    await this.client.close()\n  } \n}\n```\n\n```text\n@Module({\n  providers: [\n    {\n      provide: 'DATABASE_CLIENT',\n      useFactory: () => ({ client: null })\n    },\n    {\n      provide: 'DATABASE_CONNECTION',\n      inject: ['DATABASE_CLIENT'],\n      useFactory: async (dbClient) => {\n        ...\n        dbClient.client = client\n        const db = client.db(database)\n        return db;\n      }\n    }\n  ]\n  ...\n})\nexport class DatabaseModule {\n  constructor(@Inject('DATABASE_CLIENT') private dbClient) {}\n\n  async onModuleDestroy() {\n    await this.dbClient.client.close()\n  } \n}\n```\n\n```text\nclient\n```\n\n```text\nclient\n```\n\n========================================\n\nComments:\n- Very likely yes, that's the problem. Do a cleanup in a hook, docs.nestjs.com/fundamentals/lifecycle-events . onModuleDestroy, I guess.\n- @EstusFlask But how can I close the client as the database module is returning the `db` instead of `client`? Please have a look at the updated post regarding the service code.\n- This needs to be done in db service or module, not in a consumer, it's module's responsibility to clean up after itself. And yes, you need to keep a reference to `client` for this. Probably with a separate provider, `{ provide: 'DATABASE_CLIENT' useFactory: () => ({ client: null }) }`. Inject it to DATABASE_CONNECTION to assign client property, and to DatabaseModule to access it in onModuleDestroy. I'm not sure what's the best way to do this in Nest, would be easier if db service were a class.\n- What do you mean by `inject it to DATABASE_CONNECTION? Could you please post an example with the db service as a class?\n- I mean to use DI to inject client service into connection factory. I posted the code. I cannot confirm if it's workable but I'd expect it to be done this way, more or less.\n- It needs to be `await this.dbClient.client.close()` because dbClient has the object client. You have to use an object for the first provider?\n- I was in the middle of writing a comment. Did it work for you in the end? I expect two solutions to be equivalent and onModuleDestroy to be called in both cases. Yes, that's a typo, it should have `client` property. Yes, it's necessary to have an object to pass a reference to `client`, that's a popular recipe in JS.\n- Thanks. Yes, it is working perfectly. Sorry, for the deleted comment. But it was just the missing property, which I didn't recognize first.\n- If you can not decide which method to use this warning from nestjs documentation can be a guide \"WARNING If your class doesn't extend another provider, you should always prefer using constructor-based injection.\"","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":185,"estimatedTokens":1403}}584{"id":"stack-60617391","source":"stackoverflow","questionId":60617391,"title":"NestJs: Dynamically Create Instances of Class","tags":["dependency-injection","factory","nestjs"],"text":"Title: NestJs: Dynamically Create Instances of Class\nTags: dependency-injection, factory, nestjs\nSource: Stack Overflow\n\nQuestion:\nInstead of Singletons, I want to create dynamically class instances in NestJs. \n\nI found two ways:\n\n### 1) Directly create the class (ChripSensor is then not @Injectable)\n\n```\nimport { ChirpSensor } from './chirp-sensor/chirp-sensor';\n\n@Injectable()\nexport class SensorsService {\n registeredSensors: any;\n constructor(\n @InjectModel('Sensor') private readonly sensorModel: Model,\n private i2cService: I2cService) {\n const sensors = this.i2cService.getSensors();\n sensors.forEach((sensor) => {this.registeredSensors[sensor._id] = new ChirpSensor({name: sensor.name})});\n\n }\n```\n\nI'm wondering if that is consistent with the DI way of nest.js\n\n### 2) The second solution would be via a factory, but here I don't know how to pass the options.\n\n```\nexport const chirpFactory = {\n provide: 'CHIRP_SENSOR',\n useFactory: (options) => {\n console.log('USING FACTORY CHIRP, options', options)\n if (process.env.SIMULATION === 'true') {\n return new ChirpSensorMock(options);\n }\n else {\n return new ChirpSensor(options);\n }\n }\n};\n```\n\nNot quite sure how to continue here/ inject the factory properly as the examples create the object in the constructor without options? \n\n### Question:\n\nWhat is the `NestJs` way to create those class instances?\n\n### Edit - for B12Toastr\n\n### Module - get the Mock or Original on Compile time\n\n```\nproviders: [\n {\n provide: 'CHIRP_SENSOR',\n useValue: process.env.SIMULATION === 'true'\n ? ChirpSensorMock\n : ChirpSensor\n },\n],\n```\n\n### Sensor Service\n\n```\n@Injectable()\nexport class SensorsService {\n registeredSensors: any;\n constructor(\n @Inject('CHIRP_SENSOR') private ChirpSensorClass: any, // any works but ChirpSensorMock | ChirpSensor not\n private i2cService: I2cService\n ) {\n const sensors = this.i2cService.getSensors();\n sensors.forEach((sensor) => {this.registeredSensors[sensor._id] = new ChirpSensorClass({name: sensor.name})});\n\n }\n```\n\n========================================\n\nCode:\n```text\nimport { ChirpSensor } from './chirp-sensor/chirp-sensor';\n\n@Injectable()\nexport class SensorsService {\n  registeredSensors: any;\n  constructor(\n    @InjectModel('Sensor') private readonly sensorModel: Model<ISensor>,\n    private i2cService: I2cService) {\n       const sensors = this.i2cService.getSensors();\n       sensors.forEach((sensor) => {this.registeredSensors[sensor._id] = new ChirpSensor({name: sensor.name})});\n\n    }\n```\n\n```text\nexport const chirpFactory = {\n  provide: 'CHIRP_SENSOR',\n  useFactory: (options) => {\n    console.log('USING FACTORY CHIRP, options', options)\n    if (process.env.SIMULATION === 'true') {\n      return new ChirpSensorMock(options);\n    }\n    else {\n      return new ChirpSensor(options);\n    }\n  }\n};\n```\n\n```text\nproviders: [\n  {\n    provide: 'CHIRP_SENSOR',\n    useValue: process.env.SIMULATION === 'true'\n      ? ChirpSensorMock\n      : ChirpSensor\n  },\n],\n```\n\n```text\n@Injectable()\nexport class SensorsService {\n  registeredSensors: any;\n  constructor(\n    @Inject('CHIRP_SENSOR') private ChirpSensorClass: any, // any works but ChirpSensorMock | ChirpSensor not\n    private i2cService: I2cService\n   ) {\n    const sensors = this.i2cService.getSensors();\n    sensors.forEach((sensor) => {this.registeredSensors[sensor._id] = new ChirpSensorClass({name: sensor.name})});\n\n  }\n```\n\n```text\nNestJs\n```\n\n```js\nproviders: [\n  {\n    provide: MyOptions,\n    useValue: options\n  },\n  {\n    provide: 'CHIRP_SENSOR',\n    useFactory: (options: MyOptions) => {\n      console.log('USING FACTORY CHIRP, options', options);\n      if (process.env.SIMULATION === 'true') {\n        return new ChirpSensorMock(options);\n      } else {\n        return new ChirpSensor(options);\n      }\n    },\n  },\n],\n```\n\n```js\nproviders: [\n  {\n    provide: MyOptions,\n    useValue: options\n  },\n  {\n    provide: 'CHIRP_SENSOR',\n    useValue: process.env.SIMULATION === 'true'\n      ? ChirpSensorMock\n      : ChirpSensor\n  },\n],\n```\n\n```js\nproviders: [\n  {\n    provide: MyOptions,\n    useValue: options\n  },\n  {\n    process.env.SIMULATION === 'true' ? ChirpSensorMock : ChirpSensor\n  },\n],\n```\n\n```js\n@Injectable()\nexport class ChripSensor {\n  constructor(@inject(MyOptions) private options: MyOptions) {\n  }\n\n  // ...\n}\n```\n\n```text\nChirpSensor\n```\n\n```text\nuseValue\n```\n\n```text\nuseClass\n```\n\n```text\nuseClass\n```\n\n```text\n@Inject\n```\n\n```text\nMyOptions\n```\n\n```text\n@Inject\n```\n\n```text\nuseValue\n```\n\n```text\nuseClass\n```\n\n========================================\n\nComments:\n- In the second case: `process.env.SIMULATION === 'true' ? ChirpSensorMock : ChirpSensor` if I use this via DI in my service, how would I pass the options? Or would I import the factory and then call the factory outside of the constructor? I mean could you add how to use the solution in the `SensorsService`.\n- I mean options is still passed to either ChirpSensorMock or ChirpSensor and maybe retrieved through another service, as shown in the 1st example.\n- And it would be probably `useClass`, I guess.\n- Hi @AndiGiga, yes correct you would use DI for passing the options as in the 1st example, I added this to the code for clarification and further elaborated on this at the bottom of my answer. Depending on if you wrapped your options in a class or not, you would either provide the options as class-based service (using `useClass`) or a simple object or other type (`useValue`).\n- I made an edit above. As the options are dynamic and retrieved from i2cService I made an example above with your solution. I think it works now but only with the `any`type. Maybe you got any recommendation on how to deal with the type then. I get `This expression is not constructable. Type 'ChirpSensorMock' has no construct signatures.`\n- first you are using PascalCase for the instance you are injecting in your constructor which may cover up the import `ChirpSensorClass`, for good style and to avoid import problems it should be `chirpSensorClass: any` or better `chirpSensorClass: ChirpSensorClass`, second, try `{ provide: ChirpSensor, useClass: process.env.SIMULATION === 'true' ? ChirpSensorMock : ChirpSensor },` (note the useClass and the ChirpSensor being the DI token) and then in your SensorsService use: `constructor(private chirpSensor: ChirpSensor`. Hope it helps, good luck.\n- That's exactly what I need to do and I opted for a DynamicModule where I pass the `useClass` from outside, based on `process.env.MOCKS_ENABLED`. I hoped there was a cleaner way like I do in Angular projects, but it appears there isn't. It's ugly because you need to have a consistent imported module, whereas in Angular I just override stuff without touching anything. I was lucky because I'm working with custom modules...but what if I was using libs? ๐Ÿคฏ\n- Maybe I am wrong but the original question was: \"How to create a series of `@Injectable` `ChirpSensorClass` instances with different options(`{name: sensor.name}`) iterating over some array? And then address them somehow to `@Inject` in other places. Is it possible? As I understand in your solution `useFactory` functions will be called once for single `MyOptions` instance. Isn't it?","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":248,"estimatedTokens":1793}}585{"id":"stack-67580233","source":"stackoverflow","questionId":67580233,"title":"How to test custom Repository in Nestjs/TypeORM applications","tags":["nestjs","typeorm"],"text":"Title: How to test custom Repository in Nestjs/TypeORM applications\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to add more testing codes to improve the quality of my sample codes.\n\nCurrently, I have a problem when testing `UserRepository` (**not mock UserRepository**), there are some custom methods I added in my custom `UserRepository` like this.\n\n```\n@EntityRepository(UserEntity)\nexport class UserRepository extends Repository {\n findByEmail(email: string): Promise {\n return this.findOne({ email: email });\n }\n}\n```\n\nSo I want to verify the `findOne` is called from the parent `Repository`.\n\nI tried to add the following testing codes.\n\n```\ndescribe('UserRepository', () => {\n let local;\n let parentMock;\n\n beforeEach(() => {\n local = Object.getPrototypeOf(UserRepository);\n parentMock = {\n new: jest.fn(),\n construtor: jest.fn(),\n findOne: jest.fn(),\n };\n Object.setPrototypeOf(UserRepository, parentMock);\n });\n\n afterEach(() => {\n Object.setPrototypeOf(UserRepository, local);\n });\n\n it('should call findOne', async () => {\n const findByEmailSpy = jest.spyOn(parentMock, 'findOne');\n const users = new UserRepository();\n await users.findByEmail('test@example.com');\n expect(parentMock.mock.calls.length).toBe(1);\n expect(findByEmailSpy).toBeCalledWith({\n email: 'test@example.com',\n });\n });\n});\n```\n\nWhen running the tests, it complains there is no constructor() for `new UserRepository()`.\n\nIs there any way to fix this issue, or a better way to write these testing codes?\n\n========================================\n\nCode:\n```js\n@EntityRepository(UserEntity)\nexport class UserRepository extends Repository<UserEntity> {\n  findByEmail(email: string): Promise<UserEntity> {\n    return this.findOne({ email: email });\n  }\n}\n```\n\n```js\ndescribe('UserRepository', () => {\n  let local;\n  let parentMock;\n\n  beforeEach(() => {\n    local = Object.getPrototypeOf(UserRepository);\n    parentMock = {\n      new: jest.fn(),\n      construtor: jest.fn(),\n      findOne: jest.fn(),\n    };\n    Object.setPrototypeOf(UserRepository, parentMock);\n  });\n\n  afterEach(() => {\n    Object.setPrototypeOf(UserRepository, local);\n  });\n\n  it('should call findOne', async () => {\n    const findByEmailSpy = jest.spyOn(parentMock, 'findOne');\n    const users = new UserRepository();\n    await users.findByEmail('test@example.com');\n    expect(parentMock.mock.calls.length).toBe(1);\n    expect(findByEmailSpy).toBeCalledWith({\n      email: 'test@example.com',\n    });\n  });\n});\n```\n\n```text\nUserRepository\n```\n\n```text\nUserRepository\n```\n\n```text\nfindOne\n```\n\n```text\nRepository\n```\n\n```text\nnew UserRepository()\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { Repository } from 'typeorm';\nimport { UserEntity } from './user.entity';\nimport { UserRepository } from './user.repository';\n\ndescribe('UserRepository', () => {\n  let userRepository: UserRepository;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [UserRepository],\n    }).compile();\n\n    userRepository = module.get<UserRepository>(UserRepository);\n  });\n\n  describe('findByEmail', () => {\n    it('should return found user', async () => {\n      const email = 'email';\n      const user = {\n        email,\n      };\n      const findOneSpy = jest\n        .spyOn(userRepository, 'findOne')\n        .mockResolvedValue(user as UserEntity);\n\n      const foundUser = await userRepository.findByEmail(email);\n      expect(foundUser).toEqual(user);\n      expect(findOneSpy).toHaveBeenCalledWith(user);\n    });\n  });\n});\n```\n\n```text\nfindOne\n```\n\n========================================\n\nComments:\n- If use EntityManager and QueryBuilder in the `Repository`, eg `findByAuthor` in the PostRepository, how to mock this?\n- for QueryBuilder, it can be mocked like the following: `jest.spyOn(Repository.prototype, 'createQueryBuilder').mockReturnValue(SelectQueryBuilder.pro&zwnj;&#8203;totype); jest.spyOn(SelectQueryBuilder.prototype, 'where').mockReturnThis(); &#47;&#47; the same goes for setParameter, skip and take methods jest.spyOn(SelectQueryBuilder.prototype, 'getMany').mockResolvedValue(data);`\n- not sure about mocking `manager.findOne`, what is the reason for using `this.manager.find` instead of `this.find`?\n- I added a test make it work. But all *readonly* properties in the `Repository` should be injectable, but it does not work as expected like other injectable components.\n- Any ideas on how to do this when extending from `AbstractRepository`? I have created a separate question for it here.","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":167,"estimatedTokens":1139}}586{"id":"stack-61463636","source":"stackoverflow","questionId":61463636,"title":"Nest can't resolve dependencies of the ....Please make sure that the argument .. at index [0] is available in the","tags":["node.js","sequelize.js","nestjs"],"text":"Title: Nest can't resolve dependencies of the ....Please make sure that the argument .. at index [0] is available in the\nTags: node.js, sequelize.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/sequelize';\nimport { Conversation } from './conversation.model'\nimport { FindConversationsDto } from '../dto/conversations.find'\n\n@Injectable()\nexport class ConversationsService {\n constructor(\n @InjectModel(Conversation)\n private conversationModel: typeof Conversation\n ) { }\n\n async findConversations(queryParams: FindConversationsDto): Promise {\n return new Promise((resolve) => [])\n // return await this.conversationModel.findAll();\n\n }\n}\n```\n\nAnd I get this weird error:\n\n```\nNest can't resolve dependencies of the ConversationsService (?). Please make sure that the argument ConversationRepository at index [0] is available in the ConversationsModule context.\n\nPotential solutions:\n- If ConversationRepository is a provider, is it part of the current ConversationsModule?\n- If ConversationRepository is exported from a separate @Module, is that module imported within ConversationsModule?\n @Module({\n imports: [ /* the Module containing ConversationRepository */ ]\n })\n```\n\n`ConversationModule` is:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConversationsController } from './conversations.controller';\nimport { ConversationsService } from './conversations.service';\n\n@Module({\n controllers: [ConversationsController],\n providers: [ConversationsService]\n})\nexport class ConversationsModule {}\n```\n\nNot sure what `ConversationRepository` is referring to.\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/sequelize';\nimport { Conversation } from './conversation.model'\nimport { FindConversationsDto } from '../dto/conversations.find'\n\n@Injectable()\nexport class ConversationsService {\n    constructor(\n        @InjectModel(Conversation)\n        private conversationModel: typeof Conversation\n    ) { }\n\n    async findConversations(queryParams: FindConversationsDto): Promise<Conversation[]> {\n        return new Promise((resolve) => [])\n        // return await this.conversationModel.findAll();\n\n\n    }\n}\n```\n\n```text\nNest can't resolve dependencies of the ConversationsService (?). Please make sure that the argument ConversationRepository at index [0] is available in the ConversationsModule context.\n\nPotential solutions:\n- If ConversationRepository is a provider, is it part of the current ConversationsModule?\n- If ConversationRepository is exported from a separate @Module, is that module imported within ConversationsModule?\n  @Module({\n    imports: [ /* the Module containing ConversationRepository */ ]\n  })\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConversationsController } from './conversations.controller';\nimport { ConversationsService } from './conversations.service';\n\n@Module({\n  controllers: [ConversationsController],\n  providers: [ConversationsService]\n})\nexport class ConversationsModule {}\n```\n\n```text\nConversationModule\n```\n\n```text\nConversationRepository\n```\n\n```js\n@Module({\n  imports: [SequelizeModule.forFeature([Conversation])],\n  providers: [ConversationService],\n  controllers: [ConversationController]\n})\nexport class ConversationModule {}\n```\n\n```text\nSequelizeModule.forFeature()\n```\n\n```text\nConversationModule\n```\n\n```text\nimports\n```\n\n```text\nConversationRepository\n```\n\n```text\nConverstationModule\n```\n\n========================================\n\nComments:\n- Can you show your `ConversationModule` file well?\n- Updated with `ConversationModule`\n- I have `autoLoadModels: true` in my DB loader. Do I still need to import the models in each Module?\n- Yes, it is needed for nestjs.\n- Yes. Quote from the docs: \"Note that models that aren't registered through the forFeature() method, but are only referenced from the model (via an association), won't be included. \"","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":150,"estimatedTokens":1003}}587{"id":"stack-56693400","source":"stackoverflow","questionId":56693400,"title":"NestJS How to consume async middleware?","tags":["async-await","middleware","nestjs"],"text":"Title: NestJS How to consume async middleware?\nTags: async-await, middleware, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use NestJS framework, and want to apply several middlewares to a route in my app. Each middleware is a class implementing NestMiddleware interface. One of these middlewares is async, and is not consumed before the route handler is called. Is there a way to resolve the promise of this middleware before handling the route?\n\n### My code\n\n**Async middleware** (page-loader.middleware)\n\n```\nimport { Injectable, NestMiddleware } from '@nestjs/common';\n\n@Injectable()\n\nexport class PageLoader implements NestMiddleware {\n\n async use(req: any, res: any, next: () => void) {\n try {\n req.body.html = await req.body.fetcher.fetch();\n } catch (error) {\n throw new Error(error);\n } finally {\n next();\n }\n }\n\n}\n```\n\n**Controller** (create-article.controller)\n\n```\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { SaveArticleService } from './save-article.service';\nimport { CreateArticleDto } from './create-article.dto';\n\n@Controller()\n\nexport class CreateArticleController {\n\n constructor(private readonly saveArticleService: SaveArticleService) {}\n\n @Post('/create')\n async create(@Body() createArticleDto: CreateArticleDto) {\n return this.saveArticleService.save(createArticleDto);\n }\n\n}\n```\n\n**Module** (create-article.module)\n\n```\nimport { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';\nimport { CreateArticleController } from './create-article.controller';\nimport { SaveArticleService } from './save-article.service';\n\n// Another (sync) middleware\nimport { ExtensionExtractor } from './extension-extractor.middleware'; \n\n// The async middleware\nimport { PageLoader } from './page-loader.middleware';\n\n@Module({\n controllers: [CreateArticleController],\n providers: [SaveArticleService],\n})\n\nexport class CreateArticleModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(ExtensionExtractor, PageLoader)\n .forRoutes({ path: 'create', method: RequestMethod.POST});\n }\n}\n```\n\nI did not include a snippet of the service used in the controller, as it is not relevant to my question.\n\n### What I tried\n\nThis question did not help me solve the issue, as the middleware structure is different. I am waiting for the middleware method to resolve its promise, and not waiting for an input that is reused inside the middleware.\n\nThese github issue answers are not relevant, as the NestJS API drastically changed.\n\nThanks in advance for your help!\n\n========================================\n\nCode:\n```js\nimport { Injectable, NestMiddleware } from '@nestjs/common';\n\n@Injectable()\n\nexport class PageLoader implements NestMiddleware {\n\n  async use(req: any, res: any, next: () => void) {\n    try {\n      req.body.html = await req.body.fetcher.fetch();\n    } catch (error) {\n      throw new Error(error);\n    } finally {\n      next();\n    }\n  }\n\n}\n```\n\n```js\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { SaveArticleService } from './save-article.service';\nimport { CreateArticleDto } from './create-article.dto';\n\n@Controller()\n\nexport class CreateArticleController {\n\n  constructor(private readonly saveArticleService: SaveArticleService) {}\n\n  @Post('/create')\n  async create(@Body() createArticleDto: CreateArticleDto) {\n    return this.saveArticleService.save(createArticleDto);\n  }\n\n}\n```\n\n```js\nimport { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';\nimport { CreateArticleController } from './create-article.controller';\nimport { SaveArticleService } from './save-article.service';\n\n// Another (sync) middleware\nimport { ExtensionExtractor } from './extension-extractor.middleware'; \n\n// The async middleware\nimport { PageLoader } from './page-loader.middleware';\n\n@Module({\n  controllers: [CreateArticleController],\n  providers: [SaveArticleService],\n})\n\nexport class CreateArticleModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n    .apply(ExtensionExtractor, PageLoader)\n    .forRoutes({ path: 'create', method: RequestMethod.POST});\n  }\n}\n```\n\n```js\nimport { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\n\nfunction asyncTimeout(milliseconds: number): Promise<string> {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => resolve('DONE'), milliseconds);\n  });\n}\n\n@Module({\n  controllers: [UserController],\n  providers: [UserService],\n  exports: [UserService]\n})\nexport class UserModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply((req, res, next) => {\n        console.log('Using forRoutes(path)');\n        console.log('syncronous middleware');\n        next();\n      },\n        (async (req, res, next) => {\n          console.log('Using forRoutes(path)');\n          const start = Date.now();\n          const done = await asyncTimeout(5000);\n          console.log(done);\n          console.log('Time taken:' + (Date.now() - start));\n          next();\n        })\n      )\n      .forRoutes('/')\n      .apply((req, res, next) => {\n        console.log('Using forRoutes({path, method})');\n        console.log('syncronous middleware');\n        next();\n      },\n        (async (req, res, next) => {\n          console.log('Using forRoutes({path, method})');\n          const start = Date.now();\n          const done = await asyncTimeout(5000);\n          console.log(done);\n          console.log('Time taken:' + (Date.now() - start));\n          next();\n        })\n      )\n      .forRoutes({path: '/', method: RequestMethod.GET});\n  }\n}\n```\n\n```js\nimport { Controller, Get } from '@nestjs/common';\nimport { UserSerivce } from './user.service';\n\n@Controller('user')\nexport class UserController {\n  constructor(private readonly userService: UserService) {}\n\n  @Get('/')\n  testFunction() {\n    return {greeting: 'hello'};\n  }\n}\n```\n\n```sh\n[2019-06-20 22:40:48.191] [INFO] | Listening at http://localhost:3333/api\nUsing forRoutes(path)\nsyncronous middleware\nUsing forRoutes(path)\nDONE\nTime taken:5002\n[2019-06-20 22:40:57.346] [INFO] | [Nest] 30511 [Morgan] GET /api/user 200 5014.234 ms - 20\n```\n\n```text\n.forRoutes({path: 'path', method: method});\n```\n\n```text\nRequestMethod.GET\n```\n\n```text\n.forRoutes(path)\n```\n\n```text\n.forRoutes({path, method})\n```\n\n========================================\n\nComments:\n- Thank you really much for your help! I found an error in my async middleware, which caused my tests to fail. I corrected it, and tried to reproduce the bug you describe in your answer, but using the `.forRoutes({path, method})` strategy works fine for me...\n- So, interestingly enough, using `forRoutes('&#47;')` worked for one of my middleware but not the other, but using `forRoutes('&#47;user')` for the corresponding `forRoutes(path: '&#47;user', method: RequestMethod.GET)` makes both middleware segments fire. Mainly documenting this in case anyone else come across a similar problem.\n- Thanks for your research, I'll accept your answer and hope the readers will take a look in the comments!\n- When you make `.forRoutes({ path,method})` You need to specify exact path, not like with `.forRoutes(path)` where `&#47;` is enough for all routes, if you do with `.forRoutes({ path, method })` you need to use `*` like so `.forRoutes({ path: '&#47;*', method: RequestMethod.GET })`","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":257,"estimatedTokens":1864}}588{"id":"stack-71607700","source":"stackoverflow","questionId":71607700,"title":"ERROR [ExceptionsHandler] no elements in sequence after upgrading to NestJS v8 and RxJS v7","tags":["rxjs","observable","nestjs"],"text":"Title: ERROR [ExceptionsHandler] no elements in sequence after upgrading to NestJS v8 and RxJS v7\nTags: rxjs, observable, nestjs\nSource: Stack Overflow\n\nQuestion:\nAfter upgrading to NestJS v8, I had to upgrade my RxJS version as well from 6 to 7 then it started throwing `ERROR [ExceptionsHandler] no elements in sequence` error.\n\nThis is a sample method in one of the app services:\n\n```\nshow(): Observable {\n return from(this.repository.fetch()).pipe(\n filter((data) => data.length > 0),\n map((data) => data.map((datum) => parseData(datum)),\n );\n }\n```\n\nWhile I had NestJS v7 and RxJS v6, the method was working just fine; in other words, if the `filter` operation is not passed, the `map` operator wouldn't be called at all and the Observable stops there.\n\nBut after upgrading to NestJS v8 and RxJS v7, if my repository does not return any data, the app starts throwing `ERROR [ExceptionsHandler] no elements in sequence` error.\n\nA workaround I came up with is as follows:\n\n```\nshow(): Observable {\n return from(this.repository.fetch()).pipe(\n filter((data) => data.length > 0),\n defaultIfEmpty([]),\n map((data) => data.map((datum) => parseData(datum)),\n );\n }\n```\n\nThis way the error is gone but I have two more problems:\n\n1- the `map` operator still runs which I do not want\n\n2- the second one which is way more important to me is that I have to update all my services/methods which have a validation like this which is really crazy.\n\nmy dependencies are as follows:\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^8.4.2\",\n \"@nestjs/core\": \"^8.4.2\",\n \"rxjs\": \"^7.5.5\"\n },\n```\n\n========================================\n\nCode:\n```text\nshow(): Observable<any> {\n    return from(this.repository.fetch()).pipe(\n      filter((data) => data.length > 0),\n      map((data) => data.map((datum) => parseData(datum)),\n    );\n  }\n```\n\n```text\nshow(): Observable<any> {\n    return from(this.repository.fetch()).pipe(\n      filter((data) => data.length > 0),\n      defaultIfEmpty([]),\n      map((data) => data.map((datum) => parseData(datum)),\n    );\n  }\n```\n\n```text\n\"dependencies\": {\n    \"@nestjs/common\": \"^8.4.2\",\n    \"@nestjs/core\": \"^8.4.2\",\n    \"rxjs\": \"^7.5.5\"\n  },\n```\n\n```text\nERROR [ExceptionsHandler] no elements in sequence\n```\n\n```text\nfilter\n```\n\n```text\nmap\n```\n\n```text\nERROR [ExceptionsHandler] no elements in sequence\n```\n\n```text\nmap\n```\n\n```js\nimport {\n  CallHandler,\n  ExecutionContext,\n  Injectable,\n  NestInterceptor\n} from '@nestjs/common'\nimport { defaultIfEmpty } from 'rxjs/operators'\n\n@Injectable()\nexport class DefaultIfEmptyInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler) {\n    return next.handle().pipe(defaultIfEmpty([]))\n  }\n}\n```\n\n```js\nimport { DefaultIfEmptyInterceptor } from '../defaultIfEmpty.interceptor'\nimport { APP_INTERCEPTOR } from '@nestjs/core'\n// ...\n\n{\n  provide: APP_INTERCEPTOR,\n  useClass: DefaultIfEmptyInterceptor,\n}\n```\n\n```text\ndefaultIfEmpty\n```\n\n```text\nproviders\n```\n\n========================================\n\nComments:\n- I've seen that error before when using the `first()` operator, if the subscription is completed without having emitted a value. Are you using `first` anywhere?\n- Nest uses `lastValueFrom` under the hood. If there's no value emitted then there will be a problem. Try moving the `defaultIfEmpty` to *below* the `map` operator\n- @BizzyBob no not at all\n- @JayMcDoniel it works the way you said. My question: Has NestJS v8 started using `lastValueFrom`? One more question: Isn't there a way without adding `defaultIfEmpty` because this way I have to update the whole source code to stop getting 500 errors. Any workaround?\n- Nest 8 upgraded to RxJS v7 which deprecated `toPromise` which is why we changed to `lastValueFrom`. Instead of adding this to every service you could add it to an `interceptor` and have the interceptor set the `defaultIfEmpty` for you\n- I'm brand new to NextJs/RxJs but seems like a bad idea to assume all endpoints will return `[]` if empty? What about ones that return objects?\n- Then `defaultIfEmpty({})`. You could use metadata via a decorator to set the default and retrieve it dynamically.","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":146,"estimatedTokens":1034}}589{"id":"stack-58612424","source":"stackoverflow","questionId":58612424,"title":"Is there anyway to get types interfaces for request, response in Nest.js with Fastify","tags":["typescript","nestjs","fastify"],"text":"Title: Is there anyway to get types interfaces for request, response in Nest.js with Fastify\nTags: typescript, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI am learing Nest.js and on the beging of documentation I read that I can use it not only with **express** but also with **fastify** so I setuped up my first project with **fastify** then I started to read about controllers and I found a problem. For example if I want to get more information about user request i can slightly use `@Req req: Reguest` and this **req** is type of **Request** and it is very easy to get this interface from **express** based application, yuo only have to install `@types/express` and then you can inport **Request** interface from **express** but how(if it is possible) I can get **Request** interface if I am using **fastify**?\n\n========================================\n\nTop Answer:\nInstall the `fastify` package and import `FastifyRequest` and `FastifyReply` from there:\n\n```\nimport { Controller, Get, Req, Res } from '@nestjs/common';\nimport { FastifyReply, FastifyRequest } from 'fastify';\n\n@Controller('feature')\nexport class FeatureController {\n @Get()\n async handler(\n @Req() req: FastifyRequest,\n @Res() reply: FastifyReply,\n ) { }\n}\n```\n\n========================================\n\nCode:\n```text\n@Req req: Reguest\n```\n\n```text\n@types/express\n```\n\n```js\nimport { Controller, Get, Query, Req } from '@nestjs/common';\nimport { AppService } from './app.service';\nimport { DefaultQuery } from 'fastify';\n\n@Controller('math')\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get('add')\n  addTwoNumbers(@Query() query: DefaultQuery): number {\n    return this.appService.addTwoNumbers(query.value);\n  }\n}\n```\n\n```text\n@types/node\n```\n\n```text\n@types/fastify\n```\n\n```text\nRequest\n```\n\n```text\nReply\n```\n\n```text\nimport { Controller, Get, Req, Res } from '@nestjs/common';\nimport { FastifyReply, FastifyRequest } from 'fastify';\n\n@Controller('feature')\nexport class FeatureController {\n  @Get()\n  async handler(\n    @Req() req: FastifyRequest,\n    @Res() reply: FastifyReply,\n  ) { }\n}\n```\n\n```text\nfastify\n```\n\n```text\nFastifyRequest\n```\n\n```text\nFastifyReply\n```\n\n========================================\n\nComments:\n- No there is no any :/ but actually i found solution. Fastify provides interfaces with `@types&#47;node` and you can import them from `'fastify'` for example DefaultQuery. So if you have installed `@types&#47;node`(for nest they are already inside the project so you do not have to) you can easy acces them. Here i found my solution fastifyTypes\n- Do you know if express supports that kind of interface?\n- I'm using nestjs and fastify... I want to type my @Res but I'm not able to find the correct type/import. The import { Reply } from 'fastify'; returns an error message: Cannot find module 'fastify' or its corresponding type declarations.ts(2307)","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":101,"estimatedTokens":725}}590{"id":"stack-56928551","source":"stackoverflow","questionId":56928551,"title":"NestJS : Interceptor both map and catchError","tags":["node.js","typescript","express","rxjs","nestjs"],"text":"Title: NestJS : Interceptor both map and catchError\nTags: node.js, typescript, express, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need a NestJS interceptor that archives requests, both in exceptional and happy-path cases. Created as follows: \n\n```\npublic intercept(context: ExecutionContext, next: CallHandler): Observable {\n\n if (!this.reflector.get(RequestMetaData.IS_PUBLIC_ROUTE, context.getHandler())) {\n return next.handle().pipe(\n map(data => {\n const host = context.switchToHttp();\n const req = host.getRequest();\n const resp = host.getResponse();\n this.persistRequest(data, req, resp)\n .then(() => this.logger.log(`Request logged`))\n .catch(e => {\n this.logger.error(`Error logging request: ${e.message}`);\n });\n return data;\n }));\n }\n return next.handle();\n}\n```\n\n**Problem:**\n\nThis only logs the happy path. Because I'm not familiar with RxJS I created another to persist errors. Eg: \n\n```\npublic intercept(context: ExecutionContext, next: CallHandler): Observable {\n return next\n .handle()\n .pipe(\n catchError(err => {\n return throwError(err);\n })\n );\n}\n```\n\nHow can I define a single interceptor that archives both paths?\n\n========================================\n\nTop Answer:\n```\npublic intercept(context: ExecutionContext, next: CallHandler): Observable {\n\n if (!this.reflector.get(RequestMetaData.IS_PUBLIC_ROUTE, context.getHandler())) {\n return next.handle().pipe(\n finalize(() => {\n const host = context.switchToHttp();\n const req = host.getRequest();\n const resp = host.getResponse();\n this.persistRequest(data, req, resp)\n .then(() => this.logger.log(`Request logged`))\n .catch(e => {\n this.logger.error(`Error logging request: ${e.message}`);\n });\n }));\n }\n return next.handle();\n}\n```\n\n========================================\n\nCode:\n```text\npublic intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n\n    if (!this.reflector.get<boolean>(RequestMetaData.IS_PUBLIC_ROUTE, context.getHandler())) {\n        return next.handle().pipe(\n          map(data => {\n              const host = context.switchToHttp();\n              const req = host.getRequest();\n              const resp = host.getResponse();\n              this.persistRequest(data, req, resp)\n                .then(() => this.logger.log(`Request logged`))\n                .catch(e => {\n                    this.logger.error(`Error logging request: ${e.message}`);\n                });\n              return data;\n          }));\n    }\n    return next.handle();\n}\n```\n\n```text\npublic intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next\n      .handle()\n      .pipe(\n        catchError(err => {\n            return throwError(err);\n        })\n      );\n}\n```\n\n```text\nimport { of, EMPTY } from 'rxjs';\nimport { map, flatMap, catchError } from 'rxjs/operators';\n\nof(3,2,1,0,1,2,3).pipe(\n  flatMap(v => {\n    return of(v).pipe(\n      map(x => {    \n        if(x===0) throw Error();\n        return 6 / x;\n      }), \n      catchError(error => {\n        console.log(\"Shit happens\")\n        return EMPTY\n      }\n    )\n    )\n  } \n))\n.subscribe(val => console.log(\"Request \" + val + \" logged \"));\n```\n\n```text\npublic intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n\n    if (!this.reflector.get<boolean>(RequestMetaData.IS_PUBLIC_ROUTE, context.getHandler())) {\n\n        const host = context.switchToHttp();\n        const req = host.getRequest();\n        const resp = host.getResponse();\n\n        return next.handle().pipe(\n          tap({\n              next: (val) => {\n                  this.persistRequest(val, req, resp);\n              },\n              error: (error) => {\n                  this.persistRequest(AppError.from(error), req, resp);\n              }\n          })\n        );\n    }\n    return next.handle();\n}\n```\n\n```text\nflatMap\n```\n\n```text\ncatchError\n```\n\n```text\ntap\n```\n\n```text\npublic intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n\n    if (!this.reflector.get<boolean>(RequestMetaData.IS_PUBLIC_ROUTE, context.getHandler())) {\n        return next.handle().pipe(\n          finalize(() => {\n              const host = context.switchToHttp();\n              const req = host.getRequest();\n              const resp = host.getResponse();\n              this.persistRequest(data, req, resp)\n                .then(() => this.logger.log(`Request logged`))\n                .catch(e => {\n                    this.logger.error(`Error logging request: ${e.message}`);\n                });\n          }));\n    }\n    return next.handle();\n}\n```\n\n========================================\n\nComments:\n- Hey Michael! How's things? Would you care to provide an example? I'm not following.\n- Things are good. I have updated my answer to clarify the concept. Hope that helps.\n- I ended up using tap - thanks for pointing me in the right direction. Incidentally, the last FRP framework I used was one for Objective-C - I think it was called Reactive Cocoa.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.455Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":190,"estimatedTokens":1305}}591{"id":"stack-67194776","source":"stackoverflow","questionId":67194776,"title":"How to override an imported module in nestjs testing?","tags":["typescript","nestjs","nestjs-config"],"text":"Title: How to override an imported module in nestjs testing?\nTags: typescript, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI'm quite new on `nestjs`, met an issue regarding how to override the `load` function of `ConfigModule`, hope someone can help me out, thanks in advance!\n\nMy e2e testing:\n\n```\nconst moduleForTesting = await Test.createTestingModule({imports: [AppModule]});\n```\n\nMy App Module:\n\n```\nimport config from './config/index'\n\n@Module({\n imports: [ConfigModule.forRoot({isGlobal: true, load: [config]})]\n})\n```\n\nMy `config/index` file:\n\n```\nexport default async () => {\n someConfigs: ...\n}\n```\n\nNow I want the e2e testings use another configurations, but I don't know how to override the AppModule, nor the `load` function:\n\n```\n// AppModule\nimport config from './config/index' // This is ok for production, but need to be overridden in testing\n\n...\n imports: [ConfigModule.forRoot({isGlobal: true, load: [config]})]\n```\n\n========================================\n\nTop Answer:\nYou can use `overridProvider`\n\n```\nconst moduleForTesting = await Test.createTestingModule({imports: [AppModule]}).overrideProvider(MyService).useValue(myServiceMock).compile()\n```\n\n========================================\n\nCode:\n```js\nconst moduleForTesting = await Test.createTestingModule({imports: [AppModule]});\n```\n\n```js\nimport config from './config/index'\n\n@Module({\n  imports: [ConfigModule.forRoot({isGlobal: true, load: [config]})]\n})\n```\n\n```js\nexport default async () => {\n  someConfigs: ...\n}\n```\n\n```js\n// AppModule\nimport config from './config/index' // This is ok for production, but need to be overridden in testing\n\n...\n  imports: [ConfigModule.forRoot({isGlobal: true, load: [config]})]\n```\n\n```text\nnestjs\n```\n\n```text\nload\n```\n\n```text\nConfigModule\n```\n\n```text\nconfig/index\n```\n\n```text\nload\n```\n\n```js\n// e2e testing file\n\njest.mock('../src/config/index', () => ({\n    default: async () => ({\n        someConfigs: 'mocked config'\n    })\n})) // <--- By putting the `jest.mock` before the `createTestingModule`, the `load` array will be mocked.\n\n...\nconst moduleForTesting = await Test.createTestingModule({imports: [AppModule]});\n```\n\n```text\nconfig\n```\n\n```text\nload\n```\n\n```text\njest.mock\n```\n\n```text\nwithModule\n```\n\n```text\nTestModuleBuilder\n```\n\n```text\nconst moduleForTesting = await Test.createTestingModule({imports: [AppModule]}).overrideProvider(MyService).useValue(myServiceMock).compile()\n```\n\n```text\noverridProvider\n```\n\n```js\nexport const config = ConfigModule.forRoot({isGlobal: true, load: [config]});\n@Module({\n  imports: [\n    config \n  ],\n  controllers: [AppController],\n  providers: [AppService]\n})\nexport class AppModule {\n}\n```\n\n```js\nconst testConfig = ConfigModule.forRoot({isGlobal: false, load: []});\n\nconst builder = Test.createTestingModule({\n    imports: [AppModule]\n});\nconst override = builder.overrideModule(config);\noverride.useModule(testConfig);\nconst moduleFixture = await builder.compile();\napp = moduleFixture.createNestApplication();\nawait app.init();\n```\n\n```js\nconst builder = Test.createTestingModule({\n    imports: [AppModule]\n});\nconst override = builder.overrideModule(OtherModule);\noverride.useModule(TestOtherModule);\nconst moduleFixture = await builder.compile();\napp = moduleFixture.createNestApplication();\nawait app.init();\n```\n\n```text\nTestingModuleBuilder\n```\n\n```text\noverrideModule\n```\n\n```text\noverrideGuard\n```\n\n```text\noverrideInterceptor\n```\n\n```text\noverrideProvider\n```\n\n```text\nDynamicModule\n```\n\n```text\nOtherModule\n```\n\n========================================\n\nComments:\n- Does this answer your question: stackoverflow.com/questions/52095261/&hellip;?\n- Thank you @milo526, but I still don't know how to do it. Because the link you provided seems to use `overrideProvider`, but I need to `overrideModule`, which method is not exist.\n- Looks like this is scheduled for 10.0.0. great work. Will look into it more but do you know off hand what the difference is when using overrideProvider vs specifying a provider in the array when created the testing module ?\n- Quick search seems like I found it here","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":212,"estimatedTokens":1023}}592{"id":"stack-59438837","source":"stackoverflow","questionId":59438837,"title":"Nestjs websocket gateway, how to parse signed cookies from handshake for guard authorization?","tags":["node.js","cookies","socket.io","nestjs","nestjs-gateways"],"text":"Title: Nestjs websocket gateway, how to parse signed cookies from handshake for guard authorization?\nTags: node.js, cookies, socket.io, nestjs, nestjs-gateways\nSource: Stack Overflow\n\nQuestion:\nMy guard contains the following code:\n\n```\nlet client: Socket = context.switchToWs().getClient();\n const sessionCookie = client.handshake.headers.cookie\n .split('; ')\n .find((cookie: string) => cookie.startsWith('session'))\n .split('=')[1];\n\n const sessionId = cookieParser.signedCookie(\n sessionCookie,\n process.env.CryptoKey,\n );\n\n console.log('SESSION ID',sessionId);\n```\n\nThe resulting sessionId is still signed after calling cookieParse.signedCookie(); \n\nclient.request.cookies and signedCookies are both undefined. \n\nThe session id is there and the cookie is being sent by the browser but I am unable to parse it in the gateway.\n\n========================================\n\nTop Answer:\nIn addition to above this:\n\n```\nclient.handshake.headers.cookie?.split('; ')\n```\n\nOptional chaining (`.?`) is needed because there is possibility.\n\n========================================\n\nCode:\n```text\nlet client: Socket = context.switchToWs().getClient();\n    const sessionCookie = client.handshake.headers.cookie\n      .split('; ')\n      .find((cookie: string) => cookie.startsWith('session'))\n      .split('=')[1];\n\n    const sessionId = cookieParser.signedCookie(\n      sessionCookie,\n      process.env.CryptoKey,\n    );\n\n    console.log('SESSION ID',sessionId);\n```\n\n```text\nlet client: Socket = context.switchToWs().getClient();\n    const sessionCookie = client.handshake.headers.cookie\n      .split('; ')\n      .find((cookie: string) => cookie.startsWith('session'))\n      .split('=')[1];\n\n    const sessionId = cookieParser.signedCookie(\n      decodeURIComponent(sessionCookie),\n      process.env.CryptoKey,\n    );\n\n    console.log('SESSION ID',sessionId);\n```\n\n```text\ncookieParser.signedCookie(...)\n```\n\n```text\ndecodeURIComponent(sessionCookie)\n```\n\n```js\nclient.handshake.headers.cookie?.split('; ')\n```\n\n```text\n.?\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":87,"estimatedTokens":505}}593{"id":"stack-60505656","source":"stackoverflow","questionId":60505656,"title":"How to set response header in nestjs with fastify","tags":["nestjs","fastify"],"text":"Title: How to set response header in nestjs with fastify\nTags: nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set a custom reponse header in a nest js controller and using fastify.\n\nCurrently I'm trying to do:\n\n```\n@Post()\nasync methodName(@Res res) {\n res.set('key', 'value');\n};\n```\n\nBut I get the error:\n\n```\nres.set is not a function\n```\n\nCan someone help me?\n\n========================================\n\nTop Answer:\nIf you are needing to set a static header value as well, you can always use the `@Header()` decorator on the route handler so you could have\n\n```\n@Post()\n@Header('key', 'value')\nasync method() {\n return something;\n}\n```\n\n========================================\n\nCode:\n```ts\n@Post()\nasync methodName(@Res res) {\n    res.set('key', 'value');\n};\n```\n\n```text\nres.set is not a function\n```\n\n```text\nres.header('key', 'value');\n```\n\n```js\n@Post()\n@Header('key', 'value')\nasync method() {\n  return something;\n}\n```\n\n```text\n@Header()\n```\n\n```js\nimport { Controller, Post, Req, Res } from '@nestjs/common';\nimport { FastifyReply, FastifyRequest } from 'fastify';\nimport { parse } from 'cookie';\n\n@Controller('auth')\nexport class AuthController {\n    public static parseCookies(request: FastifyRequest): Record<string, string> {\n        const cookieString = request.headers['cookie'] as string;\n\n        return parse(cookieString || '');\n    }\n\n    public static setCookies(response: FastifyReply, ...cookies: string[]) {\n        cookies.forEach((cookie) => {\n            response.header('set-cookie', cookie);\n        });\n    }\n\n    @Post('logout')\n    public async logout(@Res({ passthrough: true }) response: FastifyReply): Promise<void> {\n        const { accessToken, refreshToken } = extract(this.configService, 'auth');\n    \n        AuthController.setCookies(response, `access_token=; Max-Age=0`, `refresh_token=; Max-Age=0`);\n    }\n}\n```\n\n========================================\n\nComments:\n- What is the type for the `response`?\n- What if I want to pass a dynamic value to a header? Let's say a filename to the \"Content-Disposition\" header?\n- You could use `@Res({ passthrough: true }) response: FastifyReply` to do `response.header()` and still have Nest handle sending the response\n- `@Res({ passthrough: true })` did the trick for me.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":102,"estimatedTokens":569}}594{"id":"stack-60334856","source":"stackoverflow","questionId":60334856,"title":"Class validator with array of nested objects in nestjs","tags":["typescript","nestjs","dto","class-validator"],"text":"Title: Class validator with array of nested objects in nestjs\nTags: typescript, nestjs, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to validate array of nested objects in nestjs and it works fine. But if I send non-array value like string or null, then I get an error:\n\n`TypeError: Cannot read property 'length' of undefined.` \n\nNested field:\n\n```\n@IsArray()\n@ValidateNested({ each: true })\n@Type(() => NestedDTO)\nnested: NestedDTO[];\n```\n\nHow can I validate that value is an array before validate nested objects?\n\nVersions:\n\n```\nNestJS: 6.10.14\nclass-validator: 0.11.0\n```\n\n========================================\n\nCode:\n```text\n@IsArray()\n@ValidateNested({ each: true })\n@Type(() => NestedDTO)\nnested: NestedDTO[];\n```\n\n```text\nNestJS: 6.10.14\nclass-validator: 0.11.0\n```\n\n```text\nTypeError: Cannot read property 'length' of undefined.\n```\n\n```text\nimport { Type } from 'class-transformer';\nimport {\n  IsString,\n  registerDecorator,\n  ValidateNested,\n  ValidationArguments,\n  ValidationOptions,\n} from 'class-validator';\n\nexport function IsArrayOfObjects(validationOptions?: ValidationOptions) {\n  return (object: unknown, propertyName: string) => {\n    registerDecorator({\n      name: 'IsArrayOfObjects',\n      target: object.constructor,\n      propertyName,\n      constraints: [],\n      options: validationOptions,\n      validator: {\n        validate(value: any): boolean {\n          return (\n            Array.isArray(value) &&\n            value.every(\n              (element: any) =>\n                element instanceof Object && !(element instanceof Array),\n            )\n          );\n        },\n        defaultMessage: (validationArguments?: ValidationArguments): string =>\n          `${validationArguments.property} must be an array of objects`,\n      },\n    });\n  };\n}\n```\n\n```text\nexport class NestedDTO {\n  @IsString()\n  someProperty: string;\n}\n```\n\n```text\n@IsArrayOfObjects()\n@ValidateNested()\n@Type(() => NestedDTO)\nnested: NestedDTO[];\n```\n\n```text\nIsArrayOfObjects\n```\n\n```text\n@Type\n```\n\n```text\nclass-transformer\n```\n\n```text\nNestedDTO\n```\n\n```text\nIsArrayOfObjects\n```\n\n```text\nvalue.length > 0\n```\n\n```text\ndefaultMessage\n```\n\n========================================\n\nComments:\n- welcome to the community, please with us your class-validator && nestjs version.\n- Thanks! Updated. NestJS: 6.10.14 class-validator: 0.11.0\n- ValidateNested() doesn't work with custom objects","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":130,"estimatedTokens":604}}595{"id":"stack-62980087","source":"stackoverflow","questionId":62980087,"title":"NestJS serialization from snake_case to camelCase","tags":["serialization","nestjs","class-transformer","mikro-orm"],"text":"Title: NestJS serialization from snake_case to camelCase\nTags: serialization, nestjs, class-transformer, mikro-orm\nSource: Stack Overflow\n\nQuestion:\nI want to achieve automatic serialization/deserialization of JSON request/response body for NestJS controllers, to be precise, automatically convert `snake_case` request body JSON keys to `camelCase` received at my controller handler and vice versa.\n\nWhat I found is to use `class-transformer`'s `@Expose({ name: 'selling_price' })`, as on the example below (I'm using MikroORM):\n\n```\n// recipe.entity.ts\n@Entity()\nexport class Recipe extends BaseEntity {\n @Property()\n name: string;\n \n @Expose({ name: 'selling_price' })\n @Property()\n sellingPrice: number;\n}\n```\n\n```\n// recipe.controller.ts\n@Controller('recipes')\nexport class RecipeController {\n constructor(private readonly service: RecipeService) {}\n\n @Post()\n async createOne(@Body() data: Recipe): Promise {\n console.log(data);\n return this.service.createOne(data);\n }\n}\n```\n\n```\n// example request body\n{\n \"name\": \"Recipe 1\",\n \"selling_price\": 50000\n}\n```\n\n```\n// log on the RecipeController.createOne handler method\n{ name: 'Recipe 1',\n selling_price: 50000 }\n\n// what I wanted on the log\n{ name: 'Recipe 1',\n sellingPrice: 50000 }\n```\n\nThere can be seen that the `@Expose` annotation works perfectly, but going further I want to be able to convert it as the attribute's name on the entity: `sellingPrice`, so I can directly pass the parsed request body to my service and to my repository method `this.recipeRepository.create(data)`. Current condition is the `sellingPrice` field would be null because there exists the `selling_price` field instead. If I don't use `@Expose`, the request JSON would need to be written on `camelCase` and that's not what I prefer.\n\nI can do DTOs and constructors and assigning fields, but I think that's rather repetitive and I'll have a lot of fields to convert due to my naming preference: `snake_case` on JSON and database columns and `camelCase` on all of the JS/TS parts.\n\nIs there a way I can do the trick cleanly? Maybe there's a solution already. Perhaps a global interceptor to convert all `snake_case` to `camel_case` but I'm not really sure how to implement one either.\n\nThanks!\n\n========================================\n\nCode:\n```text\n// recipe.entity.ts\n@Entity()\nexport class Recipe extends BaseEntity {\n  @Property()\n  name: string;\n  \n  @Expose({ name: 'selling_price' })\n  @Property()\n  sellingPrice: number;\n}\n```\n\n```text\n// recipe.controller.ts\n@Controller('recipes')\nexport class RecipeController {\n  constructor(private readonly service: RecipeService) {}\n\n  @Post()\n  async createOne(@Body() data: Recipe): Promise<Recipe> {\n    console.log(data);\n    return this.service.createOne(data);\n  }\n}\n```\n\n```text\n// example request body\n{\n    \"name\": \"Recipe 1\",\n    \"selling_price\": 50000\n}\n```\n\n```text\n// log on the RecipeController.createOne handler method\n{ name: 'Recipe 1',\n  selling_price: 50000 }\n\n// what I wanted on the log\n{ name: 'Recipe 1',\n  sellingPrice: 50000 }\n```\n\n```text\nsnake_case\n```\n\n```text\ncamelCase\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Expose({ name: 'selling_price' })\n```\n\n```text\n@Expose\n```\n\n```text\nsellingPrice\n```\n\n```text\nthis.recipeRepository.create(data)\n```\n\n```text\nsellingPrice\n```\n\n```text\nselling_price\n```\n\n```text\n@Expose\n```\n\n```text\ncamelCase\n```\n\n```text\nsnake_case\n```\n\n```text\ncamelCase\n```\n\n```text\nsnake_case\n```\n\n```text\ncamel_case\n```\n\n```js\nconst meta = em.getMetadata().get('Recipe');\nconst data = {\n  name: 'Recipe 1',\n  selling_price: 50000,\n};\nconst res = em.getDriver().mapResult(data, meta);\nconsole.log(res); // dumps `{ name: 'Recipe 1', sellingPrice: 50000 }`\n```\n\n```text\nmapResult()\n```\n\n```text\nfieldName\n```\n\n========================================\n\nComments:\n- You could use the ORM's driver method `mapResult()` that is internally used for converting the raw results from database - all it does is basically to convert fieldNames (how the db column is called) to property names (how the entity property is called).\n- That'd be neat, I'm doing similar thing as well, but against the request body. Is there a correct way to get to the `mapResult()` driver method? Getting the driver instance and `EntityMetadata`? Or do you suggest me to borrow and write the `mapResult()` implementation for my own util function, perhaps? Anyway great ORM @MartinAd&#225;mek thanks for the library :)\n- Thank you! That works like a charm. I ended up using this on my controller and probably will setup a kind of decorator to make it looks cleaner","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":194,"estimatedTokens":1141}}596{"id":"stack-70268925","source":"stackoverflow","questionId":70268925,"title":"Advantages of using @Module NestJS","tags":["nestjs"],"text":"Title: Advantages of using @Module NestJS\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm making a new NestJS app and after a lot of errors on the first because the multiple modules I created didn't have the correct `imports`, `providers`, `exports`, `TypeOrmModule.forFeature` etc made me wonder: What was the point?\n\nWhy not use only the `app.module` and just dump everything in it? All the controllers and services and entity types and any other that may come up?\n\nFrom the documentation:\n\nWe want to emphasize that modules are strongly recommended as an\neffective way to organize your components\n\nIs that the only reason? Organization?\nDoes dependency injection play a role of some kind?\n\nEdit:\n\nIf organization is the main reason, why not separate in a different folder with a controller and service? Basically a module without the imports, providers etc. Doing the same thing with less boilerplate.\n\n========================================\n\nTop Answer:\nWhy not use only the app.module and just dump everything in it?\n\nBetter yet, why use multiple files at all? Why not just have a couple thousand line `index.js` with no types, no organization, just raw JS all the way down?\n\nThe answer? Code organization and ease of re-use. By making these modules, you *should* be grouping together similar logic together. All the code for a single feature *should* be available by just importing `FeatureModule` and usable. When it comes to library modules, this becomes pretty apparent: `TypeOrmModule` has a `forRoot/forRootAsync` and a `forFeature` which exposes ways to inject repositories into your services. The `JwtModule` has a `register/registerAsync` and exposes a `JwtService` so you can configure the `JwtService` once and re-use the provider.\n\nWhen dealing with entity features this may look messier, but technically it's all still possible, so that in theory you'd be able to take `FeatureModule` from Application A and drop it into Application B and have everything still working with regards to the `FeatureModule`, similar to how pulumi has the idea of stacks and applications and you can just spin up new applications using the same group of components.\n\nThe module system, once you get the hang of it, and in my opinion, makes it very easy to recognize what all a module will be working with, with regards to other features and how they're connected. It's just a matter of discipline and learning the feature of the framework.\n\n========================================\n\nCode:\n```text\nimports\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\napp.module\n```\n\n```text\nindex.js\n```\n\n```text\nFeatureModule\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nforRoot/forRootAsync\n```\n\n```text\nforFeature\n```\n\n```text\nJwtModule\n```\n\n```text\nregister/registerAsync\n```\n\n```text\nJwtService\n```\n\n```text\nJwtService\n```\n\n```text\nFeatureModule\n```\n\n```text\nFeatureModule\n```\n\n========================================\n\nComments:\n- had the same question ever since someone forced me to use angular. I find the module concept onerous. just desperate to use decorators and classes in a language that doesn't need or want them\n- NestJS copies Angular modules model, where it provides two main advantages: pure code organization and chunking app for lazy loading. Well, since then Angular introduced standalone components specifically to simplify mental model of code organization (does this mean that standard TS modules are good enough? I think yes). And lazy loading was never a desired feature for backend. So, I'd say modules in NestJS are useless, with few minor exceptions like libraries and maybe AppModule. That's just my opinion, though, and I'm not exactly a NestJS expert.\n- So the answer is yes? Organization only (and maybe, just maybe, reuse in another project)?\n- @LucasSteffen you dont need have one module for each context.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":108,"estimatedTokens":969}}597{"id":"stack-53230332","source":"stackoverflow","questionId":53230332,"title":"Injecting Mocks in NestJS Application for Contract Testing","tags":["javascript","node.js","typescript","nestjs","pact"],"text":"Title: Injecting Mocks in NestJS Application for Contract Testing\nTags: javascript, node.js, typescript, nestjs, pact\nSource: Stack Overflow\n\nQuestion:\n### Issue\n\nI'm looking for a way to bring up a NestJS application with mocked providers. This is necessary for provider contract tests because a service needs to be brought up in isolation. Using the Pact library, testing the provider assumes that the provider service is already running. It needs to be able to make HTTP requests against the actual server (with some dependencies mocked if necessary). PactJS\n\n### Current Research\n\nI've looked into the docs for NestJS and the closest solution I can find is pasted below. From what I can tell, this solution tells the module to replace any provider called `CatsService` with `catsService`. This theoretically would work for provider contract testing purposes, but I don't think this allows for the entire app to be brought up, just a module. There is no mention in the docs for being able to bring up the app on a specific port using the testing module. I've tried to call `app.listen` on the returned app object and it fails to hit a breakpoint placed right after the call.\n\n```\nimport * as request from \"supertest\";\nimport { Test } from \"@nestjs/testing\";\nimport { CatsModule } from \"../../src/cats/cats.module\";\nimport { CatsService } from \"../../src/cats/cats.service\";\nimport { INestApplication } from \"@nestjs/common\";\n\ndescribe(\"Cats\", () => {\n let app: INestApplication;\n let catsService = { findAll: () => [\"test\"] };\n\n beforeAll(async () => {\n const module = await Test.createTestingModule({\n imports: [CatsModule]\n })\n .overrideProvider(CatsService)\n .useValue(catsService)\n .compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n it(`/GET cats`, () => {\n return request(app.getHttpServer())\n .get(\"/cats\")\n .expect(200)\n .expect({\n data: catsService.findAll()\n });\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\n### Java Example\n\nUsing Spring a configuration class, mocks can be injected into the app when running with the \"contract-test\" profile.\n\n```\n@Profile({\"contract-test\"})\n@Configuration\npublic class ContractTestConfig {\n\n @Bean\n @Primary\n public SomeRepository getSomeRepository() {\n return mock(SomeRepository.class);\n }\n\n @Bean\n @Primary\n public SomeService getSomeService() {\n return mock(SomeService.class);\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport * as request from \"supertest\";\nimport { Test } from \"@nestjs/testing\";\nimport { CatsModule } from \"../../src/cats/cats.module\";\nimport { CatsService } from \"../../src/cats/cats.service\";\nimport { INestApplication } from \"@nestjs/common\";\n\ndescribe(\"Cats\", () => {\n  let app: INestApplication;\n  let catsService = { findAll: () => [\"test\"] };\n\n  beforeAll(async () => {\n    const module = await Test.createTestingModule({\n      imports: [CatsModule]\n    })\n      .overrideProvider(CatsService)\n      .useValue(catsService)\n      .compile();\n\n    app = module.createNestApplication();\n    await app.init();\n  });\n\n  it(`/GET cats`, () => {\n    return request(app.getHttpServer())\n      .get(\"/cats\")\n      .expect(200)\n      .expect({\n        data: catsService.findAll()\n      });\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n```\n\n```text\n@Profile({\"contract-test\"})\n@Configuration\npublic class ContractTestConfig {\n\n  @Bean\n  @Primary\n  public SomeRepository getSomeRepository() {\n    return mock(SomeRepository.class);\n  }\n\n  @Bean\n  @Primary\n  public SomeService getSomeService() {\n    return mock(SomeService.class);\n  }\n}\n```\n\n```text\nCatsService\n```\n\n```text\ncatsService\n```\n\n```text\napp.listen\n```\n\n```text\nbeforeAll(async () => {\n  const moduleFixture = await Test.createTestingModule({\n    imports: [AppModule],\n  })\n    .overrideProvider(AppService).useValue({ root: () => 'Hello Test!' })\n    .compile();\n\n  app = moduleFixture.createNestApplication();\n  await app.init();\n  await app.listenAsync(3000);\n        ^^^^^^^^^^^^^^^^^^^^^\n});\n```\n\n```text\nimport * as http from 'http';\n\n// ...\n\nit('/GET /', done => {\n  http.get('http://localhost:3000/root', res => {\n    let data = '';\n    res.on('data', chunk => data = data + chunk);\n    res.on('end', () => {\n      expect(data).toEqual('Hello Test!');\n      expect(res.statusCode).toBe(200);\n      done();\n    });\n  });\n});\n```\n\n```text\nafterAll(() => app.close());\n```\n\n```text\nlisten\n```\n\n```text\nPromise\n```\n\n```text\nlistenAsync\n```\n\n```text\nlisten\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- I just realized that the part about `listenAsync` was outdated, but the rest works for me. I can also request the site in the browser while running the test. I'm running version 5.3.5\n- Thank you so much!","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":208,"estimatedTokens":1191}}598{"id":"stack-68117902","source":"stackoverflow","questionId":68117902,"title":"How can I get redis io client from NestJS CacheManager module","tags":["nestjs","node-redis","cachemanager"],"text":"Title: How can I get redis io client from NestJS CacheManager module\nTags: nestjs, node-redis, cachemanager\nSource: Stack Overflow\n\nQuestion:\nI am currently using cache manager module from NestJS and I was wondering why I can't get the NodeRedis client like this :\n\n```\nconstructor(\n @Inject(CACHE_MANAGER) private cacheManager: Cache,\n ) {\n cacheManager.store.getClient();\n }\n```\n\nI am getting this error :\n\n```\nERROR in [...].controller.ts:24:24\nTS2339: Property 'getClient' does not exist on type 'Store'.\n 22 | @Inject(CACHE_MANAGER) private cacheManager: Cache,\n 23 | ) {\n > 24 | cacheManager.store.getClient();\n | ^^^^^^^^^\n 25 | }\n```\n\nI did configured the cache-manager-redis-store when I registered the CacheModule then I supposed I could get the client.\n\n========================================\n\nCode:\n```text\nconstructor(\n    @Inject(CACHE_MANAGER) private cacheManager: Cache,\n  ) {\n    cacheManager.store.getClient();\n  }\n```\n\n```text\nERROR in [...].controller.ts:24:24\nTS2339: Property 'getClient' does not exist on type 'Store'.\n    22 |     @Inject(CACHE_MANAGER) private cacheManager: Cache,\n    23 |   ) {\n  > 24 |     cacheManager.store.getClient();\n       |                        ^^^^^^^^^\n    25 |   }\n```\n\n```js\nimport { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';\nimport { Store } from 'cache-manager';\nimport Redis from 'redis';\n\ninterface RedisCache extends Cache {\n  store: RedisStore;\n}\n\ninterface RedisStore extends Store {\n  name: 'redis';\n  getClient: () => Redis.RedisClient;\n  isCacheableValue: (value: any) => boolean;\n}\n\n@Injectable()\nexport class CacheService {\n  constructor(\n    @Inject(CACHE_MANAGER)\n    private cacheManager: RedisCache,\n  ) {\n    cacheManager.store.getClient();\n  }\n}\n```\n\n```text\ncache-manager-redis-store\n```\n\n```text\nRedisCache\n```\n\n```text\nCACHE_MANAGER\n```\n\n```text\ncache-manager\n```\n\n```text\ncaching\n```\n\n```text\nCache\n```\n\n```text\ncache-manager\n```\n\n```text\nStore\n```\n\n```text\ngetClient\n```\n\n```text\ncaching-manager\n```\n\n```text\ncache-manager-redis-store\n```\n\n```text\nStore\n```\n\n```text\ngetClient\n```\n\n```text\ncacheManager\n```\n\n```text\ngetClient\n```\n\n```text\ncacheManager\n```\n\n```text\nRedisCache\n```\n\n```text\ncache-manager-redis-store\n```\n\n```text\nredisStore.CacheManagerRedisStore.RedisCache\n```\n\n```text\nredisStore\n```\n\n```text\nCacheManagerRedisStore\n```\n\n========================================\n\nComments:\n- i got error cacheManager.store.getClient is not a function\n- So do I, do you have any progress with that?\n- In my case, with the `cache-manager-redis-yet` package, I did: `(app.get(CACHE_MANAGER) as RedisCache).store.client`. `RedisCache` is imported from the same package.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":166,"estimatedTokens":667}}599{"id":"stack-62088040","source":"stackoverflow","questionId":62088040,"title":"Storing token on server-side using nestjs","tags":["node.js","nestjs"],"text":"Title: Storing token on server-side using nestjs\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a nestjs application that consumes third party API for data. In order to use that third party API, I need to pass along an access token. This access token is application-wide and not attached to any one user. \n\nWhat would be the best place to store such a token in Nestjs, meeting the following requirements:\n\n- It must be available in the application and not per given user\n\n- It must not be exposed to the frontend application\n\n- It must work in a load balancer setup\n\nI am looking at Nestjs caching https://docs.nestjs.com/techniques/caching, but I am not sure whether that's the best practice and if it is - should I use it with in-memory storage or something like redis. \n\nThank you.\n\n========================================\n\nTop Answer:\nI used a custom provider. Nest allows you to load async custom providers.\n\n```\nexport const apiAuth = {\n provide: 'API_AUTH',\n useFactory: async (authService: AuthService) => {\n return await authService.createOrUpdateAccessToken()\n },\n inject: [AuthService]\n}\n```\n\nand below is my api client.\n\n```\n@Injectable()\nexport class ApiClient {\n constructor(@Inject('API_AUTH') private auth: IAuth, private authService: AuthService) { }\n public async getApiClient(storeId: string): Promise {\n if (((Date.now() - this.auth.createdAt.getTime()) > ((this.auth.expiresIn - 14400) * 1000))) {\n this.auth = await this.authService.createOrUpdateAccessToken()\n }\n return new ApiClient(storeId, this.auth.accessToken);\n }\n}\n```\n\nThis way token is requested from storage once and lives with the application, when expired token is re-generated and updated.\n\n========================================\n\nCode:\n```text\nexport const apiAuth = {\n  provide: 'API_AUTH',\n  useFactory: async (authService: AuthService) => {\n    return await authService.createOrUpdateAccessToken()\n  },\n  inject: [AuthService]\n}\n```\n\n```text\n@Injectable()\nexport class ApiClient {\n  constructor(@Inject('API_AUTH') private auth: IAuth, private authService: AuthService) { }\n  public async getApiClient(storeId: string): Promise<ApiClient> {\n    if (((Date.now() - this.auth.createdAt.getTime()) > ((this.auth.expiresIn - 14400) * 1000))) {\n      this.auth = await this.authService.createOrUpdateAccessToken()\n    }\n    return new ApiClient(storeId, this.auth.accessToken);\n  }\n}\n```\n\n========================================\n\nComments:\n- Hi Jay, how can I use Redis to blacklist my token on logout instead, in nestjs ?. Any resources/ideas to suggest would be greatly appreciated","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":81,"estimatedTokens":648}}600{"id":"stack-69237599","source":"stackoverflow","questionId":69237599,"title":"NestJS + Mongoose schema with a custom typescript Type","tags":["typescript","mongodb","mongoose","nestjs","mongoose-schema"],"text":"Title: NestJS + Mongoose schema with a custom typescript Type\nTags: typescript, mongodb, mongoose, nestjs, mongoose-schema\nSource: Stack Overflow\n\nQuestion:\nI'm Trying to create a Mongo Schema, using `nestjs/mongoose` decorators, from the following class:\n\n```\n@Schema()\nexport class Constraint {\n @Prop()\n reason: string;\n\n @Prop()\n status: Status;\n\n @Prop()\n time: number;\n}\n```\n\nThe problem is `Status` is defined as followed:\n\n```\nexport type Status = boolean | 'pending';\n```\n\nAnd I cannot figure out what to pass to the `status`'s `prop` decorator, since I'm getting the following error:\n\n```\nError: Cannot determine a type for the \"Constraint.status\" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a \"@Prop({ type: TYPE_HERE })\" decorator\n```\n\nand `{ type: Status }` doesn't work, since `Status` is a `type` and not a `Class`.\n\n========================================\n\nTop Answer:\nI had the same problem, and thanks to @sven-stam, as he mentioned here, I implemented Mixed type like this:\n\n```\nimport { Prop, Schema } from '@nestjs/mongoose';\nimport mongoose, {\n HydratedDocument,\n Schema as MongooseSchema,\n} from 'mongoose';\n\nexport type UserDocument = HydratedDocument;\n\n@Schema()\nclass User {\n @Prop()\n username: string\n\n @Prop({default: false, type: MongooseSchema.Types.Mixed })\n paid: boolean | 'waiting'\n}\n```\n\n========================================\n\nCode:\n```js\n@Schema()\nexport class Constraint {\n  @Prop()\n  reason: string;\n\n  @Prop()\n  status: Status;\n\n  @Prop()\n  time: number;\n}\n```\n\n```js\nexport type Status = boolean | 'pending';\n```\n\n```text\nError: Cannot determine a type for the \"Constraint.status\" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a \"@Prop({ type: TYPE_HERE })\" decorator\n```\n\n```text\nnestjs/mongoose\n```\n\n```text\nStatus\n```\n\n```text\nstatus\n```\n\n```text\nprop\n```\n\n```text\n{ type: Status }\n```\n\n```text\nStatus\n```\n\n```text\ntype\n```\n\n```text\nClass\n```\n\n```text\nstatus\n```\n\n```js\nimport { Prop, Schema } from '@nestjs/mongoose';\nimport mongoose, {\n  HydratedDocument,\n  Schema as MongooseSchema,\n} from 'mongoose';\n\nexport type UserDocument = HydratedDocument<User>;\n\n@Schema()\nclass User {\n  @Prop()\n  username: string\n\n  @Prop({default: false, type: MongooseSchema.Types.Mixed })\n  paid: boolean | 'waiting'\n}\n```\n\n========================================\n\nComments:\n- Hello, I am facing the same problem, did you find a solution ?","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":143,"estimatedTokens":617}}601{"id":"stack-65238655","source":"stackoverflow","questionId":65238655,"title":"Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?","tags":["typescript","graphql","nestjs","dry","typeorm"],"text":"Title: Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?\nTags: typescript, graphql, nestjs, dry, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm creating a GraphQL API using NestJS and TypeORM. Starting with the classic User entity I've created both the `user.type.ts` and the `user.entity.ts` as described by the Nestjs documentation.\n\nThis is an example of the content:\n\n- `user.entity.ts`\n\n```\n@Entity({ schema: 'mydb', name: 'userList' })\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n guid: string;\n\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n\n // ...\n```\n\n- `user.type.ts`\n\n```\n@ObjectType()\nexport class UserType {\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n firstName: string;\n\n @Field()\n lastName: string;\n\n // ...\n```\n\nThe question is: since they use the same fields, can I create a single class that combines the decorators of both classes?\n\nFor instance:\n\n```\n@Entity({ schema: 'mydb', name: 'userList' })\n@ObjectType()\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Field()\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n```\n\nIs it an antipattern? are there any limitations or downsides in doing it?\n\nThanks in advance\n\n========================================\n\nTop Answer:\nI have the case where the Entities don't match the objects precisely.\nI have orders with products, but I only store the productId and resolve the product data fresh from a different system.\n\nHere I think it makes more sense to separate the two for type safety.\nI don't get the real product {} object back, only the productId, but typescript thinks I have both there.\n\n========================================\n\nCode:\n```js\n@Entity({ schema: 'mydb', name: 'userList' })\nexport class User {\n\n    @Column('varchar', { name: 'guid', unique: true, length: 36 })\n    guid: string;\n\n    @Column('varchar', { name: 'firstName', length: 50 })\n    firstName: string;\n\n    @Column('varchar', { name: 'lastName', length: 100 })\n    lastName: string;\n\n    // ...\n```\n\n```js\n@ObjectType()\nexport class UserType {\n  @Field({\n    name: 'ID',\n    description: 'Global Universal ID of the User',\n  })\n  guid: string;\n\n  @Field()\n  firstName: string;\n\n  @Field()\n  lastName: string;\n\n  // ...\n```\n\n```js\n@Entity({ schema: 'mydb', name: 'userList' })\n@ObjectType()\nexport class User {\n\n    @Column('varchar', { name: 'guid', unique: true, length: 36 })\n    @Field({\n      name: 'ID',\n      description: 'Global Universal ID of the User',\n    })\n    guid: string;\n\n    @Field()\n    @Column('varchar', { name: 'firstName', length: 50 })\n    firstName: string;\n\n    @Field()\n    @Column('varchar', { name: 'lastName', length: 100 })\n    lastName: string;\n```\n\n```text\nuser.type.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.type.ts\n```\n\n========================================\n\nComments:\n- Hi! Thanks for the reply!\n- I've been using the DTO with REST, but in graphql I think they are useless since the field mapping and the validations are done by graphql. Moreover, for the arguments of the queries/mutations I'm using a separated class. The mixed class I'm referring above would be used only for the gql payload and I can easily hide/transform/extends fields with the graphl decorators. For now I really don't see the point of keeping them separated. Could you give me a real-world example?\n- @Joseph - One great example I can name is when your API field name should be different than your database's field name. If you build the entity and GraphQL object together, you are stuck with the api name and entity field names having to be the same. Might not seem like an issue, but it can be.\n- Thanks! Yes I was thinking the same but actually with the @Field decorator on Nestjs you can define the mapping of a field name. For instance: `@Field({name: ID}) guid: string;` it means that your db field is called guid but it's exposed as ID. Also you can @HideField and stuff like that. For now I don't see limitation but I'll try to spot them as well","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":166,"estimatedTokens":1109}}602{"id":"stack-76227334","source":"stackoverflow","questionId":76227334,"title":"Mongoose, how to enforce LeanDocument type?","tags":["typescript","mongoose","nestjs","typescript-generics","nestjs-mongoose"],"text":"Title: Mongoose, how to enforce LeanDocument type?\nTags: typescript, mongoose, nestjs, typescript-generics, nestjs-mongoose\nSource: Stack Overflow\n\nQuestion:\nIn our codebase we've been using `T.lean()` or `T.toObject()` and our return types would be `LeanDocument`. Mongoose 7 no longer exports LeanDocument, and the existing migration guide suggests using the following setup:\n\n```\n// Do this instead, no `extends Document`\ninterface ITest {\n name?: string;\n}\nconst Test = model('Test', schema);\n\n// If you need to access the hydrated document type, use the following code\ntype TestDocument = ReturnType;\n```\n\nBut this gives me `HydratedDocument` that I can get by `HydratedDocument`, which is not what I want since it has all the document methods on it.\n\nAs an alternative I can use just `T` as my return type, but then any `Document` is matching `T`.\n\nI'd like to enforce that the result is a POJO, to prevent documents leaking from our DAL.\n\nHow can I achieve that with typescript and mongoose types?\n\n========================================\n\nTop Answer:\nThe return type for lean documents in generel in mongoose 8 is:\n\n```\n(mongoose.FlattenMaps & Required) | null\n```\n\n========================================\n\nCode:\n```js\n// Do this instead, no `extends Document`\ninterface ITest {\n  name?: string;\n}\nconst Test = model<ITest>('Test', schema);\n\n// If you need to access the hydrated document type, use the following code\ntype TestDocument = ReturnType<(typeof Test)['hydrate']>;\n```\n\n```text\nT.lean()\n```\n\n```text\nT.toObject()\n```\n\n```text\nLeanDocument<T>\n```\n\n```text\nHydratedDocument\n```\n\n```text\nHydratedDocument<T>\n```\n\n```text\nT\n```\n\n```text\nDocument<T>\n```\n\n```text\nT\n```\n\n```js\n// utils.ts\nexport type LeanDocument<T> = T & { $locals?: never };\n```\n\n```js\nasync function getById(id: string): Promise<LeanDocument<User>> {\n  const user = await UserModel.findById(id);\n  return user;\n  //       ^ Types of property '$locals' are incompatible.\n}\n```\n\n```js\nexport type LeanDocument<T> = T & T extends { $locals: never }\n  ? T\n  : 'Please convert the document to a plain object via `.toObject()`';\n```\n\n```js\nasync function getById(id: string): Promise<LeanDocument<User>> {\n  const user = await UserModel.findById(id);\n  return user;\n  //       ^ Type 'Document<unknown, any, User> & Omit<User & { _id: ObjectId; }, never>'\n  // is not assignable to type \n  // '\"Please convert the document to a plain object via `.toObject()`\"'.ts(2322)\n}\n```\n\n```text\nType error ... \"You've forgot to convert to a lean document\".\n```\n\n```js\n(mongoose.FlattenMaps<unknown> & Required<{ _id: unknown; }>) | null\n```\n\n========================================\n\nComments:\n- Hi @EcksDy, were you able to extract POJO from mongoose document? if yes, can you please your solution\n- You can use `doc.toObject()` or `doc.toJSON()` to get a POJO instead of a document. The purpose of the question was to see how can I enforce conversion to POJO via the type system.\n- yes, i am also trying to achieve POJO using type system. Already spent couple of days without any luck. I will use toObject or toJSON as last resort\n- Look at the second edit, I've made a followup question on the topic. Just marking the return value as the type you expect is not enough, as in runtime you will have the full document returned. So while you won't be able to access document properties - they will still be there. That's why you still want to use `.toObject()` or `.toJSON()`, as these are the best ways to make sure you don't leak the actual document out.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":125,"estimatedTokens":881}}603{"id":"stack-71701061","source":"stackoverflow","questionId":71701061,"title":"Can't run nestjs build without node_modules folder","tags":["node.js","typescript","nestjs"],"text":"Title: Can't run nestjs build without node_modules folder\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm developing a **Nestjs** micro-service and need to run the build in **dist** folder using below command and it's working fine\n\n```\nnode dist/main.js\n```\n\nProblem is, above command not working without the **node_modules** folder. Why can't we run the the build folder(**dist**) without node_modules folder?\n\nThis is the error I'm getting\nhttps://i.sstatic.net/wBwab.png\n\n========================================\n\nTop Answer:\nNo, you can't. Node.js are depended on package.json for finding modules, which also depend on node_modules that store the module. Maybe you want to compile it as one ? Try this https://github.com/vercel/ncc. I never use it for Nest.js before, but you can try it.\n\n========================================\n\nCode:\n```text\nnode dist/main.js\n```\n\n```text\npkg\n```\n\n========================================\n\nComments:\n- Your answer could be improved by providing an example of the solution and how it helps the OP.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":36,"estimatedTokens":266}}604{"id":"stack-61579377","source":"stackoverflow","questionId":61579377,"title":"When to use ExceptionFilter vs BaseExceptionFilter in NestJS?","tags":["nestjs"],"text":"Title: When to use ExceptionFilter vs BaseExceptionFilter in NestJS?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nWhat is the diff b/w both types of filters. And when to use what? Please explain with any example\n\n```\n@Catch(HttpException)\nexport class HttpExceptionFilter implements ExceptionFilter {\n\n}\n\n@Catch()\nexport class AllExceptionsFilter extends BaseExceptionFilter {\n\n}\n```\n\n========================================\n\nCode:\n```text\n@Catch(HttpException)\nexport class HttpExceptionFilter implements ExceptionFilter {\n\n}\n\n@Catch()\nexport class AllExceptionsFilter extends BaseExceptionFilter {\n\n}\n```\n\n```text\nExceptionFilter\n```\n\n```text\ncatch\n```\n\n```text\n(exception: unknown, host: ArgumentHost)\n```\n\n```text\nBaseExceptionFilter\n```\n\n```text\ncatch\n```\n\n```text\nextend\n```\n\n```text\ncatch\n```\n\n```text\nsuper.catch(exception, host)\n```\n\n```text\nextends BaseExceptionFilter\n```\n\n```text\nimplements ExceptionFilter\n```\n\n========================================\n\nComments:\n- Would you please provide one example or usecase for implementing ExceptionFilter?\n- Like I said, when you don't like how Nest's `BaseExceptionFilter` works and you want your own logic in there. Not sure how to really give an example of it because it varies so much on a case to case basis. I guess the biggest thing would be you always want to send HTTP 200, but you have specialized error codes in your response payload.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":79,"estimatedTokens":351}}605{"id":"stack-63615262","source":"stackoverflow","questionId":63615262,"title":"Sentry not getting TypeScript source maps when integrated with NestJS","tags":["typescript","nestjs","source-maps","sentry"],"text":"Title: Sentry not getting TypeScript source maps when integrated with NestJS\nTags: typescript, nestjs, source-maps, sentry\nSource: Stack Overflow\n\nQuestion:\nI've created a small NestJS project recently which I attempting to integrate Sentry into. I have followed the instructions on the Nest-Raven package readme, along with the instructions provided by Sentry for TypeScript integration.\n\nUnfortunately I cannot seem to get Sentry to display the TypeScript sourcemaps, only the regular JS ones, as you can see here:\n\nhttps://i.sstatic.net/Utm3S.png\n\nI have Sentry initialised in `main.ts` as per the instructions\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { RewriteFrames } from '@sentry/integrations';\nimport * as Sentry from '@sentry/node';\nimport { AppModule } from './app.module';\n\n// This allows TypeScript to detect our global value\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace NodeJS {\n interface Global {\n __rootdir__: string;\n }\n }\n}\n\nglobal.__rootdir__ = __dirname || process.cwd();\n\nasync function bootstrap() {\n Sentry.init({\n dsn: 'https://mySentryDSN.ingest.sentry.io/0',\n integrations: [\n new RewriteFrames({\n root: global.__rootdir__,\n }),\n ],\n });\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n}\nbootstrap();\n```\n\nI have also set up `Nest-Raven` to use a Global Interceptor\n\n```\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { RavenInterceptor, RavenModule } from 'nest-raven';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n imports: [\n RavenModule,\n ...\n ],\n controllers: [AppController],\n providers: [\n AppService,\n {\n provide: APP_INTERCEPTOR,\n useValue: new RavenInterceptor(),\n },\n ],\n})\nexport class AppModule {}\n```\n\nHas anyone else encountered this issue? I am thinking that perhaps I need to upload the sourcemaps directly to Sentry as per these intstructions, however as far as I know NestJS does not make use of Webpack so I am unsure how to proceed.\n\n========================================\n\nTop Answer:\nYou can make Nest use the `webpack` compiler with `nest build --webpack`as described here. It looks like Sentry also has documentation on how to get source map support using typescript without webpack so that may be worth checking out too.\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { RewriteFrames } from '@sentry/integrations';\nimport * as Sentry from '@sentry/node';\nimport { AppModule } from './app.module';\n\n// This allows TypeScript to detect our global value\ndeclare global {\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  namespace NodeJS {\n    interface Global {\n      __rootdir__: string;\n    }\n  }\n}\n\nglobal.__rootdir__ = __dirname || process.cwd();\n\nasync function bootstrap() {\n  Sentry.init({\n    dsn: 'https://mySentryDSN.ingest.sentry.io/0',\n    integrations: [\n      new RewriteFrames({\n        root: global.__rootdir__,\n      }),\n    ],\n  });\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { RavenInterceptor, RavenModule } from 'nest-raven';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n  imports: [\n    RavenModule,\n    ...\n  ],\n  controllers: [AppController],\n  providers: [\n    AppService,\n    {\n      provide: APP_INTERCEPTOR,\n      useValue: new RavenInterceptor(),\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nmain.ts\n```\n\n```text\nNest-Raven\n```\n\n```text\ndirname: '/Users/<name>/Documents/Projects/nest-test-project/dist',\n  cwd: '/Users/<name>/Documents/Projects/nest-test-project'\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"ES2017\",\n    \"lib\": [ \"ES2020.Promise\" ],\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"sourceMap\": true,\n    \"inlineSources\": true,\n    \"sourceRoot\": \"/\"\n  }\n}\n```\n\n```js\nimport { RewriteFrames } from \"@sentry/integrations\";\n\nSentry.init({\n  dsn: \"https://examplePublicKey@o0.ingest.sentry.io/0\",\n  integrations: [\n    new RewriteFrames({\n      root: process.cwd(),\n    }),\n  ],\n});\n```\n\n```text\nRewriteFrames\n```\n\n```text\nglobal.__rootdir__\n```\n\n```text\n__dirname\n```\n\n```text\nprocess.cwd()\n```\n\n```text\n__dirname\n```\n\n```text\ndist\n```\n\n```text\ntsconfig\n```\n\n```text\nSentryModule\n```\n\n```text\nnew RewriteFrames({...})\n```\n\n```text\nroot\n```\n\n```text\nprocess.cwd()\n```\n\n```text\ntsconfig.json\n```\n\n```text\nmain.ts\n```\n\n```text\nwebpack\n```\n\n```text\nnest build --webpack\n```\n\n========================================\n\nComments:\n- hey, may you have a whole setup you used? I'm also stuck with nestjs and sentry, but it doesn't work with the correct path neither. Maybe you could post the config which was working for you? Thanks in advance! :)\n- I wish you could explain more, I also could not make that work. I came with the idea to set target to es2019 so the transpiled code is closer to the source code, then I can find the line easier. Any way, if you can please provide the tsconfig and setting you could make it work.\n- I've edited my above answer to include an example of my `tsconfig.json` and how I passed `process.cwd()` to the Sentry constructor.\n- Hello @ConorWatson and thank you for your example. I am struggling to get this to work for days ... No success yet, even having identical configuration as you and checking the value for process.cwd() - it's the correct project root. Is the uploading of typescript sourcemaps automated or should it be done by hand ? How can you check what's being sent ?\n- @FlorinMateescu-mtscsoftware I think you will have to upload them. Check here for the options you have to provide sourcemaps to sentry: docs.sentry.io/platforms/javascript/sourcemaps 1. Uploaded directly to Sentry (strongly recommended) 2. Served publicly over HTTP alongside your deployed code. When you are using nest you definitely should not make your files publicly available (same goes for other node projects). I would suggest that you write a short script that publishes sourcemaps to sentry on every production ready build.","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":252,"estimatedTokens":1595}}606{"id":"stack-49798404","source":"stackoverflow","questionId":49798404,"title":"Error : Nest cannot export component / module that is not a part of the currently processed module (DatabaseModule)","tags":["node.js","typescript","express","nestjs"],"text":"Title: Error : Nest cannot export component / module that is not a part of the currently processed module (DatabaseModule)\nTags: node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm programming a really simple app allowed make CRUD feature on a PostgreSQL DB using express.\nWhen I run my program I get this error : \nError: Nest cannot export component / module that is not a part of the currently proccessed module (DatabaseModule). Please verify whether each exported unit is available in this particular context.\n\nI really don't understand why... In the app.module.ts, I import DatabaseModule, which calls database provider (where is my postreSQL connection).\n\nI'm new on typescript, and I'm lost : / \nI only post the entry point of app, but I can send more if it's not enough and thank's for the help : \n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { ApplicationModule } from './src/app.module';\nimport * as express from 'express';\nimport 'ts-node/register';\n\nasync function bootstrap() {\n let instance: any;\n instance = express();\n const app = NestFactory.create(ApplicationModule, instance);\n app.then(instance => instance.listen(3000), () => console.log('Application is listening on port 3000'));\n}\n\nbootstrap();\n```\n\nThis app.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { MainController } from './controller/main.controller';\n\nimport { CatsModule } from './cats.module';\nimport { CatsController } from './controller/cats.controller';\n\nimport { OwnerModule } from './owner.module';\nimport { OwnerController } from './controller/owner.controller';\n\nimport {CatfoodController} from './controller/catfood.controller';\nimport { CatfoodModule } from './catfood.module';\n\nimport { DatabaseModule } from './database/database.module';\n\n@Module({\n controllers: [\n MainController,\n CatsController,\n CatfoodController,\n OwnerController,\n ],\n modules: [\n DatabaseModule,\n CatsModule,\n CatfoodModule,\n OwnerModule,\n ],\n})\n\nexport class ApplicationModule {}\n```\n\nAnd database.module :\n\n```\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n components: [...databaseProviders],\n exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\nGithub : https://github.com/lukile/catProject\n\n========================================\n\nTop Answer:\nIt seems to me that you created a module, but you didn't configure them. When you create a module using a `@Module`, you need to create at least an empty controllers array inside the `@Module`.\n\n```\nimport { Module } from \"@nestjs/common\";\n\n@Module({\n controllers: []\n})\nexport class AppModule {\n\n}\n```\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { ApplicationModule } from './src/app.module';\nimport * as express from 'express';\nimport 'ts-node/register';\n\nasync function bootstrap() {\n    let instance: any;\n    instance = express();\n    const app = NestFactory.create(ApplicationModule, instance);\n    app.then(instance => instance.listen(3000), () => console.log('Application is listening on port 3000'));\n}\n\nbootstrap();\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MainController } from './controller/main.controller';\n\nimport { CatsModule } from './cats.module';\nimport { CatsController } from './controller/cats.controller';\n\nimport { OwnerModule } from './owner.module';\nimport { OwnerController } from './controller/owner.controller';\n\nimport {CatfoodController} from './controller/catfood.controller';\nimport { CatfoodModule } from './catfood.module';\n\nimport { DatabaseModule } from './database/database.module';\n\n@Module({\n  controllers: [\n      MainController,\n      CatsController,\n      CatfoodController,\n      OwnerController,\n  ],\n    modules: [\n        DatabaseModule,\n        CatsModule,\n        CatfoodModule,\n        OwnerModule,\n    ],\n})\n\nexport class ApplicationModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n    components: [...databaseProviders],\n    exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\n```text\nmodules\n```\n\n```text\nimports\n```\n\n```text\nmodules\n```\n\n```text\nCatsModule\n```\n\n```text\nCatfoodModule\n```\n\n```text\ncontrollers\n```\n\n```text\nApplicationModule\n```\n\n```js\nimport { Module } from \"@nestjs/common\";\n\n@Module({\n  controllers: []\n})\nexport class AppModule {\n\n}\n```\n\n```text\n@Module\n```\n\n```text\n@Module\n```\n\n========================================\n\nComments:\n- Show DatabaseModule, AppModule\n- I updated the post\n- @shai - please mark the answer as the accepted answer if you are happy with it\n- Yes you were right, I modified the code to only imports modules,in array and I changed to add TypeOrmModule.forRoot() instead of DatabaseModule() (even if I think it wouldn't change a thing). Now there's another error : Nest can't resolve dependencies of the CatsService (?). Please verify whether [0] argument is available in the current context.. I export my catsService in catsModule and my catsService constructor looks like to : constructor(@InjectRepository(Cat) private readonly catRepository: Repository)\n- Do you have `TypeOrm.forFeature` in CatsModule?\n- @Module({ imports: [TypeOrmModule.forFeature([Cat])], components: [CatsService], controllers: [CatsController], }) I do : / I updated to github\n- I finally solved my problem. I restarted from the beginning, and I finally can create, read, update and delete from postgreSQL database with API connection. If it could help anyone my github is up to date :) Thank's for your help\n- @Sha&#239; good to hear. You mind posting your own answer and state clearly what was the problem and how you solved it?\n- Yes sorry ^^. The problem was I was lost : I had 2 modules and I didn't see it... And obviously I called the bad one, where I didn't import TypeOrmModule.forFeature(). In my service I used '@Inject' instead '@InjectRepository'. It couldn't work : /","metadata":{"transformedAt":"2026-08-18T18:33:02.456Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":218,"estimatedTokens":1500}}607{"id":"stack-66809411","source":"stackoverflow","questionId":66809411,"title":"Webpack Typescript errors on fresh Nestjs app","tags":["typescript","webpack","nestjs"],"text":"Title: Webpack Typescript errors on fresh Nestjs app\nTags: typescript, webpack, nestjs\nSource: Stack Overflow\n\nQuestion:\nAfter generating a new project with `nest new [project name]`, selecting my package manager and executing `yarn start` or `npm start` my project throws the following errors:\n\n```\n$ nest start\nnode_modules/@types/tapable/index.d.ts:7:15 - error TS2307: Cannot find module './node_modules/tapable' or its corresponding type declarations.\n\n7 export * from './node_modules/tapable';\n ~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:32:3 - error TS2305: Module '\"tapable\"' has no exported member 'Tapable'.\n\n32 Tapable,\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1062:23 - error TS2707: Generic type 'SyncWaterfallHook' requires between 1 and 2 type arguments.\n\n1062 resolver: SyncWaterfallHook;\n ~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1063:22 - error TS2707: Generic type 'SyncWaterfallHook' requires between 1 and 2 type arguments.\n\n1063 factory: SyncWaterfallHook;\n ~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1064:28 - error TS2707: Generic type 'AsyncSeriesWaterfallHook' requires between 1 and 2 type arguments.\n\n1064 beforeResolve: AsyncSeriesWaterfallHook;\n ~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1065:27 - error TS2707: Generic type 'AsyncSeriesWaterfallHook' requires between 1 and 2 type arguments.\n\n1065 afterResolve: AsyncSeriesWaterfallHook;\n ~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1066:27 - error TS2707: Generic type 'SyncBailHook' requires between 2 and 3 type arguments.\n\n1066 createModule: SyncBailHook;\n ~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1067:21 - error TS2707: Generic type 'SyncWaterfallHook' requires between 1 and 2 type arguments.\n\n1067 module: SyncWaterfallHook;\n ~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1068:27 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1068 createParser: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1070:30 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1070 createGenerator: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1071:24 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1071 generator: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1080:33 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1080 evaluateTypeof: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1081:27 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1081 evaluate: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1082:37 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1082 evaluateIdentifier: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1083:44 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1083 evaluateDefinedIdentifier: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1084:47 - error TS2314: Generic type 'HookMap' requires 1 type argument(s).\n\n1084 evaluateCallExpressionMember: HookMap;\n ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1085:28 - error TS2707: Generic type 'SyncBailHook' requires between 2 and 3 type arguments.\n\n1085 statement: SyncBailHook;\n```\n\nI already tried reinstalling the nest cli, stried switching between npm and yarn, removing the dist folder and removing the node_modules folder (and installing the dependencies)\n\n========================================\n\nTop Answer:\nUpgrading Nest's CLI and re-installing modules, should fix it\n\n`npm install -g @nestjs/cli@latest`\n\n`rm -rf node_modules`\n\n`rm package-lock.json`\n\n`npm install`\n\n========================================\n\nCode:\n```text\n$ nest start\nnode_modules/@types/tapable/index.d.ts:7:15 - error TS2307: Cannot find module './node_modules/tapable' or its corresponding type declarations.\n\n7 export * from './node_modules/tapable';\n                ~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:32:3 - error TS2305: Module '\"tapable\"' has no exported member 'Tapable'.\n\n32   Tapable,\n     ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1062:23 - error TS2707: Generic type 'SyncWaterfallHook<T, AdditionalOptions>' requires between 1 and 2 type arguments.\n\n1062             resolver: SyncWaterfallHook;\n                           ~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1063:22 - error TS2707: Generic type 'SyncWaterfallHook<T, AdditionalOptions>' requires between 1 and 2 type arguments.\n\n1063             factory: SyncWaterfallHook;\n                          ~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1064:28 - error TS2707: Generic type 'AsyncSeriesWaterfallHook<T, AdditionalOptions>' requires between 1 and 2 type arguments.\n\n1064             beforeResolve: AsyncSeriesWaterfallHook;\n                                ~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1065:27 - error TS2707: Generic type 'AsyncSeriesWaterfallHook<T, AdditionalOptions>' requires between 1 and 2 type arguments.\n\n1065             afterResolve: AsyncSeriesWaterfallHook;\n                               ~~~~~~~~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1066:27 - error TS2707: Generic type 'SyncBailHook<T, R, AdditionalOptions>' requires between 2 and 3 type arguments.\n\n1066             createModule: SyncBailHook;\n                               ~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1067:21 - error TS2707: Generic type 'SyncWaterfallHook<T, AdditionalOptions>' requires between 1 and 2 type arguments.\n\n1067             module: SyncWaterfallHook;\n                         ~~~~~~~~~~~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1068:27 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1068             createParser: HookMap;\n                               ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1070:30 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1070             createGenerator: HookMap;\n                                  ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1071:24 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1071             generator: HookMap;\n                            ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1080:33 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1080                 evaluateTypeof: HookMap;\n                                     ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1081:27 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1081                 evaluate: HookMap;\n                               ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1082:37 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1082                 evaluateIdentifier: HookMap;\n                                         ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1083:44 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1083                 evaluateDefinedIdentifier: HookMap;\n                                                ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1084:47 - error TS2314: Generic type 'HookMap<H>' requires 1 type argument(s).\n\n1084                 evaluateCallExpressionMember: HookMap;\n                                                   ~~~~~~~\nnode_modules/@types/webpack/index.d.ts:1085:28 - error TS2707: Generic type 'SyncBailHook<T, R, AdditionalOptions>' requires between 2 and 3 type arguments.\n\n1085                 statement: SyncBailHook;\n```\n\n```text\nnest new [project name]\n```\n\n```text\nyarn start\n```\n\n```text\nnpm start\n```\n\n```text\n\"skipLibCheck\": true\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"compilerOptions\"\n```\n\n```text\n@nestjs/cli@7.6.0\n```\n\n```text\nnpm install -g @nestjs/cli@latest\n```\n\n```text\nrm -rf node_modules\n```\n\n```text\nrm package-lock.json\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- In most cases it is not a good idea to remove `package-lock.json`.\n- @IvanP in most cases it is a good idea to remove `package-lock.json` and never track it again.","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":216,"estimatedTokens":2030}}608{"id":"stack-63107060","source":"stackoverflow","questionId":63107060,"title":"NestJS: Adding cookie-parser causes an error","tags":["cookies","nestjs"],"text":"Title: NestJS: Adding cookie-parser causes an error\nTags: cookies, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen I run this code:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport cookieParser from 'cookie-parser';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.use(cookieParser());\n await app.listen(3000);\n}\nbootstrap();\n```\n\nI get:\n\n```\n(node:28) UnhandledPromiseRejectionWarning: TypeError: cookie_parser_1.default is not a function\n at bootstrap (/usr/src/app/dist/main.js:8:36)\n at processTicksAndRejections (internal/process/task_queues.js:93:5)\n```\n\nIf I comment out \"app.use(cookieParser());\" the problem goes away, but I need the cookie parser.\n\n========================================\n\nTop Answer:\nadd/change in the tsconfig.json `\"esModuleInterop\": true`\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport cookieParser from 'cookie-parser';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.use(cookieParser());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n(node:28) UnhandledPromiseRejectionWarning: TypeError: cookie_parser_1.default is not a function\n    at bootstrap (/usr/src/app/dist/main.js:8:36)\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)\n```\n\n```text\nimport * as cookieParser from 'cookie-parser';\n```\n\n```text\n\"esModuleInterop\": true\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":380}}609{"id":"stack-66167307","source":"stackoverflow","questionId":66167307,"title":"How to inject a nestjs service into another service when both belong to the same module?","tags":["javascript","node.js","dependency-injection","nestjs"],"text":"Title: How to inject a nestjs service into another service when both belong to the same module?\nTags: javascript, node.js, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have the following scenario in NestJS:\n\n```\n// user.service.ts\n@Injectable()\nexport class UserService {\n constructor(\n private readonly userRepository: UserRepository,\n private readonly userProfileService: UserProfileService,\n ) {}\n}\n\n// user-profile.service.ts\n@Injectable()\nexport class UserProfileService {\n constructor(\n private readonly userProfileRepository: UserProfileRepository,\n ) {}\n}\n\n// user.module.ts\n@Module({\nimports: [DataRepositoryModule], // Required for the repository dependencies\n providers: [UserService, UserProfileService],\n exports: [UserService, UserProfileService],\n})\nexport class UserModule {}\n```\n\nHowever, when I try to use the UserService inside a controller from another module, I get the following error:\n\n```\nNest can't resolve dependencies of the UserService (UserRepository, ?). Please make sure that the argument dependency at index [1] is available in the UserModule context.\nPotential solutions: \n- If dependency is a provider, is it part of the current UserModule?\n- If dependency is exported from a separate @Module, is that module imported within UserModule?\n@Module({\n imports: [ /* the Module containing dependency */ ]\n })\n```\n\nController code:\n\n```\n@Controller()\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n}\n```\n\nController module:\n\n```\n@Module({\n imports: [],\n providers: [],\n controllers: [UserController],\n})\nexport class UserManagementModule {}\n```\n\nMain app.module.ts:\n\n```\n@Module({\n imports: [\n UserManagementModule,\n UserModule,\n DataRepositoryModule.forRoot(),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nI'm confused because I'm doing exactly what the error suggests, adding both services inside the providers array (UserModule). What could I be missing?\n\n========================================\n\nCode:\n```text\n// user.service.ts\n@Injectable()\nexport class UserService {\n  constructor(\n    private readonly userRepository: UserRepository,\n    private readonly userProfileService: UserProfileService,\n  ) {}\n}\n\n\n// user-profile.service.ts\n@Injectable()\nexport class UserProfileService {\n  constructor(\n    private readonly userProfileRepository: UserProfileRepository,\n  ) {}\n}\n\n\n// user.module.ts\n@Module({\nimports: [DataRepositoryModule], // Required for the repository dependencies\n  providers: [UserService, UserProfileService],\n  exports: [UserService, UserProfileService],\n})\nexport class UserModule {}\n```\n\n```text\nNest can't resolve dependencies of the UserService (UserRepository, ?). Please make sure that the argument dependency at index [1] is available in the UserModule context.\nPotential solutions:    \n- If dependency is a provider, is it part of the current UserModule?\n- If dependency is exported from a separate @Module, is that module imported within UserModule?\n@Module({\n        imports: [ /* the Module containing dependency */ ]\n      })\n```\n\n```text\n@Controller()\nexport class UserController {\n  constructor(private readonly userService: UserService) {}\n}\n```\n\n```text\n@Module({\n  imports: [],\n  providers: [],\n  controllers: [UserController],\n})\nexport class UserManagementModule {}\n```\n\n```text\n@Module({\n  imports: [\n    UserManagementModule,\n    UserModule,\n    DataRepositoryModule.forRoot(),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- Thank you, in this case the issue was solved by removing barrel files for any provider. There is a warning in the official NestJS documentation where they don't recommend using them that way: docs.nestjs.com/fundamentals/circular-dependency I think the error message is misleading though, it made me lose a lot of time.\n- There's two types of circular dependencies. Circular file imports (file A imports file B imports file A). Nest can't easily detect these, because tokens can come in as `undefined` so Nest just calls it `dependency`. The other is an injection dependency (service A injects service B injects service A). These Nest **can** detect and gives the error (most of the time) shown in the docs","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":159,"estimatedTokens":1070}}610{"id":"stack-73153403","source":"stackoverflow","questionId":73153403,"title":"Joi getting validationSchema: Joi.object() error","tags":["javascript","node.js","nestjs","joi"],"text":"Title: Joi getting validationSchema: Joi.object() error\nTags: javascript, node.js, nestjs, joi\nSource: Stack Overflow\n\nQuestion:\nAfter installing `joi` on `nestjs` framework i'm trying to validate two property by `joi` something like:\n\n```\nimport Joi from 'joi';\n...\nConfigModule.forRoot({\n isGlobal: true,\n validationSchema: Joi.object(\n {\n PORT: Joi.number().required(),\n MONGODB_URI: Joi.string().required(),\n }\n )\n}),\n...\n```\n\nbut i get this error:\n\n```\nCannot read properties of undefined (reading 'object')\n```\n\n`main.ts`:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n // @ts-ignore\n app.useGlobalFilters(new ValidationPipe());\n const configService = app.get(ConfigService);\n const port = configService.get('PORT');\n await app.listen(port);\n}\n```\n\nfull error:\n\n```\nD:\\develop\\api\\src\\app.module.ts:16\n validationSchema: Joi.object(\n ^\nTypeError: Cannot read properties of undefined (reading 'object')\n at Object. (D:\\develop\\api\\src\\app.module.ts:16:35)\n at Module._compile (node:internal/modules/cjs/loader:1105:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)\n at Module.load (node:internal/modules/cjs/loader:981:32)\n at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n at Module.require (node:internal/modules/cjs/loader:1005:19)\n at require (node:internal/modules/cjs/helpers:102:18)\n at Object. (D:\\develop\\api\\src\\main.ts:2:1)\n at Module._compile (node:internal/modules/cjs/loader:1105:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)\nPS D:\\develop\\api>\n```\n\n========================================\n\nCode:\n```js\nimport Joi from 'joi';\n...\nConfigModule.forRoot({\n    isGlobal: true,\n    validationSchema: Joi.object(\n        {\n            PORT: Joi.number().required(),\n            MONGODB_URI: Joi.string().required(),\n        }\n    )\n}),\n...\n```\n\n```text\nCannot read properties of undefined (reading 'object')\n```\n\n```js\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    // @ts-ignore\n    app.useGlobalFilters(new ValidationPipe());\n    const configService = app.get(ConfigService);\n    const port = configService.get<string>('PORT');\n    await app.listen(port);\n}\n```\n\n```text\nD:\\develop\\api\\src\\app.module.ts:16\n            validationSchema: Joi.object(\n                                  ^\nTypeError: Cannot read properties of undefined (reading 'object')\n    at Object.<anonymous> (D:\\develop\\api\\src\\app.module.ts:16:35)\n    at Module._compile (node:internal/modules/cjs/loader:1105:14)\n    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)\n    at Module.load (node:internal/modules/cjs/loader:981:32)\n    at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n    at Module.require (node:internal/modules/cjs/loader:1005:19)\n    at require (node:internal/modules/cjs/helpers:102:18)\n    at Object.<anonymous> (D:\\develop\\api\\src\\main.ts:2:1)\n    at Module._compile (node:internal/modules/cjs/loader:1105:14)\n    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)\nPS D:\\develop\\api>\n```\n\n```text\njoi\n```\n\n```text\nnestjs\n```\n\n```text\njoi\n```\n\n```text\nmain.ts\n```\n\n```text\nimport * as Joi from 'joi'\n```\n\n```text\nesModuleInterop: true\n```\n\n```text\ntsconfig.json\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":139,"estimatedTokens":825}}611{"id":"stack-72460269","source":"stackoverflow","questionId":72460269,"title":"How to read a .env file on MongooseModule in Nestjs?","tags":["mongoose","environment-variables","nestjs","config"],"text":"Title: How to read a .env file on MongooseModule in Nestjs?\nTags: mongoose, environment-variables, nestjs, config\nSource: Stack Overflow\n\nQuestion:\nSo I am trying to add a config to my NestJs project, so far I've been using MongooseModule in order to connect to the Database but I was providing the full URL in MongooseModule.forRoot().\n\nIt was something like this:\n\n```\n//app.module.ts\nimport { Module } from '@nestjs/common';\nimport { MongooseModuele } from '@nestjs/mongoose';\n\n@Module({\n imports: [MongooseModule.forRoot('mongodb://.....')]\n})\n```\n\nSo then I added the nestjs config and its looking like this:\n\n```\n//app.module.ts\nimport { Module } from '@nestjs/common';\nimport { MongooseModuele } from '@nestjs/mongoose';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n }),\n MongooseModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (config: ConfigService) => ({\n uri: config.get('DB_HOST'),\n }),\n inject: [ConfigService],\n }),\n ]\n})\n```\n\nBut then got this error:\n\n[Nest] 14098 - 06/01/2022, 7:16:42 AM ERROR [ExceptionHandler] Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\"\n\nI also tried this way:\n\n```\n//app.module.ts\nimport { Module } from '@nestjs/common';\nimport { MongooseModuele } from '@nestjs/mongoose';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n imports: [\n MongooseModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (config: ConfigService) => ({\n uri: config.get('DB_HOST'),\n }),\n inject: [ConfigService],\n }),\n ]\n})\n```\n\nnest print this error:\n\nERROR [ExceptionHandler] The `uri` parameter to `openUri()` must be a string, got \"undefined\". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.\n\nMy .env file looks like this:\n\n```\nDB_HOST=\"mongodb://.....\"\n```\n\nIt seems like that on the app.module MongooseModule is not reading my .env file, does anyone knows how to solve that?\n\nThanks\n\n========================================\n\nTop Answer:\nHere is complete working code. `connectionName` is used incase you have multiple databases in your app.\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n CostingModule,\n MongooseModule.forRootAsync({\n connectionName: 'finance',\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (config: ConfigService) => ({\n uri: config.get('MONGODB_URI_FINANCEDB'),\n }),\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\n========================================\n\nCode:\n```text\n//app.module.ts\nimport { Module } from '@nestjs/common';\nimport { MongooseModuele } from '@nestjs/mongoose';\n\n@Module({\n  imports: [MongooseModule.forRoot('mongodb://.....')]\n})\n```\n\n```text\n//app.module.ts\nimport { Module } from '@nestjs/common';\nimport { MongooseModuele } from '@nestjs/mongoose';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }),\n    MongooseModule.forRootAsync({\n     imports: [ConfigModule],\n     useFactory: async (config: ConfigService) => ({\n      uri: config.get<string>('DB_HOST'),\n     }),\n     inject: [ConfigService],\n   }),\n  ]\n})\n```\n\n```text\n//app.module.ts\nimport { Module } from '@nestjs/common';\nimport { MongooseModuele } from '@nestjs/mongoose';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n  imports: [\n    MongooseModule.forRootAsync({\n     imports: [ConfigModule],\n     useFactory: async (config: ConfigService) => ({\n      uri: config.get<string>('DB_HOST'),\n     }),\n     inject: [ConfigService],\n   }),\n  ]\n})\n```\n\n```text\nDB_HOST=\"mongodb://.....\"\n```\n\n```text\nuri\n```\n\n```text\nopenUri()\n```\n\n```text\nmongoose.connect()\n```\n\n```text\nmongoose.createConnection()\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config'\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({\n  import: [\n    MongooseModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: async (config: ConfigService) => ({\n        uri: config.get<string>('MONGODB_URI'), // Loaded from .ENV\n      })\n    })\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nset DATABASE_URL='url of your database'\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    CostingModule,\n    MongooseModule.forRootAsync({\n      connectionName: 'finance',\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: async (config: ConfigService) => ({\n        uri: config.get<string>('MONGODB_URI_FINANCEDB'),\n      }),\n    }),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\nconnectionName\n```\n\n========================================\n\nComments:\n- Don't forget to include also `ConfigModule.forRoot()`, otherwise doesnt work\n- The line just under @Module({ should read 'imports:' not 'import:', otherwise there is an error.","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":234,"estimatedTokens":1268}}612{"id":"stack-56286086","source":"stackoverflow","questionId":56286086,"title":"Download image from url by nestjs","tags":["nestjs"],"text":"Title: Download image from url by nestjs\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to download user profile picture from telegram account and store it in local storage with nestjs framework.\n\n========================================\n\nCode:\n```text\n@Controller()\nexport class Controller {\n    constructor(\n        private readonly httpService: HttpService,\n    ) {\n    }\n\n    @Get()\n    async downloadImage(@Res() res) {\n        const writer = fs.createWriteStream('./image.png');\n\n        const response = await this.httpService.axiosRef({\n            url: 'https://example.com/image.png',\n            method: 'GET',\n            responseType: 'stream',\n        });\n\n        response.data.pipe(writer);\n\n        return new Promise((resolve, reject) => {\n            writer.on('finish', resolve);\n            writer.on('error', reject);\n        });\n    }\n}\n```\n\n========================================\n\nComments:\n- Cool. It can display on the page but how to save it to local directory?","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":42,"estimatedTokens":250}}613{"id":"stack-55385041","source":"stackoverflow","questionId":55385041,"title":"Is it possible to validate single route parameter?","tags":["javascript","node.js","typescript","nestjs","class-validator"],"text":"Title: Is it possible to validate single route parameter?\nTags: javascript, node.js, typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nLet's say I have following route:\n\n```\ncompanies/{companyId}/departments/{departmentId}/employees\n```\n\nIs it possible to validate both resources ids (`companyId`, `departmentId`) separately? I've tried following but it's not working.\n\n```\nclass ResourceId {\n @IsNumberString()\n @StringNumberRange(...) // my custom validator\n id: number;\n}\n\n@Get(':companyId/departments/:departmentId/employees')\ngetEmployees(\n @Param('companyId') companyId: ResourceId,\n @Param('departmentId') departmentId: ResourceId,\n) {}\n```\n\nI have multiple cases when there is more than one parameter in the single route. I would not like to create separate validation class for every route. Is there a way to handle this problem in a different way?\n\n========================================\n\nTop Answer:\nAs of 2022, NestJS docs say that it's possible to validate route params using the built-in validation pipe.\n\nIn a controller:\n\n```\n@Get(':id')\nfindOne(@Param() params: FindOneParams) {\n return 'This action returns a user';\n}\n```\n\nValidation class:\n\n```\nimport { IsNumberString } from 'class-validator';\n\nexport class FindOneParams {\n @IsNumberString()\n id: number;\n}\n```\n\nRef: https://docs.nestjs.com/techniques/validation#auto-validation\n\n========================================\n\nCode:\n```text\ncompanies/{companyId}/departments/{departmentId}/employees\n```\n\n```text\nclass ResourceId {\n  @IsNumberString()\n  @StringNumberRange(...) // my custom validator\n  id: number;\n}\n\n@Get(':companyId/departments/:departmentId/employees')\ngetEmployees(\n  @Param('companyId') companyId: ResourceId,\n  @Param('departmentId') departmentId: ResourceId,\n) {}\n```\n\n```text\ncompanyId\n```\n\n```text\ndepartmentId\n```\n\n```text\nexport class ParamValidationPipe implements PipeTransform {\n  async transform(value, metadata: ArgumentMetadata) {\n    if (metadata.type === 'param') {\n      // This is the relevant part: value -> { id: value }\n      const valueInstance = plainToClass(metadata.metatype, { id: value });\n      const validationErrors = await validate(valueInstance);\n      if (validationErrors.length > 0) {\n        throw new BadRequestException(validationErrors, 'Invalid route param');\n      }\n      return valueInstance;\n    } else {\n      return value;\n    }\n  }\n}\n```\n\n```text\n@UsePipes(ParamValidationPipe)\n@Get(':companyId/departments/:departmentId/employees')\ngetEmployees(\n  @Param('companyId') companyId: ResourceId,\n  @Param('departmentId') departmentId: ResourceId,\n) {\n  return `id1: ${companyId.id}, id2: ${departmentId.id}`;\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nResourceId\n```\n\n```text\nValidationPipe\n```\n\n```text\n{id: '123'}\n```\n\n```text\n'123'\n```\n\n```text\n@Get(':id')\nfindOne(@Param() params: FindOneParams) {\n  return 'This action returns a user';\n}\n```\n\n```text\nimport { IsNumberString } from 'class-validator';\n\nexport class FindOneParams {\n  @IsNumberString()\n  id: number;\n}\n```\n\n========================================\n\nComments:\n- You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)\n- Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.\n- Has this been proved to work? As of Nestjs 8.4.4 with globally installed `ValidationPipe({ transform: true, whitelist: true, }`, the parameter is not being validated to be a numeric string","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":156,"estimatedTokens":896}}614{"id":"stack-65036034","source":"stackoverflow","questionId":65036034,"title":"Running cypress in GithubActions on windows environment","tags":["windows","continuous-integration","nestjs","cypress","github-actions"],"text":"Title: Running cypress in GithubActions on windows environment\nTags: windows, continuous-integration, nestjs, cypress, github-actions\nSource: Stack Overflow\n\nQuestion:\nI want to run my cypress tests in github actions. There should be a test for firefox, chrome and also edge. Cypress supports all of them: https://github.com/cypress-io/github-action#browser\n\nWhile firefox and chrome works well, the edge setup is not so faultless. This is because the edge browser runs on a windows system inside github actions.\n\nHere is the yml file which builds the next.js application and then test it with the edge browser:\n\n```\nbuild:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout code\n uses: actions/checkout@v2\n\n - uses: actions/setup-node@v2-beta\n with:\n node-version: \"12\"\n\n - name: Get yarn cache directory path\n id: yarn-cache-dir-path\n run: echo \"::set-output name=dir::$(yarn cache dir)\"\n\n - name: Cache node_modules\n id: yarn-cache\n uses: actions/cache@v2\n with:\n path: ${{ steps.yarn-cache-dir-path.outputs.dir }}\n key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}\n\n - name: Install Dependencies\n run: yarn\n\n - name: Build\n run: yarn build\n\n - name: Upload next build\n uses: actions/upload-artifact@v2\n with:\n name: dist\n path: .next\n\ne2e-test-edge:\n needs: build\n runs-on: windows-latest\n strategy:\n matrix:\n node: [12]\n\n steps:\n - name: Checkout code\n uses: actions/checkout@v2\n\n - name: Download next build from previous step\n uses: actions/download-artifact@v2\n with:\n name: dist\n path: .next\n\n - name: Cache Cypress binary\n uses: actions/cache@v2\n with:\n path: ~/.cache/Cypress\n key: cypress-${{ runner.os }}-cypress-${{ github.ref }}-${{ hashFiles('**/package.json') }}\n\n - name: Get yarn cache directory path\n id: yarn-cache-dir-path\n run: echo \"::set-output name=dir::$(yarn cache dir)\"\n\n - name: Cache node_modules\n id: yarn-cache\n uses: actions/cache@v2\n with:\n path: ${{ steps.yarn-cache-dir-path.outputs.dir }}\n key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}\n\n - name: Install Dependencies\n run: yarn install --frozen-lockfile\n\n - name: Verify Cypress\n env:\n # make sure every Cypress install prints minimal information\n CI: 1\n # print Cypress and OS info\n run: |\n npx cypress verify\n npx cypress info\n npx cypress version\n npx cypress version --component package\n npx cypress version --component binary\n npx cypress version --component electron\n npx cypress version --component node\n\n - name: Cypress edge browser tests\n uses: cypress-io/github-action@v2\n with:\n browser: edge\n start: yarn start\n\n - uses: actions/upload-artifact@v2\n if: failure()\n with:\n name: edge-cypress-screenshots\n path: cypress/screenshots\n # Test run video was always captured, so this action uses \"always()\" condition\n - uses: actions/upload-artifact@v2\n if: always()\n with:\n name: edge-cypress-videos\n path: cypress/videos\n```\n\nSo if this pipeline runs in github actions all works well. The caching parts are skipped, because this is the first build, so no cache key matches. Deps are installed as well without errors and also the `Cypress verify` part looks fine to me:\n\n```\nRun npx cypress verify\n npx cypress verify\n npx cypress info\n npx cypress version\n npx cypress version --component package\n npx cypress version --component binary\n npx cypress version --component electron\n npx cypress version --component node\n shell: C:\\Program Files\\PowerShell\\7\\pwsh.EXE -command \". '{0}'\"\n env:\n CI: 1\n\n25l[10:09:46] Verifying Cypress can run C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\\6.0.0\\Cypress [started]\n[10:09:49] Verifying Cypress can run C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\\6.0.0\\Cypress [completed]\n25h25h\nDisplaying Cypress info...\n\nDetected 3 browsers installed:\n\n1. Chrome\n - Name: chrome\n - Channel: stable\n - Version: 86.0.4240.198\n - Executable: C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\n\n2. Edge\n - Name: edge\n - Channel: stable\n - Version: 87.0.664.47\n - Executable: C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe\n\n3. Firefox\n - Name: firefox\n - Channel: stable\n - Version: 82.0.3.7617\n - Executable: C:\\Program Files\\Mozilla Firefox\\firefox.exe\n\nNote: to run these browsers, pass : to the '--browser' field\n\nExamples:\n- cypress run --browser chrome\n- cypress run --browser firefox\n\nLearn More: https://on.cypress.io/launching-browsers\n\nProxy Settings: none detected\nEnvironment Variables: none detected\n\nApplication Data: C:\\Users\\runneradmin\\AppData\\Roaming\\cypress\\cy\\development\nBrowser Profiles: C:\\Users\\runneradmin\\AppData\\Roaming\\cypress\\cy\\development\\browsers\nBinary Caches: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\n\nCypress Version: 6.0.0\nSystem Platform: win32 (10.0.17763)\nSystem Memory: 7.52 GB free 4.02 GB\nCypress package version: 6.0.0\nCypress binary version: 6.0.0\nElectron version: 11.0.2\nBundled Node version:\n12.18.3\n6.0.0\n6.0.0\n11.0.2\n\n12.18.3\n```\n\nBut then the `Cypress edge browser tests` part is reached and the following error occures:\n\n```\nRun cypress-io/github-action@v2\n with:\n browser: edge\n start: yarn start\n record: false\n config-file: cypress.json\nC:\\windows\\system32\\cmd.exe /D /S /C \"C:\\npm\\prefix\\yarn.cmd --frozen-lockfile\"\nyarn install v1.22.10\n[1/4] Resolving packages...\nsuccess Already up-to-date.\nDone in 1.08s.\nC:\\windows\\system32\\cmd.exe /D /S /C \"\"C:\\Program Files\\nodejs\\npx.cmd\" cypress cache list\"\nNo cached binary versions were found.\nC:\\windows\\system32\\cmd.exe /D /S /C \"\"C:\\Program Files\\nodejs\\npx.cmd\" cypress verify\"\nThe cypress npm package is installed, but the Cypress binary is missing.\n\nWe expected the binary to be installed here: C:\\Users\\runneradmin\\.cache\\Cypress\\6.0.0\\Cypress\\Cypress.exe\n\nReasons it may be missing:\n\n- You're caching 'node_modules' but are not caching this path: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\n- You ran 'npm install' at an earlier build step but did not persist: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\n\nProperly caching the binary will fix this error and avoid downloading and unzipping Cypress.\n\nAlternatively, you can run 'cypress install' to download the binary again.\n\nhttps://on.cypress.io/not-installed-ci-error\n\n----------\n\nPlatform: win32 (10.0.17763)\nCypress Version: 6.0.0\nError: The process 'C:\\Program Files\\nodejs\\npx.cmd' failed with exit code 1\n```\n\nI tried all the stuff the error message says:\n\n- execute `cypress install` right before the failing part\n\n- change cache dir to absolute path `C:\\Users\\runneradmin\\.cache\\Cypress`\n\nI also did not found an example of a github action yml with the combination of cypress and windows. Maybe I am too stupid to unterstand the windows machine.\n\n========================================\n\nCode:\n```text\nbuild:\n  runs-on: ubuntu-latest\n  steps:\n    - name: Checkout code\n      uses: actions/checkout@v2\n\n    - uses: actions/setup-node@v2-beta\n      with:\n        node-version: \"12\"\n\n    - name: Get yarn cache directory path\n      id: yarn-cache-dir-path\n      run: echo \"::set-output name=dir::$(yarn cache dir)\"\n\n    - name: Cache node_modules\n      id: yarn-cache\n      uses: actions/cache@v2\n      with:\n        path: ${{ steps.yarn-cache-dir-path.outputs.dir }}\n        key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}\n\n    - name: Install Dependencies\n      run: yarn\n\n    - name: Build\n      run: yarn build\n\n    - name: Upload next build\n      uses: actions/upload-artifact@v2\n      with:\n        name: dist\n        path: .next\n\ne2e-test-edge:\n  needs: build\n  runs-on: windows-latest\n  strategy:\n    matrix:\n      node: [12]\n\n  steps:\n    - name: Checkout code\n      uses: actions/checkout@v2\n\n    - name: Download next build from previous step\n      uses: actions/download-artifact@v2\n      with:\n        name: dist\n        path: .next\n\n    - name: Cache Cypress binary\n      uses: actions/cache@v2\n      with:\n        path: ~/.cache/Cypress\n        key: cypress-${{ runner.os }}-cypress-${{ github.ref }}-${{ hashFiles('**/package.json') }}\n\n    - name: Get yarn cache directory path\n      id: yarn-cache-dir-path\n      run: echo \"::set-output name=dir::$(yarn cache dir)\"\n\n    - name: Cache node_modules\n      id: yarn-cache\n      uses: actions/cache@v2\n      with:\n        path: ${{ steps.yarn-cache-dir-path.outputs.dir }}\n        key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}\n\n    - name: Install Dependencies\n      run: yarn install --frozen-lockfile\n\n    - name: Verify Cypress\n      env:\n        # make sure every Cypress install prints minimal information\n        CI: 1\n      # print Cypress and OS info\n      run: |\n        npx cypress verify\n        npx cypress info\n        npx cypress version\n        npx cypress version --component package\n        npx cypress version --component binary\n        npx cypress version --component electron\n        npx cypress version --component node\n\n    - name: Cypress edge browser tests\n      uses: cypress-io/github-action@v2\n      with:\n        browser: edge\n        start: yarn start\n\n    - uses: actions/upload-artifact@v2\n      if: failure()\n      with:\n        name: edge-cypress-screenshots\n        path: cypress/screenshots\n    # Test run video was always captured, so this action uses \"always()\" condition\n    - uses: actions/upload-artifact@v2\n      if: always()\n      with:\n        name: edge-cypress-videos\n        path: cypress/videos\n```\n\n```text\nRun npx cypress verify\n  npx cypress verify\n  npx cypress info\n  npx cypress version\n  npx cypress version --component package\n  npx cypress version --component binary\n  npx cypress version --component electron\n  npx cypress version --component node\n  shell: C:\\Program Files\\PowerShell\\7\\pwsh.EXE -command \". '{0}'\"\n  env:\n    CI: 1\n\n25l[10:09:46]  Verifying Cypress can run C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\\6.0.0\\Cypress [started]\n[10:09:49]  Verifying Cypress can run C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\\6.0.0\\Cypress [completed]\n25h25h\nDisplaying Cypress info...\n\nDetected 3 browsers installed:\n\n1. Chrome\n  - Name: chrome\n  - Channel: stable\n  - Version: 86.0.4240.198\n  - Executable: C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\n\n2. Edge\n  - Name: edge\n  - Channel: stable\n  - Version: 87.0.664.47\n  - Executable: C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe\n\n3. Firefox\n  - Name: firefox\n  - Channel: stable\n  - Version: 82.0.3.7617\n  - Executable: C:\\Program Files\\Mozilla Firefox\\firefox.exe\n\nNote: to run these browsers, pass <name>:<channel> to the '--browser' field\n\nExamples:\n- cypress run --browser chrome\n- cypress run --browser firefox\n\nLearn More: https://on.cypress.io/launching-browsers\n\nProxy Settings: none detected\nEnvironment Variables: none detected\n\nApplication Data: C:\\Users\\runneradmin\\AppData\\Roaming\\cypress\\cy\\development\nBrowser Profiles: C:\\Users\\runneradmin\\AppData\\Roaming\\cypress\\cy\\development\\browsers\nBinary Caches: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\n\nCypress Version: 6.0.0\nSystem Platform: win32 (10.0.17763)\nSystem Memory: 7.52 GB free 4.02 GB\nCypress package version: 6.0.0\nCypress binary version: 6.0.0\nElectron version: 11.0.2\nBundled Node version:\n12.18.3\n6.0.0\n6.0.0\n11.0.2\n\n12.18.3\n```\n\n```text\nRun cypress-io/github-action@v2\n  with:\n    browser: edge\n    start: yarn start\n    record: false\n    config-file: cypress.json\nC:\\windows\\system32\\cmd.exe /D /S /C \"C:\\npm\\prefix\\yarn.cmd --frozen-lockfile\"\nyarn install v1.22.10\n[1/4] Resolving packages...\nsuccess Already up-to-date.\nDone in 1.08s.\nC:\\windows\\system32\\cmd.exe /D /S /C \"\"C:\\Program Files\\nodejs\\npx.cmd\" cypress cache list\"\nNo cached binary versions were found.\nC:\\windows\\system32\\cmd.exe /D /S /C \"\"C:\\Program Files\\nodejs\\npx.cmd\" cypress verify\"\nThe cypress npm package is installed, but the Cypress binary is missing.\n\nWe expected the binary to be installed here: C:\\Users\\runneradmin\\.cache\\Cypress\\6.0.0\\Cypress\\Cypress.exe\n\nReasons it may be missing:\n\n- You're caching 'node_modules' but are not caching this path: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\n- You ran 'npm install' at an earlier build step but did not persist: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache\n\nProperly caching the binary will fix this error and avoid downloading and unzipping Cypress.\n\nAlternatively, you can run 'cypress install' to download the binary again.\n\nhttps://on.cypress.io/not-installed-ci-error\n\n----------\n\nPlatform: win32 (10.0.17763)\nCypress Version: 6.0.0\nError: The process 'C:\\Program Files\\nodejs\\npx.cmd' failed with exit code 1\n```\n\n```text\nCypress verify\n```\n\n```text\nCypress edge browser tests\n```\n\n```text\ncypress install\n```\n\n```text\nC:\\Users\\runneradmin\\.cache\\Cypress\n```\n\n```yaml\ncypress-run-windows:\n    runs-on: windows-latest\n    needs: cypress-run-ubuntu\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v1\n\n      - name: Setup node\n        uses: actions/setup-node@v1\n        with:\n          node-version: '12'\n\n      - name: Npm cache\n        uses: actions/cache@v2\n        id: cache-windows\n        with:\n          path: |\n            C:\\Users\\runneradmin\\AppData\\npm-cache\n            C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache <-----\n          key: ${{ runner.os }}-node-windows-${{ hashFiles('**/package-lock.json') }}\n          restore-keys: |\n            ${{ runner.os }}-node-windows-\n\n      - name: Npm install\n        if: steps.cache-windows.outputs.cache-hit != 'true'\n        run: npm install\n\n      - name: Cypress run on Chrome\n        uses: cypress-io/github-action@v2\n        with:\n          start: npm start\n          wait-on: http://localhost:4200\n          browser: chrome\n          install: false\n        env:\n          CYPRESS_CACHE_FOLDER: C:\\Users\\runneradmin\\AppData\\Local\\Cypress\\Cache <-----\n```\n\n```text\nactions/cache\n```\n\n```text\nactions/cache\n```\n\n```text\nactions/cache\n```\n\n```text\nCYPRESS_CACHE_FOLDER\n```\n\n```text\ncypress-io/github-action\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":518,"estimatedTokens":3451}}615{"id":"stack-76006609","source":"stackoverflow","questionId":76006609,"title":"TS2305: Module '\"@prisma/client\"' has no exported member 'User'","tags":["typescript","nestjs","gitlab-ci","prisma"],"text":"Title: TS2305: Module '\"@prisma/client\"' has no exported member 'User'\nTags: typescript, nestjs, gitlab-ci, prisma\nSource: Stack Overflow\n\nQuestion:\nI am try to set up a Gitlab CI for a nestjs project that uses prisma. When I run the pipeline, I get this error:\nenter image description here\n\nMy .gitlab-ci.yml:\n\n```\nimage: node:latest\n\nstages:\n - build\n\nbuild:\n stage: build\n before_script:\n - corepack enable\n - corepack prepare pnpm@latest-8 --activate\n - pnpm config set store-dir .pnpm-store\n script:\n - pnpm install\n - npx prisma generate\n - pnpm run build\n cache:\n key:\n files:\n - pnpm-lock.yaml\n paths:\n - .pnpm-store\n artifacts:\n paths:\n - dist\n```\n\n`user.models.ts`:\n\n```\nimport { User } from \"@prisma/client\"; # Line that is causing the build to fail in the CI\nimport { IsEmail, IsInt, IsNotEmpty, IsString } from \"class-validator\";\n\nclass UserModel implements User {\n @IsNotEmpty()\n @IsInt()\n id: number;\n\n @IsNotEmpty()\n @IsString()\n @IsEmail()\n email: string;\n\n @IsNotEmpty()\n @IsString()\n password: string;\n}\n```\n\nRunning `pnpm run build` locally works fine.\n\nWith the following scripts I have manually looked at the output generated by prisma, and I can see that `User` is being exported as a type from `index.d.ts`.\n\n```\n- cd ./node_modules/.prisma/client\n- cat index.d.ts\n- cd ../../..\n```\n\n========================================\n\nTop Answer:\nI ran into the same error in deployment, but in my case I'm building from a Dockerfile. So for anyone coming across the same but have a different setup, the fix was to add a line high up in the Dockerfile.\n\n`COPY prisma ./`\n\nExample\n\n```\nFROM node as installer\nWORKDIR /app\nCOPY prisma ./\n...the rest of your code\n```\n\n========================================\n\nCode:\n```text\nimage: node:latest\n\nstages:\n  - build\n\nbuild:\n  stage: build\n  before_script:\n    - corepack enable\n    - corepack prepare pnpm@latest-8 --activate\n    - pnpm config set store-dir .pnpm-store\n  script:\n    - pnpm install\n    - npx prisma generate\n    - pnpm run build\n  cache:\n    key:\n      files:\n        - pnpm-lock.yaml\n    paths:\n      - .pnpm-store\n  artifacts:\n    paths:\n      - dist\n```\n\n```text\nimport { User } from \"@prisma/client\"; # Line that is causing the build to fail in the CI\nimport { IsEmail, IsInt, IsNotEmpty, IsString } from \"class-validator\";\n\nclass UserModel implements User {\n    @IsNotEmpty()\n    @IsInt()\n    id: number;\n\n    @IsNotEmpty()\n    @IsString()\n    @IsEmail()\n    email: string;\n\n    @IsNotEmpty()\n    @IsString()\n    password: string;\n}\n```\n\n```text\n- cd ./node_modules/.prisma/client\n- cat index.d.ts\n- cd ../../..\n```\n\n```text\nuser.models.ts\n```\n\n```text\npnpm run build\n```\n\n```text\nUser\n```\n\n```text\nindex.d.ts\n```\n\n```text\ngenerator client {\n  ...\n  output = \"../../node_modules/.prisma/client\"\n  ...\n}\n```\n\n```text\nFROM node as installer\nWORKDIR /app\nCOPY prisma ./\n...the rest of your code\n```\n\n```text\nCOPY prisma ./\n```\n\n```text\nimport { PrismaClient, Prisma } from '@prisma/client'\n\nconst userData: Prisma.UserCreateInput[] = ...\n```\n\n```text\nimport { UserCreateInput } from '@prisma/client'\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n[npx|pnpm|npm] prisma generate\n[pnpm|npm] prisma migrate dev --name init\n```\n\n========================================\n\nComments:\n- Update: I realized that prisma generate is automatically run when doing `pnpm install` so I removed the `npx prisma generate` script and am still receiving the same error.\n- Thank you for this hint! I was checking to see if the `.prisma&#47;client` directory existed. It turned out that it didn't, so I ran `prisma generate`. This generated the necessary folder and resolved the `@prisma&#47;client` dependency.\n- This is also useful if you are in a monorepo and you need to prisma client across several repos.\n- Personally, neither option suited me. I found a solution by upgrading to the prisma v6.0.0 version.","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":202,"estimatedTokens":967}}616{"id":"stack-72393168","source":"stackoverflow","questionId":72393168,"title":"In the next major version, Nest will not allow classes annotated with @Injectable(), @Catch(), and @Controller() decorators","tags":["javascript","typescript","dependency-injection","nestjs"],"text":"Title: In the next major version, Nest will not allow classes annotated with @Injectable(), @Catch(), and @Controller() decorators\nTags: javascript, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm writing in Nest.js framework for 3 years and i got the message in by backend-application:\n\n```\nWARN [DependenciesScanner] In the next major version, Nest will not allow classes annotated with @Injectable(), @Catch(), and @Controller() decorators to appear in the \"imports\" array of a module.\nPlease remove \"ExternalOrAdmin\" (including forwarded occurrences, if any) from all of the \"imports\" arrays.\n\nScope [BackendAdminModule -> LicenseModule -> AuthModule]\n```\n\nI researched nest.js github and stuck what is the problem and why it says about some deprecation of useable decorators.\n\nDoes anyone know how to solve this problem or what will be in the next major version of Nest.js framework\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nYou can `ONLY imports module(s)` in the `imports` array, no service(s) or no controller(s) are allowed here.\n\nBelow is the general guide:\n\n- **Modules**->listed/imported in the `imports` array.\n\n- **Controllers**-> listed/imported in `controllers` array.\n\n- **Services**->listed/registered in the `providers` array.\n\n- **Services/Repositories/Injectable classes**->listed/registered in the `exports` array.\n\n**Example:**\n\nhttps://i.sstatic.net/gYihzMlI.png\n\n========================================\n\nCode:\n```text\nWARN [DependenciesScanner] In the next major version, Nest will not allow classes annotated with @Injectable(), @Catch(), and @Controller() decorators to appear in the \"imports\" array of a module.\nPlease remove \"ExternalOrAdmin\" (including forwarded occurrences, if any) from all of the \"imports\" arrays.\n\nScope [BackendAdminModule -> LicenseModule -> AuthModule]\n```\n\n```text\nimports\n```\n\n```text\nONLY imports module(s)\n```\n\n```text\nimports\n```\n\n```text\nimports\n```\n\n```text\ncontrollers\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n========================================\n\nComments:\n- Have you tried to do what it says โ€” \"Please remove \"ExternalOrAdmin\" (including forwarded occurrences, if any) from all of the \"imports\" arrays.\"? The decorators are not getting deprecated, but having services in the `imports` is.\n- @Joulukuusi, but the main reason that `ExternalOrAdmin` used there as `@UseGuards()`. And maybe it is the point, but without including `AuthModule` i have an error while sending request like `Unknown jwt strategy`. Most likely it is a lack of my architecture. But i will try to make some workaround. Thank you for the comment!\n- `ExternalOrAdmin`, since it's a guard, should then be a part of the `providers` array instead of `imports` โ€” please ensure that this is true.","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":83,"estimatedTokens":701}}617{"id":"stack-72305189","source":"stackoverflow","questionId":72305189,"title":"NestJS - Increase response timeout for particular http endpoint","tags":["javascript","node.js","express","nestjs"],"text":"Title: NestJS - Increase response timeout for particular http endpoint\nTags: javascript, node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI just started to learn about NestJS and I am wondering how could I manipulate response timeout for particular endpoints?\n\nI could do it on a server level like:\n\n```\nconst server = await app.listen(...);\n server.setTimeout(1800000)\n```\n\nor on endpoint, which looks bad:\n\n```\n@Post('/test')\n public async import(...props, @Res() res: Response): Promise {\n res.setTimeout(1800000)\n }\n```\n\nBut how could I do that on controller or method level?\nI have tried to increase timeout on endpoint using interceptors like:\n\n```\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';\nimport { Observable, throwError, TimeoutError } from 'rxjs';\nimport { catchError, take, timeout } from 'rxjs/operators';\n\n@Injectable()\nexport class TimeoutInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n\n return next.handle().pipe(\n timeout(1800000),\n catchError(err => {\n if (err instanceof TimeoutError) {\n return throwError(() => new RequestTimeoutException());\n }\n return throwError(() => err);\n }),\n );\n };\n};\n```\n\nAnd applying it on endpoint like:\n\n```\n@Post('/test')\n @UseInterceptors(TimeoutInterceptor)\n public async import(...props, @Res() res: Response): Promise {\n long running code...\n }\n```\n\nAlthough interceptor is triggered so I am able to log something\nthe timeout does not seems to work at all :/\n\n========================================\n\nTop Answer:\nOkay, if someone is curious this is what I have done:\n\n```\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class TimeoutInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n const response = context.switchToHttp().getResponse();\n response.setTimeout(600000)\n\n return next.handle();\n };\n};\n```\n\n========================================\n\nCode:\n```text\nconst server = await app.listen(...);\n  server.setTimeout(1800000)\n```\n\n```text\n@Post('/test')\n  public async import(...props, @Res() res: Response): Promise<string> {\n    res.setTimeout(1800000)\n  }\n```\n\n```text\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';\nimport { Observable, throwError, TimeoutError } from 'rxjs';\nimport { catchError, take, timeout } from 'rxjs/operators';\n\n@Injectable()\nexport class TimeoutInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n\n    return next.handle().pipe(\n      timeout(1800000),\n      catchError(err => {\n        if (err instanceof TimeoutError) {\n          return throwError(() => new RequestTimeoutException());\n        }\n        return throwError(() => err);\n      }),\n    );\n  };\n};\n```\n\n```text\n@Post('/test')\n  @UseInterceptors(TimeoutInterceptor)\n  public async import(...props, @Res() res: Response): Promise<string> {\n    long running code...\n  }\n```\n\n```text\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class TimeoutInterceptor implements NestInterceptor {\n  constructor(\n    private readonly reflector: Reflector,\n  ) {}\n\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const response = context.switchToHttp().getResponse();\n    const timeout = this.reflector.get<number>('request-timeout', context.getHandler()) || 60000;\n    response.setTimeout(timeout )\n\n    return next.handle();\n  };\n}\n```\n\n```text\nimport { applyDecorators, SetMetadata, UseInterceptors } from '@nestjs/common';\n\nconst SetTimeout = (timeout: number) => SetMetadata('request-timeout', timeout);\n\nexport function SetRequestTimeout(timeout: number = 60000) {\n  return applyDecorators(\n    SetTimeout(timeout),\n    UseInterceptors(TimeoutInterceptor),\n  );\n}\n```\n\n```text\n@SetRequestTimeout()\n```\n\n```text\n@SetRequestTimeout(10000)\n```\n\n```text\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class TimeoutInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const response = context.switchToHttp().getResponse();\n    response.setTimeout(600000)\n\n    return next.handle();\n  };\n};\n```\n\n========================================\n\nComments:\n- Here you set timeout for Observable, not the request itself. thats why your answer down there is working (as there you actually set the timeout for the request.\n- As i dont like using @UseInterceptors(Interceptor) im writing for you some decorator that would make usage must easier\n- ``` import { applyDecorators, SetMetadata, UseInterceptors } from '@nestjs/common'; const SetTimeout = (timeout: number) => SetMetadata('request-timeout', timeout); export function IsEventAdmin(timeout: number = 600000) { return applyDecorators( SetTimeout(timeout), UseInterceptors(TimeoutInterceptor), ); } ``` (you need to import the interceptor into it)\n- grr - i will put i in answer as this is totally unformatted\n- I you instruction but it doesn't work to me, could you please, if you have any documentation it here, I need more details to find out what happen.\n- @HadiiVarposhti have You added the interceptor to providers and to exports if you want to use it outside the current module?","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":191,"estimatedTokens":1405}}618{"id":"stack-48978370","source":"stackoverflow","questionId":48978370,"title":"Pass @IsInt() validation for application/x-www-form-urlencoded request type","tags":["node.js","nestjs","class-validator","class-transformer"],"text":"Title: Pass @IsInt() validation for application/x-www-form-urlencoded request type\nTags: node.js, nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nWhen I went through **Pipes** documentation I noticed that I can't make `@IsInt()` validation for **application/x-www-form-urlencoded** request correctly, cause all values which I passed I receive as string values.\n\nMy request data looks like this\nhttps://i.sstatic.net/VKazJ.png\n\nMy DTO looks like\n\n```\nimport { IsString, IsInt } from 'class-validator';\n\nexport class CreateCatDto {\n @IsString()\n readonly name: string;\n\n @IsInt()\n readonly age: number;\n\n @IsString()\n readonly breed: string;\n}\n```\n\nValidation pipe contains next code \n\n```\nimport { PipeTransform, Pipe, ArgumentMetadata, BadRequestException } from '@nestjs/common';\nimport { validate } from 'class-validator';\nimport { plainToClass } from 'class-transformer';\n\n@Pipe()\nexport class ValidationPipe implements PipeTransform {\n async transform(value, metadata: ArgumentMetadata) {\n const { metatype } = metadata;\n if (!metatype || !this.toValidate(metatype)) {\n return value;\n }\n const object = plainToClass(metatype, value);\n const errors = await validate(object);\n if (errors.length > 0) {\n throw new BadRequestException('Validation failed');\n }\n return value;\n }\n\n private toValidate(metatype): boolean {\n const types = [String, Boolean, Number, Array, Object];\n return !types.find((type) => metatype === type);\n }\n}\n```\n\nWhen I debug this pipe I noticed this state\nhttps://i.sstatic.net/BAivM.png\nWhere: \n\n- **value** - request body value\n\n- **object** - transformed via **class-transformer** value\n\n- **errors** - error object\n\nAs you can see errors tell to us that **age must be an integer number**.\n\nHow can I pass `@IsInt()` validation for **application/x-www-form-urlencoded** request?\n\nLibraries versions:\n\n- @nestjs/common@4.6.4\n\n- class-transformer@0.1.8\n\n- class-validator@0.8.1\n\nP.S: I also create a repository where you can run application to test bug. Required branch **how-to-pass-int-validation**\n\n**UPD**: after making changes from accepted answer I faced with problem that I put wrong parsed data to storage. Recorded example\n\nIs it possible to get well parsed `createCatDto` or what I need to do to save it with correct type structure?\n\n========================================\n\nTop Answer:\nAdding @Type(() => Number) resolved the issue for me.\n\n```\nimport { Type } from 'class-transformer';\nimport { IsInt, IsNotEmpty } from 'class-validator';\n\n@IsNotEmpty({ message: '' })\n@Type(() => Number)\n@IsInt({ message: '' })\nproject: number;\n```\n\n========================================\n\nCode:\n```text\nimport { IsString, IsInt } from 'class-validator';\n\nexport class CreateCatDto {\n    @IsString()\n    readonly name: string;\n\n    @IsInt()\n    readonly age: number;\n\n    @IsString()\n    readonly breed: string;\n}\n```\n\n```text\nimport { PipeTransform, Pipe, ArgumentMetadata, BadRequestException } from '@nestjs/common';\nimport { validate } from 'class-validator';\nimport { plainToClass } from 'class-transformer';\n\n@Pipe()\nexport class ValidationPipe implements PipeTransform<any> {\n    async transform(value, metadata: ArgumentMetadata) {\n        const { metatype } = metadata;\n        if (!metatype || !this.toValidate(metatype)) {\n            return value;\n        }\n        const object = plainToClass(metatype, value);\n        const errors = await validate(object);\n        if (errors.length > 0) {\n            throw new BadRequestException('Validation failed');\n        }\n        return value;\n    }\n\n    private toValidate(metatype): boolean {\n        const types = [String, Boolean, Number, Array, Object];\n        return !types.find((type) => metatype === type);\n    }\n}\n```\n\n```text\n@IsInt()\n```\n\n```text\n@IsInt()\n```\n\n```text\ncreateCatDto\n```\n\n```text\nimport { Transform } from 'class-transformer';\nimport { IsString, IsInt } from 'class-validator';\n\nexport class CreateCatDto {\n  @IsString()\n  readonly name: string;\n\n  @Transform(value => Number.isNan(+value) ? 0 : +value) // this field will be parsed to integer when `plainToClass gets called`\n  @IsInt()\n  readonly age: number;\n\n  @IsString()\n  readonly breed: string;\n}\n```\n\n```text\napplication/x-www-form-urlencoded\n```\n\n```text\nimport { Type } from 'class-transformer';\nimport { IsInt, IsNotEmpty } from 'class-validator';\n\n@IsNotEmpty({ message: '' })\n@Type(() => Number)\n@IsInt({ message: '' })\nproject: number;\n```\n\n========================================\n\nComments:\n- There's only one problem: `Number.isNan()` not exist. We need to use `isNaN()` instead of it.\n- There is another one problem: after passing it through validation I got value with string (I put update to my question). Which is the right way of passing correct data to controller?\n- According to your validation pipe, you need to return `object` variable, not the `value` variable.\n- Is this correct behavior for global pipe changes? I wrote that code based on docs and just wanna know will be this convenient to return `object` instead of `value`\n- I use `object` in projects.\n- Ok. Thanks for your help!\n- Why would you coerce `NaN` to zero? Seems rather arbitrary\n- Don't know if this solution was for an old version, but I had to do it like this: `@Transform(({ value }) => isNan(+value) ? 0 : +value )`\n- What is the source of `Type` decorator?\n- It comes from class-transformer. I added the imports in the example.\n- Better than accepted answer","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":201,"estimatedTokens":1362}}619{"id":"stack-66044062","source":"stackoverflow","questionId":66044062,"title":"Can we extends multiple classes in NestJS for TypeORM?","tags":["typescript","nestjs","typeorm"],"text":"Title: Can we extends multiple classes in NestJS for TypeORM?\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI faced a situation where I want extends multiple classes. I have class A named `a.entity.ts` and I'm extending this class to `BaseEntity` (which is the predefined class in typeORM) as :\n\n```\n@Entity()\nexport class A extends BaseEntity{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\nAlso, I have my own custom `abstract class DateAudit` for Auditing date purpose as :\n\n```\nexport abstract class DateAudit {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\nI want to use this `DateAudit` along with `BaseEntity` class in my **class A** like :\n\nexport class A extends BaseEntity, DateAudit\n\nI know multiple inheritances are not possible. Looking forward to knowing how I can achieve this type of scenario.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\n**SOLUTION 1** \n\nTo inherit columns in TypeORM you need to write an abstract class that your entity will inherit from, in your case you can do something:\n\n```\nexport type Constructor = new (...args: any[]) => T;\n\nexport function BaseEntity(Base: TBase) {\n abstract class AbstractBase extends Base {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n }\n return AbstractBase;\n}\n\nexport function DateAudit(Base: TBase) {\n abstract class AbstractBase extends Base {\n @CreateDateColumn()\n created: Date;\n\n @UpdateDateColumn()\n updated: Date;\n }\n return AbstractBase;\n}\n\nexport class EmptyClass {}\n```\n\nTo implement it :\n\n```\n@Entity()\nexport class A extends DateAudit(BaseEntity(EmptyClass)){\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\n*ps: inspired by solution from github*\n\n**Solution 2 : is to use *Embedded Entities***\n\nIn your case, we going to extend the `baseEntity`, on the other hand\nwe going to create a class for `auditEntity`\n\n```\nexport class DateAudit {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\nThen we can connect those columns in your entity :\n\n```\n@Entity()\nexport class A extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n\n @Column(type => DateAudit )\n audit: DateAudit ;\n}\n```\n\n*ps: the colmun will take `audit` as a prefix* \n\nsource : embedded-entities\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class A extends BaseEntity{\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    title: string;\n\n    @Column({length: 100, nullable: true})\n    description: string;\n}\n```\n\n```text\nexport abstract class DateAudit {\n    \n    @CreateDateColumn()\n    created: Date;\n  \n    @UpdateDateColumn()\n    updated: Date;\n  }\n```\n\n```text\na.entity.ts\n```\n\n```text\nBaseEntity\n```\n\n```text\nabstract class DateAudit\n```\n\n```text\nDateAudit\n```\n\n```text\nBaseEntity\n```\n\n```js\nexport abstract class DateAudit extends BaseEntity {\n    \n    @CreateDateColumn()\n    created: Date;\n  \n    @UpdateDateColumn()\n    updated: Date;\n  }\n```\n\n```js\n@Entity()\nexport class A extends DateAudit {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    title: string;\n\n    @Column({length: 100, nullable: true})\n    description: string;\n}\n```\n\n```text\nexport type Constructor<T = {}> = new (...args: any[]) => T;\n\nexport function BaseEntity<TBase extends Constructor>(Base: TBase) {\n    abstract class AbstractBase extends Base {\n        @PrimaryGeneratedColumn()\n          id: number;\n\n        @Column()\n         title: string;\n\n       @Column({length: 100, nullable: true})\n        description: string;\n    }\n    return AbstractBase;\n}\n\nexport function DateAudit<TBase extends Constructor>(Base: TBase) {\n    abstract class AbstractBase extends Base {\n        @CreateDateColumn()\n            created: Date;\n\n        @UpdateDateColumn()\n           updated: Date;\n    }\n    return AbstractBase;\n}\n\nexport class EmptyClass {}\n```\n\n```text\n@Entity()\nexport class A extends DateAudit(BaseEntity(EmptyClass)){\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    title: string;\n\n    @Column({length: 100, nullable: true})\n    description: string;\n}\n```\n\n```text\nexport class DateAudit {\n    \n    @CreateDateColumn()\n    created: Date;\n  \n    @UpdateDateColumn()\n    updated: Date;\n  }\n```\n\n```text\n@Entity()\nexport class A extends BaseEntity {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    title: string;\n\n    @Column({length: 100, nullable: true})\n    description: string;\n\n   @Column(type => DateAudit )\n    audit: DateAudit ;\n}\n```\n\n```text\nbaseEntity\n```\n\n```text\nauditEntity\n```\n\n```text\naudit\n```\n\n========================================\n\nComments:\n- For some who looking for a solution, this can help - stackoverflow.com/questions/26948400/&hellip;\n- Thanks @youba for this solution, this works fine. The only issue is that if you, for some reason, what to have any kind of relation in the abstract class, like ManyToOne, you cannot reference back to EntityWithTenant as it is not a BaseEntity. Imagine you have TenantType entity class TenantType extends BaseEntity { ... @OneToMany(() => EntityWithTenant, entitiyWithTenant => entitiyWithTenant.tenantType) entityWithTenant: EntityWithTenant } are there any work around inside for that too?","metadata":{"transformedAt":"2026-08-18T18:33:02.457Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":300,"estimatedTokens":1392}}620{"id":"stack-60924576","source":"stackoverflow","questionId":60924576,"title":"CORS is somehow stopping my Angular and Nestjs apps from communicating","tags":["angular","typescript","nestjs","ngxs"],"text":"Title: CORS is somehow stopping my Angular and Nestjs apps from communicating\nTags: angular, typescript, nestjs, ngxs\nSource: Stack Overflow\n\nQuestion:\nI'm building an app with Angular and NestJS using NGXS for state management. I got everything set up and served my application and got this error in the console.\n\n Access to XMLHttpRequest at 'localhost:333/api/product-index' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.\n\nAfter doing a little research I found this article explaining how to handle CORS in our Angular apps and after checking the files it tells us to modify I saw that the settings were already present. I was confused about the `server.js` file it told us to update and after looking into what's typically done in a `server.js` file I came to the conclusion that in Angular it must be the `main.ts` file however I don't know if I need to make the modifications to the `main.ts` file in my Nest app or the one in my Angular app. I'm using a `nrwl nx` monorepo for my apps as well.\n\nThis is the `proxy.conf.json` file from my angular app\n\n```\n{\n \"/cre8or-maker-backend\": {\n \"target\": \"http://localhost:3333\",\n \"secure\": false,\n \"logLevel\": \"debug\"\n }\n }\n```\n\nThis is the `serve` object of the `architect` object in my `angular.json` file.\n\n```\n\"serve\": {\n \"builder\": \"@angular-devkit/build-angular:dev-server\",\n \"options\": {\n \"browserTarget\": \"cre8or-maker:build\",\n \"proxyConfig\": \"apps/cre8or-maker/proxy.conf.json\"\n }\n```\n\nAs I said before these settings were already present in these files and the only thing that seems new to me is the part about modifying the `server.js` file which I'm assuming is the `main.ts` file in Angular world. Here's what my `main.ts` files look like\n\n`nest main.ts`\n\n```\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from './app/app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const globalPrefix = 'api';\n app.setGlobalPrefix(globalPrefix);\n const port = process.env.port || 3333;\n await app.listen(port, () => {\n console.log('Listening at http://localhost:' + port + '/' + globalPrefix);\n });\n}\n\nbootstrap();\n```\n\n`angular main.ts`\n\n```\nimport { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\n\nif (environment.production) {\n enableProdMode();\n}\n\nplatformBrowserDynamic()\n .bootstrapModule(AppModule)\n .catch(err => console.error(err));\n```\n\nI installed the `cors` npm package already, I just don't know what else I'm suppose to do to get this working, can anyone help?\n\n***UPDATE***\nI tried adding `app.enableCors();` to the `main.ts` file in my NestJs app as well as modifying the `create(AppModule)` function to be `create(AppModule, {cors: true})` and neither solve the problem. I also added the following snippet of code which didn't help either.\n\n```\napp.use((req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');\n res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');\n next();\n });\n```\n\nAs of right now I only have one state defined making an API request to the back end. Inside my state I have an action which looks like this\n\n```\n@Action(GetProductIndexList)\n getProductIndexListData({patchState, dispatch, getState}: StateContext){\n\n return this.dataService.fetchProductIndexList().pipe(tap((result)=>{\n const state = getState();\n\n patchState({items:[...state.items, ...result]});\n }));\n }\n```\n\nI make the api call inside of a service file which I'm calling `dataService` in the state's constructor. The service file looks like this.\n\n```\n@Injectable({ providedIn: 'root' })\n\nexport class ProductIndexService{\n\n constructor(private httpClient: HttpClient){}\n\n private readonly URL: string = 'localhost:3333/api';\n\n public fetchProductIndexList():Observable{\n const path: string = this.URL + '/product-index';\n\n return this.httpClient.get(path) as Observable;\n }\n}\n```\n\nIn NestJS I can successfully call the data without any errors so I know the controllers are set up properly but if anybody wants to see how I have things set up there let me know and I'll update this question with the code.\n\n========================================\n\nTop Answer:\nFor the following, I just ran into this issue while working on an Angular 13 and Nest.js 8 app in an NX workspace.\n\nFor my part, I finally solved this CORS problem by adding the line app.enableCors(); in the main.ts file of the Nest.js application.\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const globalPrefix = 'api';\n app.setGlobalPrefix(globalPrefix);\n app.enableCors();\n const port = process.env.PORT || 3000;\n await app.listen(port);\n Logger.log(\n `๐Ÿš€ Application is running on: http://localhost:${port}/${globalPrefix}`\n );\n}\n```\n\nSee the documentation:https://docs.nestjs.com/security/cors\n\n========================================\n\nCode:\n```text\n{\n    \"/cre8or-maker-backend\": {\n      \"target\": \"http://localhost:3333\",\n      \"secure\": false,\n      \"logLevel\": \"debug\"\n    }\n  }\n```\n\n```text\n\"serve\": {\n          \"builder\": \"@angular-devkit/build-angular:dev-server\",\n          \"options\": {\n            \"browserTarget\": \"cre8or-maker:build\",\n            \"proxyConfig\": \"apps/cre8or-maker/proxy.conf.json\"\n          }\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from './app/app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const globalPrefix = 'api';\n  app.setGlobalPrefix(globalPrefix);\n  const port = process.env.port || 3333;\n  await app.listen(port, () => {\n    console.log('Listening at http://localhost:' + port + '/' + globalPrefix);\n  });\n}\n\nbootstrap();\n```\n\n```text\nimport { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\n\nif (environment.production) {\n  enableProdMode();\n}\n\nplatformBrowserDynamic()\n  .bootstrapModule(AppModule)\n  .catch(err => console.error(err));\n```\n\n```text\napp.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');\n    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');\n    next();\n  });\n```\n\n```text\n@Action(GetProductIndexList)\n    getProductIndexListData({patchState, dispatch, getState}: StateContext<ProductIndexListModel>){\n\n       return this.dataService.fetchProductIndexList().pipe(tap((result)=>{\n            const state = getState();\n\n            patchState({items:[...state.items, ...result]});\n        }));\n    }\n```\n\n```text\n@Injectable({ providedIn: 'root' })\n\nexport class ProductIndexService{\n\n    constructor(private httpClient: HttpClient){}\n\n    private readonly URL: string = 'localhost:3333/api';\n\n    public fetchProductIndexList():Observable<CattegoryIndexItem[]>{\n        const path: string = this.URL + '/product-index';\n\n        return this.httpClient.get(path) as Observable<CattegoryIndexItem[]>;\n    }\n}\n```\n\n```text\nserver.js\n```\n\n```text\nserver.js\n```\n\n```text\nmain.ts\n```\n\n```text\nmain.ts\n```\n\n```text\nnrwl nx\n```\n\n```text\nproxy.conf.json\n```\n\n```text\nserve\n```\n\n```text\narchitect\n```\n\n```text\nangular.json\n```\n\n```text\nserver.js\n```\n\n```text\nmain.ts\n```\n\n```text\nmain.ts\n```\n\n```text\nnest main.ts\n```\n\n```text\nangular main.ts\n```\n\n```text\ncors\n```\n\n```text\napp.enableCors();\n```\n\n```text\nmain.ts\n```\n\n```text\ncreate(AppModule)\n```\n\n```text\ncreate(AppModule, {cors: true})\n```\n\n```text\ndataService\n```\n\n```text\nlocalhost:333\n```\n\n```text\nlocalhost:3333\n```\n\n```js\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    const globalPrefix = 'api';\n    app.setGlobalPrefix(globalPrefix);\n    app.enableCors();\n    const port = process.env.PORT || 3000;\n    await app.listen(port);\n    Logger.log(\n        `๐Ÿš€ Application is running on: http://localhost:${port}/${globalPrefix}`\n    );\n}\n```\n\n========================================\n\nComments:\n- Does this answer your question? NestJS enable cors in production\n- unfortunately that didn't help. I tried a couple things from it which I modified my question to show.\n- Can you show us where you send your request within the angular app?\n- I just updated the question again.\n- Try the following change to your URL: `private readonly URL: string = 'https:&#47;&#47;localhost:3333&#47;api';`\n- in your nest main.ts , add the following lines ` app.enableCors({origin: ['*'],credentials: true or false});`\n- ok I made the suggested modifications and the error went away, however I'm getting these errors now `core.js:6185 ERROR HttpErrorResponseย {headers: HttpHeaders, status: 0, statusText: \"Unknown Error\", url: \"https:&#47;&#47;localhost:3333&#47;api&#47;product-index\", ok: false,ย โ€ฆ}` and `GET https:&#47;&#47;localhost:3333&#47;api&#47;product-index net::ERR_CONNECTION_REFUSED`\n- I followed steps mentioned in your question: app.enableCORS(); and app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Accept'); next(); }); and it worked for me to connect my angular app with nestjs api successfully. Thanks\n- i add http:// before the localhost:3000 and only with nestjs app.enableCors(); it works! i was not need to proxy.conf.json - in the angular ( angular version 13 , nest version 8 )","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":354,"estimatedTokens":2444}}621{"id":"stack-50831216","source":"stackoverflow","questionId":50831216,"title":"NestJs - Send Response from Exception Filter","tags":["exception","nestjs"],"text":"Title: NestJs - Send Response from Exception Filter\nTags: exception, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to achieve a simple behavior: Whenever an exception is thrown I would like to send the error as a response. My kind of naive code looks like this, but doesn't respond at all:\n\n**Exception Filter:**\n\n```\nimport { ExceptionFilter, ArgumentsHost, Catch } from '@nestjs/common';\n\n@Catch()\nexport class AnyExceptionFilter implements ExceptionFilter {\n catch(exception: any, host: ArgumentsHost) {\n return JSON.stringify(\n {\n error: exception,\n },\n null,\n 4,\n );\n }\n}\n```\n\n**Module**\n\n```\n@Module({\n imports: [],\n controllers: [AppController, TestController],\n providers: [AppService, AnyExceptionFilter],\n})\nexport class AppModule {}\n```\n\n**main.ts**\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useGlobalFilters(new AnyExceptionFilter());\n await app.listen(1212);\n}\nbootstrap();\n```\n\nIs there anything I miss? Thanks in advance :)\n\n========================================\n\nTop Answer:\nJust adding a bit more info about the previous answers. The suggested code provided by @oto-meskhy here is (replicating it just for completion purposes - credits to @oto-meskhy):\n\n```\nimport { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';\n\n@Catch()\nexport class AnyExceptionFilter implements ExceptionFilter {\n catch(error: Error, host: ArgumentsHost) {\n\n const response = host.switchToHttp().getResponse();\n\n const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;\n\n response\n .status(status)\n .json(error);\n }\n}\n```\n\nThis code should work IF your NestJS application didn't defined a specific platform in the `NestFactory.create()` method. HoweHowever, if the chosen platform is `Fastify` (docs here), note that the a small piece of the code above will not work, more specifically:\n\n```\n...\n response\n .status(status)\n .send(object)\n```\n\nIn such case, your application code should change a little bit to use `Fastify`'s Reply methods, like this:\n\n```\n// fastify\n response\n .code(status)\n .send(error);\n```\n\n========================================\n\nCode:\n```js\nimport { ExceptionFilter, ArgumentsHost, Catch } from '@nestjs/common';\n\n@Catch()\nexport class AnyExceptionFilter implements ExceptionFilter {\n  catch(exception: any, host: ArgumentsHost) {\n    return JSON.stringify(\n      {\n        error: exception,\n      },\n      null,\n      4,\n    );\n  }\n}\n```\n\n```js\n@Module({\n  imports: [],\n  controllers: [AppController, TestController],\n  providers: [AppService, AnyExceptionFilter],\n})\nexport class AppModule {}\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalFilters(new AnyExceptionFilter());\n  await app.listen(1212);\n}\nbootstrap();\n```\n\n```text\nimport { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';\n\n@Catch()\nexport class AnyExceptionFilter implements ExceptionFilter {\n  catch(error: Error, host: ArgumentsHost) {\n\n    const response = host.switchToHttp().getResponse();\n\n    const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    response\n      .status(status)\n      .json(error);\n  }\n}\n```\n\n```text\nconst ctx = host.switchToHttp();\nconst response = ctx.getResponse();\n\nresponse\n  .status(status)\n  .send('Hello');\n```\n\n```text\ncatch\n```\n\n```text\nresponse\n```\n\n```text\nimport { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';\n\n@Catch()\nexport class AnyExceptionFilter implements ExceptionFilter {\n  catch(error: Error, host: ArgumentsHost) {\n\n    const response = host.switchToHttp().getResponse();\n\n    const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    response\n      .status(status)\n      .json(error);\n  }\n}\n```\n\n```text\n...\n    response\n      .status(status)\n      .send(object)\n```\n\n```text\n// fastify\n    response\n      .code(status)\n      .send(error);\n```\n\n```text\nNestFactory.create()\n```\n\n```text\nFastify\n```\n\n```text\nFastify\n```\n\n========================================\n\nComments:\n- I already tried that, but this seemed not to work for some reason. The response object hadn't even a function called \"status\". :-(","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":212,"estimatedTokens":1083}}622{"id":"stack-65111583","source":"stackoverflow","questionId":65111583,"title":"An issue with Nestjs mongoose module after installation","tags":["nestjs"],"text":"Title: An issue with Nestjs mongoose module after installation\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI installed @nestjs/mongoose with following npm command:\n\n```\nnpm i --save @nestjs/mongoose mongoose\n```\n\nBut when I try to lauch the app, I get following errors:\n\n```\nnode_modules/@nestjs/mongoose/dist/decorators/prop.decorator.d.ts:2:44 - error TS2694: Namespace '\"mongoose\"' has no exported member 'SchemaTypeOpts'.\n\nexport declare type PropOptions = mongoose.SchemaTypeOpts | mongoose.Schema | mongoose.SchemaType;\n ~~~~~~~~~~~~~~\nnode_modules/@nestjs/mongoose/dist/factories/schema.factory.d.ts:4:60 - error TS2315: Type 'Schema' is not generic.\n\nstatic createForClass(target: Type): mongoose.Schema;\n ~~~~~~~~~~~~~~~~~~\nnode_modules/@nestjs/mongoose/dist/interfaces/mongoose-options.interface.d.ts:3:10 - error TS2305: Module '\"mongoose\"' has no exported member 'ConnectionOptions'.\n\nimport { ConnectionOptions } from 'mongoose';\n ~~~~~~~~~~~~~~~~~\n\nFound 3 error(s).\n```\n\nAny help would be highly appreciated.\n\n========================================\n\nTop Answer:\nThe best combination that worked for me is the following.\n\n```\n\"@nestjs/mongoose\": \"^7.0.4\",\n\"mongoose\": \"^5.10.19\",\n\"@types/mongoose\": \"^5.10.3\", //dev-dependency\n```\n\nAs of 19 Dec 2020, any version later than that did NOT work for me.\n\n========================================\n\nCode:\n```text\nnpm i --save @nestjs/mongoose mongoose\n```\n\n```text\nnode_modules/@nestjs/mongoose/dist/decorators/prop.decorator.d.ts:2:44 - error TS2694: Namespace '\"mongoose\"' has no exported member 'SchemaTypeOpts'.\n\nexport declare type PropOptions = mongoose.SchemaTypeOpts<any> | mongoose.Schema | mongoose.SchemaType;\n                                         ~~~~~~~~~~~~~~\nnode_modules/@nestjs/mongoose/dist/factories/schema.factory.d.ts:4:60 - error TS2315: Type 'Schema' is not generic.\n\nstatic createForClass<T = any>(target: Type<unknown>): mongoose.Schema<T>;\n                                                         ~~~~~~~~~~~~~~~~~~\nnode_modules/@nestjs/mongoose/dist/interfaces/mongoose-options.interface.d.ts:3:10 - error TS2305: Module '\"mongoose\"' has no exported member 'ConnectionOptions'.\n\nimport { ConnectionOptions } from 'mongoose';\n       ~~~~~~~~~~~~~~~~~\n\nFound 3 error(s).\n```\n\n```text\nmongoose\n```\n\n```text\n5.10.x\n```\n\n```text\nmongoose\n```\n\n```text\n\"@nestjs/mongoose\": \"^7.2.0\",\n\"mongoose\": \"^5.11.5\",\n```\n\n```text\nnpm install --save @nestjs/mongoose mongoose\n```\n\n```text\n@types/mongoose\": ^5.10.2\"\n```\n\n```text\nnpm i --save @nestjs/mongoose mongoose\nnpm i --save-dev @tsed/mongoose\n```\n\n```text\n@tsed/mongoose\n```\n\n```text\n@types/mongoose\n```\n\n```text\n@types/mongoose\n```\n\n```text\n\"@nestjs/mongoose\": \"^7.0.4\",\n\"mongoose\": \"^5.10.19\",\n\"@types/mongoose\": \"^5.10.3\", //dev-dependency\n```\n\n```text\n\"@nestjs/mongoose\" - \"^9.2.0\"\n\"mongoose\" - \"^6.6.3\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":121,"estimatedTokens":711}}623{"id":"stack-67829688","source":"stackoverflow","questionId":67829688,"title":"NestJs - ConfigModule.forRoot isGlobal not working","tags":["nestjs","dotenv","nestjs-config"],"text":"Title: NestJs - ConfigModule.forRoot isGlobal not working\nTags: nestjs, dotenv, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI am trying to load the \"process.env.AUTH_SECRET\" in AuthModule, but it is giving me the undefined error \"Error: secretOrPrivateKey must have a value\".\n\nI did setup the \"isGlobal: true\" in AppModule and it was able to read \"process.env.MONGO_URL\" there fine.\n\nI have also installed dotenv, which reads fine if I do:\n\n```\nimport * as dotenv from 'dotenv';\ndotenv.config();\n\nexport const jwtConstants = {\n secret: process.env.AUTH_SECRET,\n};\n```\n\nBut I would rather do it the \"NestJs\" way as the doc says adding isGlobal should make the env available to all other modules.\n\nauth.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { UserModule } from '../user/user.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtModule } from '@nestjs/jwt';\n\n@Module({\n imports: [\n UserModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.AUTH_SECRET, //Cannot read this.\n signOptions: { expiresIn: '60s' },\n }),\n ],\n providers: [AuthService, LocalStrategy],\n exports: [AuthService, JwtModule],\n})\nexport class AuthModule {}\n```\n\napp.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { ConfigModule } from '@nestjs/config';\nimport { AuthModule } from './auth/auth.module';\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n }),\n UserModule,\n MongooseModule.forRoot(process.env.MONGO_URL), // Can read this fine\n AuthModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nWhat am I missing or doing wrong? Just for reference, I am trying to this authentication tutorial.\n\nThank you,\n\n========================================\n\nCode:\n```text\nimport * as dotenv from 'dotenv';\ndotenv.config();\n\nexport const jwtConstants = {\n  secret: process.env.AUTH_SECRET,\n};\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { UserModule } from '../user/user.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtModule } from '@nestjs/jwt';\n\n@Module({\n  imports: [\n    UserModule,\n    PassportModule,\n    JwtModule.register({\n      secret: process.env.AUTH_SECRET, //Cannot read this.\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n  providers: [AuthService, LocalStrategy],\n  exports: [AuthService, JwtModule],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { ConfigModule } from '@nestjs/config';\nimport { AuthModule } from './auth/auth.module';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n    }),\n    UserModule,\n    MongooseModule.forRoot(process.env.MONGO_URL), // Can read this fine\n    AuthModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nJWTModule.registerAsync({\n    inject: [ConfigService],\n    useFactory: (config: ConfigService) => {\n      secret: config.get<string>('AUTH_SECRET'),\n      signOptions: { expiresIn: '60s' }\n    }\n})\n```\n\n```text\nimport * as dotenv from 'dotenv';\nimport { resolve } from 'path';\ndotenv.config({ path: resolve(__dirname, '../.env') });\n```\n\n```text\nMongooseModule\n```\n\n```text\nAuthModule\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigService\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigService\n```\n\n```text\n.register\n```\n\n```text\n.registerAsync\n```\n\n```text\nConfigService\n```\n\n========================================\n\nComments:\n- try to use `JwtModule.registerAsync` instead of `JwtModule.register` to avoid using `process.env.*` just like docs.nestjs.com/techniques/http-module#async-configuration\n- Thanks but one question, why `MongooseModule` can read .env but modules inside `AuthModule` like `JWTModule` not??\n- Its most likely already in the global env. That or its just the lucky winner of a race condition","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":198,"estimatedTokens":1115}}624{"id":"stack-71198822","source":"stackoverflow","questionId":71198822,"title":"Upload dynamic multiple files in Nest JS","tags":["javascript","node.js","file-upload","nestjs"],"text":"Title: Upload dynamic multiple files in Nest JS\nTags: javascript, node.js, file-upload, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to upload files with dynamic keys, but nest.js needs to know key names.\n\nI tried this one:\n\n\r\n\r\n\n```\n@UseInterceptors(FilesInterceptor('files'))\n async uploadFile(@Query() minioDto: MinioDto, @UploadedFiles() files: Array) {\n const {bucket} = minioDto;\n return (await this.minioClientService.upload(files, bucket))?.name;\n }\n```\n\n\r\n\r\n\r\n\nHere files are static, but I want dynamic like:\n\n\r\n\r\n\n```\n@UseInterceptors(FilesInterceptor())\n async uploadFile(@Query() minioDto: MinioDto, @UploadedFiles() files: Array) {\n const {bucket} = minioDto;\n return (await this.minioClientService.upload(files, bucket))?.name;\n }\n```\n\n\r\n\r\n\r\n\nI even tried to get files from the request\nbut I couldn't\n\n========================================\n\nTop Answer:\nYou can upload multiple files with each field having a unique name using **FileFieldsInterceptor** like this -\n\n```\n@Post('upload')\n @UseGuards(JwtAuthGuard)\n @UseInterceptors(FileFieldsInterceptor([\n { name: 'profilePic', maxCount: 1 },\n { name: 'pitchDeck', maxCount: 10 },\n ]))\n uploadFiles(@UploadedFiles() files: {profilePic: Express.Multer.File[], pitchDeck: Express.Multer.File[]}){\n console.log('files', files);\n }\n```\n\n========================================\n\nCode:\n```js\n@UseInterceptors(FilesInterceptor('files'))\n    async uploadFile(@Query() minioDto: MinioDto, @UploadedFiles() files: Array<BufferedFile>) {\n        const {bucket} = minioDto;\n        return (await this.minioClientService.upload(files, bucket))?.name;\n    }\n```\n\n```js\n@UseInterceptors(FilesInterceptor())\n    async uploadFile(@Query() minioDto: MinioDto, @UploadedFiles() files: Array<BufferedFile>) {\n        const {bucket} = minioDto;\n        return (await this.minioClientService.upload(files, bucket))?.name;\n    }\n```\n\n```js\n@Post('upload')\n@UseInterceptors(AnyFilesInterceptor())\nuploadFile(@UploadedFiles() files: Array<Express.Multer.File>) {\n  console.log(files);\n}\n```\n\n```text\nAnyFilesInterceptor\n```\n\n```text\nimport { Controller, Post, UploadedFiles, UploadedFile, UseInterceptors } from '@nestjs/common';\n    import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';\n    import { AppService } from './app.service';\n    import { Express } from 'express';\n\n\n    @Controller('api/portal/file')\n\n\n    export class AppController {\n      constructor(private appService: AppService) {}\n\n\n      @Post('/multiple')\n      @UseInterceptors(FilesInterceptor('files'))\n      async uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>) {\n    \n// If you are getting the error \"Namespace 'global.Express' has no exported member 'Multer'\" then replace \"Array<Express.Multer.File>\" with \"any\" or try to remove error by installing Express/multer\n\n        const req = {\n          files,\n          prospectId: 1234,\n        };\n        return await this.appService.getUrls(req);\n      }\n\n\n      @Post('/single')\n      @UseInterceptors(FileInterceptor('file'))\n      async uploadFile(@UploadedFile() file: Express.Multer.File) {\n        const req = {\n          files: [file],\n          prospectId: 1234,\n        };\n        return await this.appService.getUrls(req);\n      }\n    }\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { FileDataReq, FileDataRes } from './dto/app.dto';\n\n@Injectable()\nexport class AppService {\n\n  async getUrls(uploadData: FileDataReq): Promise<FileDataRes> {\n    const { prospectId } = uploadData;\n    const response = { urls: [], prospectId };\n    const { files } = uploadData;\n    for (const file of files) {\n      const { originalname } = file;\n      let url = `/${prospectId}/${new Date().getTime()}_${originalname.trim().split(' ').join('_')}`;\n      response.urls.push(url);\n    }\n    return response;\n  }\n}\n```\n\n```text\nexport class FileDataReq {\n  files: Express.Multer.File[];\n  prospectId: number;\n}\n\nexport class FileDataRes {\n  urls: string[];\n  prospectId: number;\n}\n```\n\n```text\n@Post('upload')\n  @UseGuards(JwtAuthGuard)\n  @UseInterceptors(FileFieldsInterceptor([\n    { name: 'profilePic', maxCount: 1 },\n    { name: 'pitchDeck', maxCount: 10 },\n  ]))\n  uploadFiles(@UploadedFiles() files: {profilePic: Express.Multer.File[], pitchDeck: Express.Multer.File[]}){\n    console.log('files', files);\n  }\n```\n\n========================================\n\nComments:\n- Thank you! This is the only place I managed to find this information","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":181,"estimatedTokens":1117}}625{"id":"stack-50398437","source":"stackoverflow","questionId":50398437,"title":"Nestjs: @Session() return undefined","tags":["express","nestjs"],"text":"Title: Nestjs: @Session() return undefined\nTags: express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am currently migrating my server to use nest.js.\nWhen I use the `@Session()` decorator it gives me undefined.\nI do import it from @nestjs/common, this is not the issue.\n\n```\n@Get('foo')\nasync find(@Session() sess) {\n console.log(sess); // sess == undefined\n}\n```\n\nWhile, with express the session is defined\n\n```\nrouter.get('/foo/', function(req, res){\n console.log(req.session); // req.session is defined\n```\n\nThanks for your help!\n\n========================================\n\nCode:\n```text\n@Get('foo')\nasync find(@Session() sess) {\n  console.log(sess); // sess == undefined\n}\n```\n\n```text\nrouter.get('/foo/', function(req, res){\n  console.log(req.session); // req.session is defined\n```\n\n```text\n@Session()\n```\n\n```text\napp.use(session({ secret: 'nest is awesome' }))\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":218}}626{"id":"stack-59838601","source":"stackoverflow","questionId":59838601,"title":"class-validator doesn't validate arrays","tags":["arrays","validation","nestjs","class-validator"],"text":"Title: class-validator doesn't validate arrays\nTags: arrays, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI can't get the class-validator to work. It seems like I am not using it: everything works as if I didn't use class-validator. When sending a request with an incorrectly formatted body, I don't have any validation error, although I should.\n\nMy DTO:\n\n```\nimport { IsInt, Min, Max } from 'class-validator';\n\nexport class PatchForecastDTO {\n @IsInt()\n @Min(0)\n @Max(9)\n score1: number;\n\n @IsInt()\n @Min(0)\n @Max(9)\n score2: number;\n gameId: string;\n}\n```\n\nMy controller:\n\n```\n@Patch('/:encid/forecasts/updateAll')\nasync updateForecast(\n @Body() patchForecastDTO: PatchForecastDTO[],\n @Param('encid') encid: string,\n @Query('userId') userId: string\n): Promise {\n return await this.instanceService.updateForecasts(userId, encid, patchForecastDTO);\n}\n```\n\nMy bootstrap:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useGlobalPipes(new ValidationPipe());\n await app.listen(PORT);\n Logger.log(`Application is running on http://localhost:${PORT}`, 'Bootstrap');\n}\nbootstrap();\n```\n\nI can't find what's wrong. What did I miss?\n\n========================================\n\nTop Answer:\nIn the current version of NestJS (7.6.14), validating a request body that is a JSON array is supported using the built in `ParseArrayPipe`.\n\n```\n@Post()\ncreateBulk(\n @Body(new ParseArrayPipe({ items: CreateUserDto }))\n createUserDtos: CreateUserDto[],\n) {\n return 'This action adds new users';\n}\n```\n\nSee the official docs or the source code for more info.\n\n========================================\n\nCode:\n```ts\nimport { IsInt, Min, Max } from 'class-validator';\n\nexport class PatchForecastDTO {\n  @IsInt()\n  @Min(0)\n  @Max(9)\n  score1: number;\n\n  @IsInt()\n  @Min(0)\n  @Max(9)\n  score2: number;\n  gameId: string;\n}\n```\n\n```ts\n@Patch('/:encid/forecasts/updateAll')\nasync updateForecast(\n    @Body() patchForecastDTO: PatchForecastDTO[],\n    @Param('encid') encid: string,\n    @Query('userId') userId: string\n): Promise<ForecastDTO[]> {\n  return await this.instanceService.updateForecasts(userId, encid, patchForecastDTO);\n}\n```\n\n```ts\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(PORT);\n  Logger.log(`Application is running on http://localhost:${PORT}`, 'Bootstrap');\n}\nbootstrap();\n```\n\n```text\nimport { PatchForecastDTO } from './patch.forecast.dto';\nimport { IsArray, ValidateNested } from 'class-validator';\nimport { Type } from 'class-transformer';\n\nexport class PatchForecastsDTO {\n    @IsArray()\n    @ValidateNested() // perform validation on children too\n    @Type(() => PatchForecastDTO) // cast the payload to the correct DTO type\n    forecasts: PatchForecastDTO[];\n}\n```\n\n```text\n@Patch('/:encid/forecasts/updateAll')\nasync updateForecast(\n    @Body() patchForecastsDTO: PatchForecastsDTO,\n    @Param('encid') encid: string,\n    @Query('userId') userId: string\n): Promise<ForecastDTO[]> {\n  return await this.instanceService.updateForecasts(userId, encid, patchForecastsDTO);\n}\n```\n\n```js\n@Post()\ncreateBulk(\n  @Body(new ParseArrayPipe({ items: CreateUserDto }))\n  createUserDtos: CreateUserDto[],\n) {\n  return 'This action adds new users';\n}\n```\n\n```text\nParseArrayPipe\n```\n\n========================================\n\nComments:\n- You need to be much more specific about what is going wrong! Error Messages, behavior etc.\n- @FuzzyTemper done\n- This was helpful for me stackoverflow.com/questions/58343262/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":155,"estimatedTokens":892}}627{"id":"stack-53684654","source":"stackoverflow","questionId":53684654,"title":"Keyword import returns undefiend for bcrypt package","tags":["node.js","import","require","bcrypt","nestjs"],"text":"Title: Keyword import returns undefiend for bcrypt package\nTags: node.js, import, require, bcrypt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm writing on basic `Nestjs` starter project and when I `import` bcrypt - it returns `undefined`, but when I use `require('bcrypt')` it returns \n the bcrypt object.\n\nHow to import bcrypt via the `import` keyword?\n\nMy os is MacOS and I've installed bcrypt package v `^3.0.0`.\nMy node version is `10.14.1`;\n\n========================================\n\nTop Answer:\nImport is used in typescript, required is used in javascript. To use typescript, you have to install it \n`$ npm install typescript`\n\nYou've installed bcrypt, so you know how to install packages, the above line is just for completion\n\n========================================\n\nCode:\n```text\nNestjs\n```\n\n```text\nimport\n```\n\n```text\nundefined\n```\n\n```text\nrequire('bcrypt')\n```\n\n```text\nimport\n```\n\n```text\n^3.0.0\n```\n\n```text\n10.14.1\n```\n\n```text\nimport * as bcrypt from 'bcrypt'\n```\n\n```text\nnpm install --save-dev @types/bcrypt\n```\n\n```text\nimport {hash} from 'bcrypt';\n```\n\n```text\n$ npm install typescript\n```\n\n========================================\n\nComments:\n- nestjs has built-in typescript, all project is written on typescript\n- @Link sorry I didn't notice nestjs tag\n- `import {hash} from 'bcrypt';` works But why? That's because there is no export default i guess?","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":74,"estimatedTokens":344}}628{"id":"stack-72278667","source":"stackoverflow","questionId":72278667,"title":"How can I allow an empty string value for optional enum with NestJs?","tags":["nestjs"],"text":"Title: How can I allow an empty string value for optional enum with NestJs?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am successfully validating my dto for valid enum types:\n\n```\n// time-unit.enum.ts\n\nexport enum TimeUnit {\n SECONDS = 'SECONDS',\n MINUTES = 'MINUTES',\n HOURS = 'HOURS',\n DAYS = 'DAYS',\n}\n```\n\n```\n// create-thing.dto.ts\n\n@ApiPropertyOptional({\n description: 'The lead time unit.',\n example: 'DAYS',\n })\n @IsOptional()\n @IsEnum(TimeUnit)\n unit?: TimeUnit;\n```\n\nOn the front-end, I am providing a `` that is populated with an empty string for default value, then the corresponding enum values.\n\nIf I choose a value, everything works great! This is an optional field (a nullable column). So If I attempt to save without choosing something, I'll get a 400 error:\n\nleadTime.unit must be a valid enum value\n\nHow can I allow an empty string as a valid enum option?\n\n========================================\n\nCode:\n```text\n// time-unit.enum.ts\n\nexport enum TimeUnit {\n  SECONDS = 'SECONDS',\n  MINUTES = 'MINUTES',\n  HOURS = 'HOURS',\n  DAYS = 'DAYS',\n}\n```\n\n```text\n// create-thing.dto.ts\n\n@ApiPropertyOptional({\n    description: 'The lead time unit.',\n    example: 'DAYS',\n  })\n  @IsOptional()\n  @IsEnum(TimeUnit)\n  unit?: TimeUnit;\n```\n\n```text\n<select>\n```\n\n```js\n@ApiPropertyOptional({\n    description: 'The lead time unit.',\n    example: 'DAYS',\n  })\n  @Transform((params) => (params.value === '' ? null : params.value))\n  @IsOptional()\n  @IsEnum(TimeUnit)\n  unit?: TimeUnit;\n```\n\n========================================\n\nComments:\n- This thread has a couple of workarounds: github.com/typestack/class-validator/issues/326\n- An empty string is still a value. So, your best bet is to either don't pass the param at all or convert the empty string to null.\n- Finally getting back to this. Thank you so much for your suggestion! Based on your suggestion, I found that also checking for empty string/convert to `null` in my front-end application works well too.\n- what about if we use @Param decorator in controller without using dtos. How can we transform value to null if it is empty string?","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":86,"estimatedTokens":528}}629{"id":"stack-68544666","source":"stackoverflow","questionId":68544666,"title":"NestJS - Swagger - Show all enum values","tags":["typescript","enums","swagger","nestjs"],"text":"Title: NestJS - Swagger - Show all enum values\nTags: typescript, enums, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to see all enums value about my dto's property in the body section of swagger UI.\n\nI put this @ApiQuery decorator in my code:\n\n```\n@ApiQuery({\n name: 'name',\n enum: ENUM_NAME,\n isArray: true,\n})\n@Post()\nasync name(...):Promise {...}\n```\n\nBut this is used with @Query decorator to let the swagger's filter work. (Find in NestJS Swagger Doc).\n\nSo i did not put @Query in my code as you can see, because i want the enum's value in my dto.\n\nThis is the result\n\nBut it did not like this solution. it's a workaround.\n\nThere is a better way to achieve this result?\n\n========================================\n\nTop Answer:\nyou can try this way\n\n```\n@ApiProperty({\ndescription: \"List of all events\",\nisArray: true,\nenum: TriggerEventType,\nexample: Object.keys(TriggerEventType),\n})\n```\n\n========================================\n\nCode:\n```text\n@ApiQuery({\n  name: 'name',\n  enum: ENUM_NAME,\n  isArray: true,\n})\n@Post()\nasync name(...):Promise<...> {...}\n```\n\n```text\n// app.controller.ts\n\n@Post()\npublic async name(@Body() dto: NameDto): Promise<void> {}\n```\n\n```js\n// name.dto.ts\n\n// This is enum for demo\nenum Demo {\n    DEMO_1 = 'DEMO_1',\n    DEMO_2 = 'DEMO_2',\n}\n\nexport class NameDto {\n    @ApiProperty({\n        enum: Demo,\n        isArray: true,\n        example: [Demo.DEMO_1, Demo.DEMO_1],\n    })\n    public name: Demo[];\n}\n```\n\n```text\n// app.controller.ts\n\n@Post()\n@ApiBody({\n    schema: {\n       type: 'object',\n         properties: {\n            name: {\n              type: 'array',\n              items: {\n                 enum: [Demo.DEMO_1, Demo.DEMO_2],\n                 example: [Demo.DEMO_1, Demo.DEMO_2],\n              },\n            },\n        },\n    },\n})\npublic async name(@Body() dto: any): Promise<void> {}\n```\n\n```text\n@ApiProperty({\ndescription: \"List of all events\",\nisArray: true,\nenum: TriggerEventType,\nexample: Object.keys(TriggerEventType),\n})\n```\n\n```text\n@IsNotEmpty()\n  @ApiProperty({\n    enum: DiningAreaType,\n    enumName: 'DiningAreaType',\n  })\n  @IsArray()\n  @IsEnum(DiningAreaType, { each: true })\n  diningArea: DiningAreaType[];\n```\n\n========================================\n\nComments:\n- Why would you see your enums in the body section for the GET route ? For a GET route, the query section is used\n- @Jboucly You are right, the GET route i wrote was just an example. I asked this question for a POST route. I updated the post. Thank you.\n- The example property of the ApiPropertyOptions solved my problem. I actually improved it by changed from an array of values to Object.value(Demo), so if in the future i add some new values to enum, it will be shown in my swagger UI.\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":130,"estimatedTokens":745}}630{"id":"stack-58683457","source":"stackoverflow","questionId":58683457,"title":"How to return an image to the client using Nest.js framework?","tags":["image","file","return","nestjs"],"text":"Title: How to return an image to the client using Nest.js framework?\nTags: image, file, return, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am building an application, currently facing a problem I want to return an images which is stored in my server. I want to return image to React client, then it would be rendered in my component. But I can't figure out how to return the image itself. As far as I understand, I need to return image as JSON? But can't figure out how to do it in Nest.js framework.\n\n========================================\n\nCode:\n```js\nimport { join } from 'path';\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.use('/public', express.static(join(__dirname, '..', 'public'))); // <-\n  await app.listen(3000);\n}\n```\n\n```js\n{\n   image: `${baseUrl}/public/cat.png`\n}\n```\n\n```text\nmain.ts\n```\n\n```text\ncat.png\n```\n\n```text\nbaseURL\n```\n\n```text\nhttp://localhost:3000\n```\n\n========================================\n\nComments:\n- I did the same. That is in main.ts file I put the code `app.use(express.static(path.join(__dirname, '..', 'pictures')));` It is storing file in dist folder instead of inside src. Any idea why it is happening?\n- I got the error 'Cannot read properties of undefined (reading 'static')' at express.static","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":46,"estimatedTokens":321}}631{"id":"stack-70029204","source":"stackoverflow","questionId":70029204,"title":"How to profile a Nest.js application by using node CLI command?","tags":["node.js","intellij-idea","nestjs","profiling","webstorm"],"text":"Title: How to profile a Nest.js application by using node CLI command?\nTags: node.js, intellij-idea, nestjs, profiling, webstorm\nSource: Stack Overflow\n\nQuestion:\nI has been developing a Nest.js application for a REST API server, and I want to do some performance analysis by using Node.js profiling tools.\nI know that there are several tools like WebStorm V8 CPU and Memory Profiling (https://www.jetbrains.com/help/webstorm/v8-cpu-and-memory-profiling.html#node_profiling_before_you_start) and node CLI option `--prof`.\n\nHowever, I don't know how to start my Nest.js application by using `node` CLI program, so I don't know how to apply these profiling tools to my Nest.js application.\n\nIs there any way to use Node.js profiling tools to Nest.js application? Or is there any other good solutions for Nest.js application?\n\nThanks in advance.\n\n========================================\n\nCode:\n```text\n--prof\n```\n\n```text\nnode\n```\n\n```text\nnest build\n```\n\n```text\nnode --prof dist/main\n```\n\n```text\nnest start --watch -e 'node --prof'\n```\n\n```text\nnode --prof dist/main\n```\n\n========================================\n\nComments:\n- Ah... It was a lot easier than I thought. I was just thinking of using `nest start --watch`. Thank you :)","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":45,"estimatedTokens":308}}632{"id":"stack-70893348","source":"stackoverflow","questionId":70893348,"title":"Rollback of Prisma Interactive Transaction in NestJS not working when throwing an error","tags":["node.js","nestjs","rollback","prisma"],"text":"Title: Rollback of Prisma Interactive Transaction in NestJS not working when throwing an error\nTags: node.js, nestjs, rollback, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using the prisma ORM and NestJS and I got the following example code:\n\n```\nasync createMerchant(data: Prisma.MerchantCreateInput): Promise {\n return await this.prisma.$transaction(async (): Promise => {\n await this.prisma.merchant.create({\n data,\n });\n throw new Error(`Some error`);\n });\n}\n```\n\nI would expect that the transaction is rolled back as I have thrown an error, but it is not, it creates a new database entry.\n\nHere is the example of the official documentation.\n\nIs this maybe related to the dependency injection of NestJS and that the injected prisma service is not correctly recognizing the error? Or am I doing something wrong?\n\n========================================\n\nCode:\n```text\nasync createMerchant(data: Prisma.MerchantCreateInput): Promise<Merchant> {\n  return await this.prisma.$transaction(async (): Promise<Merchant> => {\n    await this.prisma.merchant.create({\n      data,\n    });\n    throw new Error(`Some error`);\n  });\n}\n```\n\n```text\nasync createMerchant(data: Prisma.MerchantCreateInput): Promise<Merchant> {\n  return await this.prisma.$transaction(async (prisma): Promise<Merchant> => {\n    // Not this.prisma, but prisma from argument\n    await prisma.merchant.create({\n      data,\n    });\n    throw new Error(`Some error`);\n  });\n}\n```\n\n========================================\n\nComments:\n- Can`t believe that I have not seen this! Thank you!\n- @Danila, can i call rollback method explicitly?","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":401}}633{"id":"stack-63499090","source":"stackoverflow","questionId":63499090,"title":"error node_modules/jest-diff/build/diffLines.d.ts(8,13): error TS1005: '=' expected. in nest js","tags":["node.js","typescript","npm","nestjs","watch"],"text":"Title: error node_modules/jest-diff/build/diffLines.d.ts(8,13): error TS1005: '=' expected. in nest js\nTags: node.js, typescript, npm, nestjs, watch\nSource: Stack Overflow\n\nQuestion:\nwhen i start and run the nestjs app in watch mode using `npm run start:dev` command\nthen this error show.\n\n```\nERROR in node_modules/jest-diff/build/diffLines.d.ts(8,13): error TS1005: '=' expected.\nnode_modules/jest-diff/build/diffLines.d.ts(8,34): error TS1005: ';' expected.\nnode_modules/jest-diff/build/index.d.ts(10,13): error TS1005: '=' expected.\nnode_modules/jest-diff/build/index.d.ts(10,34): error TS1005: ';' expected.\nnode_modules/jest-diff/build/index.d.ts(11,1): error TS1128: Declaration or statement expected.\nnode_modules/jest-diff/build/index.d.ts(11,13): error TS1005: ';' expected.\nnode_modules/jest-diff/build/index.d.ts(11,52): error TS1005: ';' expected.\nnode_modules/jest-diff/build/printDiffs.d.ts(8,13): error TS1005: '=' expected.\nnode_modules/jest-diff/build/printDiffs.d.ts(8,57): error TS1005: ';' expected.\n```\n\n========================================\n\nTop Answer:\nIf your typescript version is \"3.2.4\", downgrade jest-diff to version 25.5.0. This will fix the issue.\n`npm i jest-diff@25.5.0`\n\n========================================\n\nCode:\n```text\nERROR in node_modules/jest-diff/build/diffLines.d.ts(8,13): error TS1005: '=' expected.\nnode_modules/jest-diff/build/diffLines.d.ts(8,34): error TS1005: ';' expected.\nnode_modules/jest-diff/build/index.d.ts(10,13): error TS1005: '=' expected.\nnode_modules/jest-diff/build/index.d.ts(10,34): error TS1005: ';' expected.\nnode_modules/jest-diff/build/index.d.ts(11,1): error TS1128: Declaration or statement expected.\nnode_modules/jest-diff/build/index.d.ts(11,13): error TS1005: ';' expected.\nnode_modules/jest-diff/build/index.d.ts(11,52): error TS1005: ';' expected.\nnode_modules/jest-diff/build/printDiffs.d.ts(8,13): error TS1005: '=' expected.\nnode_modules/jest-diff/build/printDiffs.d.ts(8,57): error TS1005: ';' expected.\n```\n\n```text\nnpm run start:dev\n```\n\n```text\n\"typescript\": \"^3.9.7\"\n```\n\n```text\ntypescript version\n```\n\n```text\npackage.json\n```\n\n```text\nnpm i jest-diff@25.5.0\n```\n\n========================================\n\nComments:\n- my typescript is 4.1.3 : and in package.json > devDependencies > \"typescript\": \"^3.4.7\". I am still facing same issue. any suggestion?\n- 1 year later still the same issue, hopefully this gets fixed soon","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":66,"estimatedTokens":604}}634{"id":"stack-70634909","source":"stackoverflow","questionId":70634909,"title":"Mock bcrypt module module in Nest.js","tags":["javascript","node.js","unit-testing","jestjs","nestjs"],"text":"Title: Mock bcrypt module module in Nest.js\nTags: javascript, node.js, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to mock bcrypt hash method implementation, but get following error:\n\n```\nError: thrown: \"Exceeded timeout of 5000 ms for a test.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.\"\n```\n\nI've tried to increase timeout up to 30000. Also I've tried to mock entire bcrypt module like jest.mock('bcrypt').\nI'm new to testing and there are may be some logical errors or bad practises. I will be grateful if you point to them.\n\nMy code:\n\n```\nimport { UserService } from '../user.service';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { Repository } from 'typeorm';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport * as bcrypt from 'bcrypt';\n\nimport { UserEntity } from '../user.entity';\nimport { UserRepository } from '../user.repository';\nimport { CreateUserDto } from '../dto/create-user.dto';\nimport { userStub } from './stubs/user.stub';\n\ndescribe('UserService', () => {\n let userService: UserService;\n let userRepository: Repository;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(UserRepository),\n useClass: Repository,\n },\n ],\n }).compile();\n\n userService = module.get(UserService);\n userRepository = module.get>(\n getRepositoryToken(UserRepository),\n );\n });\n\n it('should define UserService', () => {\n expect(userService).toBeDefined();\n });\n\n it('should define userRepository', () => {\n expect(userRepository).toBeDefined();\n });\n\n describe('createUser method', () => {\n it('has called with valid data', async () => {\n const createUserDto: CreateUserDto = {\n email: userStub().email,\n firstName: userStub().firstName,\n lastName: userStub().lastName,\n password: userStub().password,\n };\n const user: UserEntity = userStub();\n const spiedBcryptHashMethod = jest\n .spyOn(bcrypt, 'hash')\n .mockImplementation(() => Promise.resolve(''));\n const spiedRepositoryCreateMethod = jest\n .spyOn(userRepository, 'create')\n .mockReturnValue(user);\n const spiedRepositorySaveMethod = jest\n .spyOn(userRepository, 'save')\n .mockResolvedValue(user);\n\n const createUserResult = await userService.createUser(createUserDto);\n\n expect(spiedBcryptHashMethod).toHaveBeenCalled();\n expect(spiedRepositoryCreateMethod).toHaveBeenCalled();\n expect(spiedRepositorySaveMethod).toHaveBeenCalledWith(user);\n expect(createUserResult).toEqual(user);\n });\n });\n});\n```\n\nError is appeared here:\n\n```\nconst spiedBcryptHashMethod = jest\n .spyOn(bcrypt, 'hash')\n .mockImplementation(() => Promise.resolve(''));\n```\n\nMy userService code:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport * as bcrypt from 'bcrypt';\n\nimport { UserRepository } from './user.repository';\nimport { CreateUserDto } from './dto/create-user.dto';\nimport { UserEntity } from './user.entity';\n\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(UserRepository) private userRepository: UserRepository,\n ) {}\n\n public async createUser(createUserDto: CreateUserDto): Promise {\n return await this.userRepository.save(\n this.userRepository.create({\n ...createUserDto,\n password: await new Promise((resolve, reject) => {\n bcrypt.hash(createUserDto.password, 10, (err, encrypted) => {\n if (err) {\n reject(err);\n }\n\n resolve(encrypted);\n });\n }).then((onFilled: string) => onFilled),\n }),\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\nError: thrown: \"Exceeded timeout of 5000 ms for a test.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.\"\n```\n\n```text\nimport { UserService } from '../user.service';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { Repository } from 'typeorm';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport * as bcrypt from 'bcrypt';\n\nimport { UserEntity } from '../user.entity';\nimport { UserRepository } from '../user.repository';\nimport { CreateUserDto } from '../dto/create-user.dto';\nimport { userStub } from './stubs/user.stub';\n\ndescribe('UserService', () => {\n  let userService: UserService;\n  let userRepository: Repository<UserEntity>;\n\n  beforeAll(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        UserService,\n        {\n          provide: getRepositoryToken(UserRepository),\n          useClass: Repository,\n        },\n      ],\n    }).compile();\n\n    userService = module.get<UserService>(UserService);\n    userRepository = module.get<Repository<UserEntity>>(\n      getRepositoryToken(UserRepository),\n    );\n  });\n\n  it('should define UserService', () => {\n    expect(userService).toBeDefined();\n  });\n\n  it('should define userRepository', () => {\n    expect(userRepository).toBeDefined();\n  });\n\n  describe('createUser method', () => {\n    it('has called with valid data', async () => {\n      const createUserDto: CreateUserDto = {\n        email: userStub().email,\n        firstName: userStub().firstName,\n        lastName: userStub().lastName,\n        password: userStub().password,\n      };\n      const user: UserEntity = userStub();\n      const spiedBcryptHashMethod = jest\n        .spyOn(bcrypt, 'hash')\n        .mockImplementation(() => Promise.resolve(''));\n      const spiedRepositoryCreateMethod = jest\n        .spyOn(userRepository, 'create')\n        .mockReturnValue(user);\n      const spiedRepositorySaveMethod = jest\n        .spyOn(userRepository, 'save')\n        .mockResolvedValue(user);\n\n      const createUserResult = await userService.createUser(createUserDto);\n\n      expect(spiedBcryptHashMethod).toHaveBeenCalled();\n      expect(spiedRepositoryCreateMethod).toHaveBeenCalled();\n      expect(spiedRepositorySaveMethod).toHaveBeenCalledWith(user);\n      expect(createUserResult).toEqual(user);\n    });\n  });\n});\n```\n\n```text\nconst spiedBcryptHashMethod = jest\n        .spyOn(bcrypt, 'hash')\n        .mockImplementation(() => Promise.resolve(''));\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport * as bcrypt from 'bcrypt';\n\nimport { UserRepository } from './user.repository';\nimport { CreateUserDto } from './dto/create-user.dto';\nimport { UserEntity } from './user.entity';\n\n@Injectable()\nexport class UserService {\n  constructor(\n    @InjectRepository(UserRepository) private userRepository: UserRepository,\n  ) {}\n\n  public async createUser(createUserDto: CreateUserDto): Promise<UserEntity> {\n    return await this.userRepository.save(\n      this.userRepository.create({\n        ...createUserDto,\n        password: await new Promise((resolve, reject) => {\n          bcrypt.hash(createUserDto.password, 10, (err, encrypted) => {\n            if (err) {\n              reject(err);\n            }\n\n            resolve(encrypted);\n          });\n        }).then((onFilled: string) => onFilled),\n      }),\n    );\n  }\n}\n```\n\n```js\njest.spyOn(bcrypt, 'hash').mockImplementation((pass, salt, cb) => cb(null, ''))\n```\n\n```text\nhash\n```\n\n```text\nPromise.resolve('')\n```\n\n```text\nawait bcrypt.hash(pass, salt)\n```\n\n```text\nPromise.resolve('')\n```\n\n```text\nthen((onFullfilled: string) => onFullfilled)\n```\n\n========================================\n\nComments:\n- Could you add in your service method as well?\n- @JayMcDoniel what do you mean? I'm using bycrypt.hash() in my userService. Maybe I don't understand you. Could you please clarify?\n- well, your mock implementation looks fine, so I was asking if you can show the entirety of the service method you're trying to test. Maybe something else is getting stuck, but I can't see why the bcrypt mock would be\n- @JayMcDoniel I've added my userService code. Please look.\n- Thank you. I know that async/await is better approach and it helped in this case. Don't know why I used callbacks :)","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":283,"estimatedTokens":1984}}635{"id":"stack-70065624","source":"stackoverflow","questionId":70065624,"title":"TypeORM, add condition in `where` if value is presented and not empty string","tags":["node.js","nestjs","typeorm","node.js-typeorm"],"text":"Title: TypeORM, add condition in `where` if value is presented and not empty string\nTags: node.js, nestjs, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using TypeOrm in my node.js project. I know to find a record from database I can do :\n\n```\nuserRepository.find({ where: { firstName: \"John\" } });\n```\n\nIt executes query:\n\n```\nSELECT * FROM \"user\"\nWHERE \"firstName\" = 'John'\n```\n\nBut now I need do add another filed check in \"where\" condition only if the value is presented. For example, I want to also check `company` in SQL \"where\" condition, but only if `company` value is presented.\n\nI tried following, I wonder can I do the following by giving a default empty string `''` if `company` doesn't present then pass it to `find` function's `where`?\n\n```\nconst company = params.company ? params.company : '';\n\nuserRepository.find({ where: { firstName: \"John\", company: company } });\n```\n\nBut it would still add `\"company\"=''` in the final SQL query which is not good. I wonder is there an existing function in TypeORM that could dynamically decide only add more condition in `where` if value is presented and not empty string?\n\n========================================\n\nTop Answer:\nNote that you don't get type safety when using spread operator. Instead you can conditionally set the property to undefined. Undefined properties in the where clause are excluded from the query. Nulls however are included.\n\nSo instead of:\n\n```\nuserRepository.find({\n where: {\n firstName: \"John\",\n ...(params?.company && { company: params.company }),\n }\n});\n```\n\nYou can write:\n\n```\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company ? params.company : undefined,\n }\n});\n\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company || undefined,\n }\n});\n```\n\nOr with nested properties:\n\n```\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company?.name && { name: params.company.name } || undefined,\n }\n});\n\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: { name: params?.company?.name || undefined},\n }\n});\n```\n\n========================================\n\nCode:\n```text\nuserRepository.find({ where: { firstName: \"John\" } });\n```\n\n```text\nSELECT * FROM \"user\"\nWHERE \"firstName\" = 'John'\n```\n\n```text\nconst company = params.company ? params.company : '';\n\nuserRepository.find({ where: { firstName: \"John\", company: company } });\n```\n\n```text\ncompany\n```\n\n```text\ncompany\n```\n\n```text\n''\n```\n\n```text\ncompany\n```\n\n```text\nfind\n```\n\n```text\nwhere\n```\n\n```text\n\"company\"=''\n```\n\n```text\nwhere\n```\n\n```text\nuserRepository.find({\n   where: {\n      firstName: \"John\",\n      ...(params?.company && { company: params.company }),\n   }\n});\n```\n\n```text\n...(undefined && { company: undefined })\n```\n\n```text\n...('company' && { company: 'company' })\n```\n\n```js\nconst companyTestWithValue = 'company';\nconst companyTestWithoutValue = '';\n\nconst whereWithValue = {\n  firstName: 'John',\n  ...(companyTestWithValue && { company: companyTestWithValue }),\n};\n\nconst whereWithoutValue = {\n  firstName: 'John',\n  ...(companyTestWithoutValue && { company: companyTestWithoutValue }),\n};\n\nconsole.log('whereWithValue:', whereWithValue);\nconsole.log('whereWithoutValue:', whereWithoutValue);\n```\n\n```text\nparams.company\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\n...{}\n```\n\n```text\nparams.company\n```\n\n```text\n...{company: 'company'}\n```\n\n```text\nif(params.company){\n        userRepository.find({ where: { firstName: \"John\", company: company } });\n      } else{\n        userRepository.find({ where: { firstName: \"John\" } });\n      }\n```\n\n```text\nuserRepository.find({\n   where: {\n      firstName: \"John\",\n      ...(params?.company && { company: params.company }),\n   }\n});\n```\n\n```text\nuserRepository.find({\n   where: {\n      firstName: \"John\",\n      company: params?.company ? params.company : undefined,\n   }\n});\n\nuserRepository.find({\n   where: {\n      firstName: \"John\",\n      company: params?.company || undefined,\n   }\n});\n```\n\n```text\nuserRepository.find({\n   where: {\n      firstName: \"John\",\n      company: params?.company?.name && { name: params.company.name } || undefined,\n   }\n});\n\nuserRepository.find({\n   where: {\n      firstName: \"John\",\n      company: { name: params?.company?.name || undefined},\n   }\n});\n```\n\n```text\nuserRepository.find({\n     where: getWhere([\n         {\n             field: \"firstName\",\n             searchTerm:\"John\",\n         },\n         {\n             field: \"company.name\",\n             searchTerm:\"company\",\n         }\n     ])\n });\n```\n\n========================================\n\nComments:\n- That's smart! Thanks!\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":260,"estimatedTokens":1217}}636{"id":"stack-63244163","source":"stackoverflow","questionId":63244163,"title":"NestJS Do I need DTO's along with entities?","tags":["node.js","nestjs","typeorm"],"text":"Title: NestJS Do I need DTO's along with entities?\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am creating simple service, that will do simple CRUD.\nSo far I have the **entity** user:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n username: string;\n\n @Column({ name: \"first_name\" })\n firstName: string;\n\n @Column({ name: \"last_name\" })\n lastName: string;\n\n @Column({ name: \"date_of_birth\" })\n birthDate: string;\n}\n```\n\nController:\n\n```\nimport { Controller, Get, Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @Get(':username')\n findOne(@Query('username') username: string) {\n return this.usersService.findByUsername(username);\n }\n}\n```\n\nService:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: Repository,\n ) {}\n\n findByUsername(username: string): Promise {\n return this.usersRepository.findOne({ username });\n }\n}\n```\n\nWith this basic example, I return values from the DB, where some Columns are rename: first_name --> firstName\n\nIt does serve my purpose, but on so many places, I see DTO's being used. I know I am not doing correct things, and that I should start using it as well.\nHow would I use the DTO approach with my example?\n\nI am trying to grasp the concept here.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  username: string;\n\n  @Column({ name: \"first_name\" })\n  firstName: string;\n\n  @Column({ name: \"last_name\" })\n  lastName: string;\n\n  @Column({ name: \"date_of_birth\" })\n  birthDate: string;\n}\n```\n\n```text\nimport { Controller, Get,  Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Get(':username')\n  findOne(@Query('username') username: string) {\n    return this.usersService.findByUsername(username);\n  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User)\n    private readonly usersRepository: Repository<User>,\n  ) {}\n\n\n  findByUsername(username: string): Promise<User | undefined> {\n    return this.usersRepository.findOne({ username });\n  }\n}\n```\n\n```js\nimport { IsNumber, IsString } from 'class-validator';\nimport { Exclude, Expose } from 'class-transformer';\n\n@Exclude()\nexport class UserResponseDto {\n  @Expose()\n  @IsNumber()\n  id: number;\n\n  @Expose()\n  @IsString()\n  username: string;\n\n  @Expose()\n  @IsString()\n  firstName: string;\n\n  @Expose()\n  @IsString()\n  lastName: string;\n\n  @Expose()\n  @IsString()\n  birthDate: string;\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User)\n    private readonly usersRepository: Repository<User>,\n  ) {}\n\n\n  async findByUsername(username: string): Promise<User | undefined> {\n    const retrievedUser = await this.usersRepository.findOne({ username });\n\n    // instantiate our UserResponseDto from retrievedUser\n    const userResponseDto = plainToClass(UserResponseDto, retrievedUser);\n\n    // validate our newly instantiated UserResponseDto\n    const errors = await validate(userResponseDto);\n    if (errors.length) {\n        throw new BadRequestException('Invalid user',\nthis.modelHelper.modelErrorsToReadable(errors));\n    }\n    return userResponseDto;\n  }\n}\n```\n\n```js\nimport { ClassSerializerInterceptor, Controller, Get,  Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\n@UseInterceptors(ClassSerializerInterceptor) // <== diff is here\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Get(':username')\n  findOne(@Query('username') username: string) {\n    return this.usersService.findByUsername(username);\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User)\n    private readonly usersRepository: Repository<User>,\n  ) {}\n\n\n  async findByUsername(username: string): Promise<User | undefined> {\n    return this.usersRepository.findOne({ username }); // <== must be an instance of the class, not a plain object\n  }\n}\n```\n\n```js\nimport { IsString } from 'class-validator';\nimport { Exclude, Expose } from 'class-transformer';\n\n@Exclude()\nexport class GetUserByUsernameRequestDto {\n  @Expose()\n  @IsString()\n  @IsNotEmpty()\n  username: string;\n}\n```\n\n```js\nimport { ClassSerializerInterceptor, Controller, Get,  Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\n@UseInterceptors(ClassSerializerInterceptor) // <== diff is here\n@UsePipes( // <= this is where magic happens :)\n    new ValidationPipe({\n        forbidUnknownValues: true,\n        forbidNonWhitelisted: true,\n        transform: true\n    })\n)\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Get(':username')\n  findOne(@Param('username') getUserByUsernameReqDto: GetUserByUsernameRequestDto) {  \n    return this.usersService.findByUsername(getUserByUsernameReqDto.username);\n  }\n}\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\nTypeORM\n```\n\n```text\nuser-response.dto.ts\n```\n\n```text\nUserResponseDto\n```\n\n```text\nUser\n```\n\n```text\nuser-response.dto.ts\n```\n\n```text\nUserResponseDto\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Expose()\n```\n\n```text\nUserResponseDto\n```\n\n```text\n@IsString()\n```\n\n```text\n@IsNumber()\n```\n\n```text\nUserResponseDto\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nEntity\n```\n\n```text\nusers.controller.ts\n```\n\n```text\nusers.service.ts\n```\n\n```text\nclass-transformer\n```\n\n```text\nGetUserByUsernameRequestDto\n```\n\n```text\nget-user-by-username.request.dto.ts\n```\n\n```text\nusers.controller.ts\n```\n\n```text\nValidationPipe\n```\n\n```text\nValidationPipe\n```\n\n========================================\n\nComments:\n- It's way easier than you think. Take a look at this example where you can use TypeORM + class-transformer + class-validator in only 3 lines of code -> HERE. There is also a library that can combine both into one single operation - HERE.\n- Thank you for your time and great explanation. After playing it around, I have come to the same conclusion. Since this is a only search controller, I could do it without DTO, but I need validation on the username property (from the user), and only way I could achieve it is with validation class in DTO.\n- alright, then it's the incoming DTO that needs to be validated, the returned DTO might not need to be validated, but only instantiated with the proper fields you want to expose. I'll edit my answer with the use of Pipes to validate and transform the incoming payload into a DTO\n- Wish I could upvote your answer several times. Thanks again!\n- I'm looking for a solution to have Entity - serializer and validator definition in one place without having trouble if a field is added to entity and update all dtos.","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":33,"totalLines":366,"estimatedTokens":1981}}637{"id":"stack-73867031","source":"stackoverflow","questionId":73867031,"title":"CSV File Processing with Nestjs and Papa Parse","tags":["csv","file-upload","nestjs","papaparse","file-processing"],"text":"Title: CSV File Processing with Nestjs and Papa Parse\nTags: csv, file-upload, nestjs, papaparse, file-processing\nSource: Stack Overflow\n\nQuestion:\nI am trying to process a CSV file in NestJS using Multer and Papa Parse. I do not want to store the file locally. I just want to parse CSV files to extract some information.\n\nHowever, I am unable to process it, I have tried two different ways. In the first one, I passed the file buffer to Papa.parse function. However, I get the error: **ReferenceError: FileReaderSync is not defined**\n\n```\n@Post('1')\n@UseInterceptors(\n FileInterceptor('file', {})\n)\nasync uploadFile(@UploadedFile() file: Express.Multer.File ){\n const csvData = papa.parse(file.buffer, {\n header: false,\n worker: true,\n delimiter: \",\",\n step: function (row){\n console.log(\"Row: \", row.data);\n }\n });\n}\n```\n\nSo tried calling the readFileSync() as shown below, but this time I got the error, **ERROR [ExceptionsHandler] ENAMETOOLONG: name too long, open**\n\n```\n@Post('2')\n@UseInterceptors(\n FileInterceptor('file', {})\n)\nasync uploadFile(@UploadedFile() file: Express.Multer.File ){\n const $file = readFileSync(file.buffer);\n const csvData = papa.parse($file, {\n header: false,\n worker: true,\n delimiter: \",\",\n step: function (row){\n console.log(\"Row: \", row.data);\n }\n });\n}\n```\n\nwill appreciate any help to resolve this issue.\n\n========================================\n\nTop Answer:\nAs mentioned by @Adrian Mian, you need to convert the file.buffer to stream before calling parse() from papaparse.\n\nIn addition, depending on your architecture, if you need to pass the file to another service (or micro-service), it may be useful to first convert the file buffer to base64.\n\nIn your controller:\n\n```\nimport { Controller, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common'\nimport { FileInterceptor } from '@nestjs/platform-express'\nimport { ApiBody, ApiConsumes, ApiOperation } from '@nestjs/swagger'\n\n@ApiOperation({\n summary: 'Import data by uploading a CSV file.',\n })\n@ApiConsumes('multipart/form-data')\n@ApiBody({\n schema: {\n type: 'object',\n properties: {\n file: {\n type: 'string',\n format: 'binary',\n },\n },\n },\n })\n @Post('import')\n @UseInterceptors(FileInterceptor('file'))\n importUsers(@UploadedFile() file: Express.Multer.File) {\n return this.importService.importData(file.buffer.toString('base64')\n }\n```\n\nimportService:\n\n```\nimport { Readable } from 'stream'\n\nasync importData(fileBufferInBase64: string) {\n const buffer = Buffer.from(fileBufferInBase64, 'base64')\n const dataStream = Readable.from(buffer)\n const parsedCsv = parse(dataStream, {\n header: true,\n skipEmptyLines: true,\n complete: (results) => {\n console.log('results:', results)\n },\n })\n}\n```\n\n========================================\n\nCode:\n```text\n@Post('1')\n@UseInterceptors(\n    FileInterceptor('file', {})\n)\nasync uploadFile(@UploadedFile() file: Express.Multer.File ){\n    const csvData = papa.parse(file.buffer, {\n        header: false,\n        worker: true,\n        delimiter: \",\",\n        step: function (row){\n            console.log(\"Row: \", row.data);\n        }\n      });\n}\n```\n\n```text\n@Post('2')\n@UseInterceptors(\n    FileInterceptor('file', {})\n)\nasync uploadFile(@UploadedFile() file: Express.Multer.File ){\n    const $file =   readFileSync(file.buffer);\n    const csvData = papa.parse($file, {\n        header: false,\n        worker: true,\n        delimiter: \",\",\n        step: function (row){\n            console.log(\"Row: \", row.data);\n        }\n      });\n}\n```\n\n```text\nconst { Readable } = require('stream');\n```\n\n```text\n@Post('1')\n@UseInterceptors(\n    FileInterceptor('file', {})\n)\nasync uploadFile(@UploadedFile() file: Express.Multer.File ){\n    const stream = Readable.from(file.buffer);\n    const csvData = papa.parse(stream, {\n        header: false,\n        worker: true,\n        delimiter: \",\",\n        step: function (row){\n            console.log(\"Row: \", row.data);\n        }\n      });\n}\n```\n\n```text\nimport { Controller, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common'\nimport { FileInterceptor } from '@nestjs/platform-express'\nimport { ApiBody, ApiConsumes, ApiOperation } from '@nestjs/swagger'\n\n@ApiOperation({\n    summary: 'Import data by uploading a CSV file.',\n  })\n@ApiConsumes('multipart/form-data')\n@ApiBody({\n    schema: {\n      type: 'object',\n      properties: {\n        file: {\n          type: 'string',\n          format: 'binary',\n        },\n      },\n    },\n  })\n  @Post('import')\n  @UseInterceptors(FileInterceptor('file'))\n  importUsers(@UploadedFile() file: Express.Multer.File) {\n    return this.importService.importData(file.buffer.toString('base64')\n  }\n```\n\n```text\nimport { Readable } from 'stream'\n\nasync importData(fileBufferInBase64: string) {\n  const buffer = Buffer.from(fileBufferInBase64, 'base64')\n  const dataStream = Readable.from(buffer)\n  const parsedCsv = parse(dataStream, {\n     header: true,\n     skipEmptyLines: true,\n     complete: (results) => {\n        console.log('results:', results)\n     },\n  })\n}\n```\n\n========================================\n\nComments:\n- github.com/mholt/PapaParse#papa-parse-for-node and stackoverflow.com/q/13230487","metadata":{"transformedAt":"2026-08-18T18:33:02.458Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":209,"estimatedTokens":1285}}638{"id":"stack-54732232","source":"stackoverflow","questionId":54732232,"title":"Nestjs MongoDb Schema/Interface Information Duplication","tags":["javascript","node.js","mongodb","mongoose","nestjs"],"text":"Title: Nestjs MongoDb Schema/Interface Information Duplication\nTags: javascript, node.js, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have been following the instructions for using MongoDb with Nestjs. I've got things working however it seems to me there is a rather unnecessary duplication of information (not DRY). Specifically it seems that we are required to make Db schema and also interfaces that match the schema. In my own code this looks something like this:\n\n```\nimport { Document, Schema } from 'mongoose';\n\nexport interface IBlogPost extends Document {\n subject: string;\n body: string;\n authorId: string;\n}\n\nexport const BlogPostSchema = new Schema({\n subject: String,\n body: String,\n authorId: String,\n});\n```\n\nThe rest of my code is in this repo if you want more context. The official example code is here.\n\nAm I doing something wrong or is this really required?\n\n========================================\n\nCode:\n```js\nimport { Document, Schema } from 'mongoose';\n\nexport interface IBlogPost extends Document {\n  subject: string;\n  body: string;\n  authorId: string;\n}\n\nexport const BlogPostSchema = new Schema({\n  subject: String,\n  body: String,\n  authorId: String,\n});\n```\n\n```text\nexport class Cat extends Typegoose {\n  @prop({ required: true })\n  name: string;\n}\n```\n\n========================================\n\nComments:\n- Thanks that's very helpful!","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":57,"estimatedTokens":346}}639{"id":"stack-72993711","source":"stackoverflow","questionId":72993711,"title":"Unable to import HttpModule in nest.js","tags":["nestjs"],"text":"Title: Unable to import HttpModule in nest.js\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to import the HttpModule module in nest.js, but I am unable to. I get the following error\n\n```\nsrc/app.module.ts:1:18 - error TS2724: '\"@nestjs/common\"' has no exported member named 'HttpModule'. Did you mean 'HttpCode'?\n```\n\nThis is my module.ts code\n\n```\nimport { Module, HttpModule } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n imports: [HttpModule],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nI also installed the module using\n\n```\nnpm i --save @nestjs/axios\n```\n\n========================================\n\nCode:\n```text\nsrc/app.module.ts:1:18 - error TS2724: '\"@nestjs/common\"' has no exported member named 'HttpModule'. Did you mean 'HttpCode'?\n```\n\n```text\nimport { Module, HttpModule } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n  imports: [HttpModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nnpm i --save @nestjs/axios\n```\n\n```text\nimport { HttpModule } from '@nestjs/axios'\n```\n\n========================================\n\nComments:\n- Change your import to `import { HttpModule } from '@nestjs&#47;axios'` github.com/nestjs/nest/issues/9385#issuecomment-1079452560","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":364}}640{"id":"stack-73139335","source":"stackoverflow","questionId":73139335,"title":"NestJs crash when I throw error in my service","tags":["typescript","nestjs"],"text":"Title: NestJs crash when I throw error in my service\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to throw an exception in my service and handle it in my controller to inform the front end of the error.\n\nTo achieve that, I have created a controller and a service that looks like that :\n\nGeneratorController :\n\n```\nApiTags('Generator')\n@Controller({\n path: 'api/generator',\n version: '1',\n})\nexport class GeneratorController {\n private readonly logger = new Logger(GeneratorController.name);\n constructor(private tractionUnitService: TractionUnitGeneratorService)\n \n @Get('batch/preview')\n @ApiResponse({\n status: 200,\n description: 'Sucessfuly get batch preview',\n })\n @ApiResponse({\n status: 404,\n description: 'Error your batch number is not found',\n })\n async batchPreview(@Query('batchNumber') batchNumber: number): Promise {\n try{\n return batch = this.tractionUnitService.getBatch(batchNumber);\n }catch(e){\n this.logger.error(e)\n throw e;\n }\n } \n}\n```\n\nTractionUnitGeneratorService\n\n```\n@Injectable()\nexport class TractionUnitGeneratorService {\n\n public async getBatch(batchNumber: number): Promise {\n const batchs = (await this.getBatchs()).value.filter((bat) => bat.batchNumber == batchNumber);\n if (batchs.length == 1) {\n return batchs[0];\n } else {\n throw new NotFoundException(`Batch nยฐ${batchNumber} not found`);\n }\n }\n}\n```\n\nI except the application to return a JSON with not found exception, like when it's done in controller. But I get a fatal exception instead that stop completely the NestJs server.\n\nHere is the message :\n\n```\nC:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\src\\generator\\traction-unit-generator\\traction-unit-generator.service.ts:75\n throw new NotFoundException({\n ^\nNotFoundException: Batch nยฐ1 not found\n at TractionUnitGeneratorService.getBatch (C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\src\\generator\\traction-unit-generator\\traction-unit-generator.service.ts:75:13)\n at GeneratorControlerController.batchPreview (C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\src\\controllers\\generator\\generator.controller.ts:105:32)\n at C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\nMy nest info :\n\n```\n[System Information]\nOS Version : Windows 10\nNodeJS Version : v16.15.0\nNPM Version : 8.5.5 \n\n[Nest CLI]\nNest CLI Version : 9.0.0\n\n[Nest Platform Information]\nplatform-express version : 9.0.1\nschematics version : 9.0.1\nswagger version : 6.0.1\ntesting version : 9.0.1\ncommon version : 9.0.1\naxios version : 0.1.0\ncore version : 9.0.1\ncli version : 9.0.0\n```\n\n========================================\n\nCode:\n```js\nApiTags('Generator')\n@Controller({\n  path: 'api/generator',\n  version: '1',\n})\nexport class GeneratorController {\n  private readonly logger = new Logger(GeneratorController.name);\n  constructor(private tractionUnitService: TractionUnitGeneratorService)\n  \n  @Get('batch/preview')\n  @ApiResponse({\n    status: 200,\n    description: 'Sucessfuly get batch preview',\n  })\n  @ApiResponse({\n    status: 404,\n    description: 'Error your batch number is not found',\n  })\n  async batchPreview(@Query('batchNumber') batchNumber: number): Promise<GenerationBatch> {\n    try{\n      return batch = this.tractionUnitService.getBatch(batchNumber);\n    }catch(e){\n      this.logger.error(e)\n      throw e;\n    }\n  } \n}\n```\n\n```js\n@Injectable()\nexport class TractionUnitGeneratorService {\n\n  public async getBatch(batchNumber: number): Promise<GenerationBatch> {\n    const batchs = (await this.getBatchs()).value.filter((bat) => bat.batchNumber == batchNumber);\n    if (batchs.length == 1) {\n      return batchs[0];\n    } else {\n      throw new NotFoundException(`Batch nยฐ${batchNumber} not found`);\n    }\n }\n}\n```\n\n```text\nC:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\src\\generator\\traction-unit-generator\\traction-unit-generator.service.ts:75\n      throw new NotFoundException({\n            ^\nNotFoundException: Batch nยฐ1 not found\n    at TractionUnitGeneratorService.getBatch (C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\src\\generator\\traction-unit-generator\\traction-unit-generator.service.ts:75:13)\n    at GeneratorControlerController.batchPreview (C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\src\\controllers\\generator\\generator.controller.ts:105:32)\n    at C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n    at C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n    at C:\\Users\\mrsolarius\\Documents\\Projets\\****\\back\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\n[System Information]\nOS Version     : Windows 10\nNodeJS Version : v16.15.0\nNPM Version    : 8.5.5 \n\n[Nest CLI]\nNest CLI Version : 9.0.0\n\n[Nest Platform Information]\nplatform-express version : 9.0.1\nschematics version       : 9.0.1\nswagger version          : 6.0.1\ntesting version          : 9.0.1\ncommon version           : 9.0.1\naxios version            : 0.1.0\ncore version             : 9.0.1\ncli version              : 9.0.0\n```\n\n```text\n.catch((e)=>console.error(e))\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- run `npx nest info` and the output with us, please. I don't see anything wrong that could crash the server\n- Does this actually crash the server, in that you can't send any more requests, or is this just a logged error?\n- @MicaelLevi I have update my question ^^\n- @JayMcDoniel yes when that happen I can't handle any new request cause the server is closed\n- Is the error you rethrow in your controller ever caught?\n- @WillAlexander Normally, it's caught by nestjs to send a clean API JSON response","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":195,"estimatedTokens":1519}}641{"id":"stack-55498140","source":"stackoverflow","questionId":55498140,"title":"Saving Buffer on Postgres bytea with TypeORM only store 10 bytes","tags":["node.js","postgresql","typescript","nestjs","typeorm"],"text":"Title: Saving Buffer on Postgres bytea with TypeORM only store 10 bytes\nTags: node.js, postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to save some images on a postgres db, but only 10 bytes of data are being saved.\n\nThe flow is something like this:\n\nI receive a base64 encoded string on my server, then i load that to a Buffer, set it to my entity and save it. \nBut then a try to restore that information from db and i'm getting only 10 bytes of data, verified with octet_length() on a query.\n\nMy entity attribute definition:\n\n```\n@Column({ \"name\": \"entima_imagem\", \"type\": \"bytea\", \"nullable\": false })\nentima_imagem: Buffer;\n```\n\nThe code where i receive the data and save it:\n\n```\nentity.entima_imagem = Buffer.from(base64String, \"base64\");\nconst repository = this.getRepositoryTarget(Entity);\nconst saved = await repository.save(entity);\n```\n\nOn the server, before saving, i'm writing the file on disc and i can visualize it without problem.\n\n========================================\n\nTop Answer:\nI had similar issue. It looks like typeorm has problems with 0x00 byte. It slices everything starting from first 0 byte.\n\nA similar workaround worked for me:\n\n```\n@Column({ type: \"bytea\", nullable: false })\npublic file: Buffer;\n```\n\nwhile saving:\n\n```\nlog.file = (\"\\\\x\" + file.toString( \"hex\" )) as any;\n```\n\nCreating a buffer from \"\\\\x\"+content string as @JDuwe suggested didn't work for me.\nI had to provide a string to typeorm, not Buffer.\n\n========================================\n\nCode:\n```js\n@Column({ \"name\": \"entima_imagem\", \"type\": \"bytea\", \"nullable\": false })\nentima_imagem: Buffer;\n```\n\n```js\nentity.entima_imagem = Buffer.from(base64String, \"base64\");\nconst repository = this.getRepositoryTarget(Entity);\nconst saved = await repository.save<any>(entity);\n```\n\n```js\nentity.entima_imagem = Buffer.from(\"\\\\x\" + Buffer.from(base64String, \"base64\").toString(\"hex\"));\n```\n\n```text\n@Column({ type: \"bytea\", nullable: false })\npublic file: Buffer;\n```\n\n```text\nlog.file = (\"\\\\x\" + file.toString( \"hex\" )) as any;\n```\n\n```text\n@Column({\n    name: 'imageData',\n    type: 'bytea',\n    nullable: false,\n})\nimageData: Buffer;\n```\n\n```text\nconstructor(imageDataBase64: string) {\n    if (imageDataBase64) {\n        this.imageData = Buffer.from(imageDataBase64, 'base64');\n    }\n}\n```\n\n```text\nimageData.toString('base64')\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":97,"estimatedTokens":591}}642{"id":"stack-77601527","source":"stackoverflow","questionId":77601527,"title":"Nest.js - DTO validation and transforming string to date","tags":["node.js","typescript","nestjs","class-validator","class-transformer"],"text":"Title: Nest.js - DTO validation and transforming string to date\nTags: node.js, typescript, nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'm expecting the coming request to be ISO 8601 standard timestampz, something like \"2023-12-04T15:30:00Z\" (naturally it comes as a string inside JSON, I'm trying to convert it to javascript Date)\n\nHere's my DTO class:\n\n```\nexport class CreateBookingDto implements ICreateBookingDto {\n @ApiProperty()\n @IsISO8601({ strict: true, strictSeparator: true })\n @Transform(() => Date)\n @IsNotEmpty()\n from_date: Date;\n\n @ApiProperty()\n @IsISO8601({ strict: true })\n @IsNotEmpty()\n @Type(() => Date)\n to_date: Date;\n}\n```\n\nWhen I try to send a request, I receive this Bad Request Exception message: \"from_date must be a valid ISO 8601 date string\" (same for to_date)\n\nthe request:\n\n```\n{\n \"from_date\": \"2023-12-04T15:30:00Z\",\n \"to_date\": \"2023-12-04T16:30:00Z\"\n}\n```\n\nI tried this too:\n\n```\n@Type(({ value }) => new Date(value))\nto_date: Date;\n```\n\nbut still the same issue\n\nBut when I change like this:\n\n```\nfrom_date: any;\n// to_date also\n```\n\nIt's accepting the request, I can change it to string to make it work, but I want Date.\n\nSo, my questions are:\n\n- How can I correctly transform the coming \"from_date\" and \"to_date\" to Date type?\n\n- Even when I set them to any, it accepts dates like \"2023-12-04\", I'm expecting only timestampz strictly, what is the proper way?\n\n========================================\n\nCode:\n```js\nexport class CreateBookingDto implements ICreateBookingDto {\n  @ApiProperty()\n  @IsISO8601({ strict: true, strictSeparator: true })\n  @Transform(() => Date)\n  @IsNotEmpty()\n  from_date: Date;\n\n  @ApiProperty()\n  @IsISO8601({ strict: true })\n  @IsNotEmpty()\n  @Type(() => Date)\n  to_date: Date;\n}\n```\n\n```json\n{\n    \"from_date\": \"2023-12-04T15:30:00Z\",\n    \"to_date\": \"2023-12-04T16:30:00Z\"\n}\n```\n\n```js\n@Type(({ value }) => new Date(value))\nto_date: Date;\n```\n\n```js\nfrom_date: any;\n// to_date also\n```\n\n```js\nexport class CreateBookingDto implements ICreateBookingDto {\n  @ApiProperty()\n  @IsISO8601({ strict: true, strictSeparator: true })\n  @Transform(({ value }) => {\n    const isValidDate = isISO8601(value, { strict: true, strictSeparator: true });\n    if (!isValidDate) {\n      throw new Error(`Property \"from_date\" should be a valid ISO8601 date string`);\n    }\n    return new Date(value);\n  })\n  @IsNotEmpty()\n  from_date: Date;\n\n  @ApiProperty()\n  @IsISO8601({ strict: true })\n  @IsNotEmpty()\n  @Type(() => Date)\n  to_date: Date;\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-valdiator\n```\n\n```text\n@IsISO8601()\n```\n\n```text\nDate\n```\n\n```text\n@IsDate()\n```\n\n```text\nDate\n```\n\n```text\n@Transform()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":153,"estimatedTokens":691}}643{"id":"stack-70807876","source":"stackoverflow","questionId":70807876,"title":"How to reference the app instance in a module in Nest.js","tags":["node.js","typescript","nestjs"],"text":"Title: How to reference the app instance in a module in Nest.js\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm working on a project that's using multiple Nest repos, around 4.\nEvery repo needs to implementing logging to log things like\n\n- Server lifecycle events\n\n- Uncaught errors\n\n- HTTP requests/responses\n\nIdeally, I'd like to package everything up into a module which I can publish to my company's NPM organization and just consume directly in each of my projects.\nThat way, it would take very minimal code to get logging set up in each project.\n\nOne of the things I'd like to log in my server lifecycle event is the server's url.\nI know you can get this via `app.getUrl()` in the bootstrapping phase, but it would be great to have access to the app instance in a module's lifecycle hook like so.\n\n```\n@Module({})\nexport class LoggingModule implements NestModule {\n onApplicationBootstrap() {\n console.log(`Server started on ${app.getUrl()}`)\n }\n beforeApplicationShutdown() {\n console.log('shutting down')\n }\n onApplicationShutdown() {\n console.log('successfully shut down')\n }\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(LoggingMiddleware).forRoutes('*')\n }\n}\n```\n\nIs this possible?\n\n========================================\n\nTop Answer:\nNot sure is that hacky... I'm using this to prevent the server from starting in case of pending migrations.\n\n```\n// AppModule.ts\nexport class AppModule implements NestModule {\n app: INestApplication;\n\n async configure(consumer: MiddlewareConsumer) {\n if (await this.hasPendingMigrations()) {\n setTimeout(()=> {\n this.logger.error(\"There are pending migrations!\")\n process.exitCode = 1;\n this.app.close();\n }, 1000);\n }\n //...\n }\n\n public setApp(app: INestApplication) {\n this.app = app;\n }\n\n //...\n}\n\n//main.ts\nconst app = await NestFactory.create(AppModule, {\n logger: config.cfgServer.logger,\n});\napp.get(AppModule).setApp(app);\n```\n\n========================================\n\nCode:\n```text\n@Module({})\nexport class LoggingModule implements NestModule {\n  onApplicationBootstrap() {\n    console.log(`Server started on ${app.getUrl()}`)\n  }\n  beforeApplicationShutdown() {\n    console.log('shutting down')\n  }\n  onApplicationShutdown() {\n    console.log('successfully shut down')\n  }\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(LoggingMiddleware).forRoutes('*')\n  }\n}\n```\n\n```text\napp.getUrl()\n```\n\n```text\napp.getUrl()\n```\n\n```text\nHttpAdapterHost\n```\n\n```text\nexport class AppHost {\n  app: INestApplication\n}\n```\n\n```text\n@Module({\n  providers: [AppHost]\n  exports: [AppHost]\n})\nexport class AppHostModule {}\n```\n\n```text\n// after NestFactory.create() ...\napp.select(AppHostModule).get(AppHost).app = app;\n```\n\n```text\nbootstrap()\n```\n\n```text\nAppHost\n```\n\n```text\nonModuleInit\n```\n\n```text\nonApplicationBootstrap\n```\n\n```js\n// AppModule.ts\nexport class AppModule implements NestModule {\n  app: INestApplication;\n\n  async configure(consumer: MiddlewareConsumer) {\n    if (await this.hasPendingMigrations()) {\n      setTimeout(()=> {\n        this.logger.error(\"There are pending migrations!\")\n        process.exitCode = 1;\n        this.app.close();\n      }, 1000);\n    }\n    //...\n  }\n\n  public setApp(app: INestApplication) {\n    this.app = app;\n  }\n\n  //...\n}\n\n//main.ts\nconst app = await NestFactory.create(AppModule, {\n  logger: config.cfgServer.logger,\n});\napp.get(AppModule).setApp(app);\n```\n\n========================================\n\nComments:\n- FWIW, I'm not sure why you need the `url` here, but I log as normal and my log shipping logic grabs the hostname from the machine and appends it as a label before shipping the logs. (grafana alloy). That keeps the implementation detail of where my app is running out of my app. I have a small startup script in my docker image that configures alloy (logging), including injecting the host name. If you have a similar docker set up, you could get the info from the host container and make it available to the app via an env variable or command arg. E.g., `$HOSTNAME` is already available.","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":177,"estimatedTokens":1012}}644{"id":"stack-67392575","source":"stackoverflow","questionId":67392575,"title":"How to access Response object in NestJS GraphQL resolver","tags":["node.js","typescript","graphql","nestjs","typegraphql"],"text":"Title: How to access Response object in NestJS GraphQL resolver\nTags: node.js, typescript, graphql, nestjs, typegraphql\nSource: Stack Overflow\n\nQuestion:\nHow can I access pass `@Res()` into my graphql resolvers?\n\nthis doesn't work:\n\n```\n@Mutation(() => String)\n login(@Args('loginInput') loginInput: LoginInput, @Res() res: Response) {\n return this.authService.login(loginInput, res);\n }\n```\n\n========================================\n\nCode:\n```text\n@Mutation(() => String)\n  login(@Args('loginInput') loginInput: LoginInput, @Res() res: Response) {\n    return this.authService.login(loginInput, res);\n  }\n```\n\n```text\n@Res()\n```\n\n```text\n@Res()\n```\n\n```text\nres\n```\n\n```text\ncontext\n```\n\n```text\ncontext: ({ req, res }) => ({ req, res })\n```\n\n```text\nGraphqlModule\n```\n\n```text\n@Context() ctx\n```\n\n```text\nctx.res\n```\n\n========================================\n\nComments:\n- Is there any way to implement this in a type-safe manner, without explicit type assertions that use the `as` operator?","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":62,"estimatedTokens":248}}645{"id":"stack-72104120","source":"stackoverflow","questionId":72104120,"title":"Nestjs: cannot inject ConfigService while testing","tags":["typescript","dependency-injection","jestjs","nestjs","typeorm"],"text":"Title: Nestjs: cannot inject ConfigService while testing\nTags: typescript, dependency-injection, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm having problems setting up a unit test that utilizes the `ConfigService` to set up TypeORM. The test below fails with the following message:\n\nNest can't resolve dependencies of the TypeOrmModuleOptions (?).\nPlease make sure that the argument ConfigService at index [0] is\navailable in the TypeOrmCoreModule context.\n\nI've tried adding the `ConfigService` as a provider, but with no luck. Any ideas on what I'm doing wrong?\n\n```\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { Test } from '@nestjs/testing';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\ndescribe('TypeORM setup', () => {\n beforeEach(async () => {\n await Test.createTestingModule({\n providers: [ConfigService],\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRootAsync({\n useFactory: (config: ConfigService) => ({ ...config.get('db') }),\n inject: [ConfigService],\n }),\n ],\n }).compile();\n });\n\n it('dummy', () => {\n true === true;\n });\n});\n```\n\n========================================\n\nCode:\n```text\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { Test } from '@nestjs/testing';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\ndescribe('TypeORM setup', () => {\n    beforeEach(async () => {\n        await Test.createTestingModule({\n            providers: [ConfigService],\n            imports: [\n                ConfigModule.forRoot(),\n                TypeOrmModule.forRootAsync({\n                    useFactory: (config: ConfigService) => ({ ...config.get('db') }),\n                    inject: [ConfigService],\n                }),\n            ],\n        }).compile();\n    });\n\n    it('dummy', () => {\n        true === true;\n    });\n});\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\n{ isGlobal: true }\n```\n\n```text\nConfigModule\n```\n\n```text\nimports: [ConfigModule]\n```\n\n```text\nTypeOrmModule.forRootAsync()\n```\n\n========================================\n\nComments:\n- weird enough, `imports: [ConfigModule]` was working for me to run the app but the config wasn't loaded (undefined variables) while running the e2e tests. I had to use `imports: [ConfigModule.forRoot()],` in `MongooseModule.forRootAsync` to fix the issue","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":94,"estimatedTokens":592}}646{"id":"stack-68704447","source":"stackoverflow","questionId":68704447,"title":"Nest.js pass variable from middleware to controller","tags":["typescript","express","nestjs"],"text":"Title: Nest.js pass variable from middleware to controller\nTags: typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI couldn't find a clear way of passing variables from a middleware to a constructure in Nest.js. I'm validating a JWT inside my `AuthMiddleware` and I want to make this token accessible to the controllers.\n\nBelow is just an extract of my middleware to provide a code sample. I want to make the `token` accessible inside of my Controllers.\n\n```\nimport { Request, Response, NextFunction } from 'express';\n// other imports\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n async use(req: Request, res: Response, next: NextFunction) {\n const authHeader = req.header('authorization');\n\n if (!authHeader) {\n throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);\n }\n\n const bearerToken: string[] = authHeader.split(' ');\n const token: string = bearerToken[1];\n\n res.locals.token = token;\n }\n}\n```\n\nI already tried to make the token accessible by changing the `res.locals` variable but the response object is still empty in my controller.\nThis is my controller in which I want to access the token of the middleware:\n\n```\n@Controller('did')\nexport default class DidController {\n constructor(private readonly didService: DidService) {}\n\n @Get('verify')\n async verifyDid(@Response() res): Promise {\n console.log(res)\n // {}\n return res;\n }\n```\n\n========================================\n\nTop Answer:\n```\nimport { Request, Response, NextFunction } from 'express';\n// other imports\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n async use(req: Request, res: Response, next: NextFunction) {\n const authHeader = req.header('authorization');\n\n if (!authHeader) {\n throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);\n }\n\n const bearerToken: string[] = authHeader.split(' ');\n const token: string = bearerToken[1];\n\n res.locals.token = token;\n\n next(); ====> add this to middleware\n }\n}\n```\n\nController\n\n```\nimport { Controller, Get, Response } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n constructor() {}\n\n @Get('verify')\n async verifyDid(@Response() res): Promise {\n console.log(res.locals);\n return res;\n }\n}\n```\n\n**Applying Middleware**\n\n```\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(AuthMiddleware).forRoutes('*');\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { Request, Response, NextFunction } from 'express';\n// other imports\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n  async use(req: Request, res: Response, next: NextFunction) {\n    const authHeader = req.header('authorization');\n\n    if (!authHeader) {\n      throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);\n    }\n\n    const bearerToken: string[] = authHeader.split(' ');\n    const token: string = bearerToken[1];\n\n    res.locals.token = token;\n  }\n}\n```\n\n```js\n@Controller('did')\nexport default class DidController {\n  constructor(private readonly didService: DidService) {}\n\n  @Get('verify')\n  async verifyDid(@Response() res): Promise<string> {\n    console.log(res)\n    // {}\n    return res;\n  }\n```\n\n```text\nAuthMiddleware\n```\n\n```text\ntoken\n```\n\n```text\nres.locals\n```\n\n```text\nimport { Request, Response, NextFunction } from 'express';\n// other imports\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n  async use(req /*: Request */, res: Response, next: NextFunction) {\n    const authHeader = req.header('authorization');\n\n    if (!authHeader) {\n      throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);\n    }\n\n    const bearerToken: string[] = authHeader.split(' ');\n    const token: string = bearerToken[1];\n\n    req.token  = token; // request type is commented out otherwise typescript won't allow setting this\n\n    next();\n  }\n}\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const TOKEN = createParamDecorator(\n  (_data: unknown, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return request.token; // extract token from request\n  },\n);\n```\n\n```text\nimport { Controller, Get, Response } from '@nestjs/common';\nimport { TOKEN } from './token.decorator';\n\n@Controller()\nexport class AppController {\n  constructor() {}\n\n\n  @Get('verify')\n  async verifyDid(@TOKEN() token): Promise<string> {\n    console.log(token);\n    return 'whateverYouWant';\n  }\n}\n```\n\n```text\nRequest/Response\n```\n\n```text\nimport { Request, Response, NextFunction } from 'express';\n// other imports\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n  async use(req: Request, res: Response, next: NextFunction) {\n    const authHeader = req.header('authorization');\n\n    if (!authHeader) {\n      throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);\n    }\n\n    const bearerToken: string[] = authHeader.split(' ');\n    const token: string = bearerToken[1];\n\n    res.locals.token  = token;\n\n    next();  ====> add this to middleware\n  }\n}\n```\n\n```text\nimport { Controller, Get, Response } from '@nestjs/common';\n\n\n@Controller()\nexport class AppController {\n  constructor() {}\n\n\n  @Get('verify')\n  async verifyDid(@Response() res): Promise<string> {\n    console.log(res.locals);\n    return res;\n  }\n}\n```\n\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(AuthMiddleware).forRoutes('*');\n  }\n}\n```\n\n========================================\n\nComments:\n- did you try to attach in `req` instead of `res`?\n- Tried to attach it to the body but didn't work\n- I also can't attach it to just the `req` object because the type `Request` from express doesn't has that key.\n- you can but you'll have to write your own interface/type extending the `Request` type. btw I just tested `req.locals = 123` and it worked as expected. Make sure your middleware is running before the `verifyDid` method\n- yea worked when just defining req as any\n- I still prefer to attach the token to the `req.locals` and not to the body because in some requests I work with the whole body and the token inside the body would change the object from the request\n- @JonasLevin i tested with locals and added updated code","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":261,"estimatedTokens":1572}}647{"id":"stack-59681572","source":"stackoverflow","questionId":59681572,"title":"How to inject a request scoped provider at NestJS controller?","tags":["node.js","typescript","nestjs"],"text":"Title: How to inject a request scoped provider at NestJS controller?\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a request scoped injectable for logging.\n\nf.e.\n\n```\nimport { Injectable, Scope } from '@nestjs/common';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class RequestLogger {\n public log(message: string) {\n console.log(message);\n }\n}\n```\n\n(disregard for a moment that it doesn't use a constructor with the request yet; that's beside the point)\n\nAnd I also have a controller with some singleton injections.\n\nI'd like to inject the request injectable in a way that will allow the controller to be initiated just once. Injecting it at the constructor will make the controller be recreated on each request, so surely that's not the way (is it?).\n\nI tried to place it in the method signature, but that doesn't seem to do anything.\n\ne.g.\n\n```\n@Controller('register')\nexport class RegisterApiController {\n public constructor(\n private readonly registerService: RegisterService,\n ) {\n console.log('Controller initiated');\n }\n\n @Post()\n public async postIndex(\n @Inject(RequestLogger) logger: RequestLogger,\n ): Promise {\n console.log('request made');\n logger.log('Logger message to log');\n\n return this.registerService.register();\n }\n}\n```\n\nafter application bootstrap (that also includes \"Controller initiated\"), each request terminates with error 500, and in the console\n\n```\nRequest made\n[TypeError] Cannot read property 'log' of undefined\n```\n\nIs there a way to inject a request scoped injectable without forcing a recreation of the controller that uses it? What is it?\n\nIf there isn't another way, is there at least a way to move initial controller logic somewhere else, so that what needs to be done once on first controller init can be done there?\n\n========================================\n\nTop Answer:\nThis is possible with the library I've created recently, which it's free from bubbles up injection chain and performance issues:\n\nhttps://github.com/kugacz/nj-request-scope\n\nAfter register `RequestScopeModule` in your module class:\n\n```\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\n imports: [RequestScopeModule],\n})\n```\n\nyour example request-scope `RequestLogger` class would look like this:\n\n```\nimport { Injectable, Scope } from '@nestjs/common';\nimport { RequestScope } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestLogger {\n public log(message: string) {\n console.log(message);\n }\n}\n```\n\nand in your example controller, add the class field `logger`.\n\nThe `logger` field will be a new `RequestLogger` instance created for every request without recreating a new instance of RegisterApiController.\n\n```\n@Controller('register')\nexport class RegisterApiController {\n public constructor(\n private readonly registerService: RegisterService,\n private readonly logger: RequestLogger,\n ) {\n console.log('Controller initiated');\n }\n\n @Post()\n public async postIndex(): Promise {\n console.log('request made');\n logger.log('Logger message to log');\n\n return this.registerService.register();\n }\n}\n```\n\nAnother example you can find here: https://github.com/kugacz/nj-request-scope-example/tree/main/src/request.scope\n\n========================================\n\nCode:\n```js\nimport { Injectable, Scope } from '@nestjs/common';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class RequestLogger {\n  public log(message: string) {\n    console.log(message);\n  }\n}\n```\n\n```js\n@Controller('register')\nexport class RegisterApiController {\n  public constructor(\n    private readonly registerService: RegisterService,\n  ) {\n    console.log('Controller initiated');\n  }\n\n  @Post()\n  public async postIndex(\n    @Inject(RequestLogger) logger: RequestLogger,\n  ): Promise<unknown> {\n    console.log('request made');\n    logger.log('Logger message to log');\n\n    return this.registerService.register();\n  }\n}\n```\n\n```sh\nRequest made\n[TypeError] Cannot read property 'log' of undefined\n```\n\n```text\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\n    imports: [RequestScopeModule],\n})\n```\n\n```text\nimport { Injectable, Scope } from '@nestjs/common';\nimport { RequestScope } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestLogger {\n  public log(message: string) {\n    console.log(message);\n  }\n}\n```\n\n```text\n@Controller('register')\nexport class RegisterApiController {\n  public constructor(\n    private readonly registerService: RegisterService,\n    private readonly logger: RequestLogger,\n  ) {\n    console.log('Controller initiated');\n  }\n\n  @Post()\n  public async postIndex(): Promise<unknown> {\n    console.log('request made');\n    logger.log('Logger message to log');\n\n    return this.registerService.register();\n  }\n}\n```\n\n```text\nRequestScopeModule\n```\n\n```text\nRequestLogger\n```\n\n```text\nlogger\n```\n\n```text\nlogger\n```\n\n```text\nRequestLogger\n```\n\n========================================\n\nComments:\n- I ended up doing a custom decorator, combined with an interceptor. The interceptor puts the new logger in the request (unconditionally, because I want to log every request anyway), and the decorator gets it from the request (enabling additional logs within the controller handler).\n- This sounds buggy or at the very least, too hacky. I would expect any class (including controllers) in a DI framework to be constructed every time one of its injected values changes (which should be never). At the same time, I would not expect a class to be recreated just for a method call inside the class. Request specific injections to an otherwise server wide controller should be passed into the method arguments somehow IMO.\n- This solution is similar to the Java Spring DI request scope mechanism, which I wouldn't consider buggy or hacky. Spring also uses a Proxy Pattern for request scope injections. Request scope DI usage in my library, NestJS and Java Spring is almost the same and I would call it the expected industry standard. The final behavior (request scope) is exactly the same, but my library is more performant than the original NestJS solution.\n- I didn't look into the code too much, but if it indeed uses Spring Proxy approach, this is a recommended way of doing it, no questions asked. NestJS really made me sad. I hoped it's a wannabe Spring for JS. But it goes against some of the best features of Spring such as: Injectables are not really proxied, so you can't put a cache, or validation rules at it. All it has is an interceptor layer at the level of REST Controllers. And we all know, Controllers are just ports, not the actual API, Services are THE API","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":228,"estimatedTokens":1648}}648{"id":"stack-61076769","source":"stackoverflow","questionId":61076769,"title":"NestJS minimize dockerfile","tags":["docker","dockerfile","nestjs"],"text":"Title: NestJS minimize dockerfile\nTags: docker, dockerfile, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to dockerize my nestjs api. With the config listed below, the image gets 319MB big. What would be a more simple way to reduce the image size, than multi staging?\n\nDockerfile\n\n```\nFROM node:12.13-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCMD npm start\n```\n\n.dockerignore\n\n```\n.git\n.gitignore\nnode_modules/\ndist/\n```\n\n========================================\n\nCode:\n```text\nFROM node:12.13-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCMD npm start\n```\n\n```text\n.git\n.gitignore\nnode_modules/\ndist/\n```\n\n```text\nFROM node:12.14.1-alpine AS build\n\n\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY . ./\n\nRUN npm run build && npm prune --production\n\n\nFROM node:12.14.1-alpine\n\nWORKDIR /app\nENV NODE_ENV=production\n\nCOPY --from=build /app/dist /app/dist\nCOPY --from=build /app/node_modules /app/node_modules\n\nEXPOSE 3000\nENTRYPOINT [ \"node\" ]\nCMD [ \"dist/main.js\" ]\n```\n\n========================================\n\nComments:\n- maybe it makes sense to change the order of COPY --from=build /app/dist /app/dist COPY --from=build /app/node_modules /app/node_modules to COPY --from=build /app/node_modules /app.node_modules COPY --from=build /app/dist /app/dist so the least changed node_modules go first and docker cache is used more and build is more efficient?","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":73,"estimatedTokens":348}}649{"id":"stack-60997683","source":"stackoverflow","questionId":60997683,"title":"Error Cannot find module , testing Nestjs Services","tags":["node.js","nestjs"],"text":"Title: Error Cannot find module , testing Nestjs Services\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm having a hard time with testing services on Nestjs, i believe is something related to my lack of knowledge on how the dependency injection works for tests, weird thing is only getting errors on the test. I have 3 modules Teste, Teste2, Teste3, Teste2 imports Teste3 service, and Teste imports Teste2 service. I tried exporting Teste2 and Teste3, and importing their modules, works fine when i run npm start. Doesnt work on the test thought...\n\nTeste\n\n```\n@Module({\n imports: [],\n providers: [ TesteService,Teste2Service],\n exports: [TesteService],\n controllers: [TesteController]\n })\n export class TesteModule {}\n@Injectable()\nexport class TesteService {\nconstructor(private teste2Service: Teste2Service){}\n\n teste(){\n return this.teste2Service.hello();\n }\n}\n```\n\nTeste2\n\n```\n@Module({\n imports: [Teste3Module],\n providers: [Teste2Service],\n exports: [Teste2Service]\n})\nexport class Teste2Module {}\n@Injectable()\nexport class Teste2Service {\n constructor(private teste3Service: Teste3Service){}\n hello(){\n return this.teste3Service.hello();\n }\n}\n```\n\nTeste3\n\n```\n@Module({\n providers: [Teste3Service],\n exports: [Teste3Service]\n})\nexport class Teste3Module {}\n\n@Injectable()\nexport class Teste3Service {\n\n hello(){\n return 'Hello World';\n }\n}\n```\n\nthe actual test\n\n```\ndescribe('TesteService', () => {\n let service: TesteService;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports:[Teste2Module],\n providers: [TesteService],\n }).compile();\n\n service = module.get(TesteService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n});\n```\n\nThe error \nsrc/teste/teste.service.spec.ts\n\n```\nCannot find module 'src/teste2/teste2.service' from 'teste.service.ts'\n```\n\n========================================\n\nCode:\n```text\n@Module({\n    imports: [],\n    providers: [ TesteService,Teste2Service],\n    exports: [TesteService],\n    controllers: [TesteController]\n  })\n  export class TesteModule {}\n@Injectable()\nexport class TesteService {\nconstructor(private teste2Service: Teste2Service){}\n\n    teste(){\n        return this.teste2Service.hello();\n    }\n}\n```\n\n```text\n@Module({\n  imports: [Teste3Module],\n  providers: [Teste2Service],\n  exports: [Teste2Service]\n})\nexport class Teste2Module {}\n@Injectable()\nexport class Teste2Service {\n    constructor(private teste3Service: Teste3Service){}\n    hello(){\n        return this.teste3Service.hello();\n    }\n}\n```\n\n```text\n@Module({\n  providers: [Teste3Service],\n  exports: [Teste3Service]\n})\nexport class Teste3Module {}\n\n@Injectable()\nexport class Teste3Service {\n\n    hello(){\n        return 'Hello World';\n    }\n}\n```\n\n```text\ndescribe('TesteService', () => {\n  let service: TesteService;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports:[Teste2Module],\n      providers: [TesteService],\n    }).compile();\n\n    service = module.get<TesteService>(TesteService);\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n});\n```\n\n```text\nCannot find module 'src/teste2/teste2.service' from 'teste.service.ts'\n```\n\n========================================\n\nComments:\n- Is there a way of reusing the nest alias? This fixed my e2e test, but still failing while importing the AppModule, which depends on a `@shared` lib\n- You can config the paths in tsconfig file -> compilerOptions. Something like that: \"paths\": { \"@apis/*\": [\"src/apis/*\"] }","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":172,"estimatedTokens":890}}650{"id":"stack-57820514","source":"stackoverflow","questionId":57820514,"title":"How to return a custom response from the class-validator in NestJS","tags":["javascript","typescript","nestjs","class-validator"],"text":"Title: How to return a custom response from the class-validator in NestJS\nTags: javascript, typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nIs it possible to return a custom error response from class-validator inside of NestJs.\n\nNestJS currently returns an error message like this:\n\n```\n{\n \"statusCode\": 400,\n \"error\": \"Bad Request\",\n \"message\": [\n {\n \"target\": {},\n \"property\": \"username\",\n \"children\": [],\n \"constraints\": {\n \"maxLength\": \"username must be shorter than or equal to 20 characters\",\n \"minLength\": \"username must be longer than or equal to 4 characters\",\n \"isString\": \"username must be a string\"\n }\n },\n ]\n}\n```\n\nHowever the service that consumes my API needs something more akin to:\n\n```\n{\n \"status\": 400,\n \"message\": \"Bad Request\",\n \"success\": false,\n \"meta\": {\n \"details\": {\n \"maxLength\": \"username must be shorter than or equal to 20 characters\",\n \"minLength\": \"username must be longer than or equal to 4 characters\",\n \"isString\": \"username must be a string\"\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nWhen you define `ValidationPipe` you can provide `exceptionFactory`.\n\n```\nnew ValidationPipe({\n exceptionFactory: (errors) => new HttpException({ error: \"BAD_REQUEST\" }, 400)\n})\n```\n\nThe first argument type is string, but you can provide object.\nAccording to the NestJS documentation:\n\n`To override just the message portion of the JSON response body, supply a string in the response argument. To override the entire JSON response body, pass an object in the response argument. Nest will serialize the object and return it as the JSON response body.`\n\n========================================\n\nCode:\n```text\n{\n    \"statusCode\": 400,\n    \"error\": \"Bad Request\",\n    \"message\": [\n        {\n            \"target\": {},\n            \"property\": \"username\",\n            \"children\": [],\n            \"constraints\": {\n                \"maxLength\": \"username must be shorter than or equal to 20 characters\",\n                \"minLength\": \"username must be longer than or equal to 4 characters\",\n                \"isString\": \"username must be a string\"\n            }\n        },\n    ]\n}\n```\n\n```text\n{\n    \"status\": 400,\n    \"message\": \"Bad Request\",\n    \"success\": false,\n    \"meta\": {\n        \"details\": {\n            \"maxLength\": \"username must be shorter than or equal to 20 characters\",\n            \"minLength\": \"username must be longer than or equal to 4 characters\",\n            \"isString\": \"username must be a string\"\n        }\n    }\n}\n```\n\n```text\nimport { ExceptionFilter, Catch, ArgumentsHost, BadRequestException } from '@nestjs/common';\nimport { Request, Response } from 'express';\n\n@Catch(BadRequestException)\nexport class BadRequestExceptionFilter implements ExceptionFilter {\n  catch(exception: BadRequestException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n    const status = exception.getStatus();\n\n    response\n      .status(status)\n      // you can manipulate the response here\n      .json({\n        statusCode: status,\n        timestamp: new Date().toISOString(),\n        path: request.url,\n      });\n  }\n}\n```\n\n```text\nnew ValidationPipe({\n      exceptionFactory: (errors) =>  new HttpException({ error: \"BAD_REQUEST\" }, 400)\n})\n```\n\n```text\nValidationPipe\n```\n\n```text\nexceptionFactory\n```\n\n```text\nTo override just the message portion of the JSON response body, supply a string in the response argument. To override the entire JSON response body, pass an object in the response argument. Nest will serialize the object and return it as the JSON response body.\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":139,"estimatedTokens":913}}651{"id":"stack-63978181","source":"stackoverflow","questionId":63978181,"title":"NestJS Middleware Not Executed","tags":["javascript","node.js","typescript","nestjs","fastify"],"text":"Title: NestJS Middleware Not Executed\nTags: javascript, node.js, typescript, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nThe NestJS class or functional middleware doesn't run when connected from a Module. It is also not working for a single path, controller or for every path. Connecting functional middleware from main.ts works fine. \n\n```\n//main.ts\nimport { ValidationPipe } from '@nestjs/common'\nimport { NestFactory } from '@nestjs/core'\nimport { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'\nimport { AppModule } from './app.module'\n\ndeclare const module: any\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule, new FastifyAdapter())\n\n app.useGlobalPipes(new ValidationPipe())\n\n await app.listen(2100)\n\n if (module.hot) {\n module.hot.accept()\n module.hot.dispose(() => app.close())\n }\n}\nbootstrap()\n```\n\n```\n//app.module.ts\nimport { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'\nimport { AuthMiddleware } from './middleware/auth.middleware'\nimport { UserModule } from './user/user.module'\n\n@Module({\n imports: [UserModule],\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(AuthMiddleware)\n .forRoutes('(.*)')\n }\n}\n```\n\n```\n//auth.middleware.ts\nimport { Injectable, NestMiddleware } from '@nestjs/common'\nimport { FastifyRequest, FastifyReply } from 'fastify'\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n use(req: FastifyRequest, res: FastifyReply, next: () => void) {\n console.log('test auth middleware')\n next()\n }\n}\n```\n\nExpected output: test auth middleware \n\nActual: nothing\n\n========================================\n\nTop Answer:\nWhat worked for me is:\nI defined the route earlier like below with a `/` at the end of the route.\n\n```\n@Controller('v1/partnerPortal/')\nexport class SubscriptionController {\n constructor()\n}\n```\n\nI remove the slash and it is now working for me\n\n```\n@Controller('v1/partnerPortal')\nexport class SubscriptionController {\n constructor()\n}\n```\n\nMy module code:\n\n```\nexport class SubscriptionModule {\n configure(consumer: MiddlewareConsumer): void {\n consumer.apply(KeyAuthMiddlewareService).forRoutes(SubscriptionController);\n }\n}\n```\n\nHope this helps\n\n========================================\n\nCode:\n```text\n//main.ts\nimport { ValidationPipe } from '@nestjs/common'\nimport { NestFactory } from '@nestjs/core'\nimport { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'\nimport { AppModule } from './app.module'\n\ndeclare const module: any\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter())\n\n  app.useGlobalPipes(new ValidationPipe())\n\n  await app.listen(2100)\n\n  if (module.hot) {\n    module.hot.accept()\n    module.hot.dispose(() => app.close())\n  }\n}\nbootstrap()\n```\n\n```text\n//app.module.ts\nimport { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'\nimport { AuthMiddleware } from './middleware/auth.middleware'\nimport { UserModule } from './user/user.module'\n\n@Module({\n  imports: [UserModule],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(AuthMiddleware)\n      .forRoutes('(.*)')\n  }\n}\n```\n\n```text\n//auth.middleware.ts\nimport { Injectable, NestMiddleware } from '@nestjs/common'\nimport { FastifyRequest, FastifyReply } from 'fastify'\n\n@Injectable()\nexport class AuthMiddleware implements NestMiddleware {\n  use(req: FastifyRequest, res: FastifyReply, next: () => void) {\n    console.log('test auth middleware')\n    next()\n  }\n}\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm run start:dev\n```\n\n```text\n/dist\n```\n\n```text\nforRoutes({path: '*', method: RequestMethod.ALL })\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\napp.use(functionalMiddleware);\n```\n\n```text\nconst createAppE2e = async (): Promise<INestApplication> => {\n   const moduleRef = await Test.createTestingModule({\n     imports: [AppModule],\n   });\n   const app = moduleRef.createNestApplication();\n   app.use(functionalMiddleware);\n   await app.init();\n   return app;\n}\n```\n\n```text\nexport class PartnerModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(ModuleSpecificMiddleware);\n  }\n}\n```\n\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(AuthMiddleware);\n    consumer.apply(ModuleSpecificMiddleware).forRoutes(PartnerController); // This was the solution\n  }\n}\n```\n\n```text\n@Controller('v1/partnerPortal/')\nexport class SubscriptionController {\n  constructor()\n}\n```\n\n```text\n@Controller('v1/partnerPortal')\nexport class SubscriptionController {\n  constructor()\n}\n```\n\n```text\nexport class SubscriptionModule {\n  configure(consumer: MiddlewareConsumer): void {\n    consumer.apply(KeyAuthMiddlewareService).forRoutes(SubscriptionController);\n  }\n}\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- I agree, had the same problem and after that, it works.\n- I found that ensuring you install the same fastify version as what @nestjs/platform-fastify uses also fixes the problem.\n- Your are right, it's working for me with same solution, Thanks you\n- Not sure i've understand what should my package.json looks like? just @nestjs/platform-fastify\n- @BallonUra If you have installed both packages @nestjs/platform-fastify and fastify, then uninstall both with \"npm uninstall\" and then install just @nestjs/platform-fastify\n- Thanks! adding a slash at end of the route / path worked","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":246,"estimatedTokens":1398}}652{"id":"stack-55570009","source":"stackoverflow","questionId":55570009,"title":"I'm using a passport-jwt auth strategy in my nestJS app (with authGuard), how to get access to the token payload in my controller?","tags":["node.js","typescript","jwt","nestjs","passport-jwt"],"text":"Title: I'm using a passport-jwt auth strategy in my nestJS app (with authGuard), how to get access to the token payload in my controller?\nTags: node.js, typescript, jwt, nestjs, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get access to the jwt payload in a route that is protected by an `AuthGuard`.\n\nI'm using `passport-jwt` and the token payload is the email of the user.\n\nI could achieve this by runing the code bellow: \n\n```\nimport {\n Controller,\n Headers,\n Post,\n UseGuards,\n} from '@nestjs/common';\nimport { JwtService } from '@nestjs/jwt';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Post()\n@UseGuards(AuthGuard())\nasync create(@Headers() headers: any) {\n Logger.log(this.jwtService.decode(headers.authorization.split(' ')[1]));\n}\n```\n\nI want to know if there's a better way to do it?\n\n========================================\n\nCode:\n```text\nimport {\n    Controller,\n    Headers,\n    Post,\n    UseGuards,\n} from '@nestjs/common';\nimport { JwtService } from '@nestjs/jwt';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Post()\n@UseGuards(AuthGuard())\nasync create(@Headers() headers: any) {\n    Logger.log(this.jwtService.decode(headers.authorization.split(' ')[1]));\n}\n```\n\n```text\nAuthGuard\n```\n\n```text\npassport-jwt\n```\n\n```text\nasync validate(payload: JwtPayload) {\n  // You can fetch additional information if needed \n  const user = await this.userService.findUser(payload);\n  if (!user) {\n    throw new UnauthorizedException();\n  }\n  return {user, email: payload.email};\n}\n```\n\n```text\n@Post()\n@UseGuards(AuthGuard())\nasync create(@Req() request) {\n    Logger.log(req.user.email);\n}\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const User = createParamDecorator((data, req) => {\n  return req.user;\n});\n```\n\n```text\nJwtStrategy\n```\n\n```text\nvalidate\n```\n\n```text\nJwtPayload\n```\n\n```text\nuser\n```\n\n```text\n@User\n```\n\n```text\n@Req\n```\n\n========================================\n\nComments:\n- Side note: better create an instance of `Logger` than using it statically. See this answer: stackoverflow.com/a/52907695/4694994\n- I don't think you need to call `validateUser(payload)` in your `validate` function. your payload is already valid by this point, and decoded by `Passport`. You should simply return the new object `return {user, email: payload.email};`\n- It ist just as in the docs: \"A \"verify callback\", which is where you tell Passport how to interact with your user store (where you manage user accounts). Here, you verify whether a user exists (and/or create a new user), and whether their credentials are valid. The Passport library expects this callback to return a full user if the validation succeeds, or a null if it fails (failure is defined as either the user is not found, or, in the case of passport-local, the password does not match).\" docs.nestjs.com/techniques/authentication\n- For the other strategies, yes, but for JWT its not necessary because your token was signed and verified. See the later section of that documentation on why you don't have to validate the user here once again.\n- Yes, this is right, you do not need to validate the token itself again. However, you might want to use the hook to fetch additional data to attach it to the request. Or if you have a long-lived token, (which may not be recommended for most cases), you might want to check if the user still exists, was blacklisted etc. I've edited the answer to include your point.\n- The parameter decorator should be implemented using execution context: `import { createParamDecorator, ExecutionContext } from '@nestjs&#47;common'; export const User = createParamDecorator( (data: any, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); return request.user; }, )`","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":118,"estimatedTokens":936}}653{"id":"stack-63618612","source":"stackoverflow","questionId":63618612,"title":"NestJS - Use service inside Interceptor (not global interceptor)","tags":["nestjs","nestjs-jwt"],"text":"Title: NestJS - Use service inside Interceptor (not global interceptor)\nTags: nestjs, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI have a controller that uses custom interceptor:\n\nController:\n\n```\n@UseInterceptors(SignInterceptor)\n @Get('users')\n async findOne(@Query() getUserDto: GetUser) {\n return await this.userService.findByUsername(getUserDto.username)\n }\n```\n\nI have also I SignService, which is wrapper around NestJwt:\n\nSignService module:\n\n```\n@Module({\n imports: [\n JwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n privateKey: configService.get('PRIVATE_KEY'),\n publicKey: configService.get('PUBLIC_KEY'),\n signOptions: {\n expiresIn: configService.get('JWT_EXP_TIME_IN_SECONDS'),\n algorithm: 'RS256',\n },\n }),\n inject: [ConfigService],\n }),\n ],\n providers: [SignService],\n exports: [SignService],\n})\nexport class SignModule {}\n```\n\nAnd Finally SignInterceptor:\n\n```\n@Injectable()\nexport class SignInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n return next.handle().pipe(map(data => this.sign(data)))\n }\n\n sign(data) {\n const signed = {\n ...data,\n _signed: 'signedContent',\n }\n\n return signed\n }\n}\n```\n\nSignService works properly and I use it. I would like to use this as an interceptor\nHow can I inject SignService in to SignInterceptor, so I can use the functions it provides?\n\n========================================\n\nCode:\n```js\n@UseInterceptors(SignInterceptor)\n    @Get('users')\n    async findOne(@Query() getUserDto: GetUser) {\n        return await this.userService.findByUsername(getUserDto.username)\n    }\n```\n\n```js\n@Module({\n    imports: [\n        JwtModule.registerAsync({\n            imports: [ConfigModule],\n            useFactory: async (configService: ConfigService) => ({\n                privateKey: configService.get('PRIVATE_KEY'),\n                publicKey: configService.get('PUBLIC_KEY'),\n                signOptions: {\n                    expiresIn: configService.get('JWT_EXP_TIME_IN_SECONDS'),\n                    algorithm: 'RS256',\n                },\n            }),\n            inject: [ConfigService],\n        }),\n    ],\n    providers: [SignService],\n    exports: [SignService],\n})\nexport class SignModule {}\n```\n\n```js\n@Injectable()\nexport class SignInterceptor implements NestInterceptor {\n    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n        return next.handle().pipe(map(data => this.sign(data)))\n    }\n\n    sign(data) {\n        const signed = {\n            ...data,\n            _signed: 'signedContent',\n        }\n\n        return signed\n    }\n}\n```\n\n```text\n@Module({\n  imports: [SignModule], // Import the SignModule into the ApiModule.\n  controllers: [UsersController],\n  providers: [SignInterceptor],\n})\nexport class ApiModule {}\n```\n\n```text\n@Injectable()\nexport class SignInterceptor implements NestInterceptor {\n  constructor(private signService: SignService) {}\n\n  //...\n}\n```\n\n```text\nSignInterceptor\n```\n\n```text\nApiModule\n```\n\n```text\nSignService\n```\n\n```text\nSignInterceptor\n```\n\n```text\n@UseInterceptors(SignInterceptor)\n```\n\n```text\nSignInterceptor\n```\n\n========================================\n\nComments:\n- Moments after I posted the question I did the same thing. In any case thanks. Answer accepted","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":163,"estimatedTokens":831}}654{"id":"stack-70682220","source":"stackoverflow","questionId":70682220,"title":"TypeORM SUM Operator on Relation's field","tags":["mysql","nestjs","typeorm"],"text":"Title: TypeORM SUM Operator on Relation's field\nTags: mysql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am a student trying to develop a music library just to try out new technologies.\n\nCurrently I use NestJS together with TypeORM as my backend technologies (as well as a MySQL database).\n\nWhat am I trying to achieve? I want to get the total duration of a playlist. So a playlist consists of many songs and songs can appear in multiple playlists. So we have a many-to-many relationship at this point.\nNow for getting the totalDuration I thought using some kind of SUM operator is a great idea. Exactly here is my problem: How would I do that using TypeORM?\n\nI tried following querybuilder:\n\n```\nconst playlist = await this.playlistRepository.createQueryBuilder(\"playlist\")\n .where(\"playlist.id = :playlistId\", { playlistId })\n\n // This is for relations\n .leftJoinAndSelect(\"playlist.author\", \"author\")\n .leftJoinAndSelect(\"playlist.artwork\", \"artwork\")\n .leftJoinAndSelect(\"playlist.collaborators\", \"collaborators\")\n .leftJoin(\"playlist.songs\", \"songs\")\n\n // Counting the songs\n .loadRelationCountAndMap(\"playlist.songsCount\", \"playlist.songs\")\n\n // SUM up the duration of every song to get total duration of the playlist\n .addSelect('SUM(songs.duration)', 'totalDuration')\n .groupBy(\"playlist.id\")\n .getOne()\n```\n\nBut that gave me an error I don't know how to solve:\n\n```\nQueryFailedError: Expression #16 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'soundcore_dev.collaborators.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n```\n\nThe resulting query that is build by TypeORM looks like this:\n\n```\nSELECT \n\n `playlist`.`id` AS `playlist_id`, \n `playlist`.`createdAt` AS `playlist_createdAt`, \n `playlist`.`authorId` AS `playlist_authorId`, \n `playlist`.`artworkId` AS `playlist_artworkId`, \n\n `author`.`id` AS `author_id`, \n `artwork`.`id` AS `artwork_id`, \n\n `collaborators`.`id` AS `collaborators_id`,\n \n SUM(`songs`.`duration`) AS `totalDuration` \n\n FROM \n `sc_playlist` `playlist` \n LEFT JOIN `sc_sso_user` `author` ON `author`.`id`=`playlist`.`authorId`\n LEFT JOIN `sc_artwork` `artwork` ON `artwork`.`id`=`playlist`.`artworkId` \n LEFT JOIN `sc_collaborators2playlist` `playlist_collaborators` ON `playlist_collaborators`.`playlistId`=`playlist`.`id` \n LEFT JOIN `sc_sso_user` `collaborators` ON `collaborators`.`id`=`playlist_collaborators`.`ssoUserId` \n LEFT JOIN `sc_song2playlist` `playlist_songs` ON `playlist_songs`.`playlistId`=`playlist`.`id` \n LEFT JOIN `sc_song` `songs` ON `songs`.`id`=`playlist_songs`.`songId` \n\n WHERE \n `playlist`.`id` = ? \n GROUP BY \n `playlist`.`id`\n```\n\nI did some research only and found how to sum up using typeORM, but I didn't get it to work for me. The above code and so on is everything I've found. I think I'm justing missing something quite important...\n\nMaybe some one can support me on this. I would really appreciate this.\nHave a great day! And thanks in advance for your kind support.\n\n========================================\n\nCode:\n```js\nconst playlist = await this.playlistRepository.createQueryBuilder(\"playlist\")\n        .where(\"playlist.id = :playlistId\", { playlistId })\n\n        // This is for relations\n        .leftJoinAndSelect(\"playlist.author\", \"author\")\n        .leftJoinAndSelect(\"playlist.artwork\", \"artwork\")\n        .leftJoinAndSelect(\"playlist.collaborators\", \"collaborators\")\n        .leftJoin(\"playlist.songs\", \"songs\")\n\n        // Counting the songs\n        .loadRelationCountAndMap(\"playlist.songsCount\", \"playlist.songs\")\n\n        // SUM up the duration of every song to get total duration of the playlist\n        .addSelect('SUM(songs.duration)', 'totalDuration')\n        .groupBy(\"playlist.id\")\n        .getOne()\n```\n\n```text\nQueryFailedError: Expression #16 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'soundcore_dev.collaborators.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n```\n\n```sql\nSELECT \n\n        `playlist`.`id` AS `playlist_id`, \n        `playlist`.`createdAt` AS `playlist_createdAt`, \n        `playlist`.`authorId` AS `playlist_authorId`, \n        `playlist`.`artworkId` AS `playlist_artworkId`, \n\n        `author`.`id` AS `author_id`, \n        `artwork`.`id` AS `artwork_id`, \n\n        `collaborators`.`id` AS `collaborators_id`,\n \n        SUM(`songs`.`duration`) AS `totalDuration` \n\n    FROM \n        `sc_playlist` `playlist` \n        LEFT JOIN `sc_sso_user` `author` ON `author`.`id`=`playlist`.`authorId`\n        LEFT JOIN `sc_artwork` `artwork` ON `artwork`.`id`=`playlist`.`artworkId`  \n        LEFT JOIN `sc_collaborators2playlist` `playlist_collaborators` ON `playlist_collaborators`.`playlistId`=`playlist`.`id` \n        LEFT JOIN `sc_sso_user` `collaborators` ON `collaborators`.`id`=`playlist_collaborators`.`ssoUserId`  \n        LEFT JOIN `sc_song2playlist` `playlist_songs` ON `playlist_songs`.`playlistId`=`playlist`.`id` \n        LEFT JOIN `sc_song` `songs` ON `songs`.`id`=`playlist_songs`.`songId` \n\n    WHERE \n        `playlist`.`id` = ? \n    GROUP BY \n        `playlist`.`id`\n```\n\n```text\nconst playlist = await this.playlistRepository.createQueryBuilder(\"playlist\")\n    .where(\"playlist.id = :playlistId\", { playlistId })\n\n    // This is for relations\n    .leftJoin(\"playlist.songs\", \"songs\")\n\n    // Counting the songs\n    //.select('COUNT(songs.id)', 'numbersongs') in case you want count of songs\n\n    // SUM up the duration of every song to get total duration of the playlist\n    .addSelect('SUM(songs.duration)', 'totalDuration')\n    .getRawOne()\n```\n\n```text\nsum,max,avg,..\n```\n\n```text\ngetRawOne\n```\n\n```text\ngetRawMany\n```\n\n========================================\n\nComments:\n- Should be marked as an answer, works for my example, needed to sum the product prices!","metadata":{"transformedAt":"2026-08-18T18:33:02.459Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":163,"estimatedTokens":1479}}655{"id":"stack-68744139","source":"stackoverflow","questionId":68744139,"title":"Exposing an array of object using class-transformer","tags":["typescript","nestjs","typeorm","class-transformer"],"text":"Title: Exposing an array of object using class-transformer\nTags: typescript, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI am not able to expose an array of objects.\nThe Followers array is not getting exposed, even though I exposed in the `UserDto`\n\nthis is what I am getting,\n\n```\n{\n \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n \"userName\": \"jdbfjl\",\n \"email\": \"jdfbaj@gmail.com\",\n \"bio\": \"Duuude\",\n \"avatar\": \"sjldflaeulajsnlnaefb\",\n \"followerCount\": 0,\n \"followeeCount\": 0,\n \"verified\": false,\n \"followers\": [\n {},\n {},\n {}\n ],\n \"followees\": [\n {}\n ]\n }\n```\n\nand expected is like\n\n```\n{\n \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n \"createdAt\": \"2021-08-11T11:07:11.688Z\",\n \"updatedAt\": \"2021-08-11T11:07:11.688Z\",\n \"userName\": \"ashdviah\",\n \"email\": \"hsdvhas@gmail.com\",\n \"bio\": \"I am Handsome\",\n \"avatar\": \"sjldflaeulajsnlnaefb\",\n \"followerCount\": 0,\n \"followeeCount\": 0,\n \"verified\": false,\n \"followers\": [\n {\n \"id\": \"db1d30c6-5607-4d87-8838-69f906c3c44e\",\n \"createdAt\": \"2021-08-11T11:09:33.018Z\",\n \"updatedAt\": \"2021-08-11T11:09:33.018Z\"\n },\n {\n \"id\": \"31492cd6-7c56-48f6-aff3-792a980b5100\",\n \"createdAt\": \"2021-08-11T11:11:01.288Z\",\n \"updatedAt\": \"2021-08-11T11:11:01.288Z\"\n },\n ],\n \"followees\": [\n {\n \"id\": \"ab095d0d-b9fa-41a4-be35-13fe9dd6f7a1\",\n \"createdAt\": \"2021-08-11T12:55:18.139Z\",\n \"updatedAt\": \"2021-08-11T12:55:18.139Z\"\n }\n ]\n }\n```\n\nI am getting this output when I am not specifying interceptor to that route... But it turns out that I am exposing password entry with it...\n\nmy current approach is something like this : which is not working as expected... what am i missing here ?\n\n```\nclass mock {\n @Expose() id : string;\n @Expose() createdAt : Date;\n @Expose() updatedAt : Date;\n}\n\nexport class UserDto {\n @Expose()\n id : string;\n \n @Expose()\n userName : string;\n \n @Expose()\n email : string;\n\n @Expose()\n bio : string;\n\n @Expose()\n avatar : string;\n\n @Expose()\n followerCount : number;\n\n @Expose()\n followeeCount : number;\n\n @Expose()\n verified : boolean;\n\n @Expose()\n followers : Array;\n\n @Expose()\n followees : Array;\n}\n```\n\nAnd transform is getting done by one interceptor that I used at the controller.\n\nusage : `@Serialize(UserDto)` decorator\n\n```\nexport function Serialize(dto: ClassConstructor) {\n return UseInterceptors(new Serializeinterceptor(dto));\n}\n\nexport class Serializeinterceptor implements NestInterceptor {\n constructor(private dto: any) {}\n\n intercept(context: ExecutionContext, handler: CallHandler) {\n return handler.handle().pipe(\n map((data: any) => {\n return plainToClass(this.dto, data, {\n excludeExtraneousValues: true,\n });\n }),\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n    \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n    \"userName\": \"jdbfjl\",\n    \"email\": \"jdfbaj@gmail.com\",\n    \"bio\": \"Duuude\",\n    \"avatar\": \"sjldflaeulajsnlnaefb\",\n    \"followerCount\": 0,\n    \"followeeCount\": 0,\n    \"verified\": false,\n    \"followers\": [\n      {},\n      {},\n      {}\n    ],\n    \"followees\": [\n      {}\n    ]\n  }\n```\n\n```text\n{\n    \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n    \"createdAt\": \"2021-08-11T11:07:11.688Z\",\n    \"updatedAt\": \"2021-08-11T11:07:11.688Z\",\n    \"userName\": \"ashdviah\",\n    \"email\": \"hsdvhas@gmail.com\",\n    \"bio\": \"I am Handsome\",\n    \"avatar\": \"sjldflaeulajsnlnaefb\",\n    \"followerCount\": 0,\n    \"followeeCount\": 0,\n    \"verified\": false,\n    \"followers\": [\n      {\n        \"id\": \"db1d30c6-5607-4d87-8838-69f906c3c44e\",\n        \"createdAt\": \"2021-08-11T11:09:33.018Z\",\n        \"updatedAt\": \"2021-08-11T11:09:33.018Z\"\n      },\n      {\n        \"id\": \"31492cd6-7c56-48f6-aff3-792a980b5100\",\n        \"createdAt\": \"2021-08-11T11:11:01.288Z\",\n        \"updatedAt\": \"2021-08-11T11:11:01.288Z\"\n      },\n    ],\n    \"followees\": [\n      {\n        \"id\": \"ab095d0d-b9fa-41a4-be35-13fe9dd6f7a1\",\n        \"createdAt\": \"2021-08-11T12:55:18.139Z\",\n        \"updatedAt\": \"2021-08-11T12:55:18.139Z\"\n      }\n    ]\n  }\n```\n\n```text\nclass mock {\n  @Expose() id : string;\n  @Expose() createdAt : Date;\n  @Expose() updatedAt : Date;\n}\n\nexport class UserDto {\n  @Expose()\n  id : string;\n  \n  @Expose()\n  userName : string;\n  \n  @Expose()\n  email : string;\n\n  @Expose()\n  bio : string;\n\n  @Expose()\n  avatar : string;\n\n  @Expose()\n  followerCount : number;\n\n  @Expose()\n  followeeCount : number;\n\n  @Expose()\n  verified : boolean;\n\n  @Expose()\n  followers : Array<mock>;\n\n  @Expose()\n  followees : Array<mock>;\n}\n```\n\n```text\nexport function Serialize(dto: ClassConstructor) {\n  return UseInterceptors(new Serializeinterceptor(dto));\n}\n\nexport class Serializeinterceptor implements NestInterceptor {\n  constructor(private dto: any) {}\n\n  intercept(context: ExecutionContext, handler: CallHandler) {\n    return handler.handle().pipe(\n      map((data: any) => {\n        return plainToClass(this.dto, data, {\n          excludeExtraneousValues: true,\n        });\n      }),\n    );\n  }\n}\n```\n\n```text\nUserDto\n```\n\n```text\n@Serialize(UserDto)\n```\n\n```text\n@Type(() => ClassType)\n```\n\n```text\n@Type(() => mock)\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":268,"estimatedTokens":1252}}656{"id":"stack-54493998","source":"stackoverflow","questionId":54493998,"title":"Do not pass e2e tests in framework NestJS","tags":["javascript","typescript","e2e-testing","nestjs","typeorm"],"text":"Title: Do not pass e2e tests in framework NestJS\nTags: javascript, typescript, e2e-testing, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI use the **NestJS** framework. When using **@nestjs/typeorm**, I create a repository with users. Using this approach to creating a repository, my **e2e tests**. When working with a database, all data is successfully saved. There are no problems with the connection. Here are my files:\n\n**app.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { AuthModule } from './modules/auth/auth.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n AuthModule,\n ],\n})\nexport class AppModule {\n constructor(private readonly connection: Connection) { }\n}\n```\n\n**auth.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { Users } from '../../entity/Users';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Users])],\n controllers: [AuthController],\n providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\n**auth.service.ts**\n\n```\n...\n // my repo\n constructor(\n @InjectRepository(Users)\n private readonly usersRepository: Repository,\n ) { }\n...\n```\n\n**app.e2e-spec.ts**\n\n```\nimport { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppModule } from './../src/app.module';\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleFixture = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(404)\n .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); //todo fix me\n });\n});\n```\n\nEverything is written in accordance with the documentation. When you run **npm run test:e2e**, the console gives the following error:\n\n```\n> project@0.0.0 test:e2e \n> jest --config ./test/jest-e2e.json\n\n[Nest] 7206 - 2/2/2019, 5:06:52 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)...\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n[Nest] 7206 - 2/2/2019, 5:06:55 PM [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3234ms\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n FAIL test/app.e2e-spec.ts (6.198s)\n AppController (e2e)\n โœ• / (GET) (6ms)\n\n โ— AppController (e2e) โ€บ / (GET)\n\n Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.\n\n at mapper (../node_modules/jest-jasmine2/build/queue_runner.js:41:52)\n\n โ— AppController (e2e) โ€บ / (GET)\n\n TypeError: Cannot read property 'getHttpServer' of undefined\n\n 17 |\n 18 | it('/ (GET)', () => {\n > 19 | return request(app.getHttpServer())\n | ^\n 20 | .get('/')\n 21 | .expect(404)\n 22 | .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); // todo fix me\n\n at Object. (app.e2e-spec.ts:19:24)\n```\n\nPlease, help me!\n\n========================================\n\nTop Answer:\nBe sure to close the `app` object with `app.close()` per the example at https://docs.nestjs.com/fundamentals/testing#end-to-end-testing.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { AuthModule } from './modules/auth/auth.module';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    AuthModule,\n  ],\n})\nexport class AppModule {\n  constructor(private readonly connection: Connection) { }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { Users } from '../../entity/Users';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Users])],\n  controllers: [AuthController],\n  providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\n```text\n...\n      // my repo\n      constructor(\n        @InjectRepository(Users)\n        private readonly usersRepository: Repository<Users>,\n      ) { }\n...\n```\n\n```text\nimport { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppModule } from './../src/app.module';\n\ndescribe('AppController (e2e)', () => {\n  let app: INestApplication;\n\n  beforeAll(async () => {\n    const moduleFixture = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  it('/ (GET)', () => {\n    return request(app.getHttpServer())\n      .get('/')\n      .expect(404)\n      .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); //todo fix me\n  });\n});\n```\n\n```text\n> project@0.0.0 test:e2e \n> jest --config ./test/jest-e2e.json\n\n[Nest] 7206   - 2/2/2019, 5:06:52 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)...\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n[Nest] 7206   - 2/2/2019, 5:06:55 PM   [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3234ms\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n FAIL  test/app.e2e-spec.ts (6.198s)\n  AppController (e2e)\n    โœ• / (GET) (6ms)\n\n  โ— AppController (e2e) โ€บ / (GET)\n\n    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.\n\n      at mapper (../node_modules/jest-jasmine2/build/queue_runner.js:41:52)\n\n  โ— AppController (e2e) โ€บ / (GET)\n\n    TypeError: Cannot read property 'getHttpServer' of undefined\n\n      17 |\n      18 |   it('/ (GET)', () => {\n    > 19 |     return request(app.getHttpServer())\n         |                        ^\n      20 |       .get('/')\n      21 |       .expect(404)\n      22 |       .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); // todo fix me\n\n      at Object.<anonymous> (app.e2e-spec.ts:19:24)\n```\n\n```js\nimport { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppController } from './../src/app.controller';\nimport { AppService } from './../src/app.service';\n\ndescribe('AppController (e2e)', () => {\n  let app: INestApplication;\n\n  beforeAll(async () => {\n    const moduleFixture = await Test.createTestingModule({\n      imports: [],\n      controllers: [AppController],\n      providers: [AppService],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  it('/ (GET)', () => {\n    return request(app.getHttpServer())\n      .get('/')\n      .expect(404)\n      .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); //todo fix me\n  });\n});\n```\n\n```text\nAppModule\n```\n\n```text\nAppController\n```\n\n```text\nAppService\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nTest\n```\n\n```text\noverrideProvider\n```\n\n```text\nuseClass\n```\n\n```text\nuseValue\n```\n\n```text\nuseFactory\n```\n\n```text\nTypeOrmModule\n```\n\n```text\napp\n```\n\n```text\napp.close()\n```\n\n```text\n/api\n```\n\n```text\n// mytest.e2e-spec.ts\nimport * as request from 'supertest';\nimport { Test } from \"@nestjs/testing\";\nimport { INestApplication } from '@nestjs/common';\nimport { MyTestsController } from './myTests.controller';\nimport { MyTestsService } from \".\";\nimport { Warehouse } from './myTest.entity';\nimport { getRepositoryToken } from '@nestjs/typeorm';\n\ndescribe(\"MyTestsController (e2e)\", () => {\n\n  let app: INestApplication;\n  const myTests = [\n    {\n      id: \"1ccc2222a-8072-4ff0-b5ff-103cc85f3be6\",\n      name: \"Name #1\",\n    }\n  ];\n\n  const myTestsCount = 1;\n  const getAllResult = { myTests, myTestsCount };\n  // Mock data for service\n  let myTestsService = { getAll: () => getAllResult };\n\n  beforeAll(async () => {\n    const module = await Test.createTestingModule({\n      providers: [\n        MyTestsService,\n        {\n          provide: getRepositoryToken(Warehouse),\n          useValue: myTestsService\n        }\n      ],\n      controllers: [MyTestsController],\n    })\n      .overrideProvider(MyTestsService)\n      .useValue(myTestsService)\n      .compile();\n\n    app = module.createNestApplication();\n    await app.init();\n  });\n\n  beforeEach(async () => {});\n\n  it(`/GET all myTests`, async() => {\n    return await request(app.getHttpServer())\n      .get('/myTests')\n      .expect(200)\n      .expect(myTestsService.getAll());\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n\n});\n```\n\n```text\n// myTests.service.ts\npublic async getAll(query?): Promise<myTestsRO> {\n  const qb = await this.repo.createQueryBuilder(\"myTests\");\n  const myTestsCount = await qb.getCount();\n\n  if (\"limit\" in query) {\n    qb.limit(query.limit);\n  }\n\n  if (\"offset\" in query) {\n    qb.offset(query.offset);\n  }\n\n  const myTests = await qb\n    .getMany()\n    .then(myTests =>\n      myTests.map(entity => WarehouseDto.fromEntity(entity))\n    );\n\n  return { myTests, myTestsCount };\n}\n```\n\n```text\n// myTest.controller.ts\n@Get()\npublic async getAll(@Query() query): Promise<myTestsRO> {\n  try {\n    return await this.myTestsService.getAll(query);\n  } catch (error) {\n    throw new InternalServerErrorException(error.message);\n  }\n}\n```\n\n```text\nTypeOrmModule\n```\n\n========================================\n\nComments:\n- >Unable to connect to the database. Error: getaddrinfo ENOTFOUND postgres postgres:5432\n- What are you using to configure your database connection? Is it something that depends on the environment? Is the env where tests are running able to connect to that db? (like, are you running the tests in docker and docker doesn't have access to that db?)\n- I have the same problem\n- He's doing e2e (end to end) testing, not unit testing.","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":424,"estimatedTokens":2539}}657{"id":"stack-72355901","source":"stackoverflow","questionId":72355901,"title":"Property '_id' does not exist on type. Getting type error when trying to access property _id on result of a promise in nestjs application","tags":["javascript","typescript","mongodb","nestjs","mongoose-schema"],"text":"Title: Property '_id' does not exist on type. Getting type error when trying to access property _id on result of a promise in nestjs application\nTags: javascript, typescript, mongodb, nestjs, mongoose-schema\nSource: Stack Overflow\n\nQuestion:\nIn my nest application I am getting type error when calling `_id` on `user` because mongoose defines the `_id` automatically & therefore its not present in my schema which is defined as type for the promise.\n\nWhen the promise type is changed to any like `Promise` then there is no type error.\n\n```\nasync create(createUserDto: CreateUserDto): Promise {\n const createdUser = await new this.userModel(createUserDto).save();\n return createdUser;\n }\n```\n\nbut I want to know is this the correct way or I should be doing something else.\n\nI do not want to define `_id` in schema to solve this issue.\n\n```\n@Prop({ auto: true})\n _id!: mongoose.Types.ObjectId;\n```\n\n**user.schema.ts**\n\n```\n// all the imports here....\n\nexport type UserDocument = User & Document;\n\n@Schema({ timestamps: true })\nexport class User {\n\n @Prop({ required: true, unique: true, lowercase: true })\n email: string;\n\n @Prop()\n password: string;\n\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n**users.controller.ts**\n\n```\n@Controller('users')\n@TransformUserResponse(UserResponseDto)\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @Post()\n async create(@Body() createUserDto: CreateUserDto) {\n const user = await this.usersService.create(createUserDto);\n return user._id;\n }\n\n}\n```\n\n**users.service.ts**\n\n```\n// all the imports here.... \n \n@Injectable()\nexport class UsersService {\n constructor(@InjectModel(User.name) private userModel: Model) {}\n\n async create(createUserDto: CreateUserDto): Promise {\n const createdUser = await new this.userModel(createUserDto).save();\n return createdUser;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nasync create(createUserDto: CreateUserDto): Promise<User> {\n    const createdUser = await new this.userModel(createUserDto).save();\n    return createdUser;\n  }\n```\n\n```text\n@Prop({ auto: true})\n _id!: mongoose.Types.ObjectId;\n```\n\n```text\n// all the imports here....\n\nexport type UserDocument = User & Document;\n\n@Schema({ timestamps: true })\nexport class User {\n\n  @Prop({ required: true, unique: true, lowercase: true })\n  email: string;\n\n  @Prop()\n  password: string;\n\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n```text\n@Controller('users')\n@TransformUserResponse(UserResponseDto)\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Post()\n  async create(@Body() createUserDto: CreateUserDto) {\n      const user = await this.usersService.create(createUserDto);\n      return user._id;\n  }\n\n}\n```\n\n```text\n// all the imports here....  \n   \n@Injectable()\nexport class UsersService {\n  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}\n\n  async create(createUserDto: CreateUserDto): Promise<User> {\n    const createdUser = await new this.userModel(createUserDto).save();\n    return createdUser;\n  }\n}\n```\n\n```text\n_id\n```\n\n```text\nuser\n```\n\n```text\n_id\n```\n\n```text\nPromise<any>\n```\n\n```text\n_id\n```\n\n```js\nasync create(createUserDto: CreateUserDto): Promise<UserDocument> {\n    const createdUser = await new this.userModel(createUserDto).save();\n    return createdUser;\n  }\n```\n\n```text\ncreate\n```\n\n```text\nPromise<UserDocument>\n```\n\n```text\nPromise<User>\n```\n\n```text\nUserDocument\n```\n\n```text\n_id\n```\n\n========================================\n\nComments:\n- You can use `Document.prototype.id` to get the `_id` in string form. In other words use `user.id` instead.\n- It's okay to define the _id in the schema, if the problem is to define the same property to all your schema you could define a base model and extend that model to your models.\n- @JakeHolzinger `user.id` is also showing type error like I said because in the User schema `id` is not present.\n- A typescript error? If you return `UserDocument` in your `UserService` you should have access to the id. The `User` type does not have an id property.\n- Hello i am also facing this problem . did you solved it and how ?? is it possible without manually define _id property?\n- @MahmudulHassan I removed the promise type from User to Any and the type error went away.\n- This kind of information should be in the NestJS doc. Thank you !","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":199,"estimatedTokens":1107}}658{"id":"stack-56686391","source":"stackoverflow","questionId":56686391,"title":"Right way to get ConfigService when bootstrap microservice","tags":["node.js","microservices","nestjs"],"text":"Title: Right way to get ConfigService when bootstrap microservice\nTags: node.js, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to know if i'm getting ConfigService the right way during bootstrap my microservice.\n\nIs there a way to do it using NestFactory.createMicroservice()?\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(CoreModule, {\n logger: new MyLogger(),\n });\n const configService: ConfigService = app.get(ConfigService);\n app.connectMicroservice({\n transport: Transport.TCP,\n options: {\n port: configService.PORT,\n },\n });\n await app.startAllMicroservicesAsync();\n}\n```\n\n========================================\n\nTop Answer:\nSince NestJS v11.0.0, you can configure microservices using asynchronous options resolved from the dependency injection (DI) container. This enhancement allows for more dynamic and flexible microservice configurations. Hereโ€™s how you can implement this:\n\n**Example: Configuring a Microservice with Asynchronous Options**\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { PaymentsModule } from './payments.module';\nimport { MicroserviceOptions, Transport } from '@nestjs/microservices';\nimport { ConfigService } from '@nestjs/config';\n\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice>(PaymentsModule, {\n inject: [ConfigService],\n useFactory: (configService: ConfigService) => ({\n transport: Transport.TCP,\n options: {\n host: '0.0.0.0',\n port: configService.get('PORT', 5001),\n },\n })\n });\n\n await app.listen();\n}\n\nbootstrap();\n```\n\nIn this example:\n\n- **Dependency Injection:** The `ConfigService` is injected to access environment variables or configuration settings.\n\n- **Asynchronous Factory:** The `useFactory` function utilizes the injected `ConfigService` to dynamically set the microserviceโ€™s host and port.\n\nThis feature was introduced in Pull Request #12622 of the NestJS repository.\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(CoreModule, {\n    logger: new MyLogger(),\n  });\n  const configService: ConfigService = app.get(ConfigService);\n  app.connectMicroservice({\n    transport: Transport.TCP,\n    options: {\n      port: configService.PORT,\n    },\n  });\n  await app.startAllMicroservicesAsync();\n}\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, {\n    logger: new MyLogger()\n  });\n  const config = app.get<ConfigService>(ConfigService);\n  const port = config.get('PORT');\n  configure(app, config);\n  await app.listen(port);\n  scribe.info(\n    `Listening at http://localhost:${port}/${config.get('GLOBAL_PREFIX')}`\n  );\n}\n```\n\n```js\nconst configService: ConfigService = app.get(ConfigService);\n```\n\n```js\nconst configService = app.get<ConfigService>(ConfigService);\n```\n\n```text\nMyLogger\n```\n\n```text\nconfigure(app, config)\n```\n\n```text\nbootstrap\n```\n\n```text\napp.get()\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { PaymentsModule } from './payments.module';\nimport { MicroserviceOptions, Transport } from '@nestjs/microservices';\nimport { ConfigService } from '@nestjs/config';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice<AsyncOptions<MicroserviceOptions>>(PaymentsModule, {\n    inject: [ConfigService],\n    useFactory: (configService: ConfigService) => ({\n      transport: Transport.TCP,\n      options: {\n        host: '0.0.0.0',\n        port: configService.get<number>('PORT', 5001),\n      },\n    })\n  });\n\n  await app.listen();\n}\n\nbootstrap();\n```\n\n```text\nConfigService\n```\n\n```text\nuseFactory\n```\n\n```text\nConfigService\n```\n\n========================================\n\nComments:\n- There is a Github issue on this topic: github.com/nestjs/nest/issues/2343\n- How can I use `createMicroservice` with configService?\n- I think the OP has answered his own question correctly for nest js microservices. Thank you OP. The example in this answer is for a regular HTTP service. Which is also useful.\n- I think you should expand on this answer to describe the configure() method. It's not clear how to configure an app after it is created. For me, I had to create the configureService before creating the app, otherwise the wrong MQTT options would be used. This answer helped: stackoverflow.com/a/70070499/632088","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":165,"estimatedTokens":1079}}659{"id":"stack-66794387","source":"stackoverflow","questionId":66794387,"title":"How to update an entity with relations using QueryBuilder in TypeORM","tags":["node.js","nestjs","typeorm"],"text":"Title: How to update an entity with relations using QueryBuilder in TypeORM\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have `UserEntity` and `AddressEntity`, they are related as `OneToOne`, that's one user may have only one address. `UserEntity` has fields `firstName`, `secondName`, `address`. `AddressEntity` has fields `country` and `city`.\n\nIf I wanted to update `UserEntity` without doing it to its relations I would do this:\n\n```\nawait entityManager.getRepository(UserEntity)\n .createQueryBuilder('users')\n .update(UserEntity)\n .set(updateUserObject)\n .where('users.id = :userId', { userId })\n .execute();\n```\n\nwhere `updateUserObject` is formed from a request body. That's to say, if I need to update `firstName`, the object would look like this: `{ firstName: 'Joe' }`. Now what is unclear is how to use that builder if I have the following `updateUserObject`:\n\n```\n{\n firstName: \"Bob\",\n address: {\n \"city\": \"Ottawa\"\n }\n}\n```\n\nThe official documentation does not address such cases.\n\n========================================\n\nCode:\n```text\nawait entityManager.getRepository(UserEntity)\n                         .createQueryBuilder('users')\n                         .update(UserEntity)\n                         .set(updateUserObject)\n                         .where('users.id = :userId', { userId })\n                         .execute();\n```\n\n```text\n{\n    firstName: \"Bob\",\n    address: {\n        \"city\": \"Ottawa\"\n    }\n}\n```\n\n```text\nUserEntity\n```\n\n```text\nAddressEntity\n```\n\n```text\nOneToOne\n```\n\n```text\nUserEntity\n```\n\n```text\nfirstName\n```\n\n```text\nsecondName\n```\n\n```text\naddress\n```\n\n```text\nAddressEntity\n```\n\n```text\ncountry\n```\n\n```text\ncity\n```\n\n```text\nUserEntity\n```\n\n```text\nupdateUserObject\n```\n\n```text\nfirstName\n```\n\n```text\n{ firstName: 'Joe' }\n```\n\n```text\nupdateUserObject\n```\n\n```js\n@Entity('user')\nexport class UserEntity {\n  ...\n\n  @OneToOne(\n    () => AddressEntity,\n    {\n      // Make sure that when you delete or update a user, it will affect the\n      // corresponding `AddressEntity`\n      cascade: true,\n      // Make sure when you use `preload`, `AddressEntity` of the user will also\n      // return (This means whenever you use any kind of `find` operations on\n      // `UserEntity`, it would load this entity as well)\n      eager: true\n    }\n  )\n  @JoinColumn()\n  address: AddressEntity;\n}\n```\n\n```js\nconst partialUserEntity = {\n    id: userId,\n    firstName: \"Bob\",\n    address: {\n        \"city\": \"Ottawa\"\n    }\n};\n\nconst userRepository = await entityManager.getRepository(UserEntity);\n\n// Here we load the current user entity value from the database and replace\n// all the related values from `partialUserEntity`\nconst updatedUserEntity = await userRepository.preload(partialUserEntity);\n\n// Here we update (create if not exists) `updatedUserEntity` to the database\nawait userRepository.save(updatedUserEntity);\n```\n\n```js\n/* \n * If `updatedUserEntity.address.id` is `undefined`\n */\n\n// `generateIDForAddress` is a function which would return an `id`\nconst generatedIDForAddress = generateIDForAddress();\nconst partialUserEntity = {\n    id: userId,\n    firstName: \"Bob\",\n    address: {\n        \"id\": generatedIDForAddress,\n        \"city\": \"Ottawa\"\n    }\n};\n```\n\n```text\nUserEntity\n```\n\n```text\nentityManager\n```\n\n```text\nUserEntity\n```\n\n```text\nAddressEntity\n```\n\n```text\nid\n```\n\n```text\nAddressEntity\n```\n\n```text\nsave\n```\n\n```text\nUPDATE\n```\n\n```text\nUserEntity\n```\n\n```text\nAddressEntity\n```\n\n```text\npreload\n```\n\n```text\nsave\n```\n\n========================================\n\nComments:\n- I'm not sure if I correctly understand your question. Do you want to partially update the user without mutating the address?\n- you can't update relationships entity,you have to make another query to update the adress\n- @sandrooco yes, I'd like to be able to update the user partially. I'm implementing the `PATCH` verb right now for the user entity.\n- @Youba So basically, it means that if I have n relations I will have to make n requests or something?\n- @Alber no it's not related to requests, you should make another querybuilder for address, like now, you have one for user, you'll add another one for address because it is another entity\n- @Youba well I meant requests to the DB. I mean that I have one query builder for user and then to update my user I execute the QB using `await` and then I will fire off another query with one more query builder for the address entity. Am I correct?\n- @Alber yes, you right, just to let you know in SQL we should do the same we don't have the ability to update in the same query\n- Wow, sounds great! I've already implemented it somewhat differently though but I will try your method later. Perhaps I will have some question. Yaay, thank you! :)","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":229,"estimatedTokens":1186}}660{"id":"stack-67282484","source":"stackoverflow","questionId":67282484,"title":"SubcribeMessage decorator doesn't trigger on event 'message'","tags":["typescript","nestjs","ws"],"text":"Title: SubcribeMessage decorator doesn't trigger on event 'message'\nTags: typescript, nestjs, ws\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a WebSocket server on my NestJS backend, and when I try subscribing on the default 'message' event type, the method `handleMessage()` doesn't get triggered.\n\nThe `listenForMessages()` method however works (which is triggered after the init of the server). Does anyone know why the decorator `@SubscribeMessage('message')` doesn't work?\n\n```\n@WebSocketGateway()\nexport class AppWebsocketGateway implements OnGatewayInit, OnGatewayDisconnect {\n private clientIds = new Map();\n // @ts-ignore\n @WebSocketServer() server: Server;\n private logger: Logger = new Logger('WebsocketGateway');\n\n constructor(private readonly evseService: EvseService) {\n }\n\n listenForMessages() {\n this.server.on('connection', (ws) => {\n ws.on('message', (e) => {\n console.log(e);\n });\n });\n this.logger.log('message received');\n }\n\n @SubscribeMessage('message')\n handleMessage(@ConnectedSocket() client: any, payload: any): void {\n this.logger.log('I received a message from the client!');\n this.server.emit('msgToClient', payload);\n }\n\n afterInit(server: Server) {\n this.logger.log('Init');\n this.listenForMessages();\n }\n\n handleDisconnect(@ConnectedSocket() client: any) {\n this.logger.log(`Client disconnected: ${client.id}`);\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@WebSocketGateway()\nexport class AppWebsocketGateway implements OnGatewayInit, OnGatewayDisconnect {\n  private clientIds = new Map<string, string>();\n  // @ts-ignore\n  @WebSocketServer() server: Server;\n  private logger: Logger = new Logger('WebsocketGateway');\n\n  constructor(private readonly evseService: EvseService) {\n  }\n\n  listenForMessages() {\n    this.server.on('connection', (ws) => {\n      ws.on('message', (e) => {\n        console.log(e);\n      });\n    });\n    this.logger.log('message received');\n  }\n\n\n  @SubscribeMessage('message')\n  handleMessage(@ConnectedSocket() client: any, payload: any): void {\n    this.logger.log('I received a message from the client!');\n    this.server.emit('msgToClient', payload);\n  }\n\n  afterInit(server: Server) {\n    this.logger.log('Init');\n    this.listenForMessages();\n  }\n\n  handleDisconnect(@ConnectedSocket() client: any) {\n    this.logger.log(`Client disconnected: ${client.id}`);\n  }\n}\n```\n\n```text\nhandleMessage()\n```\n\n```text\nlistenForMessages()\n```\n\n```text\n@SubscribeMessage('message')\n```\n\n```text\n//@SubscribeMessage('message') will look for the message that are in the format :\n{\n  event:'message',\n  data: {someData} // Whatever in the data field will be the payload in \n                   //handleMessage()\n}\n\n// Another example \n// @SubscribeMessage('get_profile') will look for messages in the format : \n\n{\n  event:'get_profile',\n  data: {someData} // Whatever in the data field will be the payload in \n                   //handleMessage()\n}\n```\n\n```text\n{\nevent : <event>,\ndata : <any>, // Can be string, number, object, buffer, whatever you want\n}\n```\n\n```text\n@SubscribeMessage('message')\n```\n\n```text\nlistenForMessages()\n```\n\n```text\nws.on('message', callback);\n```\n\n```text\nlistenForMessages()\n```\n\n```text\n@SubscribeMessage(<event>)\n```\n\n========================================\n\nComments:\n- Thanks for the extensive answer, do you know to which 'eventType' I should listen then in `@SubscribeMessage()`. Because my WSS clients do not specify any eventType, it's just send out by `ws.send(dataGoesHere)`. I thought the default eventType in that case was 'message'.\n- As I said before, you should have a format when sending data to the gateway. So you should send stringified version of : `{event:'message',date:{sender:1,content:'hello'}}` from the front end. This will trigger the `@SubscribeMessage('message')` and the `payload` will be `{sender:1,content:'hello'}`\n- Thanks for confirming, unfortunately I have no control over the clients as I'm developing a WebSocket Server to handle clients that operate through a certain protocol. This is the right answer though so I'll check it!\n- If you have no control over the data being sent from the front-end, I suggest that you isolate the websocket section, since you'll be using the library specific techniques and API's. It will be a great relief when you have to refactor or add a new feature.\n- Is it documented somewhere? On the official documentation, they say that you can send your message as such: `socket.emit(\"eventName\", someData);`, there is no indication that you need to send the event name as well in the data like `socket.emit(\"eventName\", { event: \"eventName\", data: someData });` and I'm a little bit confused between your answer and the official documentation. Can you please add some references?","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":152,"estimatedTokens":1188}}661{"id":"stack-64203140","source":"stackoverflow","questionId":64203140,"title":"nestjs microservices - have one clientProxy to publish message to any microService","tags":["microservices","nestjs"],"text":"Title: nestjs microservices - have one clientProxy to publish message to any microService\nTags: microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nSometimes, you want to say, \"I have this message, who can handle it?\"\n\nIn `nestjs` a client proxy is bounded directly to a single `microservice`.\n\nSo, as an example, let say that I have the following micro-services:\n`CleaningService`, `FixingService`.\n\nBoth of the above can handle the message `car`, but only `CleaningService` can handle the message `glass`.\n\nSo, I want to have something like:\n\n```\nthis.generalProxy.emit('car', {id: 2});\n```\n\nIn this case, I want **2 different** `microservices` to handle the car: `CleaningService` and `FixingService`.\n\nin this case:\n\n```\nthis.generalProxy.emit('glass', {id: 5});\n```\n\nI want only `CleaningService` to handle it.\n\nHow is that possible? how can I create `clientProxy` that is not bonded directly to a `specific` `microservice`.\n\n========================================\n\nTop Answer:\nFor anyone encountering a similar issue: when using @golevelup/nestjs-rabbitmq in a multi-instance microservices setup, your consumer instance must be configured as an HTTP server. Using RMQ transport in NestJS will not work as expected.\n\nThis is because RabbitMQ's Pub/Sub pattern operates over TCP, requiring a different approach for handling multiple instances.\n\n========================================\n\nCode:\n```text\nthis.generalProxy.emit('car', {id: 2});\n```\n\n```text\nthis.generalProxy.emit('glass', {id: 5});\n```\n\n```text\nnestjs\n```\n\n```text\nmicroservice\n```\n\n```text\nCleaningService\n```\n\n```text\nFixingService\n```\n\n```text\ncar\n```\n\n```text\nCleaningService\n```\n\n```text\nglass\n```\n\n```text\nmicroservices\n```\n\n```text\nCleaningService\n```\n\n```text\nFixingService\n```\n\n```text\nCleaningService\n```\n\n```text\nclientProxy\n```\n\n```text\nspecific\n```\n\n```text\nmicroservice\n```\n\n```js\n@Injectable()\nexport class CleaningService {\n  @RabbitSubscribe({\n    exchange: 'app',\n    routingKey: 'cars',\n    queue: 'cleaning-cars',\n  })\n  public async cleanCar(msg: {}) {\n    console.log(`Received message: ${JSON.stringify(msg)}`);\n  }\n\n  @RabbitSubscribe({\n    exchange: 'app',\n    routingKey: 'glass',\n    queue: 'cleaning-glass',\n  })\n  public async cleanGlass(msg: {}) {\n    console.log(`Received message: ${JSON.stringify(msg)}`);\n  }\n}\n```\n\n```js\n@Injectable()\nexport class FixingService {\n  @RabbitSubscribe({\n    exchange: 'app',\n    routingKey: 'cars',\n    queue: 'fixing-cars',\n  })\n  public async fixCar(msg: {}) {\n    console.log(`Received message: ${JSON.stringify(msg)}`);\n  }\n}\n```\n\n```js\namqpConnection.publish('app', 'cars', { year: 2020, make: 'toyota' });\n```\n\n========================================\n\nComments:\n- What microservice transport are you using under the hood?\n- @JesseCarter Rmq, what is that matter? isn't it totally abstract?\n- This is great, I actually bumped into this at the begining and totally forget about it. 2 questions though. 1. Do you by any chance have a sample project for microservices? 1. is it production-ready? thanks!\n- @SexyMF I don't have a sample project using this library but there are extensive e2e tests in the project for this library that test against actual RabbitMQ instances which you could reference. It is production ready. I've used it in several projects and it has pretty wide adoption inside the Nest community\n- Is there a best practice for using @golevelup/nestjs-rabbitmq when deploy a publisher and a subscriber on different instances i.e different servers or processes. I find that when I do I ran into an issue ` An unsupported event was received. It has been negative acknowledged, so it will not be re-delivered. Pattern: undefined {\"context\":\"Server\"}` Is it possible to use @golevelup/nestjs-rabbitmq library in separate instances connected to the same queue?","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":155,"estimatedTokens":954}}662{"id":"stack-60042350","source":"stackoverflow","questionId":60042350,"title":"Customise the response on verification failure for a jwt Strategy NestJs","tags":["authentication","jwt","nestjs","passport-jwt"],"text":"Title: Customise the response on verification failure for a jwt Strategy NestJs\nTags: authentication, jwt, nestjs, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nI successfully implemented a jwt strategy for authentication using nestJs.\n\nBelow is the code for the jwt strategy\n\n```\nimport { ServerResponse } from './../helpers/serverResponse.helper';\nimport { Injectable, UnauthorizedException, HttpStatus } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { config as env } from 'dotenv';\nimport { Bugsnag } from '../helpers/bugsnag.helper';\n\nenv();\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {\n constructor(\n private readonly logger: Bugsnag,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET_KEY,\n passReqToCallback: true,\n });\n\n }\n\n async validate(payload, done: Function) {\n try {\n const validClaims = await this.authService.verifyTokenClaims(payload);\n\n if (!validClaims)\n return done(new UnauthorizedException('invalid token claims'), false);\n done(null, payload);\n } catch (err) {\n this.logger.notify(err);\n return ServerResponse.throwError({\n success: false,\n status: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'JwtStrategy class, validate function',\n errors: [err],\n });\n }\n }\n}\n```\n\nI saw here that the validate function will be called only when a valid token was provided in the request headers and I'm okay with that. However, I would like to know if it is possible to customize the response object which is sent in that case (*invalid token provided*).\n\nIf yes, how do I do that ?\n\n========================================\n\nTop Answer:\nYou can use the `AuthGuard('jwt')`'s `handleRequest` method to throw any exception on JWT Validation failure.\n\n```\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n handleRequest(err: any, user: any, info: any, context: any, status: any) {\n if (info instanceof JsonWebTokenError) {\n throw new UnauthorizedException('Invalid Token!');\n }\n\n return super.handleRequest(err, user, info, context, status);\n }\n}\n```\n\n`JsonWebTokenError` comes from `jsonwebtoken` library, which is used internally by passport.\n\n========================================\n\nCode:\n```js\nimport { ServerResponse } from './../helpers/serverResponse.helper';\nimport { Injectable, UnauthorizedException, HttpStatus } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { config as env } from 'dotenv';\nimport { Bugsnag } from '../helpers/bugsnag.helper';\n\nenv();\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {\n    constructor(\n    private readonly logger: Bugsnag,\n    ) {\n    super({\n        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n        secretOrKey: process.env.JWT_SECRET_KEY,\n        passReqToCallback: true,\n    });\n\n    }\n\n    async validate(payload, done: Function) {\n    try {\n        const validClaims = await this.authService.verifyTokenClaims(payload);\n\n        if (!validClaims)\n            return done(new UnauthorizedException('invalid token claims'), false);\n        done(null, payload);\n    } catch (err) {\n        this.logger.notify(err);\n        return ServerResponse.throwError({\n        success: false,\n        status: HttpStatus.INTERNAL_SERVER_ERROR,\n        message: 'JwtStrategy class, validate function',\n        errors: [err],\n        });\n    }\n    }\n}\n```\n\n```text\nUnauthorizedException\n```\n\n```text\nAuthGuard('jwt')\n```\n\n```text\ntry/catch\n```\n\n```text\nsuper.canActivate(context)\n```\n\n```text\nUnauthorizedException\n```\n\n```js\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  handleRequest(err: any, user: any, info: any, context: any, status: any) {\n    if (info instanceof JsonWebTokenError) {\n      throw new UnauthorizedException('Invalid Token!');\n    }\n\n    return super.handleRequest(err, user, info, context, status);\n  }\n}\n```\n\n```text\nAuthGuard('jwt')\n```\n\n```text\nhandleRequest\n```\n\n```text\nJsonWebTokenError\n```\n\n```text\njsonwebtoken\n```\n\n```js\n... import dependencies\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  ...\n  handleRequest(err, user, info) {\n    if (!user) {\n      throw new UnauthorizedException(err || info);\n    }\n    return user;\n  }\n}\n```\n\n```js\n... import dependencies\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  ...\n  handleRequest(err, user, info) {\n    if (!user) {\n      throw err || info;\n    }\n    return user;\n  }\n}\n```\n\n```text\nerr\n```\n\n```text\ninto an\n```\n\n```text\nerr\n```\n\n```text\ninfo\n```\n\n```text\nException\n```\n\n```text\n500 internal error\n```\n\n========================================\n\nComments:\n- Thank you @jay McDoniel. Exception filters solved the problem quite nicely\n- Thank you ! I've been looking for this all day. For those who don't read the docs like myself, Nestjs docs have it explained too: docs.nestjs.com/recipes/passport#extending-guards","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":230,"estimatedTokens":1264}}663{"id":"stack-66224449","source":"stackoverflow","questionId":66224449,"title":"Class validator: Use class member as decorator argument","tags":["node.js","typescript","decorator","nestjs","class-validator"],"text":"Title: Class validator: Use class member as decorator argument\nTags: node.js, typescript, decorator, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI have a signup DTO where one member is dependent of another.\n\nThe `IsPostalCode` on `zip` needs to know the countryCode/locale, which is one of the other class members.\n\nIs it possible to use a class member as decorator argument?\n\n```\nimport {\n IsEmail,\n IsISO31661Alpha2,\n IsPostalCode,\n IsString\n} from \"class-validator\"\n\nexport class SignupDto {\n @IsEmail()\n email: string\n\n @IsString()\n password: string\n\n @IsISO31661Alpha2()\n countryCode: string\n\n // Something like this\n @IsPostalCode(this.countryCode)\n zip: string\n}\n```\n\n========================================\n\nTop Answer:\nYou can create a custom validator like below:\n\n```\nimport {\n ValidationOptions,\n registerDecorator,\n ValidationArguments,\n buildMessage,\n} from 'class-validator';\n/**\n* Install validator package from npm. class-validator uses validator under the \n* hood\n*/\nimport {isISO31661Alpha2,isPostalCode} from 'validator';\n\nexport function IsPostalCodeOf(\n property: string,\n validationOptions?: ValidationOptions,\n) {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return function(object: Object, propertyName: string) {\n registerDecorator({\n name: 'isPostalCodeOf',\n target: object.constructor,\n propertyName: propertyName,\n constraints: [property],\n options: validationOptions,\n validator: {\n validate(value: any, args: ValidationArguments) {\n // Getting the country code field from the argument.\n // countryCode field from SignupDto\n const [countryCodeField] = args.constraints;\n // Getting the value of the countryCode Field\n const countryCode = (args.object as any)[countryCodeField];\n // Checking if the country code is valid even though it is checked \n // at class level \n if (!isISO31661Alpha2(countryCode)) {\n // Invalid county code\n return false;\n }\n // Checks if the value (zip) belongs in the extracted countryCode \n // field\n return isPostalCode(value,countryCode);\n },\n // Specifiy your error message here.\n defaultMessage: buildMessage(\n eachPrefix =>\n `${eachPrefix} $property must be a valid postal \n code in the specified country `,\n validationOptions,\n ),\n },\n });\n };\n}\n```\n\nUsage:\n\n```\nexport class SignupDto {\n @IsEmail()\n email: string\n\n @IsString()\n password: string\n\n @IsISO31661Alpha2()\n countryCode: string\n\n @IsPostalCodeOf('countryCode')\n zip: string\n}\n```\n\n========================================\n\nCode:\n```js\nimport {\n  IsEmail,\n  IsISO31661Alpha2,\n  IsPostalCode,\n  IsString\n} from \"class-validator\"\n\nexport class SignupDto {\n  @IsEmail()\n  email: string\n\n  @IsString()\n  password: string\n\n  @IsISO31661Alpha2()\n  countryCode: string\n\n  // Something like this\n  @IsPostalCode(this.countryCode)\n  zip: string\n}\n```\n\n```text\nIsPostalCode\n```\n\n```text\nzip\n```\n\n```text\n@ValidatorConstraint({ name: 'isPostalCodeByCountryCode', async: false })\n    class IsPostalCodeByCountryCode implements ValidatorConstraintInterface {\n      validate(zip: string, args: ValidationArguments): boolean {\n        return isPostalCode(zip, (args.object as any).countryCode);\n      }\n    \n      defaultMessage(args: ValidationArguments): string {\n        return `Invalid zip \"${(args.object as any).zip}\" for country \"${(args.object as any).countryCode}\"`;\n      }\n    }\n```\n\n```text\n@Validate(IsPostalCodeByCountryCode)\n  public zip: string;\n```\n\n```text\nValidate\n```\n\n```text\nzip\n```\n\n```text\ncountryCode\n```\n\n```text\nimport {\n  ValidationOptions,\n  registerDecorator,\n  ValidationArguments,\n  buildMessage,\n} from 'class-validator';\n/**\n* Install validator package from npm. class-validator uses validator under the \n* hood\n*/\nimport {isISO31661Alpha2,isPostalCode} from 'validator';\n\nexport function IsPostalCodeOf(\n  property: string,\n  validationOptions?: ValidationOptions,\n) {\n  // eslint-disable-next-line @typescript-eslint/ban-types\n  return function(object: Object, propertyName: string) {\n    registerDecorator({\n      name: 'isPostalCodeOf',\n      target: object.constructor,\n      propertyName: propertyName,\n      constraints: [property],\n      options: validationOptions,\n      validator: {\n        validate(value: any, args: ValidationArguments) {\n          // Getting the country code field from the argument.\n          // countryCode field from SignupDto\n          const [countryCodeField] = args.constraints;\n          // Getting the value of the countryCode Field\n          const countryCode = (args.object as any)[countryCodeField];\n          // Checking if the country code is valid even though it is checked \n          // at class level \n          if (!isISO31661Alpha2(countryCode)) {\n          // Invalid county code\n            return false;\n          }\n          // Checks if the value (zip) belongs in the extracted countryCode \n          // field\n          return isPostalCode(value,countryCode);\n        },\n        // Specifiy your error message here.\n        defaultMessage: buildMessage(\n          eachPrefix =>\n            `${eachPrefix} $property must be a valid postal \n             code in the specified country `,\n          validationOptions,\n        ),\n      },\n    });\n  };\n}\n```\n\n```text\nexport class SignupDto {\n  @IsEmail()\n  email: string\n\n  @IsString()\n  password: string\n\n  @IsISO31661Alpha2()\n  countryCode: string\n\n  @IsPostalCodeOf('countryCode')\n  zip: string\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":248,"estimatedTokens":1343}}664{"id":"stack-65910928","source":"stackoverflow","questionId":65910928,"title":"Nest JS Guards - Use one of two strategies","tags":["javascript","typescript","nestjs"],"text":"Title: Nest JS Guards - Use one of two strategies\nTags: javascript, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy app has two JWT based strategies:\n\n- Single sign on for my organization and its members. An external provider creates a JWT for this case.\n\n- Email/Password authenticated external users. My app creates a JWT for this case.\n\nOn any given route, I only need one of these to succeed to allow access. The problem is that if multiple guards are declared, then ALL guards must succeed.\n\nFor example, this would require both guards to succeed, but only one will ever succeed.\n\n```\n@UseGuards(AuthGuard('local-jwt'))\n@UseGuards(AuthGuard('azure-ad'))\nsomeRoute(\n @CurrentUser currentUser: User,\n) {\n //...\n}\n```\n\nOn this issue, I found this snippet:\n\n```\n@Injectable()\nexport class ComposeGuard implements CanActivate {\n constructor(private allowGuard: AllowGuard, private authGuard: AuthGuard, private roleGuard: RoleGuard) {\n }\n\n async canActivate(context: ExecutionContext): Promise {\n return await this.allowGuard.canActivate(context) || (await this.authGuard.canActivate(context) && await this.roleGuard.canActivate(context));\n }\n}\n```\n\nThis seems to allow the custom logic I need, but I have no idea how to import the guards as dependencies. A guard does not seem to be a class, so it's valid for dependency injection. And a strategy is a class, but does not have a `canActivate` method.\n\nThe other option I found was to make one strategy inherit from the other. But that's an ugly semantic mess since they are parallel, and do not depend on one another at all.\n\n========================================\n\nCode:\n```text\n@UseGuards(AuthGuard('local-jwt'))\n@UseGuards(AuthGuard('azure-ad'))\nsomeRoute(\n  @CurrentUser currentUser: User,\n) {\n  //...\n}\n```\n\n```text\n@Injectable()\nexport class ComposeGuard implements CanActivate {\n  constructor(private allowGuard: AllowGuard, private authGuard: AuthGuard, private roleGuard: RoleGuard) {\n  }\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    return await this.allowGuard.canActivate(context) || (await this.authGuard.canActivate(context) &&  await this.roleGuard.canActivate(context));\n  }\n}\n```\n\n```text\ncanActivate\n```\n\n```text\n@UseGuards(AuthGuard(['strategy1', 'strategy2']))\n```\n\n========================================\n\nComments:\n- How about multiple global guards? Is there a way to make them work like that?\n- I have an `OrGuard` package that allows for something like that\n- Thanks! Great help! That one should really be part of the Nest.JS core.","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":82,"estimatedTokens":637}}665{"id":"stack-63585893","source":"stackoverflow","questionId":63585893,"title":"GraphQL + NestJS - how can I access @Args in a guard?","tags":["graphql","nestjs","guard","args"],"text":"Title: GraphQL + NestJS - how can I access @Args in a guard?\nTags: graphql, nestjs, guard, args\nSource: Stack Overflow\n\nQuestion:\nI need the to somehow access the `objectId` from `@Args` inside the guard so as to check if the sender has the `objectId` assigned to his account. Any idea how I could implement it?\n\n```\n@Query(() => [Person])\n @UseGuards(ObjectMatch)\n async pplWithObject(@Args('objectId') id: string): Promise {\n return await this.objService.getPeopleWithObject(id);\n }\n```\n\nIs it possible to access the passed argument from the context?\n\n```\nconst ctx = GqlExecutionContext.create(context);\n const request = ctx.getContext().req;\n```\n\n========================================\n\nCode:\n```text\n@Query(() => [Person])\n      @UseGuards(ObjectMatch)\n      async pplWithObject(@Args('objectId') id: string): Promise<Person[]> {\n        return await this.objService.getPeopleWithObject(id);\n      }\n```\n\n```text\nconst ctx = GqlExecutionContext.create(context);\n    const request = ctx.getContext().req;\n```\n\n```text\nobjectId\n```\n\n```text\n@Args\n```\n\n```text\nobjectId\n```\n\n```js\nconst ctx = GqlExecutionContext.create(context);\nconsole.log(ctx.getArgs()) // object with your query args\nctx.getArgs()['objectId']\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":55,"estimatedTokens":306}}666{"id":"stack-66956387","source":"stackoverflow","questionId":66956387,"title":"Nestjs e2e testing of an application within a monorepo fails to resolve @app import from library with jest despite config in package.json","tags":["jestjs","nestjs","nestjs-testing"],"text":"Title: Nestjs e2e testing of an application within a monorepo fails to resolve @app import from library with jest despite config in package.json\nTags: jestjs, nestjs, nestjs-testing\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run e2e tests for a monorepo application that also utilises several libraries from within the monorepo, all imports throughout the application are resolved using \"@app\" imports, for example `import { ConfigService } from \"@app/config\"`\n\nHowever, when trying to run e2e tests via the command:\n\n```\n\"test:public\": \"jest --config ./apps/public-microservice/test/jest-e2e.json\",\n```\n\nJest throws:\n\n```\nCannot find module '@app/config' from '../src/public-microservice.module.ts'\n```\n\nI've looked at this demo-repo from @jmcdo29 and can't find anything that is different with my configuration.\n\nI've noticed there was an issue about wrong configurations being generated via jest here in 2019, but it has long been resolved, and my configuration for jest in package.json does indeed mention:\n\n```\n\"moduleNameMapper\": {\n \"@app/config/(.*)\": \"/libs/config/src/$1\",\n \"@app/config\": \"/libs/config/src\",\n```\n\nwhilst the local targeted file by the package.json script command only contains:\n\n```\n{\n \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n \"rootDir\": \".\",\n \"testEnvironment\": \"node\",\n \"testRegex\": \".e2e-spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n }\n}\n```\n\nIs there something that's missing from my command or my configuration?\n\nIs there anything I need to specify to tell jest to extend the configuration for jest available in package.json?\n\nAny help investingating this is appreciated, thanks.\n\n========================================\n\nTop Answer:\nInstead of using the generated e2e suite config file, we can use the jest cli to override the `testRegex` value in package.json which is used for the unit tests.\n\nIn `package.json` change the `test:e2e script` like this:\n\n```\n\"test:e2e\": \"jest --testRegex .e2e-spec.ts$\"\n```\n\nNow you don't have to use an external config for e2e testing, the config as defined in package.json is used for both unit and e2e tests now and only the testRegex is overriden to target e2e tests instead of unit tests when `npm run test:e2e` is called.\n\nThis way you only have to configure moduleNameMappers once in package.json.\n\n========================================\n\nCode:\n```text\n\"test:public\": \"jest --config ./apps/public-microservice/test/jest-e2e.json\",\n```\n\n```text\nCannot find module '@app/config' from '../src/public-microservice.module.ts'\n```\n\n```text\n\"moduleNameMapper\": {\n      \"@app/config/(.*)\": \"<rootDir>/libs/config/src/$1\",\n      \"@app/config\": \"<rootDir>/libs/config/src\",\n```\n\n```text\n{\n  \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n  \"rootDir\": \".\",\n  \"testEnvironment\": \"node\",\n  \"testRegex\": \".e2e-spec.ts$\",\n  \"transform\": {\n    \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n  }\n}\n```\n\n```text\nimport { ConfigService } from \"@app/config\"\n```\n\n```json\n\"moduleNameMapper\": {\n    \"@app/config/(.*)\": \"<rootDir>../../../libs/config/src/$1\",\n    \"@app/config\": \"<rootDir>../../../libs/config/src\",\n  },\n```\n\n```text\n\"test:e2e\": \"jest --testRegex .e2e-spec.ts$\"\n```\n\n```text\ntestRegex\n```\n\n```text\npackage.json\n```\n\n```text\ntest:e2e script\n```\n\n```text\nnpm run test:e2e\n```\n\n========================================\n\nComments:\n- did you solve this problem?\n- yep, I had to copy & update the `jest.moduleNameMapper` value from package.json into the specific test configuration at `&#47;apps&#47;public-microservice&#47;test&#47;jest-e2e.json`--- the CLI only updates the package.json values, not the individual e2e test as you add libs & apps\n- @SebastianG could you please add answer with correct configuration please?\n- @Sergii added an answer with my specific case\n- I simplified this to `\"moduleNameMapper\": { \"@app&#47;(.*)\": \"..&#47;..&#47;..&#47;libs&#47;$1&#47;src\" }`and now it works for every library","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":132,"estimatedTokens":970}}667{"id":"stack-52419933","source":"stackoverflow","questionId":52419933,"title":"Nest can't resolve dependencies of the service which imports JwtService","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Nest can't resolve dependencies of the service which imports JwtService\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to use @nestjs/jwt. Particularly its `registerAsync` method (my config service loads the configuration asynchronously). I am registering `JwtModule` in the `AuthModule`, which then loads specific modules for each login/registration providers. Then I add `JwtService` to the providers of `EmailService` but it fails.\n\nThe structure of the application is as follows (very schematic):\n\n**app.module.ts**\n\n```\n@Module({\n imports: [\n AuthModule,\n ...\n ]\n})\nexport class ApplicationModule {}\n```\n\n**auth.module.ts**\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.registerAsync({\n useFactory: async (config: ConfigService) => ({\n secretOrPrivateKey: config.get('jwt.secret')\n }),\n inject: [ConfigService]\n }),\n EmailAuthModule\n ],\n exports: [JwtModule]\n})\nexport class AuthModule {}\n```\n\n**email.module.ts**\n\n```\n@Module({\n imports: [...],\n controllers: [...],\n providers: [EmailService, ...]\n})\nexport class EmailAuthModule {}\n```\n\n**email.service.ts**\n\n```\n@Injectable()\nexport class EmailService {\n constructor(\n private readonly jwtService: JwtService\n ) {}\n}\n```\n\nApplication fails with this error upon startup:\n\n```\nNest can't resolve dependencies of the EmailService (UsersService, ?). Please make sure that the argument at index [1] is available in the current context. +70ms\nError: Nest can't resolve dependencies of the EmailService (UsersService, ?). Please make sure that the argument at index [1] is available in the current context.\n at Injector.lookupComponentInExports (/Users/.../api/node_modules/@nestjs/core/injector/injector.js:146:19)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)\n at Object. (/Users/.../api/node_modules/ts-node/src/_bin.ts:177:12)\n at Module._compile (internal/modules/cjs/loader.js:689:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n at Module.load (internal/modules/cjs/loader.js:599:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n at Function.Module._load (internal/modules/cjs/loader.js:530:3)\n at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)\n```\n\nWhat did I miss?\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    AuthModule,\n    ...\n  ]\n})\nexport class ApplicationModule {}\n```\n\n```text\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.registerAsync({\n      useFactory: async (config: ConfigService) => ({\n        secretOrPrivateKey: config.get('jwt.secret')\n      }),\n      inject: [ConfigService]\n    }),\n    EmailAuthModule\n  ],\n  exports: [JwtModule]\n})\nexport class AuthModule {}\n```\n\n```text\n@Module({\n  imports: [...],\n  controllers: [...],\n  providers: [EmailService, ...]\n})\nexport class EmailAuthModule {}\n```\n\n```text\n@Injectable()\nexport class EmailService {\n  constructor(\n    private readonly jwtService: JwtService\n  ) {}\n}\n```\n\n```text\nNest can't resolve dependencies of the EmailService (UsersService, ?). Please make sure that the argument at index [1] is available in the current context. +70ms\nError: Nest can't resolve dependencies of the EmailService (UsersService, ?). Please make sure that the argument at index [1] is available in the current context.\n    at Injector.lookupComponentInExports (/Users/.../api/node_modules/@nestjs/core/injector/injector.js:146:19)\n    at process._tickCallback (internal/process/next_tick.js:68:7)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)\n    at Object.<anonymous> (/Users/.../api/node_modules/ts-node/src/_bin.ts:177:12)\n    at Module._compile (internal/modules/cjs/loader.js:689:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)\n    at Module.load (internal/modules/cjs/loader.js:599:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:530:3)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)\n```\n\n```text\nregisterAsync\n```\n\n```text\nJwtModule\n```\n\n```text\nAuthModule\n```\n\n```text\nJwtService\n```\n\n```text\nEmailService\n```\n\n```text\nEmailService\n```\n\n```text\nJwtService\n```\n\n```text\nEmailAuthModule\n```\n\n```text\nJwtService\n```\n\n```text\nJwtService\n```\n\n```text\nEmailAuthModule\n```\n\n```text\nimports\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtModule\n```\n\n```text\nEmailAuthModule\n```\n\n========================================\n\nComments:\n- Possible duplicate of Nest js cannot resolve dependencies. in Auth service","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":208,"estimatedTokens":1176}}668{"id":"stack-67314814","source":"stackoverflow","questionId":67314814,"title":"How to expose in different ports some of the NestJS application routes","tags":["routes","port","nestjs"],"text":"Title: How to expose in different ports some of the NestJS application routes\nTags: routes, port, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS application that is served in one specific port, but I need to expose some of the routes (in example Prometheus metrics /metrics) with other port.\n\nIs possible to do it within a NestJS application?\n\n========================================\n\nCode:\n```js\nasync function bootstrap() {\n  // module with the selected endpoints\n  const firstApp = await NestFactory.create(FirstAppModule);\n  await firstApp.listen(3001);\n  // module with different endpoints\n  const secondApp = await NestFactory.create(SecondAppModule);\n  await secondApp.listen(3002);\n}\n```\n\n========================================\n\nComments:\n- The specific route was in the same main module, but I will extract it in order to make it available in a different port.","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":27,"estimatedTokens":221}}669{"id":"stack-66422241","source":"stackoverflow","questionId":66422241,"title":"How to add DTO in NestJS","tags":["typescript","nestjs"],"text":"Title: How to add DTO in NestJS\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a simple app using `nestjs`.\n\nWhen I add `CreateUserDTO` in `UserService` I get following TS error.\n\nsrc/user/user.service.ts:11:40 - error TS2345: Argument of type 'CreateUserDTO' is not assignable to parameter of type 'User'.\nType 'CreateUserDTO' is missing the following properties from type 'User': $add, $set, $get, $count, and 32 more.\n11 return await this.userModel.create(userData);\n\nI checked a lot of codes about DTO, but I don't know the reason.\n\nHere is code.\n\n```\nimport { Column, Model, PrimaryKey, Table } from 'sequelize-typescript';\n\n@Table\nexport class User extends Model {\n @PrimaryKey\n @Column\n userId: string;\n\n @Column\n name: string;\n}\n```\n\n```\nexport class CreateUserDTO {\n userId: string;\n name: string;\n}\n```\n\n```\n@Injectable()\nexport class UserService {\n constructor(@InjectModel(User) private userModel: typeof User) {}\n\n async createUser(userData: CreateUserDTO) {\n const user = await this.userModel.create(userData);\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou should convert your DTO to your model typeORM dont do that, just work with the models.\n\nSee my api with nestjs, https://github.com/Malagutte/lottery-domain-api/blob/main/src/game/game.service.ts#L83\n\n========================================\n\nCode:\n```js\nimport { Column, Model, PrimaryKey, Table } from 'sequelize-typescript';\n\n@Table\nexport class User extends Model<User> {\n  @PrimaryKey\n  @Column\n  userId: string;\n\n  @Column\n  name: string;\n}\n```\n\n```js\nexport class CreateUserDTO {\n  userId: string;\n  name: string;\n}\n```\n\n```js\n@Injectable()\nexport class UserService {\n  constructor(@InjectModel(User) private userModel: typeof User) {}\n\n  async createUser(userData: CreateUserDTO) {\n    const user = await this.userModel.create<User>(userData);\n  }\n}\n```\n\n```text\nnestjs\n```\n\n```text\nCreateUserDTO\n```\n\n```text\nUserService\n```\n\n```js\nexport class CreateUserDto {\n  firstName: string;\n\n  lastName: string;\n\n  email: string;\n\n  password: string;\n}\n```\n\n```js\nimport { CreateUserDto } from './dto/create-user.dto';\n\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  public async createUser(@Body() user: CreateUserDto) {\n    await this.usersService.register(user);\n  }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { UsersEntity } from './users.entity';\nimport { CreateUserDto } from './dto/create-user.dto';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n  constructor(private readonly usersRepository: UsersRepository) {}\n  \n  public async register(user: CreateUserDto): Promise<UsersEntity> {\n    return this.usersRepository.save({ ...user });\n  }\n}\n```\n\n```text\nextends Model<User>\n```\n\n```text\ncreate-user.dto.ts\n```\n\n```text\nusers.controller.ts\n```\n\n```text\nusers.service.ts\n```\n\n========================================\n\nComments:\n- When I delete ``, it works. Thank you\n- Yes, you were extending the `User` methods from TypeOrm. You'r welcome !","metadata":{"transformedAt":"2026-08-18T18:33:02.460Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":164,"estimatedTokens":774}}670{"id":"stack-70747462","source":"stackoverflow","questionId":70747462,"title":"NestJS - Nested polymorphism in sub schema","tags":["mongoose","polymorphism","nestjs","mongoose-schema"],"text":"Title: NestJS - Nested polymorphism in sub schema\nTags: mongoose, polymorphism, nestjs, mongoose-schema\nSource: Stack Overflow\n\nQuestion:\nIn NestJs, I am trying to let mongoose create a document based on a schema of which one of its properties can have different types. However, when I am saving the document, all the properties related to a specific type are lost. What am I missing? For simplicity reasons in this snippet I used an array of strings instead of typing out the enum\n\n```\n@Schema()\nexport class ClassAModel {\n @Prop({ type: ClassBSchema, required: true })\n object!: ClassB1Model | ClassB2Model\n}\n\nexport const ClassASchema = SchemaFactory.createForClass(ClassAModel)\n\n///\n@Schema({ _id: false })\nexport class ClassB1Model {\n @Prop({ enum: ['B1'], required: true })\n type!: 'B1'\n \n @Prop({ required: true })\n onlyForClassB1Model!: string\n}\n\nexport const ClassB1Schema = SchemaFactory.createForClass(ClassB1Model)\n\n///\n@Schema({ _id: false })\nexport class ClassB2Model {\n @Prop({ enum: ['B2'], required: true })\n type!: 'B2'\n \n @Prop({ required: true })\n onlyForClassB2Model!: string\n}\n\nexport const ClassB2Schema = SchemaFactory.createForClass(ClassB2Model)\n\n///\n@Schema({ _id: false, discriminatorKey: 'type' })\nexport class ClassBModel {\n @Prop({ enum: ['B1', 'B2'], required: true })\n type!: 'B1' | 'B2'\n}\n\nexport const ClassBSchema = SchemaFactory.createForClass(ClassBModel)\n\nClassBSchema.discriminators = {\n B1: ClassB1Schema,\n B2: ClassB2Schema,\n}\n```\n\nWhen I try to save the document using the model instance, it only saved the props that are defined in ClassBModel (so only type). All other props are not being picked up.\n\n```\n// some class method\n public async saveDoc(): Promise {\n const payload = {\n object: {\n type: 'B2',\n onlyForClassB2Model: 'random string'\n }\n }\n return this.model.create(payload) // yields { object: { type: 'B2' } }\n }\n```\n\nI know that discriminators for top level documents can be defined as described in the NestJSDocs, using discrimimators in the nestjs module, but this is a different case where the discriminators are inside of the injected model. How can I make mongoose recognise that it needs to save all the properties from the payload?\n\n========================================\n\nTop Answer:\nI faced the same issue and based on @ant_hony 's research did a utility function that simplifies that if you have lots of similar cases in your project. Just leaving it here, maybe it helps someone ๐Ÿ™‚๐Ÿคž\n\n```\nimport { DiscriminatorOptions } from '@nestjs/mongoose/dist/interfaces/model-definition.interface';\ntype TClass = new (...args: any[]) => T;\n\nfunction initDiscriminators(rootClass: T, path: string, discriminators: DiscriminatorOptions[]): Schema {\n const root = SchemaFactory.createForClass(rootClass);\n const child = root.path(path);\n\n discriminators.forEach((discriminator) => {\n child['discriminator'](discriminator.name, discriminator.schema);\n });\n\n return root;\n}\n```\n\nhaving this usage is pretty simple:\n\n```\nconst ClassASchema = initDiscriminators(ClassAModel, 'type', [\n { name: 'B1', schema: SchemaFactory.createForClass(ClassB1Model) },\n { name: 'B2', schema: SchemaFactory.createForClass(ClassB2Model) }\n]);\n```\n\n========================================\n\nCode:\n```text\n@Schema()\nexport class ClassAModel {\n  @Prop({ type: ClassBSchema, required: true })\n  object!: ClassB1Model | ClassB2Model\n}\n\nexport const ClassASchema = SchemaFactory.createForClass(ClassAModel)\n\n///\n@Schema({ _id: false })\nexport class ClassB1Model  {\n  @Prop({ enum: ['B1'], required: true  })\n  type!: 'B1'\n  \n  @Prop({ required: true  })\n  onlyForClassB1Model!: string\n}\n\nexport const ClassB1Schema = SchemaFactory.createForClass(ClassB1Model)\n\n///\n@Schema({ _id: false })\nexport class ClassB2Model  {\n  @Prop({ enum: ['B2'], required: true  })\n  type!: 'B2'\n  \n  @Prop({ required: true })\n  onlyForClassB2Model!: string\n}\n\nexport const ClassB2Schema = SchemaFactory.createForClass(ClassB2Model)\n\n///\n@Schema({ _id: false, discriminatorKey: 'type' })\nexport class ClassBModel {\n  @Prop({ enum: ['B1', 'B2'], required: true  })\n  type!: 'B1' | 'B2'\n}\n\nexport const ClassBSchema = SchemaFactory.createForClass(ClassBModel)\n\nClassBSchema.discriminators = {\n  B1: ClassB1Schema,\n  B2: ClassB2Schema,\n}\n```\n\n```text\n// some class method\n public async saveDoc(): Promise<void> {\n   const payload = {\n     object: {\n       type: 'B2',\n       onlyForClassB2Model: 'random string'\n     }\n   }\n   return this.model.create(payload) // yields { object: { type: 'B2' } }\n }\n```\n\n```js\nimport { Schema as MongooseSchema } from 'mongoose'\n\n@Schema()\nexport class ClassAModel {\n  @Prop({ type: ClassBSchema, required: true })\n  object!: ClassB1Model | ClassB2Model\n}\n\nexport const ClassASchema = SchemaFactory.createForClass(ClassAModel)\nconst classBSchema = ClassASchema.path<MongooseSchema.Types.Embedded>('object')\nclassBSchema.discriminator('B1', ClassB1Schema)\nclassBSchema.discriminator('B2', ClassB2Schema)\n```\n\n```js\n///\n@Schema({ _id: false })\nexport class ClassB1Model  {\n  type!: 'B1'\n  \n  @Prop({ required: true  })\n  onlyForClassB1Model!: string\n}\n\nexport const ClassB1Schema = SchemaFactory.createForClass(ClassB1Model)\n\n///\n@Schema({ _id: false })\nexport class ClassB2Model  {\n  type!: 'B2'\n  \n  @Prop({ required: true })\n  onlyForClassB2Model!: string\n}\n```\n\n```js\n@Schema({ _id: false, discriminatorKey: 'type' })\nexport class ClassBModel {\n  @Prop({ enum: ['B1', 'B2'], required: true  })\n  type!: 'B1' | 'B2'\n}\n\nexport const ClassBSchema = SchemaFactory.createForClass(ClassBModel)\n```\n\n```text\ndiscriminators\n```\n\n```text\nimport { DiscriminatorOptions } from '@nestjs/mongoose/dist/interfaces/model-definition.interface';\ntype TClass<T = any> = new (...args: any[]) => T;\n\nfunction initDiscriminators<T extends TClass>(rootClass: T, path: string, discriminators: DiscriminatorOptions[]): Schema<T> {\n    const root = SchemaFactory.createForClass(rootClass);\n    const child = root.path(path);\n\n    discriminators.forEach((discriminator) => {\n        child['discriminator'](discriminator.name, discriminator.schema);\n    });\n\n    return root;\n}\n```\n\n```text\nconst ClassASchema = initDiscriminators(ClassAModel, 'type', [\n  { name: 'B1', schema: SchemaFactory.createForClass(ClassB1Model) },\n  { name: 'B2', schema: SchemaFactory.createForClass(ClassB2Model) }\n]);\n```\n\n========================================\n\nComments:\n- A sloppy way would just to define all properties in a single model and then make the all subtype properties optional, but I definitely prefer to just have the different subtypes defined clearly in the mongoose schemas\n- what you mean here > For simplicity reasons in this snippet I used an array of strings instead of typing out the enum can u give more details abt the original use case? I've been looking for this solution for ages\n- thank you! This should really be a part of the official documentation. I feel its a pretty common use case and it was incredibly difficult to find this answer. docs.nestjs.com/techniques/mongodb#discriminators github.com/nestjs/nest/issues/9313\n- The type 'Schema.Types.Embedded' doesn't exist. Might this be version specific? I'm using version 8.2.0","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":247,"estimatedTokens":1790}}671{"id":"stack-65500666","source":"stackoverflow","questionId":65500666,"title":"How do I access context and args in resolver at the same time?","tags":["javascript","nestjs"],"text":"Title: How do I access context and args in resolver at the same time?\nTags: javascript, nestjs\nSource: Stack Overflow\n\nQuestion:\nThis is an example of a resolver in my nestJS application (using graphQL):\n\nIn the first query I'm accessing the context, in the second one I'm accessing the args via decorator.\n\n```\nimport { Args, Query, Resolver } from '@nestjs/graphql'\n\n@Resolver('List')\nexport class ListResolvers {\n constructor(private readonly listService: ListService) {}\n\n @Query(() => [Data])\n async getList(obj, args, context) {\n const token = context.token\n return this.listService.getList(token)\n }\n\n @Query(() => [Data])\n async getList(\n @Args('param') param: GetListParam\n ): Promise> {\n return this.listService.getList(param)\n }\n}\n```\n\nBut I do need to pass both: `param` and `token`:\n\n```\nreturn this.listService.searchList(param, token)\n```\n\nHow do I access the context in the second query (the one using `@Args`)?\n\n========================================\n\nCode:\n```text\nimport { Args, Query, Resolver } from '@nestjs/graphql'\n\n@Resolver('List')\nexport class ListResolvers {\n  constructor(private readonly listService: ListService) {}\n\n  @Query(() => [Data])\n  async getList(obj, args, context) {\n    const token = context.token\n    return this.listService.getList(token)\n  }\n\n  @Query(() => [Data])\n  async getList(\n    @Args('param') param: GetListParam\n  ): Promise<Array<Data>> {\n    return this.listService.getList(param)\n  }\n}\n```\n\n```text\nreturn this.listService.searchList(param, token)\n```\n\n```text\nparam\n```\n\n```text\ntoken\n```\n\n```text\n@Args\n```\n\n```text\nimports: [\nGraphQLModule.forRoot({ ..., context: ({req}) => ({req})})\n]\n```\n\n```text\n@Query(() => [Data])\n  async getList(\n    @Args('param') param: GetListParam,\n    @Context('req') req\n  ): Promise<Array<Data>> {\n    const token = req.headers.authorization;\n    return this.listService.getList(param)\n  }\n```\n\n========================================\n\nComments:\n- From where do I get `@Context` and `req`? I already set `context: ({ req }) => ({ token: req.headers.authorization })` in the app.modules.ts\n- @user3142695 What do you mean from where? just import Context from @nestjs/graphql, and use it in resolver like this `@Context('token') token`. This should work","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":102,"estimatedTokens":562}}672{"id":"stack-71659168","source":"stackoverflow","questionId":71659168,"title":"why and when we should use `autoLoadEntities` in nestjs Typeorm","tags":["nestjs","typeorm"],"text":"Title: why and when we should use `autoLoadEntities` in nestjs Typeorm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am curious to know that why and when we should use `autoLoadEntities` in nestjs Typeorm.\n\n========================================\n\nCode:\n```text\nautoLoadEntities\n```\n\n```text\nautoLoadEntities\n```\n\n```text\nforRoot()\n```\n\n```text\ntrue\n```\n\n```text\nglob\n```\n\n```text\nentity\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":33,"estimatedTokens":101}}673{"id":"stack-66003386","source":"stackoverflow","questionId":66003386,"title":"How to get IP address from request context nestjs?","tags":["typescript","nestjs"],"text":"Title: How to get IP address from request context nestjs?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to build simple authentication using IP addresses, some IP address that I whitelisted can access the API. But I got a problem when I use `request.ip` it only output `::1` which is not a real IP address.\n\nHow to get the user IP Address in nestjs? Here are my code right now\n\n```\nimport {\n Injectable,\n CanActivate,\n ExecutionContext,\n Logger,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n canActivate(\n context: ExecutionContext,\n ): boolean | Promise | Observable {\n const request = context.switchToHttp().getRequest();\n const allowedIp: Array = ['129.2.2.2', '129.2.2.2'];\n if (process.env.ENV === 'production') {\n const ip = request.connection.remoteAddress;\n Logger.log(ip, 'ACCESSED IP ADDRESS');\n if (allowedIp.includes(ip)) {\n return true;\n } else {\n return false;\n }\n } else {\n return true;\n }\n }\n}\n```\n\nEdit:\n\nTurns out that `::1` are valid address for 'localhost' but when I deploy it on server and access the app from browser its log `::ffff:127.0.0.1` not my real IP.\n\n========================================\n\nTop Answer:\n```\nasync tokenByUserData(@Context() context, @Args('token') token: string) {\n const {\n req: { user, ip },\n } = context;\n console.log({ ip });\n const { userId } = user || {};\n enter code here\n```\n\nhere u can get ip and ::1 for localhost`enter code here`\n\n========================================\n\nCode:\n```text\nimport {\n  Injectable,\n  CanActivate,\n  ExecutionContext,\n  Logger,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  canActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const allowedIp: Array<string> = ['129.2.2.2', '129.2.2.2'];\n    if (process.env.ENV === 'production') {\n      const ip = request.connection.remoteAddress;\n      Logger.log(ip, 'ACCESSED IP ADDRESS');\n      if (allowedIp.includes(ip)) {\n        return true;\n      } else {\n        return false;\n      }\n    } else {\n      return true;\n    }\n  }\n}\n```\n\n```text\nrequest.ip\n```\n\n```text\n::1\n```\n\n```text\n::1\n```\n\n```text\n::ffff:127.0.0.1\n```\n\n```text\nX-Forwarded-For\n```\n\n```text\nnginx\n```\n\n```text\n::1\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nasync tokenByUserData(@Context() context, @Args('token') token: string) {\n    const {\n      req: { user, ip },\n    } = context;\n    console.log({ ip });\n    const { userId } = user || {};\n    enter code here\n```\n\n```text\nenter code here\n```\n\n========================================\n\nComments:\n- Is there a way to handle this for both proxied and non-proxied environments? I've looked at this question but typescript complains about `string | string[]` when I try to remove the IPv6 mask (`::ffff:x.x.x.x`). Using a type guard was mentioned, but I'm sure there's an elegant, straightforward solution I'm missing","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":147,"estimatedTokens":768}}674{"id":"stack-58437564","source":"stackoverflow","questionId":58437564,"title":"npm run start:dev cannot find module","tags":["nestjs","typeorm"],"text":"Title: npm run start:dev cannot find module\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nnpm run start works fine, but npm run start: dev throws this error:\n\n```\n7:14:22 PM - Found 0 errors. Watching for file changes.\ninternal/modules/cjs/loader.js:638\nthrow err;\n^\nError: Cannot find module 'src/models/note.model'\nat Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)\nat Function.Module._load (internal/modules/cjs/loader.js:562:25)\nat Module.require (internal/modules/cjs/loader.js:692:17)\nat require (internal/modules/cjs/helpers.js:25:18)\nat Object. (C:\\Users\\Anuitex-169\\Desktop\\VersF\\nest\\server\\dist\\note\\note.service.js:17:22)\nat Module._compile (internal/modules/cjs/loader.js:778:30)\nat Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\nat Module.load (internal/modules/cjs/loader.js:653:32)\nat tryModuleLoad (internal/modules/cjs/loader.js:593:12)\nat Function.Module._load (internal/modules/cjs/loader.js:585:3)\n```\n\nThis error appeared from the very beginning of my project, and I canโ€™t understand why. I decided to forget about this problem since npm run start works well. But somehow uncomfortable (\n\nMy app.module.ts\nMy package.json file:\n\n```\n{\n \"name\": \"server\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"rimraf dist && tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n \"start:dev\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node dist/main.js\\\"\",\n \"start:debug\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node --inspect-brk dist/main.js\\\"\",\n \"start:prod\": \"node dist/main.js\",\n \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"^6.0.0\",\n \"@nestjs/core\": \"^6.0.0\",\n \"@nestjs/platform-express\": \"^6.0.0\",\n \"@nestjs/typeorm\": \"^6.1.3\",\n \"mongodb\": \"^3.3.2\",\n \"path\": \"^0.12.7\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.3.3\",\n \"typeorm\": \"^0.2.19\"\n },\n \"devDependencies\": {\n \"@nestjs/testing\": \"^6.0.0\",\n \"@types/express\": \"4.16.1\",\n \"@types/jest\": \"24.0.11\",\n \"@types/multer\": \"^1.3.10\",\n \"@types/node\": \"11.13.4\",\n \"@types/supertest\": \"2.0.7\",\n \"jest\": \"24.7.1\",\n \"prettier\": \"1.17.0\",\n \"supertest\": \"4.0.2\",\n \"ts-jest\": \"24.0.2\",\n \"ts-node\": \"8.1.0\",\n \"tsc-watch\": \"2.2.1\",\n \"tsconfig-paths\": \"3.8.0\",\n \"tslint\": \"5.16.0\",\n \"typescript\": \"3.4.3\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \".\",\n \"roots\": [\n \"/src/\",\n \"/libs/\",\n \"/apps/\"\n ],\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"./coverage\",\n \"testEnvironment\": \"node\"\n }\n }\n```\n\nPlease help me deal with this problem.\n\n========================================\n\nCode:\n```text\n7:14:22 PM - Found 0 errors. Watching for file changes.\ninternal/modules/cjs/loader.js:638\nthrow err;\n^\nError: Cannot find module 'src/models/note.model'\nat Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)\nat Function.Module._load (internal/modules/cjs/loader.js:562:25)\nat Module.require (internal/modules/cjs/loader.js:692:17)\nat require (internal/modules/cjs/helpers.js:25:18)\nat Object.<anonymous> (C:\\Users\\Anuitex-169\\Desktop\\VersF\\nest\\server\\dist\\note\\note.service.js:17:22)\nat Module._compile (internal/modules/cjs/loader.js:778:30)\nat Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\nat Module.load (internal/modules/cjs/loader.js:653:32)\nat tryModuleLoad (internal/modules/cjs/loader.js:593:12)\nat Function.Module._load (internal/modules/cjs/loader.js:585:3)\n```\n\n```text\n{\n      \"name\": \"server\",\n      \"version\": \"0.0.1\",\n      \"description\": \"\",\n      \"author\": \"\",\n      \"license\": \"MIT\",\n      \"scripts\": {\n        \"build\": \"rimraf dist && tsc -p tsconfig.build.json\",\n        \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n        \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n        \"start:dev\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node dist/main.js\\\"\",\n        \"start:debug\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node --inspect-brk dist/main.js\\\"\",\n        \"start:prod\": \"node dist/main.js\",\n        \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n        \"test\": \"jest\",\n        \"test:watch\": \"jest --watch\",\n        \"test:cov\": \"jest --coverage\",\n        \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n        \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n      },\n      \"dependencies\": {\n        \"@nestjs/common\": \"^6.0.0\",\n        \"@nestjs/core\": \"^6.0.0\",\n        \"@nestjs/platform-express\": \"^6.0.0\",\n        \"@nestjs/typeorm\": \"^6.1.3\",\n        \"mongodb\": \"^3.3.2\",\n        \"path\": \"^0.12.7\",\n        \"reflect-metadata\": \"^0.1.12\",\n        \"rimraf\": \"^2.6.2\",\n        \"rxjs\": \"^6.3.3\",\n        \"typeorm\": \"^0.2.19\"\n      },\n      \"devDependencies\": {\n        \"@nestjs/testing\": \"^6.0.0\",\n        \"@types/express\": \"4.16.1\",\n        \"@types/jest\": \"24.0.11\",\n        \"@types/multer\": \"^1.3.10\",\n        \"@types/node\": \"11.13.4\",\n        \"@types/supertest\": \"2.0.7\",\n        \"jest\": \"24.7.1\",\n        \"prettier\": \"1.17.0\",\n        \"supertest\": \"4.0.2\",\n        \"ts-jest\": \"24.0.2\",\n        \"ts-node\": \"8.1.0\",\n        \"tsc-watch\": \"2.2.1\",\n        \"tsconfig-paths\": \"3.8.0\",\n        \"tslint\": \"5.16.0\",\n        \"typescript\": \"3.4.3\"\n      },\n      \"jest\": {\n        \"moduleFileExtensions\": [\n          \"js\",\n          \"json\",\n          \"ts\"\n        ],\n        \"rootDir\": \".\",\n        \"roots\": [\n          \"<rootDir>/src/\",\n          \"<rootDir>/libs/\",\n          \"<rootDir>/apps/\"\n        ],\n        \"testRegex\": \".spec.ts$\",\n        \"transform\": {\n          \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n        },\n        \"coverageDirectory\": \"./coverage\",\n        \"testEnvironment\": \"node\"\n      }\n    }\n```\n\n```text\nat Object.<anonymous> (C:\\Users\\Anuitex-169\\Desktop\\VersF\\nest\\server\\dist\\note\\note.service.js:17:22)\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\nsrc/models/note.model\n```\n\n```text\n../models/note.model\n```\n\n========================================\n\nComments:\n- Jay is very close I believe. Most likely very similar issue: stackoverflow.com/a/57964735/4319037 (both are about dist/dev and correctly locating entities; please note a bit different regexp). Does your `build` run correctly?\n- The glob actually looks correct in this case, using dirname instead of a hardcoded src or dist, in just trying to the stack trace that says the note.service.js is trying to import from src/models/note.model","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":222,"estimatedTokens":1712}}675{"id":"stack-61854512","source":"stackoverflow","questionId":61854512,"title":"NestJS - TypeORM - ManyToOne Entity is undefined","tags":["typescript","entity","nestjs","typeorm","many-to-one"],"text":"Title: NestJS - TypeORM - ManyToOne Entity is undefined\nTags: typescript, entity, nestjs, typeorm, many-to-one\nSource: Stack Overflow\n\nQuestion:\nI am trying to link to entities `Child` & `Client`\n\nSo I have created 2 entities :\n\n```\n// src/children/child.entity.ts\n\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(type => Client, client => client.children, { eager: false })\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\nand \n\n```\n// src/clients/client.entity.ts\n\n@Entity()\nexport class Client extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @OneToMany(type => Child, child => child.client, { eager: true })\n children: Child[];\n\n}\n```\n\nI'm able to create a `client` & a `child`. When I get a `client`, I can retrieve all his `children`.\n\nBut I am not able to retrieve a `client` with a `child` : \n\nFor example, in `children.controller.ts`\n\nhttps://i.sstatic.net/QKIXK.png\n\nWhen I visit `http://locahost:3000/children/1/parent`\n\nI got on the console : \n\nhttps://i.sstatic.net/hZemK.png\n\nI am really stuck because I don't know how to solve this issue.\n\nHere is `children.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { ChildrenController } from './children.controller';\nimport { ChildrenService } from './children.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ChildRepository } from './child.repository';\nimport { ClientRepository } from 'src/clients/client.repository';\nimport { ClientsService } from 'src/clients/clients.service';\nimport { Client } from 'src/clients/client.entity';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([ChildRepository, ClientRepository, Client]),\n ],\n controllers: [ChildrenController],\n providers: [ChildrenService, ClientsService]\n})\nexport class ChildrenModule {}\n```\n\nHere is `typeorm.config`\n\n```\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'myusername',\n password: '',\n database: 'mydatabase',\n entities: [__dirname + '/../**/*.entity.{js,ts}'],\n synchronize: true,\n}\n```\n\n**Edit 1 :**\n\n`children.controller.ts`\n\n```\n// src/children/children.controller.ts\n\n@Controller('children')\nexport class ChildrenController {\n\n constructor(\n private childrenService: ChildrenService,\n private clientsService: ClientsService\n ) {}\n\n @Get('/:id')\n async getChild(id: number): Promise {\n return await this.childrenService.getChild(id);\n }\n}\n```\n\n`children.service.ts`\n\n```\n// src/children/children.service.ts\n\n@Injectable()\nexport class ChildrenService {\n constructor(\n @InjectRepository(ChildRepository)\n private childRepository: ChildRepository,\n @InjectRepository(ClientRepository)\n private clientRepository: ClientRepository\n ) {}\n\n async getChild(id: number): Promise {\n return await this.childRepository.findOne(id)\n }\n}\n```\n\nThanks for you help ๐Ÿ˜€\n\n========================================\n\nTop Answer:\nas @Yevhenii mention, you forgot to add JoinColumn but you have to specify the client column: \n\n```\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(()=> Client, (client) => client.children, { eager: false })\n @JoinColumn([{ name: \"clientId\", referencedColumnName: \"id\" }])\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\nDon't hesitate to tell me the result.\n\n========================================\n\nCode:\n```js\n// src/children/child.entity.ts\n\n@Entity()\nexport class Child extends BaseEntity {\n\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstname: string;\n\n  @Column()\n  lastname: string;\n\n  @ManyToOne(type => Client, client => client.children, { eager: false })\n  client: Client\n\n  @Column()\n  clientId: number;\n}\n```\n\n```js\n// src/clients/client.entity.ts\n\n@Entity()\nexport class Client extends BaseEntity {\n\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstname: string;\n\n  @Column()\n  lastname: string;\n\n  @OneToMany(type => Child, child => child.client, { eager: true })\n  children: Child[];\n\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ChildrenController } from './children.controller';\nimport { ChildrenService } from './children.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ChildRepository } from './child.repository';\nimport { ClientRepository } from 'src/clients/client.repository';\nimport { ClientsService } from 'src/clients/clients.service';\nimport { Client } from 'src/clients/client.entity';\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([ChildRepository, ClientRepository, Client]),\n  ],\n  controllers: [ChildrenController],\n  providers: [ChildrenService, ClientsService]\n})\nexport class ChildrenModule {}\n```\n\n```js\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n  type: 'postgres',\n  host: 'localhost',\n  port: 5432,\n  username: 'myusername',\n  password: '',\n  database: 'mydatabase',\n  entities: [__dirname + '/../**/*.entity.{js,ts}'],\n  synchronize: true,\n}\n```\n\n```js\n// src/children/children.controller.ts\n\n@Controller('children')\nexport class ChildrenController {\n\n  constructor(\n    private childrenService: ChildrenService,\n    private clientsService: ClientsService\n  ) {}\n\n  @Get('/:id')\n  async getChild(id: number): Promise<Child> {\n    return await this.childrenService.getChild(id);\n  }\n}\n```\n\n```js\n// src/children/children.service.ts\n\n@Injectable()\nexport class ChildrenService {\n  constructor(\n    @InjectRepository(ChildRepository)\n    private childRepository: ChildRepository,\n    @InjectRepository(ClientRepository)\n    private clientRepository: ClientRepository\n  ) {}\n\n  async getChild(id: number): Promise<Child> {\n    return await this.childRepository.findOne(id)\n  }\n}\n```\n\n```text\nChild\n```\n\n```text\nClient\n```\n\n```text\nclient\n```\n\n```text\nchild\n```\n\n```text\nclient\n```\n\n```text\nchildren\n```\n\n```text\nclient\n```\n\n```text\nchild\n```\n\n```text\nchildren.controller.ts\n```\n\n```text\nhttp://locahost:3000/children/1/parent\n```\n\n```text\nchildren.module.ts\n```\n\n```text\ntypeorm.config\n```\n\n```text\nchildren.controller.ts\n```\n\n```text\nchildren.service.ts\n```\n\n```js\n@Entity()\nexport class Child extends BaseEntity {\n\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstname: string;\n\n  @Column()\n  lastname: string;\n\n  @ManyToOne(type => Client, client => client.children, { eager: false })\n  @JoinColumn()\n  client: Client\n\n  @Column()\n  clientId: number;\n}\n```\n\n```js\nasync getChild(id: number): Promise<Child> {\n    return await this.childRepository.findOne(id, {\n      relations: ['client']\n    })\n  }\n```\n\n```js\n@ManyToOne(type => Client, client => client.children, { eager: true })\n  @JoinColumn()\n  client: Client\n```\n\n```text\n@JoinColumn()\n```\n\n```text\neager\n```\n\n```text\ntrue\n```\n\n```text\nchildren.service.ts\n```\n\n```text\neager\n```\n\n```text\nChild\n```\n\n```text\n@Entity()\nexport class Child extends BaseEntity {\n\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstname: string;\n\n  @Column()\n  lastname: string;\n\n  @ManyToOne(()=> Client, (client) => client.children, { eager: false })\n  @JoinColumn([{ name: \"clientId\", referencedColumnName: \"id\" }])\n  client: Client\n\n  @Column()\n  clientId: number;\n}\n```\n\n========================================\n\nComments:\n- what code contains your `getChild` method?\n- I have added the code for getChild to retrieve the child into the database.\n- thanks for your answer ! I still have the issue. I have a restart the server after the update. Not working + I have remove database tables and still not working.\n- after you changed database you need generate migration and apply it\n- I am sorry but I dont how to proceed it. I thought with `synchronize: true` everything will be auto-updated\n- You're right about `synchronize: true`. I've added one more advice to my answer, try it\n- adding `{ relations: ['client'] }` solved the issue ! Thanks a lot !\n- Thanks for you answer. The solution given by Yevhenii is working well.","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":450,"estimatedTokens":2050}}676{"id":"stack-67432760","source":"stackoverflow","questionId":67432760,"title":"Nestjs | e2e testing | \"smuggle/inject\" custom environment variables before ConfigModule triggers validation","tags":["node.js","typescript","nestjs"],"text":"Title: Nestjs | e2e testing | \"smuggle/inject\" custom environment variables before ConfigModule triggers validation\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow can I \"smuggle\" my own testing environment variables into the ConfigModule/ConfigService before the `envValidation` occurs?\nThis would be useful to check that:\n\n- the function `envValidation` is doing its job correctly;\n\n- downstream, the application is behaving according to the variables set.\n\n```\n// AppModule.ts\n\nimport { validate as envValidate } from './configs/EnvValidation';\n\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: (configService: ConfigService) => ({\n type: configService.get('DATABASE_TYPE'),\n host: configService.get('DATABASE_HOST'),\n port: configService.get('DATABASE_PORT'),\n username: configService.get('DATABASE_USERNAME'),\n password: configService.get('DATABASE_PASSWORD'),\n database: configService.get('DATABASE_NAME'),\n entities: [EntityA, EntityB],\n entityPrefix: \"simple_auth_\",\n synchronize: true,\n } as ConnectionOptions),\n inject: [ConfigService],\n }),\n TypeOrmModule.forFeature([EntityA, EntityB]),\n ConfigModule.forRoot({\n cache: true,\n validate: envValidate\n })\n ],\n controllers: [\n // controllers...\n ],\n providers: [\n // providers...\n ],\n})\nexport class AppModule {}\n```\n\n```\n// EnvValidation.ts\n\nclass EnvironmentVariables {\n @IsIn(['mysql', 'postgres'])\n @IsDefined()\n @IsNotEmpty()\n DATABASE_TYPE: string;\n\n @IsDefined()\n @IsNotEmpty()\n DATABASE_HOST: string;\n\n @IsPort()\n @IsDefined()\n @IsNotEmpty()\n DATABASE_PORT: string;\n\n// (...)\n}\n\nexport function validate(config: Record) {\n const validatedConfig = plainToClass(EnvironmentVariables, config, {\n enableImplicitConversion: true\n });\n const errors = validateSync(validatedConfig, {\n skipMissingProperties: false\n });\n\n if (errors.length > 0) {\n const msgs = errors.map((err) => Object.values(err.constraints)[0]);\n const errorMsg = msgs.join(', ');\n\n throw new Error(`Error loading environment variables. ${errorMsg}`);\n }\n\n return validatedConfig;\n}\n```\n\n```\n// e2e-spec.ts\n\ndescribe('(e2e)', () => {\n beforeEach(async () => {});\n\n afterEach(async () => {});\n\n it('should pass while setting: DATABASE_TYPE=postgres, DATABASE_HOST=localhost, ...', async () => {\n\n const envVariablesToUse = {\n DATABASE_TYPE: 'postgres',\n DATABASE_HOST: 'localhost',\n // more variables for this test...\n }\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [\n AppModule,\n // ??\n ]\n })\n .overrideModule(ConfigModule)\n .useValue(ConfigModule.forRoot({envVars: envVariablesToUse})) // stackoverflow padding: It looks like your post is mostly code; please add some more details.\n\nstackoverflow padding: It looks like your post is mostly code; please add some more details.\n\n========================================\n\nCode:\n```js\n// AppModule.ts\n\n\nimport { validate as envValidate } from './configs/EnvValidation';\n\n\n@Module({\n    imports: [\n        TypeOrmModule.forRootAsync({\n            imports: [ConfigModule],\n            useFactory: (configService: ConfigService) => ({\n                type: configService.get('DATABASE_TYPE'),\n                host: configService.get('DATABASE_HOST'),\n                port: configService.get<number>('DATABASE_PORT'),\n                username: configService.get('DATABASE_USERNAME'),\n                password: configService.get('DATABASE_PASSWORD'),\n                database: configService.get('DATABASE_NAME'),\n                entities: [EntityA, EntityB],\n                entityPrefix: \"simple_auth_\",\n                synchronize: true,\n            }  as ConnectionOptions),\n            inject: [ConfigService],\n        }),\n        TypeOrmModule.forFeature([EntityA, EntityB]),\n        ConfigModule.forRoot({\n            cache: true,\n            validate: envValidate\n        })\n    ],\n    controllers: [\n        // controllers...\n    ],\n    providers: [\n        // providers...\n    ],\n})\nexport class AppModule {}\n```\n\n```js\n// EnvValidation.ts\n\n\nclass EnvironmentVariables {\n    @IsIn(['mysql', 'postgres'])\n    @IsDefined()\n    @IsNotEmpty()\n    DATABASE_TYPE: string;\n\n    @IsDefined()\n    @IsNotEmpty()\n    DATABASE_HOST: string;\n\n    @IsPort()\n    @IsDefined()\n    @IsNotEmpty()\n    DATABASE_PORT: string;\n\n// (...)\n}\n\n\nexport function validate(config: Record<string, unknown>) {\n    const validatedConfig = plainToClass(EnvironmentVariables, config, {\n        enableImplicitConversion: true\n    });\n    const errors = validateSync(validatedConfig, {\n        skipMissingProperties: false\n    });\n\n    if (errors.length > 0) {\n        const msgs = errors.map((err) => Object.values(err.constraints)[0]);\n        const errorMsg = msgs.join(', ');\n\n        throw new Error(`Error loading environment variables. ${errorMsg}`);\n    }\n\n    return validatedConfig;\n}\n```\n\n```js\n// e2e-spec.ts\n\n\n\ndescribe('(e2e)', () => {\n    beforeEach(async () => {});\n\n    afterEach(async () => {});\n\n    it('should pass while setting: DATABASE_TYPE=postgres, DATABASE_HOST=localhost, ...', async () => {\n\n        const envVariablesToUse = {\n            DATABASE_TYPE: 'postgres',\n            DATABASE_HOST: 'localhost',\n            // more variables for this test...\n        }\n\n        const moduleFixture: TestingModule = await Test.createTestingModule({\n            imports: [\n                AppModule,\n                // ??\n            ]\n        })\n            .overrideModule(ConfigModule)\n            .useValue(ConfigModule.forRoot({envVars: envVariablesToUse}))  // <-- Question 1: How to override the environment variables object with a custom one in order to test the rules defined in the EnvironmentVariables class and to test the implications of these configurations downstream?\n\n            .overrideProvider(ConfigService) // <-- Question 2: How to override the ConfigService? May be handy to replace its behaviour(?)\n            .useValue(MockConfigService)\n            .compile();\n\n        const app = moduleFixture.createNestApplication();\n\n        let successfullyLoadedEnvVariables = true;\n        try {\n            await app.init();\n        }\n        catch(err){\n            successfullyLoadedEnvVariables = false;\n        }\n\n        expect(successfullyLoadedEnvVariables).toBe(true);\n\n        // Then, hit some endpoints to ensure the app is behaving as expected\n    });\n});\n```\n\n```text\nenvValidation\n```\n\n```text\nenvValidation\n```\n\n========================================\n\nComments:\n- can you write an example how code looks like?","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":262,"estimatedTokens":1629}}677{"id":"stack-70486412","source":"stackoverflow","questionId":70486412,"title":"How convert Express.Multer.File to Blob data?","tags":["javascript","typescript","express","nestjs","multer"],"text":"Title: How convert Express.Multer.File to Blob data?\nTags: javascript, typescript, express, nestjs, multer\nSource: Stack Overflow\n\nQuestion:\nI have a **NestJs** project in my controller I accept an **Express.Multer.File** but I need to send it to another server. How can I convert it to **Blob** for passing to **FormData**?\n\n```\n#action in my controller\n\n @Post('/upload')\n @UseInterceptors(FileInterceptor('avatar'))\n async uploadUserProfileAvatar(@UploadedFile() file: Express.Multer.File){\n \n console.log(file)\n let blob = new Blob(file.mimetype)\n let formData = new FormData()\n //can't set because file is not Blob\n formData.append('file',file)\n\n let request$ = this.httpService.post('http://test_server/file',formData,{headers:{\n 'Content-Type':'multipart/form-data'\n }}).pipe(\n map(response => response.data)\n )\n\n request$.subscribe( response => {\n console.log(response)\n return response\n })\n }\n```\n\nI will be grateful for every answer!\n\n**EDIT:**\n\nThanks again for your help! As a result, I managed to successfully send the code in this way:\n\n```\n@Post('/upload')\n @UseInterceptors(FileInterceptor('avatar'))\n async uploadUserProfileAvatar(@UploadedFile() file: Express.Multer.File){\n\n const FormData = require('form-data');\n const formData = new FormData();\n formData.append('file', Buffer.from(file.buffer) , file.originalname);\n\n let request$ = this.httpService.post('http://nginx_files/file',formData,{headers:formData.getHeaders()}).pipe(\n map(response => response.data)\n )\n\n request$.subscribe( response => {\n console.log(response)\n return response\n })\n }\n```\n\n========================================\n\nTop Answer:\n@MiyRon\n\nYou get the Error \"TypeError: source.on is not a function\", because formData accepts only three types of elements. String, Buffer and Stream.\n\nSo you can fix it with:\n\n```\nformData.append('file', JSON.stringify(fileContent), 'file_name.ext');\n```\n\n========================================\n\nCode:\n```js\n#action in my controller\n\n    @Post('/upload')\n    @UseInterceptors(FileInterceptor('avatar'))\n    async uploadUserProfileAvatar(@UploadedFile() file: Express.Multer.File){\n        \n        console.log(file)\n        let blob = new Blob(file.mimetype)\n        let formData = new FormData()\n        //can't set because file is not Blob\n        formData.append('file',file)\n\n\n        let request$ = this.httpService.post('http://test_server/file',formData,{headers:{\n            'Content-Type':'multipart/form-data'\n        }}).pipe(\n            map(response => response.data)\n        )\n\n        request$.subscribe( response => {\n            console.log(response)\n            return response\n        })\n    }\n```\n\n```text\n@Post('/upload')\n    @UseInterceptors(FileInterceptor('avatar'))\n    async uploadUserProfileAvatar(@UploadedFile() file: Express.Multer.File){\n\n        const FormData = require('form-data');\n        const formData = new FormData();\n        formData.append('file', Buffer.from(file.buffer) , file.originalname);\n\n\n        let request$ = this.httpService.post('http://nginx_files/file',formData,{headers:formData.getHeaders()}).pipe(\n                map(response => response.data)\n            )\n\n        request$.subscribe( response => {\n            console.log(response)\n            return response\n        })\n    }\n```\n\n```js\nconst FormData = require('form-data');\n\n  const formData = new FormData();\n  formData.append('file', fileContent, 'file_name.ext');\n\n  let request$ = this.httpService.post('http://test_server/file',\n    formData,\n    { headers: formData.getHeaders() }\n  ).pipe(\n            map(response => response.data)\n        )\n```\n\n```text\nformdata\n```\n\n```text\nformData.append('file', JSON.stringify(fileContent), 'file_name.ext');\n```\n\n```js\nimport * as FormData from 'form-data';\n\n// ...\n\n    processFile(file: Express.Multer.File) {\n        const formData = new FormData();\n\n        formData.append('file', Buffer.from(file.buffer), {\n            filename: file.originalname,\n            contentType: file.mimetype,\n        });\n\n        return this.httpService\n            .post('http://test_server/file', formData, {\n                headers: {\n                    ...formData.getHeaders(),\n                    'Content-Length': `${formData.getLengthSync()}`,\n                },\n            })\n            .pipe(map((response) => response.data));\n    }\n```\n\n```text\nContent-Length\n```\n\n```text\ncontentType\n```\n\n========================================\n\nComments:\n- `blob = new Blob(file.mimetype)` looks incorrect.\n- Thank you! But my question is, what is the advantage of this package over the standard FormData?\n- FormData is not a part of NodeJs, see also the answer stackoverflow.com/a/63577074/1376618\n- unfortunately this code raises an error `TypeError: source.on is not a function` what could be the problem?\n- What code exactly? Can you update your post?","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":185,"estimatedTokens":1210}}678{"id":"stack-71543148","source":"stackoverflow","questionId":71543148,"title":"Nestjs Global Validation Pipe unable to Parse Boolean Query Param","tags":["node.js","typescript","nestjs"],"text":"Title: Nestjs Global Validation Pipe unable to Parse Boolean Query Param\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn following controller, in the GET call I intend to pass a boolean parameter.\n\n```\n@Controller('tests')\nexport class TestController {\n constructor(private readonly testService: TestService) {}\n\n @Get()\n async getTests(@Query() params: QueryParamDto) {\n return await this.testService.getTests(params.var);\n }\n}\n```\n\nand the Service method understands the type of `params.var` as a `boolean`.\n\n```\n@Injectable()\nexport class TestService {\n @Get()\n async getTests(var: boolean) {\n return ...;\n }\n}\n```\n\nThe `QueryParamDto` looks like.\n\n```\nexport class QueryParamDto {\n @IsDefined()\n @IsBoolean()\n var: boolean;\n}\n```\n\nI have defined a Global Validation Pipe in `main.ts`.\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useGlobalPipes(\n new ValidationPipe({\n transform: true,\n }),\n );\n await app.listen(3000);\n}\nbootstrap();\n```\n\nHowever, when I make a call to the endpoint `/tests?var=true` it is unable to parse the var as a boolean and errors.\n\n```\n{\n \"statusCode\": 400,\n \"message\": [\n \"var must be a boolean value\"\n ],\n \"error\": \"Bad Request\"\n}\n```\n\nMy understanding is that `app.useGlobalPipes(new ValidationPipe({transform: true...})` should automatically parse the params type as defined in the Dto, in this case `var` as `boolean` in `QueryParamDto`.\n\n========================================\n\nTop Answer:\nI've just had this issue, my solution is as below:\n\n```\n@IsDefined()\n@Transform(({ value }) => {\n if (value === 'true') return true;\n if (value === 'false') return false;\n return value;\n })\n@IsBoolean()\nvar: boolean;\n```\n\n========================================\n\nCode:\n```text\n@Controller('tests')\nexport class TestController {\n    constructor(private readonly testService: TestService) {}\n\n    @Get()\n    async getTests(@Query() params: QueryParamDto) {\n        return await this.testService.getTests(params.var);\n    }\n}\n```\n\n```text\n@Injectable()\nexport class TestService {\n    @Get()\n    async getTests(var: boolean) {\n        return ...;\n    }\n}\n```\n\n```text\nexport class QueryParamDto {\n    @IsDefined()\n    @IsBoolean()\n    var: boolean;\n}\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(\n    new ValidationPipe({\n      transform: true,\n    }),\n  );\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n{\n    \"statusCode\": 400,\n    \"message\": [\n        \"var must be a boolean value\"\n    ],\n    \"error\": \"Bad Request\"\n}\n```\n\n```text\nparams.var\n```\n\n```text\nboolean\n```\n\n```text\nQueryParamDto\n```\n\n```text\nmain.ts\n```\n\n```text\n/tests?var=true\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({transform: true...})\n```\n\n```text\nvar\n```\n\n```text\nboolean\n```\n\n```text\nQueryParamDto\n```\n\n```text\ntransform\n```\n\n```text\nplainToClass\n```\n\n```text\nclass-transformer\n```\n\n```text\nstring\n```\n\n```text\n@Transform()\n```\n\n```text\ntransformOptions.enableImplicitConversion\n```\n\n```text\n@IsDefined()\n@Transform(({ value }) => {\n     if (value === 'true') return true;\n     if (value === 'false') return false;\n          return value;\n      })\n@IsBoolean()\nvar: boolean;\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":212,"estimatedTokens":808}}679{"id":"stack-65074489","source":"stackoverflow","questionId":65074489,"title":"how to migrate from express.js to nest.js, route by route","tags":["node.js","express","nestjs"],"text":"Title: how to migrate from express.js to nest.js, route by route\nTags: node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there a proper way to migrate an app based on express.js to a nest.js app, doing so route by route ?\nI couldn't find official documentation or open question about this.\n\nOnly support i could find was this opened question: Migrating Express application to NestJS\n\n========================================\n\nCode:\n```js\nimport express, {json, urlencoded} from \"express\";\n// imports legacy API; the file exports `module.exports = router;`\n// where router is `const router = express.Router();`\nimport api from './legacy/routes/api.cjs';\n\nconfig();\n\nconst expressApp = express();\nexpressApp.use(json());\nexpressApp.use(urlencoded({extended: false}));\nexpressApp.use('/api', api);\n\nasync function bootstrap() {\n  const adapter = new ExpressAdapter(expressApp);\n  const app = await NestFactory.create(AppModule, adapter);\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nconst server = http.createServer(app);\nserver.listen(port, () => logger.logger.info(`API running on localhost:${port}`));\n```\n\n```text\nExpressAdapter\n```\n\n```text\nexpress()\n```\n\n========================================\n\nComments:\n- Hey did you find anything on this?\n- Well from what I know its not possible. Since nest start a server on its own. You would need 2 servers, the legacy and the new one and then migrate endpoint by endpoint as you please\n- its been indeed a long time ! i wish i had this before haha !\n- @Sufiane yup, it is kind of interesting there are not many examples or docs available. I envy you that you have probably already finished this, I have a long journey ahead :(\n- keep the faith ! its gonna be quicker than you think !","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":55,"estimatedTokens":438}}680{"id":"stack-60557452","source":"stackoverflow","questionId":60557452,"title":"Nest can't resolve dependencies of the (?). Please make sure that the argument PatientProfileRepository at index [0]","tags":["typescript","testing","nestjs"],"text":"Title: Nest can't resolve dependencies of the (?). Please make sure that the argument PatientProfileRepository at index [0]\nTags: typescript, testing, nestjs\nSource: Stack Overflow\n\nQuestion:\n### background\n\nWhen passing test code with ci while creating a program with nest.js\n\nI got this error\n\n```\nexpect(received).toBeDefined()\n\nReceived: undefined\n\nNest can't resolve dependencies of the ProfilesService (?). Please make sure that the argument PatientProfileRepository at index [0] is available in the RootTestModule context.\n```\n\n### Problems, unknown points\n\n```\ndescribe('ProfilesService', () => {\n let service: ProfilesService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [ProfilesService],\n }).compile()\n\n service = module.get(ProfilesService)\n })\n\n it('should be defined', () => {\n expect(service).toBeDefined()\n })\n})\n```\n\nController has similar code\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport ProfilesController from './profiles.controller'\n\ndescribe('Profiles Controller', () => {\n let controller: ProfilesController\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [ProfilesController],\n }).compile()\n\n controller = module.get(ProfilesController)\n })\n\n it('should be defined', () => {\n expect(controller).toBeDefined()\n })\n})\n```\n\nI don't know why controller and service are responsible for undefind.\nI'm glad if anyone can tell me.\nThank you\n\n========================================\n\nCode:\n```text\nexpect(received).toBeDefined()\n\nReceived: undefined\n\n\nNest can't resolve dependencies of the ProfilesService (?). Please make sure that the argument PatientProfileRepository at index [0] is available in the RootTestModule context.\n```\n\n```text\ndescribe('ProfilesService', () => {\n  let service: ProfilesService\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [ProfilesService],\n    }).compile()\n\n    service = module.get<ProfilesService>(ProfilesService)\n  })\n\n  it('should be defined', () => {\n    expect(service).toBeDefined()\n  })\n})\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing'\nimport ProfilesController from './profiles.controller'\n\ndescribe('Profiles Controller', () => {\n  let controller: ProfilesController\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      controllers: [ProfilesController],\n    }).compile()\n\n    controller = module.get<ProfilesController>(ProfilesController)\n  })\n\n  it('should be defined', () => {\n    expect(controller).toBeDefined()\n  })\n})\n```\n\n```text\nproviders: [\n {\n    provide: ProfilesService,\n    useValue: {},\n },\n]\n```\n\n```text\nproviders: [\n ProfilesService,\n {\n    provide: getRepositoryToken(PatientProfile),\n    useValue: {},\n },\n],\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":717}}681{"id":"stack-61438698","source":"stackoverflow","questionId":61438698,"title":"NestJS env variable undefined","tags":["javascript","node.js","nestjs","dotenv"],"text":"Title: NestJS env variable undefined\nTags: javascript, node.js, nestjs, dotenv\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set configuration variables on my project using the official documentation.\n\nI added the following line to my app.module.ts imports:\n\n```\nConfigModule.forRoot({\n isGlobal: true\n}),\n```\n\nI created a .env file at the root of my project with the following content:\n\n```\nMY_VARIABLE=myself\n```\n\nAnd I use dependecy injection to get access to the configuration service:\n\n```\nconstructor(private configService: ConfigService) {}\n```\n\nHowever the following line logs 'Env variable: undefined'\n\n```\nconsole.log('Env variable: ', this.configService.get('MY_VARIABLE'));\n```\n\n========================================\n\nTop Answer:\nI have the same problem. Then I figure out that I have imported process from `import process from 'node:process';` this is not needed. After removing this its working fine.\n\n========================================\n\nCode:\n```text\nConfigModule.forRoot({\n  isGlobal: true\n}),\n```\n\n```text\nMY_VARIABLE=myself\n```\n\n```text\nconstructor(private configService: ConfigService) {}\n```\n\n```text\nconsole.log('Env variable: ', this.configService.get<any>('MY_VARIABLE'));\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```text\ndotenv\n```\n\n```text\nfunctions\n```\n\n```text\n.env\n```\n\n```text\nimport process from 'node:process';\n```\n\n========================================\n\nComments:\n- Sounds like you've got it set up properly. Can you a reproduction? In the snippets you've provided I can't see a problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":91,"estimatedTokens":388}}682{"id":"stack-50654877","source":"stackoverflow","questionId":50654877,"title":"TypeError: Class constructor MixinStrategy cannot be invoked without 'new'","tags":["typescript","jwt","passport.js","nestjs"],"text":"Title: TypeError: Class constructor MixinStrategy cannot be invoked without 'new'\nTags: typescript, jwt, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI was following along with the jwt example like found here https://docs.nestjs.com/techniques/authentication. I copied and pasted the example. After npm installing the necessary bits and bops I got this error which does not occur in the sample which I just copied. Of which I have no idea what it means! Anyone any ideas?\n\n```\nTypeError: Class constructor MixinStrategy cannot be invoked without 'new'\n\n 8 | export class JwtStrategy extends PassportStrategy(Strategy) {\n 9 | constructor(private readonly authService: AuthService) {\n> 10 | super({\n 11 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n 12 | secretOrKey: 'secretKey',\n 13 | });\n\n at new JwtStrategy (data/auth/strategies/jwt.strategy.ts:10:5)\n at resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:64:84)\n at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:86:30)\n```\n\n========================================\n\nTop Answer:\nIn my case issue was in tsconfig.ts file, I'm using nest.js and after cli command `typeorm init` it overwrite tsconfig so `npm run start:dev` was throwing exception: **TypeError: Class constructor MixinStrategy cannot be invoked without 'new'**\n\nnote: is also overwrites package.json with older version of `typescipt, @ts/node, ts-node`\n\n========================================\n\nCode:\n```text\nTypeError: Class constructor MixinStrategy cannot be invoked without 'new'\n\n   8 | export class JwtStrategy extends PassportStrategy(Strategy) {\n   9 |   constructor(private readonly authService: AuthService) {\n> 10 |     super({\n  11 |       jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n  12 |       secretOrKey: 'secretKey',\n  13 |     });\n\n  at new JwtStrategy (data/auth/strategies/jwt.strategy.ts:10:5)\n  at resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:64:84)\n  at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:86:30)\n```\n\n```text\nnpm i -D @types/passport-jwt\n```\n\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n...\n```\n\n```text\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AbstractStrategy, PassportStrategy } from '@nestjs/passport';\n...\nconst PassportJwtStrategy: new(...args) => AbstractStrategy & Strategy = PassportStrategy(Strategy);\n\n@Injectable()\nexport class JwtStrategy extends PassportJwtStrategy {\n...\n```\n\n```text\n@types/passport-jwt\n```\n\n```text\n@nestjs/passport\n```\n\n```text\nPassportStrategy\n```\n\n```text\nany\n```\n\n```text\ntypeorm init\n```\n\n```text\nnpm run start:dev\n```\n\n```text\ntypescipt, @ts/node, ts-node\n```\n\n========================================\n\nComments:\n- Can you provide a way to replicate the problem - a repo, etc? Could be specific to package versions or whatever.\n- Sure, clone this folder github.com/nestjs/nest/tree/master/sample/19-auth npm i && npm start it will show up, on windows 10 and node 8.11.2\n- I wasn't able to replicate the error you've got. There's no problem with MixinStrategy. Your current code likely differs from the one you've linked. But I've got problems with typings. I'd suggest to open an issue regarding this example (19-auth misses @types/passport-jwt dependency) in github.com/nestjs/nest and in github.com/nestjs/passport regarding improper PassportStrategy type. Any way, I wasn't able to make this example workable; the server runs but responds with 404.\n- Not sure if anything can be done at this point. I was seriously considering NestJS as my next framework but it seems it is just not mature enough. The documentation is somewhat lacking and examples that don't work out of the box don't really help. Thanks for bringing this problem to SO, this was eye-opening.\n- no my code was the sample code, bit for bit the same. I cloned the sample in my project but the error was there before I could change anything. anyhow I used this github.com/bojidaryovchev/nest-angular to fix it.Nest is a great framework that is if you love angular and the little problems it has are hardly unovercomable. You should try it for sure.\n- Yes, the resemblance with Angular makes it easy to adopt but the issue with `any` type seems a bit off for TS-oriented framework, Angular typing is much more solid. Thanks for a boilerplate link, I'll give it a try.\n- check your tsconfig.json to ensure \"target\" is \"es6\"\n- This issue is fixed in `1.0.11` patch release.\n- Both the original code and this throws \"TypeError: Class constructor MixinStrategy cannot be invoked without 'new'\" when setting the \"target\" to \"ES5\" in tsconfig.json. Is there a way for ES5? @estus\n- @Smartkid I would expect that for ES5 target because TS uses established recipe for inheritance, `_this = Parent.call(this)`. It's expected that entire class hierarchy is transpiled to make it work, otherwise this will result in an error because native classes cannot be called without `new`. Why would you use ES5 target in Node any way?\n- @estus Thanks for your explanation. I use yarn workspace to come code between a nestjs server project and a react based project (which targets to ES5 to avoid babel). The Jest support of older versions of WebStorm seems to run unit-tests using the tsconfig under the workspace root directory and ignores the tsconfig under sub projects. It looks like the WebStorm fixed this issue in 2018.1.4 .\n- @Smartkid Thanks for the information regarding Webstorm, good to know,\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":112,"estimatedTokens":1448}}683{"id":"stack-61061869","source":"stackoverflow","questionId":61061869,"title":"DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL In React App","tags":["reactjs","rest","axios","nestjs"],"text":"Title: DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL In React App\nTags: reactjs, rest, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm facing with a mysterious error. When I'm trying to send one specific query to the server, I'm receiving the following error\n\n```\nDOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL\nat dispatchXhrRequest (http://localhost:6789/static/js/20.chunk.js:180790:13)\nat new Promise ()\nat xhrAdapter (http://localhost:6789/static/js/20.chunk.js:180773:10)\nat dispatchRequest (http://localhost:6789/static/js/20.chunk.js:181396:10)\n```\n\nAnd here I logged the actual url string\n\n```\nhttp://localhost:3000โ€‹/usersโ€‹/5โ€‹/paymentsโ€‹/disconnect\n```\n\nIf I send the same query but from my hosting to dev server, I see error 404 and url like this\n\n```\nhttps://example.com/users%E2%80%8B/5%E2%80%8B/payments%E2%80%8B/disconnect\n```\n\nThis is my function which sends the query\n\n```\nconst query = `${url}โ€‹/usersโ€‹/${userId}โ€‹/paymentsโ€‹/disconnect`;\n\n console.debug('Url', query);\n\n try {\n const { status } = await axios.delete(query);\n return status;\n } catch (e) {\n console.debug(e);\n return 500;\n }\n}\n```\n\nInteresting thing, all other endpoints work fine. The same behavior on chrome and firefox.\n\nWhat can cause problems like this?\n\n========================================\n\nCode:\n```text\nDOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL\nat dispatchXhrRequest (http://localhost:6789/static/js/20.chunk.js:180790:13)\nat new Promise (<anonymous>)\nat xhrAdapter (http://localhost:6789/static/js/20.chunk.js:180773:10)\nat dispatchRequest (http://localhost:6789/static/js/20.chunk.js:181396:10)\n```\n\n```text\nhttp://localhost:3000โ€‹/usersโ€‹/5โ€‹/paymentsโ€‹/disconnect\n```\n\n```text\nhttps://example.com/users%E2%80%8B/5%E2%80%8B/payments%E2%80%8B/disconnect\n```\n\n```text\nconst query = `${url}โ€‹/usersโ€‹/${userId}โ€‹/paymentsโ€‹/disconnect`;\n\n  console.debug('Url', query);\n\n  try {\n    const { status } = await axios.delete(query);\n    return status;\n  } catch (e) {\n    console.debug(e);\n    return 500;\n  }\n}\n```\n\n```text\n%E2%80%8B\n```\n\n```text\nconst query = `${url}โ€‹/usersโ€‹/${userId}โ€‹/paymentsโ€‹/disconnect`;\n```\n\n```text\n/\n```\n\n```text\n/\n```\n\n========================================\n\nComments:\n- It works. Thank you a lot! Then I don't understand, how does this character could appeare in the code?\n- @IvanBanha โ€” Most likely: It was typed or copy/pasted.\n- Wow, hard to believe but this actually was my problem. I had two invisible double byte characters (U+200B : ZERO WIDTH SPACE [ZWSP]) in my URL string. Thank you @Quentin","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":649}}684{"id":"stack-58477104","source":"stackoverflow","questionId":58477104,"title":"Nestjs: Image uploaded even if body validation fails","tags":["javascript","nestjs"],"text":"Title: Nestjs: Image uploaded even if body validation fails\nTags: javascript, nestjs\nSource: Stack Overflow\n\nQuestion:\nFirst of all, I apologize for my weak English.\n\nI have a method that accepts PUT request, and it receives a file and BlogModel. When I submit the form from frontend and the BlogModel's validation is failed the file is still uploaded.\n\nmain.ts\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './core/app.module';\nimport { ValidationPipe } from '@nestjs/common';\nimport { join } from 'path';\nimport { NestExpressApplication } from '@nestjs/platform-express';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useStaticAssets(join(__dirname, '..', 'src/public'));\n app.setBaseViewsDir(join(__dirname, '..', 'src/views'));\n\n app.setViewEngine('hbs');\n app.useGlobalPipes(new ValidationPipe());\n await app.listen(3000);\n}\nbootstrap();\n```\n\naddBlog method\n\n```\n@Put()\n @UseInterceptors(FileInterceptor('thumbnail', { storage: BlogStorage }))\n addBlog(@UploadedFile() file, @Body() addBlogModel: AddBlogModel) {\n console.log(file);\n }\n```\n\nadd-blog.model.ts\n\n```\nimport { IsArray, IsBoolean, IsNotEmpty, IsOptional, IsString, Length } from 'class-validator';\nimport { Expose } from 'class-transformer';\n\nexport class AddBlogModel {\n @IsNotEmpty()\n @IsString()\n title: string;\n\n @IsString()\n @Length(10, 225)\n @IsOptional()\n introduction: string;\n\n @IsNotEmpty()\n @IsString()\n content: string;\n\n @IsBoolean()\n @Expose({name: 'is_published'})\n isPublished: boolean;\n\n @IsArray()\n @IsNotEmpty()\n tags: string[];\n\n @IsString()\n @IsNotEmpty()\n category: string;\n}\n```\n\nindex.hbs\n\n```\n\n \n \n \n\n Submit\n\n $(document).ready(function () {\n $(\"#form\").on('submit', function (e) {\n e.preventDefault();\n const data = $(this).serializeArray()\n const data_from_array = {}\n var formData = new FormData()\n\n $.map(data, function(n, i){\n formData.append(n['name'], n['value'])\n });\n\n const file = $('input[type=\"file\"]')[0].files[0]\n\n formData.append('thumbnail', file)\n\n const config = {\n headers: {\n 'content-type': 'multipart/form-data'\n }\n }\n axios.put('http://localhost:3000/blogs', formData, config).then(res => {\n console.log(res)\n }).catch(err => {\n console.log(err.response)\n })\n });\n })\n\n```\n\nI expect the file is not uploaded if the validation is failed.\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './core/app.module';\nimport { ValidationPipe } from '@nestjs/common';\nimport { join } from 'path';\nimport { NestExpressApplication } from '@nestjs/platform-express';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(AppModule);\n  app.useStaticAssets(join(__dirname, '..', 'src/public'));\n  app.setBaseViewsDir(join(__dirname, '..', 'src/views'));\n\n  app.setViewEngine('hbs');\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n@Put()\n  @UseInterceptors(FileInterceptor('thumbnail', { storage: BlogStorage }))\n  addBlog(@UploadedFile() file, @Body() addBlogModel: AddBlogModel) {\n    console.log(file);\n  }\n```\n\n```text\nimport { IsArray, IsBoolean, IsNotEmpty, IsOptional, IsString, Length } from 'class-validator';\nimport { Expose } from 'class-transformer';\n\nexport class AddBlogModel {\n  @IsNotEmpty()\n  @IsString()\n  title: string;\n\n  @IsString()\n  @Length(10, 225)\n  @IsOptional()\n  introduction: string;\n\n  @IsNotEmpty()\n  @IsString()\n  content: string;\n\n  @IsBoolean()\n  @Expose({name: 'is_published'})\n  isPublished: boolean;\n\n  @IsArray()\n  @IsNotEmpty()\n  tags: string[];\n\n  @IsString()\n  @IsNotEmpty()\n  category: string;\n}\n```\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\n</head>\n\n<body>\n<form id=\"form\">\n    <input name=\"title\" id=\"title\"/>\n    <input name=\"content\" id=\"content\"/>\n    <input type=\"file\" name=\"thumbnail\" id=\"thumbnail\"/>\n\n    <button type=\"submit\">Submit</button>\n</form>\n\n<script src=\"https://code.jquery.com/jquery.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js\"></script>\n<script type=\"text/javascript\">\n    $(document).ready(function () {\n        $(\"#form\").on('submit', function (e) {\n            e.preventDefault();\n            const data = $(this).serializeArray()\n            const data_from_array = {}\n            var formData = new FormData()\n\n            $.map(data, function(n, i){\n                formData.append(n['name'], n['value'])\n            });\n\n            const file = $('input[type=\"file\"]')[0].files[0]\n\n            formData.append('thumbnail', file)\n\n            const config = {\n                headers: {\n                    'content-type': 'multipart/form-data'\n                }\n            }\n            axios.put('http://localhost:3000/blogs', formData, config).then(res => {\n                console.log(res)\n            }).catch(err => {\n                console.log(err.response)\n            })\n        });\n    })\n</script>\n</body>\n</html>\n```\n\n========================================\n\nComments:\n- Please show the UploadedFile decorator as well.\n- @Thomas thanx for the response, the UploadedFile decorator is exported from Nestjs framework. github.com/nestjs/nest/blob/master/packages/common/decorator&zwnj;&#8203;s/&hellip; FileInterceptor() decorator is exported from @nestjs/platform-express package while @UploadedFile() from @nestjs/common.","metadata":{"transformedAt":"2026-08-18T18:33:02.461Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":234,"estimatedTokens":1347}}685{"id":"stack-62154082","source":"stackoverflow","questionId":62154082,"title":"NestJS/Class-transformer @Type Discriminator object doesn't correctly validate data","tags":["node.js","nestjs"],"text":"Title: NestJS/Class-transformer @Type Discriminator object doesn't correctly validate data\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a generic class as following:\n\n```\nimport {IsArray, IsNotEmpty, IsString, ValidateNested} from \"class-validator\";\nimport {PatientInfoValidator} from \"./businessInfo/PatientInfoValidator\";\nimport {TypeValidator} from \"./TypeValidator\";\nimport {Type} from \"class-transformer\";\n\nexport class GenericValidator {\n @IsString()\n @IsNotEmpty()\n userId: string;\n\n @ValidateNested({each:true})\n @Type(() => TypeValidator)\n type: TypeValidator;\n}\n```\n\nAnd two classes which inherit from this class\n\n```\nimport {IsArray, IsNotEmpty, IsString, ValidateNested} from \"class-validator\";\nimport {PatientInfoValidator} from \"./businessInfo/PatientInfoValidator\";\nimport {Type} from \"class-transformer\";\nimport {BusinessInfoValidator} from \"./BusinessInfoValidator\";\nimport {GenericValidator} from \"./GenericValidator\";\nimport {TypeValidator} from \"./TypeValidator\";\n\nexport class BodyValidator extends GenericValidator {\n @IsString()\n @IsNotEmpty()\n userId: string;\n\n @ValidateNested({each:true})\n @Type(() => TypeValidator)\n type: TypeValidator;\n\n @ValidateNested({each:true})\n @Type(() => BusinessInfoValidator)\n businessInformation: BusinessInfoValidator;\n\n @IsArray()\n sheetLink: string[];\n\n validate: boolean;\n}\n```\n\nAnd:\n\n```\nimport {GenericValidator} from \"./GenericValidator\";\nimport {IsNotEmpty, IsString, ValidateNested} from \"class-validator\";\nimport {Type} from \"class-transformer\";\nimport {TypeValidator} from \"./TypeValidator\";\n\nexport class CaseTwoValidator extends GenericValidator {\n @IsString()\n @IsNotEmpty()\n userId: string;\n\n @ValidateNested({each:true})\n @Type(() => TypeValidator)\n type: TypeValidator;\n\n newKey: string;\n}\n```\n\nThese are used in the DTO for validation:\n\n```\nimport { ApiProperty } from '@nestjs/swagger';\nimport {ValidateNested} from \"class-validator\";\nimport { Type } from 'class-transformer';\nimport { BodyValidator} from \"../validators/BodyValidator\";\nimport { GenericValidator} from \"../validators/GenericValidator\";\nimport { CaseTwoValidator} from \"../validators/CaseTwoValidator\";\n\nexport class CreateSheetsDto {\n @ApiProperty()\n @ValidateNested({ each: true })\n @Type(() => GenericValidator, {\n keepDiscriminatorProperty: true,\n discriminator: {\n property: \"type.label\",\n subTypes: [\n { value: BodyValidator, name: \"Hors dissection et syndrome neurologique\" },\n { value: CaseTwoValidator, name: \"NewCase\" }\n ]\n }\n })\n readonly body: BodyValidator | CaseTwoValidator;\n}\n```\n\nI'm expecting the controller having this DTO as params to:\nReject as Bad request all request body which are not conform to BodyValidator or CaseTwoValidator format.\n\nCurrent behavior: \nAPI requests are very permissive, and doesn't enforce nested checks.\n\nI was wondering if I'm missing something obvious having spent 3hours on this issue.\n\n========================================\n\nCode:\n```text\nimport {IsArray, IsNotEmpty, IsString, ValidateNested} from \"class-validator\";\nimport {PatientInfoValidator} from \"./businessInfo/PatientInfoValidator\";\nimport {TypeValidator} from \"./TypeValidator\";\nimport {Type} from \"class-transformer\";\n\nexport class GenericValidator {\n    @IsString()\n    @IsNotEmpty()\n    userId: string;\n\n    @ValidateNested({each:true})\n    @Type(() => TypeValidator)\n    type: TypeValidator;\n}\n```\n\n```text\nimport {IsArray, IsNotEmpty, IsString, ValidateNested} from \"class-validator\";\nimport {PatientInfoValidator} from \"./businessInfo/PatientInfoValidator\";\nimport {Type} from \"class-transformer\";\nimport {BusinessInfoValidator} from \"./BusinessInfoValidator\";\nimport {GenericValidator} from \"./GenericValidator\";\nimport {TypeValidator} from \"./TypeValidator\";\n\nexport class BodyValidator extends GenericValidator {\n    @IsString()\n    @IsNotEmpty()\n    userId: string;\n\n    @ValidateNested({each:true})\n    @Type(() => TypeValidator)\n    type: TypeValidator;\n\n    @ValidateNested({each:true})\n    @Type(() => BusinessInfoValidator)\n    businessInformation: BusinessInfoValidator;\n\n    @IsArray()\n    sheetLink: string[];\n\n    validate: boolean;\n}\n```\n\n```text\nimport {GenericValidator} from \"./GenericValidator\";\nimport {IsNotEmpty, IsString, ValidateNested} from \"class-validator\";\nimport {Type} from \"class-transformer\";\nimport {TypeValidator} from \"./TypeValidator\";\n\nexport class CaseTwoValidator extends GenericValidator {\n    @IsString()\n    @IsNotEmpty()\n    userId: string;\n\n    @ValidateNested({each:true})\n    @Type(() => TypeValidator)\n    type: TypeValidator;\n\n    newKey: string;\n}\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\nimport {ValidateNested} from \"class-validator\";\nimport { Type } from 'class-transformer';\nimport { BodyValidator} from \"../validators/BodyValidator\";\nimport { GenericValidator} from \"../validators/GenericValidator\";\nimport { CaseTwoValidator} from \"../validators/CaseTwoValidator\";\n\nexport class CreateSheetsDto {\n    @ApiProperty()\n    @ValidateNested({ each: true })\n    @Type(() => GenericValidator, {\n        keepDiscriminatorProperty: true,\n        discriminator: {\n            property: \"type.label\",\n            subTypes: [\n                { value: BodyValidator, name: \"Hors dissection et syndrome neurologique\" },\n                { value: CaseTwoValidator, name: \"NewCase\" }\n            ]\n        }\n        })\n    readonly body: BodyValidator | CaseTwoValidator;\n}\n```\n\n```text\n@IsString\n```\n\n========================================\n\nComments:\n- Thanks, I'll start there and see if it helps making the feature work","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":210,"estimatedTokens":1390}}686{"id":"stack-55026507","source":"stackoverflow","questionId":55026507,"title":"How to use validation in NestJs with HTML rendering?","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: How to use validation in NestJs with HTML rendering?\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nNestJS uses validation with validation pipes and \n\n```\n@UsePipes(ValidationPipe)\n```\n\nIf this fails it throws an exception. This is fine for REST APIs that return JSON. \n\nHow would one validate parameters when using HTML rendering and return \n\n```\n{ errors: ['First error'] }\n```\n\nto an hbs template?\n\n========================================\n\nTop Answer:\nI've been driving myself half mad trying to find a \"Nest like\" way to do this while still retaining a degree of customisability, and I think I finally have it. Firstly, we want an error that has a reference to the exisiting `class-validator` errors, so we create a custom error class like so:\n\n```\nimport { ValidationError } from 'class-validator';\n\nexport class ValidationFailedError extends Error {\n validationErrors: ValidationError[];\n target: any;\n\n constructor(validationErrors) {\n super();\n this.validationErrors = validationErrors;\n this.target = validationErrors[0].target\n }\n}\n```\n\n(We also have a reference to the class we tried to validate, so we can return our object as appropriate)\n\nThen, in `main.ts`, we can set a custom exception factory like so:\n\n```\napp.useGlobalPipes(\n new ValidationPipe({\n exceptionFactory: (validationErrors: ValidationError[] = []) => {\n return new ValidationFailedError(validationErrors);\n },\n }),\n );\n```\n\nNext, we create an `ExceptionFilter` to catch our custom error like so:\n\n```\n@Catch(ValidationFailedError)\nexport class ValidationExceptionFilter implements ExceptionFilter {\n view: string\n objectName: string\n\n constructor(view: string, objectName: string) {\n this.view = view;\n this.objectName = objectName;\n }\n\n async catch(exception: ValidationFailedError, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n\n response.render(this.view, {\n errors: exception.validationErrors,\n [this.objectName]: exception.target,\n url: request.url,\n });\n }\n}\n```\n\nWe also add an initializer, so we can specify what view to render and what the object's name is, so we can set up our filter on a controller method like so:\n\n```\n@Post(':postID')\n @UseFilters(new ValidationExceptionFilter('blog-posts/edit', 'blogPost'))\n @Redirect('/blog-posts', 301)\n async update(\n @Param('id') postID: string,\n @Body() editBlogPostDto: EditBlogPostDto,\n ) {\n await this.blogPostsService.update(postID, editBlogPostDto);\n }\n```\n\nHope this helps some folks, because I like NestJS, but it does seem like the docuemntation and tutorials are much more set up for JSON APIs than for more traditional full stack CRUD apps.\n\n========================================\n\nCode:\n```text\n@UsePipes(ValidationPipe)\n```\n\n```text\n{ errors: ['First error'] }\n```\n\n```text\n@Injectable()\nexport class ErrorsInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    return call$.pipe(\n        // Here you can map (or rethrow) errors\n        catchError(err => ({errors: [err.message]}),\n      ),\n    );\n  }\n}\n```\n\n```text\nInterceptor\n```\n\n```text\n@UseInterceptors(ErrorsInterceptor)\n```\n\n```text\nimport { ValidationError } from 'class-validator';\n\nexport class ValidationFailedError extends Error {\n  validationErrors: ValidationError[];\n  target: any;\n\n  constructor(validationErrors) {\n    super();\n    this.validationErrors = validationErrors;\n    this.target = validationErrors[0].target\n  }\n}\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      exceptionFactory: (validationErrors: ValidationError[] = []) => {\n        return new ValidationFailedError(validationErrors);\n      },\n    }),\n  );\n```\n\n```text\n@Catch(ValidationFailedError)\nexport class ValidationExceptionFilter implements ExceptionFilter {\n  view: string\n  objectName: string\n\n  constructor(view: string, objectName: string) {\n    this.view = view;\n    this.objectName = objectName;\n  }\n\n  async catch(exception: ValidationFailedError, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n\n    response.render(this.view, {\n      errors: exception.validationErrors,\n      [this.objectName]: exception.target,\n      url: request.url,\n    });\n  }\n}\n```\n\n```text\n@Post(':postID')\n  @UseFilters(new ValidationExceptionFilter('blog-posts/edit', 'blogPost'))\n  @Redirect('/blog-posts', 301)\n  async update(\n    @Param('id') postID: string,\n    @Body() editBlogPostDto: EditBlogPostDto,\n  ) {\n    await this.blogPostsService.update(postID, editBlogPostDto);\n  }\n```\n\n```text\nclass-validator\n```\n\n```text\nmain.ts\n```\n\n```text\nExceptionFilter\n```\n\n========================================\n\nComments:\n- Do you have a single hbs error template that you want to render on errors or should the error be rendered in the route's hbs template?\n- Errors should be rendered in the hbs template (in the form).","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":212,"estimatedTokens":1257}}687{"id":"stack-47694296","source":"stackoverflow","questionId":47694296,"title":"How to deploy Nestjs App (on Azure)?","tags":["node.js","express","nestjs"],"text":"Title: How to deploy Nestjs App (on Azure)?\nTags: node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy a Nestjs API (with Auth0 authentication). When I run it in VS Code with `npm run start:watch server`, everything's fine. \nNow the question is: what should I do to deploy it on a webserver? Should I only copy the dist folder (after runnin `tsc`)? what about node_modules? Should I leave the port to 3000?\nAs a side note I am trying to deploy it on Azure but I guess the questions holds for any platform.\n\nMany thanks!\n\n========================================\n\nCode:\n```text\nnpm run start:watch server\n```\n\n```text\ntsc\n```\n\n```text\npostinstall\n```\n\n```text\ntsc\n```\n\n```text\ntsc --sourceMap false\n```\n\n```text\nstart\n```\n\n========================================\n\nComments:\n- Check this it's same case, May help reddit.com/r/node/comments/asi53v/deploying_nestjs_api_to_az&zwnj;&#8203;ure/&hellip;\n- This answer is correct, but the nestjs starter now has these commands already in the package.json, under \"prestart:prod\": \"tsc \", \"start:prod\": \"node dist/main.js\"","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":43,"estimatedTokens":273}}688{"id":"stack-51695868","source":"stackoverflow","questionId":51695868,"title":"How to return a 404 HTTP status code when promise resolve to undefined in Nest?","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: How to return a 404 HTTP status code when promise resolve to undefined in Nest?\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn order to avoid boilerplate code (checking for undefined in every controller, over and over again), how can I automatically return a 404 error when the promise in `getOne` returns undefined?\n\n```\n@Controller('/customers')\nexport class CustomerController {\n constructor (\n @InjectRepository(Customer) private readonly repository: Repository\n ) { }\n\n @Get('/:id')\n async getOne(@Param('id') id): Promise {\n return this.repository.findOne(id)\n .then(result => {\n if (typeof result === 'undefined') {\n throw new NotFoundException();\n }\n\n return result;\n });\n }\n}\n```\n\nNestjs provides an integration with TypeORM and in the example repository is a TypeORM `Repository` instance.\n\n========================================\n\nCode:\n```text\n@Controller('/customers')\nexport class CustomerController {\n  constructor (\n      @InjectRepository(Customer) private readonly repository: Repository<Customer>\n  ) { }\n\n  @Get('/:id')\n  async getOne(@Param('id') id): Promise<Customer|undefined> {\n      return this.repository.findOne(id)\n         .then(result => {\n             if (typeof result === 'undefined') {\n                 throw new NotFoundException();\n             }\n\n             return result;\n         });\n  }\n}\n```\n\n```text\ngetOne\n```\n\n```text\nRepository\n```\n\n```text\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> { {\n    // next.handle() is an Observable of the controller's result value\n    return next.handle()\n      .pipe(tap(data => {\n        if (data === undefined) throw new NotFoundException();\n      }));\n  }\n}\n```\n\n```text\n// Apply the interceptor to *all* endpoints defined in this controller\n@Controller('user')\n@UseInterceptors(NotFoundInterceptor)\nexport class UserController {\n```\n\n```text\n// Apply the interceptor only to this endpoint\n@Get()\n@UseInterceptors(NotFoundInterceptor)\ngetUser() {\n  return Promise.resolve(undefined);\n}\n```\n\n```text\nNotFoundException\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Thanks works very well! It would be great to define the interceptor as a factory, meaning passing arguments without the need to call `new NotFoundInterceptor()`. Do you have any idea how?\n- Great! :-) Have a look at `useFactory` in custom providers. You can inject the arguments of the factory as a provider itself. Depending on your use case, this might be what you need.","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":650}}689{"id":"stack-60345974","source":"stackoverflow","questionId":60345974,"title":"How to create a mongodb connection provider in Nestjs","tags":["node.js","mongodb","typescript","nestjs"],"text":"Title: How to create a mongodb connection provider in Nestjs\nTags: node.js, mongodb, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a database connection provider in Nestjs for MongoDB.\n\nI inspected the `user.controller.ts` and mongoDbProvider by putting breakpoints and found that the controller gets before the database connection is made. How do I make a database connection before the controllers get initialized?\n\nNest.js documentation says that useFactory method will run before any other module that depends on it.\n\n `src/mongo-db/mongodb.provider.ts`\n\n```\nimport { MongoClient } from \"mongodb\";\nimport { MONGODB_PROVIDER } from \"../constants\";\n\nexport const mongoDbProviders = [\n {\n provide: MONGODB_PROVIDER,\n useFactory: async () => {\n MongoClient.connect('mongodb://localhost:27017',\n { useUnifiedTopology: true },\n (error, client) => {\n return client.db('nestjs-sample');\n });\n }\n },\n\n];\n```\n\n `src/mongo-db/mongo-db.module.ts`\n\n```\nimport { mongoDbProviders } from './mongo-db.providers';\n\n@Module({\n providers: [...mongoDbProviders],\n exports: [...mongoDbProviders],\n})\nexport class MongoDbModule {\n\n}\n```\n\n `src/constants.ts`\n\n```\nexport const MONGODB_PROVIDER = 'MONGODB_CONNECTION';\n```\n\nI imported `MongoDbModule` into `user.module.ts`\n\n `src/user/user.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\nimport { MongoDbModule } from 'src/mongo-db/mongo-db.module';\n\n@Module({\n imports: [MongoDbModule],\n controllers: [UserController],\n providers: [UserService]\n})\nexport class UserModule {}\n```\n\nHere I injected the `db` from `mongoDbProvider` into `UserController` constructor. But the constructor runs before db connection.\n\n `src/user/user.controller.ts`\n\n```\nimport { Controller, Post, Req, Get, Res, Inject } from '@nestjs/common';\nimport { Request, Response } from \"express\";\nimport { MONGODB_PROVIDER } from 'src/constants';\n\n@Controller('users')\nexport class UserController {\n\n constructor(@Inject(MONGODB_PROVIDER) private readonly db: any) {\n\n }\n\n @Post()\n async create(@Req() request: Request, @Res() response: Response) {\n this.db.collection('users').insertOne(request.body, (err, result) => {\n if (err) {\n response.status(500).json(err);\n } else {\n response.status(201);\n response.send(result);\n }\n });\n }\n\n @Get()\n get(@Req() request: Request, @Res() response: Response) {\n response.status(400).json({\n message: 'kidilam service'\n });\n }\n\n}\n```\n\n========================================\n\nTop Answer:\nIt is because after the callback is called, the connection object returned is basically lost. If it is a must for you to use a factory provider, you could try using a closure in the callback to MongoClient.connect, together with a value provider. I mean with an approach such as this:\n\n```\nimport { MongoClient } from \"mongodb\";\nimport { MONGODB_PROVIDER } from \"../constants\";\n\nconst MONGODB_PROVIDER_RESOLVED = 'MONGODB_PROVIDER_RESOLVED'\nlet connection = undefined;\nexport const mongoDbProviders = [\n {\n provide: MONGODB_PROVIDER_RESOLVED,\n useValue: connection\n },\n {\n provide: MONGODB_PROVIDER,\n useFactory: async () => {\n MongoClient.connect('mongodb://localhost:27017',\n { useUnifiedTopology: true },\n (error, client) => {\n connection = client.db('nestjs-sample');\n });\n\n }\n },\n\n];\n```\n\nThen inject both MONGODB_PROVIDER and MONGODB_PROVIDER_RESOLVED:\n\n```\nconstructor(@Inject(MONGODB_PROVIDER) private readonly _db: any, @Inject(MONGODB_PROVIDER) private readonly db: any)\n```\n\nThe first dependency injection will force your factory's code to run. The second will hold the resolved connection. That is a bit clumsy, I agree. What could be better would be probably using a class provider:\n\n```\nimport { Injectable } from '@nestjs/common';\n@Injectable()\nexport class MongoDBProvider {\n connection\n constructor(){\n MongoClient.connect('mongodb://localhost:27017',\n { useUnifiedTopology: true },\n ((error, client) => {\n this.connection = client.db('nestjs-sample');\n }).bind(this));\n }\n}\n```\n\nYou can now use it in your controller:\n\n```\nconstructor( private readonly db: MongoDBProvider) {\n\n }\n```\n\n========================================\n\nCode:\n```text\nimport { MongoClient } from \"mongodb\";\nimport { MONGODB_PROVIDER } from \"../constants\";\n\nexport const mongoDbProviders = [\n  {\n    provide: MONGODB_PROVIDER,\n    useFactory: async () => {\n      MongoClient.connect('mongodb://localhost:27017',\n        { useUnifiedTopology: true },\n        (error, client) => {\n          return client.db('nestjs-sample');\n        });\n    }\n  },\n\n];\n```\n\n```text\nimport { mongoDbProviders } from './mongo-db.providers';\n\n@Module({\n  providers: [...mongoDbProviders],\n  exports: [...mongoDbProviders],\n})\nexport class MongoDbModule {\n\n}\n```\n\n```text\nexport const MONGODB_PROVIDER = 'MONGODB_CONNECTION';\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\nimport { MongoDbModule } from 'src/mongo-db/mongo-db.module';\n\n@Module({\n  imports: [MongoDbModule],\n  controllers: [UserController],\n  providers: [UserService]\n})\nexport class UserModule {}\n```\n\n```text\nimport { Controller, Post, Req, Get, Res, Inject } from '@nestjs/common';\nimport { Request, Response } from \"express\";\nimport { MONGODB_PROVIDER } from 'src/constants';\n\n@Controller('users')\nexport class UserController {\n\n  constructor(@Inject(MONGODB_PROVIDER) private readonly db: any) {\n\n  }\n\n  @Post()\n  async create(@Req() request: Request, @Res() response: Response) {\n    this.db.collection('users').insertOne(request.body, (err, result) => {\n      if (err) {\n        response.status(500).json(err);\n      } else {\n        response.status(201);\n        response.send(result);\n      }\n    });\n  }\n\n  @Get()\n  get(@Req() request: Request, @Res() response: Response) {\n    response.status(400).json({\n      message: 'kidilam service'\n    });\n  }\n\n}\n```\n\n```text\nuser.controller.ts\n```\n\n```text\nsrc/mongo-db/mongodb.provider.ts\n```\n\n```text\nsrc/mongo-db/mongo-db.module.ts\n```\n\n```text\nsrc/constants.ts\n```\n\n```text\nMongoDbModule\n```\n\n```text\nuser.module.ts\n```\n\n```text\nsrc/user/user.module.ts\n```\n\n```text\ndb\n```\n\n```text\nmongoDbProvider\n```\n\n```text\nUserController\n```\n\n```text\nsrc/user/user.controller.ts\n```\n\n```text\nimport { MongoClient } from \"mongodb\";\nimport { MONGODB_PROVIDER } from \"../constants\";\n\nexport const mongoDbProviders = [\n  {\n    provide: MONGODB_PROVIDER,\n    useFactory: async () => new Promise((resolve, reject) => {\n      MongoClient.connect('mongodb://localhost:27017',\n      { useUnifiedTopology: true },\n      (error, client) => {\n        if (error) {\n          reject(error);\n        } else {\n          resolve(client.db('nestjs-sample'));\n        }\n      });\n    })\n  },\n];\n```\n\n```text\nuseFactory\n```\n\n```text\nasync\n```\n\n```text\nMongoClient.connect()\n```\n\n```text\nPromise\n```\n\n```text\nimport { MongoClient } from \"mongodb\";\nimport { MONGODB_PROVIDER } from \"../constants\";\n\nconst MONGODB_PROVIDER_RESOLVED = 'MONGODB_PROVIDER_RESOLVED'\nlet connection = undefined;\nexport const mongoDbProviders = [\n  {\n    provide: MONGODB_PROVIDER_RESOLVED,\n    useValue: connection\n  },\n  {\n    provide: MONGODB_PROVIDER,\n    useFactory: async () => {\n      MongoClient.connect('mongodb://localhost:27017',\n        { useUnifiedTopology: true },\n        (error, client) => {\n          connection = client.db('nestjs-sample');\n        });\n\n    }\n  },\n\n];\n```\n\n```text\nconstructor(@Inject(MONGODB_PROVIDER) private readonly _db: any, @Inject(MONGODB_PROVIDER) private readonly db: any)\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\n@Injectable()\nexport class MongoDBProvider {\n    connection\n    constructor(){\n      MongoClient.connect('mongodb://localhost:27017',\n            { useUnifiedTopology: true },\n            ((error, client) => {\n              this.connection = client.db('nestjs-sample');\n            }).bind(this));\n    }\n}\n```\n\n```text\nconstructor( private readonly db: MongoDBProvider) {\n\n  }\n```\n\n```text\nimport { MongoClient, Db } from 'mongodb';\n\nexport const databaseProviders = [\n  {\n    provide: 'DATABASE_CONNECTION',\n    useFactory: async (): Promise<Db> => {\n      try {\n        const client = await MongoClient.connect('mongodb://localhost:27017', {\n          useUnifiedTopology: true,\n        });\n\n        return client.db('my_db');\n      } catch (e) {\n        throw e;\n      }\n    }\n  },\n];\n```\n\n```text\nasync/await\n```\n\n```text\nexport const databaseProviders = [\n  {\n    provide: \"MAIN_DATABASE_CONNECTION\",\n    useFactory: async (): Promise<mongodb.Db> => {\n      try {\n        const client = await mongodb.MongoClient.connect(process.env.CLUSTER, {\n        });\n        const db = client.db(\"dbName\");\n        return db;\n      } catch (error) {\n        throw error;\n      }\n    },\n  }\n]\n```\n\n```text\nuseFactory\n```\n\n```js\n// We can also use MongoClient in nestJs using DipendencyInjection\n// first we have to create database connection \n\n// fileName :- db/dbConnection.service.ts\n\n        import { Injectable } from '@nestjs/common';\n        import { MongoClient } from 'mongodb';\n        import { config } from 'dotenv';\n        config();\n\n        let dbInstance;\n        const url = process.env.MONGO_URL || 'mongodb://localhost:27017/SocialUserEr';\n\n        @Injectable()\n        export class DbConnection {  constructor() {\n            this.connect();\n          }\n          connect() {\n            const client = new MongoClient(url);\n            client\n              .connect()\n              .then((connection) => {\n                dbInstance = connection.db();\n                console.log('Database connection Succeeded');\n              })\n              .catch((err) => {\n                console.log(err);\n              });\n          }\n          db() {\n            if (dbInstance) return dbInstance;\n          }\n        }\n\nThen we have to export it for use anywhere: ex\n\n// fileName:- db/db.module.ts\n\n        import { Module } from '@nestjs/common';\n        import { DbConnection } from './db.service';\n\n        @Module({\n          imports: [],\n          exports: [DbConnection],\n          providers: [DbConnection],\n        })\n        export class DbModule {}\n\n     \n// for Using this connection inside a module you have to import DbModule : ex\n// In this module we want to use db connection so we have to import db module\n\n// fileName:- auth/auth.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { DbModule } from 'src/db/db.module';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\n\n@Module({\n  imports: [DbModule],\n  controllers: [AuthController],\n  providers: [AuthService],\n})\nexport class AuthModule {}\n\n// And lastly for using inside any module you have to just \n// fileName :- auth.service.ts\n\nimport { Injectable } from '@nestjs/common';\nimport { DbConnection } from 'src/db/db.service';\n\n@Injectable()\nexport class AuthService {\n  constructor(private database: DbConnection) {}\n  async createUser(userInfo) {\n    console.log(userInfo);\n    return await this.database.db().collection('user').insertOne(userInfo);\n  }\n}\n\n<!-- begin snippet: js hide: false console: true babel: false -->\n```\n\n```text\nimport { MongoClient } from \"mongodb\";\nimport { MONGODB_PROVIDER } from \"../configs/constants\";\nimport { Logger } from \"@nestjs/common\";\n\nexport const mongoDbProvider = [\n    {\n      provide: MONGODB_PROVIDER,\n      useFactory: async () => {\n        const client = new MongoClient('mongodb://localhost:27017');\n  \n        try {\n          await client.connect();\n          Logger.log(\"Connected to Mongo Database\");\n          return client.db('demo');\n        } catch (error) {\n            Logger.error(`Couldnt connect to Mysql ${error}`, \"MongoProvider\");\n          throw error;\n        }\n      },\n    },\n  ];\n```\n\n========================================\n\nComments:\n- As a consequence, this solution contains a lot of overhead that you can omit using ready to use and available out-of-the-box dedicated @nestjs/mongoose package.\n- I can't use a class provider because the class `MongoDbProvider` will call the constructor but won't wait until the database connection is made. So the `db` object in the controller would be null.\n- This question has been answered already more than a year ago. Please don't add answers that do not improve the existing answers.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":552,"estimatedTokens":3173}}690{"id":"stack-48823174","source":"stackoverflow","questionId":48823174,"title":"How to create decorator in nest.js?","tags":["typescript","decorator","nestjs"],"text":"Title: How to create decorator in nest.js?\nTags: typescript, decorator, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm having troubles with this for quite a while. My decorator is supposed to give information for checking field for unique value. It looks like so:\n\n```\nexport const IsUnique = (\n metadata: {\n entity: any,\n field: string,\n },\n): PropertyDecorator => {\n return createPropertyDecorator(constants.custom_decorators.is_unique, metadata);\n};\n```\n\nAnd my validation looks like so:\n\n```\nimport { HttpException } from '@nestjs/common';\nimport { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common';\nimport {validate, ValidationError} from 'class-validator';\nimport { plainToClass } from 'class-transformer';\nimport constants from '../../../constants';\n\n@Pipe()\nexport class ValidationPipe implements PipeTransform {\n async transform(value, metadata: ArgumentMetadata) {\n console.log(arguments);\n const { metatype } = metadata;\n if (!metatype || !this.toValidate(metatype)) {\n return value;\n }\n\n const object = plainToClass(metatype, value);\n const errors = await validate(object);\n const myErrors = await this.uniqueValidation(object);\n if (errors.length > 0) {\n throw new HttpException(errors, HttpStatus.BAD_REQUEST);\n }\n return value;\n }\n\n private toValidate(metatype): boolean {\n const types = [String, Boolean, Number, Array, Object];\n return !types.find((type) => metatype === type);\n }\n\n private async uniqueValidation(object): Promise{\n const md = Reflect.getMetadata('swagger/apiModelPropertiesArray', object);\n console.log(md);\n\n return null;\n }\n}\n```\n\nAfter executing code, looks like `md=undefined`. So how I can retrieve my metadata? Maybe, I'm using `createPropertyDecorator` in a wrong way?\n\nEDIT:\nAfter couple of hours I realized that nestjs doesn't have `createPropertyDecorator`, I've imported it from swagger module (BIG mistake). So I need to create my own function. Now I'm doing it like so:\n\n```\nexport const IsUnique = (\n metadata: {\n entity: any,\n field: string,\n },\n): PropertyDecorator => {\n return (target: object, propertyKey: string) => {\n const args = Reflect.getMetadata(constants.custom_decorators.is_unique, target, propertyKey) || {};\n const modifiedArgs = Object.assign(args, { IsUnique: metadata.field });\n Reflect.defineMetadata(constants.custom_decorators.is_unique, modifiedArgs, target);\n };\n};\n```\n\nSo, my question is the same - how to properly define metadata, so it never interference with others?\n\n========================================\n\nCode:\n```text\nexport const IsUnique = (\n  metadata: {\n    entity: any,\n    field: string,\n  },\n): PropertyDecorator => {\n  return createPropertyDecorator(constants.custom_decorators.is_unique, metadata);\n};\n```\n\n```text\nimport { HttpException } from '@nestjs/common';\nimport { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common';\nimport {validate, ValidationError} from 'class-validator';\nimport { plainToClass } from 'class-transformer';\nimport constants from '../../../constants';\n\n@Pipe()\nexport class ValidationPipe implements PipeTransform<any> {\n  async transform(value, metadata: ArgumentMetadata) {\n    console.log(arguments);\n    const { metatype } = metadata;\n    if (!metatype || !this.toValidate(metatype)) {\n      return value;\n    }\n\n    const object = plainToClass(metatype, value);\n    const errors = await validate(object);\n    const myErrors = await this.uniqueValidation(object);\n    if (errors.length > 0) {\n      throw new HttpException(errors, HttpStatus.BAD_REQUEST);\n    }\n    return value;\n  }\n\n  private toValidate(metatype): boolean {\n    const types = [String, Boolean, Number, Array, Object];\n    return !types.find((type) => metatype === type);\n  }\n\n  private async uniqueValidation(object): Promise<ValidationError[]|null>{\n    const md = Reflect.getMetadata('swagger/apiModelPropertiesArray', object);\n    console.log(md);\n\n    return null;\n  }\n}\n```\n\n```text\nexport const IsUnique = (\n  metadata: {\n    entity: any,\n    field: string,\n  },\n): PropertyDecorator => {\n  return (target: object, propertyKey: string) => {\n    const args = Reflect.getMetadata(constants.custom_decorators.is_unique, target, propertyKey) || {};\n    const modifiedArgs = Object.assign(args, { IsUnique: metadata.field });\n    Reflect.defineMetadata(constants.custom_decorators.is_unique, modifiedArgs, target);\n  };\n};\n```\n\n```text\nmd=undefined\n```\n\n```text\ncreatePropertyDecorator\n```\n\n```text\ncreatePropertyDecorator\n```\n\n```text\nexport class SignInUser {\n    @IsEmail()\n    email: string;\n\n    @Length(6, 50)\n    password: string;\n}\n```\n\n```text\nsignIn(@Body(new ValidationPipe()) signIn: SignInUser) {}\n```\n\n```text\nNOTE: I use ValidationPipe from @nestjs/common\n```\n\n========================================\n\nComments:\n- I need to check if user email is unique. How do i achieve that?\n- Here is example github.com/typestack/class-validator/blob/master/sample/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":184,"estimatedTokens":1229}}691{"id":"stack-67237523","source":"stackoverflow","questionId":67237523,"title":"OAuth2 flow in full-stack NestJS application","tags":["express","oauth-2.0","google-oauth","passport.js","nestjs"],"text":"Title: OAuth2 flow in full-stack NestJS application\nTags: express, oauth-2.0, google-oauth, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nYet another OAuth2 question that isn't quite covered elsewhere.\n\nI'm using NestJS backend, React frontend, Passport and my own DB for authentication. Trying to add an\nOAuth2 identity provider (Google).\n\nI configured my NestJS app as an OAuth Client. After logging in I'm receiving the callback at which point I have an `access_token` and the requested user details extracted from the payload of the `id_token`. This is encapsulated in a class extending `PassportStrategy(Strategy, 'google')` and an `AuthGuard('google')` and much of it is handled automatically. Code here.\n\nAt this point however, I need to maintain an authenticated session between backend (NestJS) and frontend (React). I suppose I need a JWT, but I'm wondering about the best approach:\n\n- Can I use a token provided by the IdP (e.g. `id_token` or `access_token`)? So that I don't have to worry about issuing tokens myself. I.e. the frontend receives the token (either from backend, or the IdP directly), sends it on every request, backend verifies it with the IdP on every request (`verifyIdToken` or `getTokenInfo` of `google-auth-library`).\n\nOne drawback here is the extra network request every time. I'm not sure if there's a need for that because the IdP is only used to identify the user, not for access to other resources. Another drawback is that I need to store a refresh token and handle when the token expires (get new one, update it on the frontend).\n\n- So alternatively, could I just issue a JWT myself and not worry about checking in with the IdP? Once the JWT expires I'd need to prompt the user to log in again. In this case, I wouldn't need to store the IdP tokens. But is this good practice? One issue I can think of is that I won't detect if the user revokes access in the IdP (until the JWT expires).\n\n========================================\n\nTop Answer:\nprobably my solution would be helpful.\n\nyou could access complete source code of my app that implemented with react typescript (redux toolkit rtk Query) and nestjs included of google oauth2 flow with passport.js. resource\n\n========================================\n\nCode:\n```text\naccess_token\n```\n\n```text\nid_token\n```\n\n```text\nPassportStrategy(Strategy, 'google')\n```\n\n```text\nAuthGuard('google')\n```\n\n```text\nid_token\n```\n\n```text\naccess_token\n```\n\n```text\nverifyIdToken\n```\n\n```text\ngetTokenInfo\n```\n\n```text\ngoogle-auth-library\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":65,"estimatedTokens":631}}692{"id":"stack-63853358","source":"stackoverflow","questionId":63853358,"title":"How to do code sharing in NestJS through Yarn Workspaces","tags":["typescript","next.js","nestjs","monorepo","yarn-workspaces"],"text":"Title: How to do code sharing in NestJS through Yarn Workspaces\nTags: typescript, next.js, nestjs, monorepo, yarn-workspaces\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do a proof of concept for a simple monorepo application. I decided to just use `Yarn Workspaces` (I think Lerna maybe here is overkill) to set up my package architecture.\n\nI have a `shared` package that I'm using to code with the frontend and the backend. I successfully achieved to make it works for the frontend (As I'm using NextJS in the frontend there was already a NPM library named next-transpile-module to get everything running up smoothly) but now, I'm stuck at the backend, and I'm not sure if it's even possible because I couldn't find information on Google.\n\nHere's the error that it's throwing up when I try to start the API:\n\n```\n/Users/Alfonso/git/taurus/packages/shared/dist/index.js:1\nexport var PRODUCT_NAME = \"ACME\";\n^^^^^^\n\nSyntaxError: Unexpected token 'export'\n at wrapSafe (internal/modules/cjs/loader.js:1054:16)\n at Module._compile (internal/modules/cjs/loader.js:1102:27)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n at Module.load (internal/modules/cjs/loader.js:986:32)\n at Function.Module._load (internal/modules/cjs/loader.js:879:14)\n at Module.require (internal/modules/cjs/loader.js:1026:19)\n at require (internal/modules/cjs/helpers.js:72:18)\n at Object. (/Users/Alfonso/git/taurus/packages/api/dist/app.service.js:11:18)\n at Module._compile (internal/modules/cjs/loader.js:1138:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n```\n\nIt's exactly the same error (`Unexpected token 'export'`) that I was getting in the `client` package, but as I mentioned, that NPM lib named `next-transpile-module` fixed it.. so it should be something related to transpilation but I have no idea! :)\n\n========================================\n\nTop Answer:\nAnd what would be the solution?\n\nTo elaborate on a solution for this. When running yarn workspace I am able to transpile a shared typescript library for Next.js because of `next-transpile-module` by simply running `yarn workspace @project/app start`. The same solution doesn't work for my backend `Nest.js` service. Running `yarn workspace @project/service start` will resolve in `SyntaxError: Unexpected token 'export'`.\n\nTo fix this, you'll need to build the shared library first targeting `commonjs` and configure the service to run the built code instead.\n\n**project/packages/common/package.json**\n\n```\n{\n \"name\": \"@project/common\",\n \"version\": \"1.0.0\",\n \"main\": \"dist/index\",\n \"license\": \"MIT\",\n \"private\": true,\n \"scripts\": {\n \"build\": \"tsc\",\n \"start\": \"yarn build & node ./dist/index\"\n },\n \"devDependencies\": {\n \"typescript\": \"^4.8.4\"\n }\n}\n```\n\n**project/packages/common/tsconfig.json**\n\n```\n{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"lib\": [\"esnext\"],\n \"esModuleInterop\": true,\n \"allowSyntheticDefaultImports\": true,\n \"strict\": true,\n \"rootDir\": \"src\",\n \"outDir\": \"dist\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"baseUrl\": \"./src\",\n \"noImplicitAny\": true\n },\n \"include\": [\"src\"]\n}\n```\n\n**/project/packages/service/package.json**\n\n```\n{\n \"name\": \"@project/service\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"author\": \"\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"start\": \"nest start\",\n },\n \"dependencies\": {\n \"@project/common\": \"*\",\n ...\n }\n}\n```\n\nBuilt the shared libs to `commonjs` and use the built files instead. There may be better ways of doing this since having to build isn't ideal. It's possible that we can do more with `ts-node` and transpile the shared library at runtime somehow.\n\n========================================\n\nCode:\n```text\n/Users/Alfonso/git/taurus/packages/shared/dist/index.js:1\nexport var PRODUCT_NAME = \"ACME\";\n^^^^^^\n\nSyntaxError: Unexpected token 'export'\n    at wrapSafe (internal/modules/cjs/loader.js:1054:16)\n    at Module._compile (internal/modules/cjs/loader.js:1102:27)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n    at Module.load (internal/modules/cjs/loader.js:986:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:879:14)\n    at Module.require (internal/modules/cjs/loader.js:1026:19)\n    at require (internal/modules/cjs/helpers.js:72:18)\n    at Object.<anonymous> (/Users/Alfonso/git/taurus/packages/api/dist/app.service.js:11:18)\n    at Module._compile (internal/modules/cjs/loader.js:1138:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n```\n\n```text\nYarn Workspaces\n```\n\n```text\nshared\n```\n\n```text\nUnexpected token 'export'\n```\n\n```text\nclient\n```\n\n```text\nnext-transpile-module\n```\n\n```text\nexports\n```\n\n```text\nmodule.exports\n```\n\n```text\nexports\n```\n\n```text\n{\n  \"name\": \"@project/common\",\n  \"version\": \"1.0.0\",\n  \"main\": \"dist/index\",\n  \"license\": \"MIT\",\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"start\": \"yarn build & node ./dist/index\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^4.8.4\"\n  }\n}\n```\n\n```text\n{\n  \"extends\": \"../../tsconfig.json\",\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"esnext\"],\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"rootDir\": \"src\",\n    \"outDir\": \"dist\",\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"baseUrl\": \"./src\",\n    \"noImplicitAny\": true\n  },\n  \"include\": [\"src\"]\n}\n```\n\n```text\n{\n  \"name\": \"@project/service\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"start\": \"nest start\",\n  },\n  \"dependencies\": {\n    \"@project/common\": \"*\",\n    ...\n  }\n}\n```\n\n```text\nnext-transpile-module\n```\n\n```text\nyarn workspace @project/app start\n```\n\n```text\nNest.js\n```\n\n```text\nyarn workspace @project/service start\n```\n\n```text\nSyntaxError: Unexpected token 'export'\n```\n\n```text\ncommonjs\n```\n\n```text\ncommonjs\n```\n\n```text\nts-node\n```\n\n========================================\n\nComments:\n- And what would be the solution?","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":251,"estimatedTokens":1540}}693{"id":"stack-61368016","source":"stackoverflow","questionId":61368016,"title":"Nest: ENOENT: no such file or directory, open","tags":["angular","nestjs"],"text":"Title: Nest: ENOENT: no such file or directory, open\nTags: angular, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm creating a saml strategy and I created a certs folder with my keys in it. The problem is that when I build the project I get this error:\n\n```\n[Nest] 14078 - 04/22/2020, 4:33:34 PM [ExceptionHandler] ENOENT: no such file or directory, open '/Users/wilsonsilva/Desktop/EduTec/formations-tool/dist/server-app/src/auth/certs/key.pem' +115ms\n```\n\nSo when I went to the specified path (dist folder) the folder *certs* folder was indeed missing. Can someone help me find a solution?\n\nI'm using Angular 8 with Ng Universal (NestJS)\n\n========================================\n\nTop Answer:\ndelete the dist folders and then restart your project\n\n========================================\n\nCode:\n```text\n[Nest] 14078   - 04/22/2020, 4:33:34 PM   [ExceptionHandler] ENOENT: no such file or directory, open '/Users/wilsonsilva/Desktop/EduTec/formations-tool/dist/server-app/src/auth/certs/key.pem' +115ms\n```\n\n```text\n/dist/\n```\n\n```text\nkey.pem\n```\n\n```text\nkey.pem\n```\n\n========================================\n\nComments:\n- Did you try searching this site for `[angular] ENOENT no such file`? It appears to have several existing questions and answers that might help.","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":43,"estimatedTokens":317}}694{"id":"stack-70847785","source":"stackoverflow","questionId":70847785,"title":"How Typeorm define stored procedures, functions and triggers to DB. With migrations if possible","tags":["typescript","stored-procedures","nestjs","typeorm"],"text":"Title: How Typeorm define stored procedures, functions and triggers to DB. With migrations if possible\nTags: typescript, stored-procedures, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a stored function in a Postgress DB. The reason is that we might have several consumers from this DB, and we currently use the Migrations of typeorm to generate our tables from our entities.\n\nLooking into the documentation of typeorm and the source code of the library I find that there are some implementations of \"Listeners\" to certain events and \"Subscribers\" as well.\n\nThe problem with this approach is that it is tight to the technology or ORM itself...\n\nIs it possible to generate a raw query as a migration with a similar definition to this:\n\n```\nimport { MigrationInterface, QueryRunner } from \"typeorm\";\n\nexport class ProcedureCreation123123123 implements MigrationInterface {\n name = 'ProcedureCreation123123123'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`\n CREATE OR REPLACE FUNCTION validate_update() RETURNS TRIGGER\n BEGIN\n ...\n END;\n CREATE TRIGGER validate_update_value\n BEFORE UPDATE\n ON table\n FOR EACH ROW\n EXECUTE PROCEDURE validate_update();\n `);\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`DROP TRIGGER \"validate_update_value\"`);\n }\n\n}\n```\n\nI went through the generate of a migration documentation of typeorm to see how to generate such a migration, but the only way to generate it is by having differences in the entities in relation to the DB.\n\nAdding a listener to the entity to try to generate the trigger as part of the migration did not work either. And the generation stated there were no changes in database schema.\n\nOne more alternative would be to invoke on module init of my nestjs service to define a raw query that will do exactly this things, but it sounds wrong to run such a code everytime I start the service and may be add or not this function...\n\nIf there is any advice on how to do such a change to my DB in conjunction with the migrations of typeorm would be great.\n\n========================================\n\nCode:\n```text\nimport { MigrationInterface, QueryRunner } from \"typeorm\";\n\nexport class ProcedureCreation123123123 implements MigrationInterface {\n    name = 'ProcedureCreation123123123'\n\n    public async up(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.query(`\n          CREATE OR REPLACE FUNCTION validate_update() RETURNS TRIGGER\n          BEGIN\n            ...\n          END;\n          CREATE TRIGGER validate_update_value\n          BEFORE UPDATE\n            ON table\n            FOR EACH ROW\n            EXECUTE PROCEDURE validate_update();\n        `);\n    }\n\n    public async down(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.query(`DROP TRIGGER \"validate_update_value\"`);\n    }\n\n}\n```\n\n```text\ntypeorm migration:create -n NameOfMigration\n```\n\n```text\nup\n```\n\n```text\ndown\n```\n\n========================================\n\nComments:\n- Thanks for showing me how to define custom PG function in TypeORM, I couldn't find this in their docs. Really helped!","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":94,"estimatedTokens":786}}695{"id":"stack-61864912","source":"stackoverflow","questionId":61864912,"title":"Processing an exception through Apollo Server (NestJS)","tags":["node.js","exception","graphql","nestjs","apollo-server"],"text":"Title: Processing an exception through Apollo Server (NestJS)\nTags: node.js, exception, graphql, nestjs, apollo-server\nSource: Stack Overflow\n\nQuestion:\nis there a way how to run an exception through the apollo exception handler manually?\n\nI have 90% of the application in GraphQL but still have two modules as REST and I'd like to unify the way the exceptions are handled.\n\nSo the GQL queries throw the standard 200 with errors array containing message, extensions etc.\n\n```\n{\n \"errors\": [\n {\n \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n \"locations\": [{ \"line\": 2, \"column\": 3 }],\n \"path\": [ \"users\" ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"response\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n \"status\": 401,\n \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" }\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\nwhere the REST throws the real 401 with JSON:\n\n```\n{\n \"statusCode\": 401,\n \"error\": \"Unauthorized\"\n}\n```\n\nSo can I simply catch and wrap the **exception in the Apollo Server format** or do I have to format my REST errors manually? Thanks\n\nI am using NestJS and the GraphQL module.\n\n========================================\n\nTop Answer:\nFor future readers who also get the `response.status is not a function` error: For me trying to return an HTTP response in GraphQL mode did not work. You can prevent this by extending the answer of eol and using a switch on the `host`'s `type` to do the right error handling. For GraphQL for example this worked well in my case:\n\n```\n@Catch(RestApiError)\nexport class RestApiErrorFilter implements ExceptionFilter {\n catch (exception: RestApiError, host: GqlArgumentsHost) {\n switch (host.getType ()) {\n case 'http':\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const status = 200;\n response\n .status(status)\n .json(RestApiErrorFilter.getApolloServerFormatError(exception));\n break;\n case 'graphql':\n throw exception;\n break;\n default:\n throw new Error('unsupported host type' + host.getType())\n }\n }\n}\n```\n\nSadly you will still need to handle Apollo's `ApolloError.graphQLErrors` in the front-end separately.\n\n========================================\n\nCode:\n```text\n{\n  \"errors\": [\n    {\n      \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n      \"locations\": [{ \"line\": 2, \"column\": 3 }],\n      \"path\": [ \"users\" ],\n      \"extensions\": {\n        \"code\": \"INTERNAL_SERVER_ERROR\",\n        \"exception\": {\n          \"response\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n          \"status\": 401,\n          \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" }\n        }\n      }\n    }\n  ],\n  \"data\": null\n}\n```\n\n```text\n{\n    \"statusCode\": 401,\n    \"error\": \"Unauthorized\"\n}\n```\n\n```text\n@Catch(RestApiError)\nexport class RestApiErrorFilter implements ExceptionFilter {\n    catch(exception: RestApiError, host: ArgumentsHost) {\n        const ctx      = host.switchToHttp();\n        const response = ctx.getResponse();\n        const status   = 200;\n        response\n            .status(status)                \n            .json(RestApiErrorFilter.getApolloServerFormatError(exception);\n}\n\nprivate static getApolloServerFormatError(exception: RestApiErrorFilter) {\n    return {}; // do your conversion here\n}\n```\n\n```js\n@Catch(RestApiError)\nexport class RestApiErrorFilter implements ExceptionFilter {\n  catch (exception: RestApiError, host: GqlArgumentsHost) {\n    switch (host.getType < GqlContextType > ()) {\n      case 'http':\n        const ctx = host.switchToHttp();\n        const response = ctx.getResponse();\n        const status = 200;\n        response\n          .status(status)\n          .json(RestApiErrorFilter.getApolloServerFormatError(exception));\n        break;\n      case 'graphql':\n        throw exception;\n        break;\n      default:\n        throw new Error('unsupported host type' + host.getType())\n    }\n  }\n}\n```\n\n```text\nresponse.status is not a function\n```\n\n```text\nhost\n```\n\n```text\ntype\n```\n\n```text\nApolloError.graphQLErrors\n```\n\n========================================\n\nComments:\n- Yes this sounds good enough and I was thinking of this solution but I have to do the conversion myself - I was hoping I could somehow execute the Apollo Server Error Handler so it does most of the conversion for me...\n- Oh ok, I missed that, sorry! Maybe you could import this error class (github.com/apollographql/apollo-server/blob/&hellip;) and throw such an error instance? It should then be caught by the corresponding error handler: github.com/apollographql/apollo-server/blob/master/packages/&zwnj;&#8203;&hellip;\n- That looks promising! Thanks a lot - I'll give it a try this week!\n- For me it says response.status is not a function :(\n- @SerShubham: Please post a new question with all the details, thank you.","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":170,"estimatedTokens":1192}}696{"id":"stack-62794555","source":"stackoverflow","questionId":62794555,"title":"How Test e2e Nestjs API with GRAPHQL","tags":["testing","graphql","nestjs","e2e-testing","graphql-mutation"],"text":"Title: How Test e2e Nestjs API with GRAPHQL\nTags: testing, graphql, nestjs, e2e-testing, graphql-mutation\nSource: Stack Overflow\n\nQuestion:\nWhen I create my Owner via graphql-playground it works fine,\nbut my test fail and response me that 'body.data.createOwner is undefined', there no data.\n\n```\n// owner.e2e.spec.ts\ndescribe('Owner test (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleRef = await Test.createTestingModule({\n imports: [\n GraphQLModule.forRoot({\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n }),\n OwnerModule,\n DatabaseModule\n ]\n }).compile();\n app = moduleRef.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await app.close();\n })\n\n const createOwnerQuery = `\n mutation createOwner($OwnerInput: OwnerInput!) {\n createOwner(ownerInput: $OwnerInput) {\n _id\n name\n firstname\n email\n password\n firstsub\n expsub\n createdAt\n updatedAt\n }\n }\n `;\n \n let id: string = '';\n\n it('createOwner', () => {\n return request(app.getHttpServer())\n .post('/graphql')\n .send({\n operationName: 'createOwner',\n variables: {\n OwnerInput: {\n name: 'adar',\n firstname: 'adar',\n email: 'adar@test.com',\n password: 'testing',\n firstsub: '2020-08-14',\n expsub: '2020-07-13'\n }\n },\n query: createOwnerQuery,\n })\n .expect(({ body }) => {\n const data = body.data.createOwner {\n > 100 | const data = body.data.createOwner\n | ^\n 101 | id = data._id\n 102 | expect(data.name).toBe(owner.name)\n 103 | expect(data.email).toBe(owner.email)\n\n at owner.e2e-spec.ts:100:40\n at Test._assertFunction (../node_modules/supertest/lib/test.js:283:11)\n at Test.assert (../node_modules/supertest/lib/test.js:173:18)\n at Server.localAssert (../node_modules/supertest/lib/test.js:131:12)\n\nTest Suites: 1 failed, 1 total\nTests: 1 failed, 1 total\nSnapshots: 0 total\nTime: 9.645 s, estimated 10 s\nRan all test suites.\n```\n\n========================================\n\nCode:\n```text\n// owner.e2e.spec.ts\ndescribe('Owner test (e2e)', () => {\n    let app: INestApplication;\n\n    beforeAll(async () => {\n        const moduleRef = await Test.createTestingModule({\n            imports: [\n                GraphQLModule.forRoot({\n                    autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n                }),\n                OwnerModule,\n                DatabaseModule\n            ]\n        }).compile();\n        app = moduleRef.createNestApplication();\n        await app.init();\n    });\n\n    afterAll(async () => {\n        await app.close();\n    })\n\n    const createOwnerQuery = `\n           mutation createOwner($OwnerInput: OwnerInput!) {\n            createOwner(ownerInput: $OwnerInput) {\n              _id\n              name\n              firstname\n              email\n              password\n              firstsub\n              expsub\n              createdAt\n              updatedAt\n            }\n          }\n    `;\n   \n    let id: string = '';\n\n    it('createOwner', () => {\n        return request(app.getHttpServer())\n            .post('/graphql')\n            .send({\n                operationName: 'createOwner',\n                variables: {\n                   OwnerInput: {\n                        name: 'adar',\n                        firstname: 'adar',\n                        email: 'adar@test.com',\n                        password: 'testing',\n                        firstsub: '2020-08-14',\n                        expsub: '2020-07-13'\n                    }\n                },\n                query: createOwnerQuery,\n            })\n            .expect(({ body }) => {\n                const data = body.data.createOwner <-- test fail at this line\n                id = data._id\n                expect(data.name).toBe(owner.name)\n                expect(data.email).toBe(owner.email)\n                expect(data.firstsub).toBe(owner.firstsub)\n            })\n            .expect(200)\n    })\n```\n\n```text\n// Output terminal\n\n FAIL  test/owner.e2e-spec.ts (9.567 s)\n  Owner test (e2e)\n    โœ• createOwner (79 ms)\n\n  โ— Owner test (e2e) โ€บ createOwner\n\n    TypeError: Cannot read property 'createOwner' of undefined\n\n       98 |             })\n       99 |             .expect(({ body }) => {\n    > 100 |                 const data = body.data.createOwner\n          |                                        ^\n      101 |                 id = data._id\n      102 |                 expect(data.name).toBe(owner.name)\n      103 |                 expect(data.email).toBe(owner.email)\n\n      at owner.e2e-spec.ts:100:40\n      at Test._assertFunction (../node_modules/supertest/lib/test.js:283:11)\n      at Test.assert (../node_modules/supertest/lib/test.js:173:18)\n      at Server.localAssert (../node_modules/supertest/lib/test.js:131:12)\n\nTest Suites: 1 failed, 1 total\nTests:       1 failed, 1 total\nSnapshots:   0 total\nTime:        9.645 s, estimated 10 s\nRan all test suites.\n```\n\n========================================\n\nComments:\n- is owner a module or the entire app?\n- it's a module (also my entity)\n- Try just importing your `AppModule` instead, it will contain all the setup needed to run your application normally.","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":195,"estimatedTokens":1267}}697{"id":"stack-59475068","source":"stackoverflow","questionId":59475068,"title":"Prevent restart of NestJS Server when making changes in certain directories","tags":["typescript","webpack","nestjs"],"text":"Title: Prevent restart of NestJS Server when making changes in certain directories\nTags: typescript, webpack, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using the default `nest start --watch` command to run the application in watch mode.\n\nThe server restarts upon the change of any source file, which is as expected.\n\nHowever, I need to ignore some directories or files from restarting the server when a change occurs.\n\nIs there a way to achieve this in NestJS?\n\n========================================\n\nTop Answer:\nI was able to fix this by editing tsconfig.build.json file and add the folder to the exclude array.\n\"exclude\": [..., \"your-folder\"]\n\n========================================\n\nCode:\n```text\nnest start --watch\n```\n\n```text\n{\n    \"watch\": [\"src\"],\n    \"ext\": \"ts\",  \n    \"ignore\": [\"public\"],\n    \"exec\": \"ts-node ./src/main\"\n  }\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntsconfig.build.json\n```\n\n```text\n\"exclude\": [..., \"your-folder\"]\n```\n\n========================================\n\nComments:\n- I think it starts tsc in watch mode, and you can configure what is going to be ignored in tsc configuration, I think in that case those files are not going to be transpiled to js. So looks like; no there is no way.\n- Imo, I'd take a look at what the nest cli does, how it is linked to wepback's config (hot reload feature from it notably I guess). Don't have time to investigate further as of now, will take a look later if you're still stuck\n- Hi @A.Maitre, have you had a chance to investigate on this issue yet? My name is Nechar. I am stuck in the same issue as Nik. The solution provided by WRAD did not work for me.\n- I still would like TypeScript to transpile my .ts files to .js files. I just need to prevent the server from a re-start on few directories.\n- The solution that you provided would only help prevent the TS file from being compiled to JS. But it wouldn't stop the server from being restart.\n- How about for newer versions of NestJS where nodemon is no longer used?\n- @avejidah even if nest does not use nodemon, you can still tsc --watch and use nodemon in development.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.462Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":58,"estimatedTokens":595}}698{"id":"stack-79781811","source":"stackoverflow","questionId":79781811,"title":"npm i successful but no @types/node","tags":["node.js","typescript","npm","nestjs"],"text":"Title: npm i successful but no @types/node\nTags: node.js, typescript, npm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run a NestJS project that worked perfectly before, but after a full reset of my Mac I'm hitting a weird TypeScript error:\n\n```\nsrc/health/health.service.ts:13:20 - error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.\n\n13 environment: process.env.NODE_ENV || 'development',\n ~~~~~~~\n\n[15:55:39] Found 38 errors. Watching for file changes.\n```\n\nI tried installing the types:\n\n```\nnpm i --save-dev @types/node\n```\n\nOutput:\n\n```\nup to date, audited 209 packages in 2s\n\n41 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\n```\n\nBut the package is not actually there:\n\n```\nโฏ ls node_modules/@types/node | head\n\nls: node_modules/@types/node: No such file or directory\n```\n\nSo npm reports success, but `node_modules/@types/node` is missing.\n\nEnvironment:\n\n```\nโฏ node -v\nv20.19.5\nโฏ npm -v\n10.8.2\n```\n\nThings I already tried:\n\n`rm -rf node_modules package-lock.json`\n\n`npm cache clean --force`\n\nnvm uninstall + reinstall Node\n\nInstalling `@types/node` explicitly (`npm install --save-dev @types/node@20`)\n\nInstalling via tarball (`npm install --save-dev https://registry.npmjs.org/@types/node/-/node-22.7.9.tgz`)\n\nVerified registry:\n\n```\nโฏ npm config get registry\nhttps://registry.npmjs.org/\n```\n\ntried also creating a new folder -> `npm init` -> intall @types/node and still not working\n\nChecked with `npm list @types/node` โ†’ always shows (empty)\n\nNone of these fixed it.\n\nThings I did not try but right now seem like a good idea:\n\n- try yarn\n\n- Manually extracting the tarball into `node_modules/@types/node`\n\nWhy does npm claim `@types/node` is installed, but the folder is missing? How can I fix this so TypeScript recognizes Node globals (process, fs, path, etc.) again?\n\nEDIT 1:\n\ncommand:\nโฏ npm --verbose i --save-dev @types/node\nOutput:\n\n```\nnpm verbose cli /Users/alexandrusandu/.nvm/versions/node/v20.19.5/bin/node /Users/alexandrusandu/.nvm/versions/node/v20.19.5/bin/npm\nnpm info using npm@10.8.2\nnpm info using node@v20.19.5\nnpm verbose title npm i @types/node\nnpm verbose argv \"--loglevel\" \"verbose\" \"i\" \"--save-dev\" \"@types/node\"\nnpm verbose logfile logs-max:10 dir:/Users/alexandrusandu/.npm/_logs/2025-10-03T13_32_14_397Z-\nnpm verbose logfile /Users/alexandrusandu/.npm/_logs/2025-10-03T13_32_14_397Z-debug-0.log\nnpm http fetch GET 200 https://registry.npmjs.org/@types%2fnode 341ms (cache revalidated)\nnpm http fetch POST 200 https://registry.npmjs.org/-/npm/v1/security/advisories/bulk 265ms\n\nup to date, audited 209 packages in 2s\n\n41 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\nnpm verbose cwd /Users/alexandrusandu/workspace/magic/configuratorxstate\nnpm verbose os Darwin 24.6.0\nnpm verbose node v20.19.5\nnpm verbose npm v10.8.2\nnpm verbose exit 0\nnpm info ok\n\nโฏ ls node_modules/@types/node\nls: node_modules/@types/node: No such file or directory\n```\n\nEDIT 2 (still not fixed just a stupid workaround):\n\nI tried Manually extracting the tarball into `node_modules/@types/node` and the project starts without an issue.\n\nEDIT 3\nFound out it is not a dependency issue as it is not limited to \"@types/node\". Discovered that same thing is happening for \"eslint-plugin-filenames\".\n\nHOW TO FIX:\n\nFinallhy found the issue. Don't know the root cause tho. VSCode is injecting in the integrated temrinal NODE_ENV=production so devDependencies are not installed. So if anybody has this issue the way to solve it is either in the integrated terminal rewrite that to development or find where VSCode has that setting to inject it. I am still searching for that myself.\n\n========================================\n\nTop Answer:\nWhat you describe can't happen normally.\n\nTry another npm version (11 at this moment) with `npm i -g npm@11`. If you don't want to change it globally, use `npx npm@11 i`.\n\nThat you keep doing `npm i --save-dev @types/node` every time is unneeded and potentially faulty. You need to do this once, check that `@types/node` appeared in package.json, then do:\n\n```\nrm -rf node_modules package-lock.json && npm i --verbose\n```\n\nAnd then you can expect that either all packages are installed or it fails.\n\nIt could be one of many npm's unresolved bugs. Try Yarn 1.x aka Yarn Classic with `npm i -g yarn@1`, it's a more stable npm replacement.\n\n========================================\n\nCode:\n```text\nsrc/health/health.service.ts:13:20 - error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.\n\n13       environment: process.env.NODE_ENV || 'development',\n                      ~~~~~~~\n\n[15:55:39] Found 38 errors. Watching for file changes.\n```\n\n```bash\nnpm i --save-dev @types/node\n```\n\n```none\nup to date, audited 209 packages in 2s\n\n41 packages are looking for funding\n  run `npm fund` for details\n\nfound 0 vulnerabilities\n```\n\n```bash\nโฏ ls node_modules/@types/node | head\n\nls: node_modules/@types/node: No such file or directory\n```\n\n```bash\nโฏ node -v\nv20.19.5\nโฏ npm -v\n10.8.2\n```\n\n```bash\nโฏ npm config get registry\nhttps://registry.npmjs.org/\n```\n\n```text\nnpm verbose cli /Users/alexandrusandu/.nvm/versions/node/v20.19.5/bin/node /Users/alexandrusandu/.nvm/versions/node/v20.19.5/bin/npm\nnpm info using npm@10.8.2\nnpm info using node@v20.19.5\nnpm verbose title npm i @types/node\nnpm verbose argv \"--loglevel\" \"verbose\" \"i\" \"--save-dev\" \"@types/node\"\nnpm verbose logfile logs-max:10 dir:/Users/alexandrusandu/.npm/_logs/2025-10-03T13_32_14_397Z-\nnpm verbose logfile /Users/alexandrusandu/.npm/_logs/2025-10-03T13_32_14_397Z-debug-0.log\nnpm http fetch GET 200 https://registry.npmjs.org/@types%2fnode 341ms (cache revalidated)\nnpm http fetch POST 200 https://registry.npmjs.org/-/npm/v1/security/advisories/bulk 265ms\n\nup to date, audited 209 packages in 2s\n\n41 packages are looking for funding\n  run `npm fund` for details\n\nfound 0 vulnerabilities\nnpm verbose cwd /Users/alexandrusandu/workspace/magic/configuratorxstate\nnpm verbose os Darwin 24.6.0\nnpm verbose node v20.19.5\nnpm verbose npm  v10.8.2\nnpm verbose exit 0\nnpm info ok\n\n\n\nโฏ  ls node_modules/@types/node\nls: node_modules/@types/node: No such file or directory\n```\n\n```text\nnode_modules/@types/node\n```\n\n```text\nrm -rf node_modules package-lock.json\n```\n\n```text\nnpm cache clean --force\n```\n\n```text\n@types/node\n```\n\n```text\nnpm install --save-dev @types/node@20\n```\n\n```text\nnpm install --save-dev https://registry.npmjs.org/@types/node/-/node-22.7.9.tgz\n```\n\n```text\nnpm init\n```\n\n```text\nnpm list @types/node\n```\n\n```text\nnode_modules/@types/node\n```\n\n```text\n@types/node\n```\n\n```text\nnode_modules/@types/node\n```\n\n```text\nrm -rf node_modules package-lock.json && npm i --verbose\n```\n\n```text\nnpm i -g npm@11\n```\n\n```text\nnpx npm@11 i\n```\n\n```text\nnpm i --save-dev @types/node\n```\n\n```text\n@types/node\n```\n\n```text\nnpm i -g yarn@1\n```\n\n========================================\n\nComments:\n- What is your working directory when you run these commands? Are you at the project root (the same directory as your `package.json`)? After running `npm i --save-dev @types&#47;node`, do you see `@types&#47;node` in your `package.json`?\n- Project root, of course. \"devDependencies\": { ... \"@types/node\": \"^20.19.19\", ... },\n- Can you try again with `--verbose` (`npm --verbose i --save-dev @types&#47;node`) and edit your question to include the output?\n- Thank you for the comment. I edited the question with the verbose logs\n- Thanks for that. The \"up to date\" bit means npm thinks that `@types&#47;node` already exists in your package directory. I need to sign off for now, but would suggest looking at your npm/nvm configuration next for clues.\n- Ok, will try but reinstlaled the versions about 3 times now in hopes i will get it working. also installed npm directly without nvm and still nothimg. I will keep digging.\n- Use `@` if you want to notify users. What you describe can't happen normally. Try another npm version (11). If you don't want to change it globally, use `npx npm@11 i`. That you keep doing `npm i --save-dev @types&#47;node` every time is unneeded and potentially faulty. You need to do this once, check that `@types&#47;node` appeared in package.json, then you do `rm -rf node_modules package-lock.json && npm i --verbose` and can expect that either all packages are installed or it fails. It could be one of many npm's unresolved bugs. Try Yarn 1 aka classic, it's a more stable npm replacement\n- @EstusFlask ok, so npm 11 worked, installed correctly. But still, the question remains, what the hell happened. Before the reset i was using npm 10.9.x and it worked fine. even tho it is solved i will keep digging a little bit more. Don't know if i can approve your answer from a comment tho. Thank you for your help!\n- @Cristian-AlexandruSANDU Glad it helped. I posted it for visibility, probably this can help someone else. As said, it could be a bug. I never saw it but big repos like npm are known for keeping open issues for years, then they are closed due to inactivity and the work is done. And you could make it worse by installing a specific dep with `npm install --save-dev @types&#47;node@20` instead of `npm i`, they are known to behave differently\n- I was too eager and didn't have time to go through the project. It didn't install it even with the npm. I am stupid enough to run the wrong project as i was in a hurry with something else. โฏ npm -v 11.6.1 โฏ ls node_modules/@types/node | head ls: node_modules/@types/node: No such file or directory after a full npm install (cache cleared, deleted modules and lock). will try now yarn and let you know\n- With yarn it works just fine but still issues with npm\n- @Cristian-AlexandruSANDU Glad it helped, I always keep it as a backup choice and had to migrate more than one project to it because of npm's quirks. Still not sure what a problem with npm could be. But since you use nvm, it could be something specific to it. Try using other version managers like \"n\" and installing node directly, this could be different\n- I found the issue, it was not npm or node but my vscode instlal. Still don't know the root cause as to where the setting is or why it happened but vscode on every instance of integrated temrinal it adds NODE_ENV=production so skipping the devDeps. Feel stupid for not echo-ing that env variable earlier but it didn't even cross my mind that it would be something this stupid... it is what it is.\n- Did you not check it outside vsc terminal? Makes sense then, this was a tricky part to solve. Consider posting a self-answer, can help someone with the same problem as yours","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":305,"estimatedTokens":2676}}699{"id":"stack-59918712","source":"stackoverflow","questionId":59918712,"title":"How to manipulate cookies in Passport-JS AuthGuard with NestJS?","tags":["passport.js","nestjs"],"text":"Title: How to manipulate cookies in Passport-JS AuthGuard with NestJS?\nTags: passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo, I set up the Local and JWT strategies normally, and they work wonderfully. I set the JWT cookie through the login route. I want to also set the refresh cookie token, and then be able to remove and reset the JWT token through the JWT AuthGuard, refreshing it manually and setting the `ignoreExpiration` flag to true.\n\nI want to be able to manipulate the cookies through the JWT AuthGuard. I can already view them, but I can't seem to set them. Is there a way to be able to do this?\n\n```\n/************************\n * auth.controller.ts\n ************************/\nimport { Controller, Request, Get, Post, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { AuthService } from './auth/auth.service';\nimport { SetCookies, CookieSettings } from '@ivorpad/nestjs-cookies-fastify';\nimport { ConfigService } from '@nestjs/config';\n\n@Controller('auth')\nexport class AuthController {\n constructor(\n private readonly authService: AuthService,\n private readonly configService: ConfigService,\n ) {}\n\n @UseGuards(AuthGuard('local'))\n @Post('login')\n @SetCookies()\n async login(@Request() request) {\n const jwtCookieSettings = this.configService.get('shared.auth.jwtCookieSettings');\n request._cookies = [{\n name : jwtCookieSettings.name,\n value : await this.authService.signJWT(request.user),\n options: jwtCookieSettings.options,\n }];\n }\n\n @UseGuards(AuthGuard('jwt'))\n @Get('profile')\n async getProfile(@Request() req) {\n return req.user;\n }\n}\n\n/************************\n * jwt.strategy.ts\n ************************/\nimport { Strategy, StrategyOptions } from 'passport-jwt';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, Request } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly configService: ConfigService) {\n super(configService.get('shared.auth.strategy.jwt.strategyOptions'));\n }\n \n async validate(@Request() request, payload: any) {\n return payload;\n }\n}\n```\n\n========================================\n\nCode:\n```js\n/************************\n * auth.controller.ts\n ************************/\nimport { Controller, Request, Get, Post, UseGuards } from '@nestjs/common';\nimport { AuthGuard }                                 from '@nestjs/passport';\nimport { AuthService }                from './auth/auth.service';\nimport { SetCookies, CookieSettings } from '@ivorpad/nestjs-cookies-fastify';\nimport { ConfigService }              from '@nestjs/config';\n\n\n@Controller('auth')\nexport class AuthController {\n    constructor(\n        private readonly authService: AuthService,\n        private readonly configService: ConfigService,\n    ) {}\n\n    @UseGuards(AuthGuard('local'))\n    @Post('login')\n    @SetCookies()\n    async login(@Request() request) {\n        const jwtCookieSettings = this.configService.get<CookieSettings>('shared.auth.jwtCookieSettings');\n        request._cookies = [{\n            name   : jwtCookieSettings.name,\n            value  : await this.authService.signJWT(request.user),\n            options: jwtCookieSettings.options,\n        }];\n    }\n\n\n    @UseGuards(AuthGuard('jwt'))\n    @Get('profile')\n    async getProfile(@Request() req) {\n        return req.user;\n    }\n}\n\n/************************\n * jwt.strategy.ts\n ************************/\nimport { Strategy, StrategyOptions } from 'passport-jwt';\nimport { PassportStrategy }          from '@nestjs/passport';\nimport { Injectable, Request }       from '@nestjs/common';\nimport { ConfigService }             from '@nestjs/config';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor(private readonly configService: ConfigService) {\n        super(configService.get<StrategyOptions>('shared.auth.strategy.jwt.strategyOptions'));\n    }\n    \n    async validate(@Request() request, payload: any) {\n        return payload;\n    }\n}\n```\n\n```text\nignoreExpiration\n```\n\n```text\nvalidate\n```\n\n```text\nrequest.res.cookie()\n```\n\n```text\nrequest.res.clearCookie()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":141,"estimatedTokens":1046}}700{"id":"stack-69435456","source":"stackoverflow","questionId":69435456,"title":"NestJS and Serverless - handler 'handler' is not a function","tags":["typescript","nestjs","serverless-framework","serverless"],"text":"Title: NestJS and Serverless - handler 'handler' is not a function\nTags: typescript, nestjs, serverless-framework, serverless\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement NestJS as a AWS Serverless function using serverless-framework.\n\nI was following this official documentation and my code is exactly as in the documentation. However when I launch it I get the error `Failure: offline: handler 'handler' in [..] is not a function`.\n\n**If I go into my compiled source code of `main.js` and change the line `exports.handler = handler;` to `module.exports.handler = handler;` it starts working.**\n\nI also tried to do change the code in `main.ts` to accommodate this but it does not help since webpack is compiling it differently then.\n\n```\n// main.ts\nconst handler ...;\nmodule.exports.handler = handler;\n```\n\nHere is my `main.ts`\n\n```\nimport { ValidationPipe } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Callback, Context, Handler } from 'aws-lambda';\nimport serverlessExpress from '@vendia/serverless-express';\nimport { AppModule } from './app.module';\n\nlet server: Handler;\n\nasync function bootstrap(): Promise {\n const app = await NestFactory.create(AppModule);\n app.useGlobalPipes(\n new ValidationPipe({\n whitelist: true,\n }),\n );\n await app.init();\n\n const expressApp = app.getHttpAdapter().getInstance();\n return serverlessExpress({ app: expressApp });\n}\n\nexport const handler: Handler = async (event: any, context: Context, callback: Callback) => {\n server = server ?? (await bootstrap());\n return server(event, context, callback);\n};\n```\n\nHere is my `serverless.yml`\n\n```\nservice:\n name: serverless-example\n\nplugins:\n - serverless-offline\n\nprovider:\n name: aws\n runtime: nodejs12.x\n\nfunctions:\n main:\n handler: dist/main.handler\n events:\n - http:\n method: ANY\n path: /\n - http:\n method: ANY\n path: '{proxy+}'\n```\n\nHere is my webpack.config.js\n\n```\nreturn {\n ...options,\n externals: [],\n output: {\n ...options.output,\n libraryTarget: 'commonjs2',\n },\n // ... the rest of the configuration\n};\n```\n\nAnd lastly here is my tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"skipLibCheck\": true,\n \"strictNullChecks\": false,\n \"noImplicitAny\": false,\n \"strictBindCallApply\": false,\n \"forceConsistentCasingInFileNames\": false,\n \"noFallthroughCasesInSwitch\": false,\n \"esModuleInterop\": true\n }\n}\n```\n\nAm I missing some config on webpack? Or maybe change in the typescript config files? I have no idea and documentation says that it should just work, however it does not.\n\nTheoretically all I need is it to be `module.exports.handler = handler` instead of `exports.handler = handler` in my compiled file because as I said I did change it and it started to work properly.\n\nThis is the interim fix I'm using but obviously this is wrong way of approaching it.\n\n```\n\"build\": \"nest build --webpack && sed -i 's/exports.handler = handler;/module.exports.handler = handler;/g' dist/main.js\",\n```\n\n========================================\n\nTop Answer:\nI resolved this by creating ensuring that the webpack output has a `libraryTarget` of `commonjs2`. Create (or edit) a `webpack.config.js` file in the root of the project with the following content ensuring that we set the `libraryTarget` to `commonjs2`:\n\n```\nmodule.exports = (options) => {\n return {\n ...options,\n output: {\n ...options.output,\n libraryTarget: 'commonjs2',\n },\n };\n};\n```\n\nIn my `serverless.yml` I have the following defined for my lambda function:\n\n```\n...\n\nfunctions:\n example:\n handler: \"./dist/apps/example/main.js.handler\"\n...\n```\n\nPlease note that `main.js.handler` should be changed if your entrypoint/function is different. For example if it was `entrypoint` this string would be `dist/apps/example/main.js.entrypoint`\n\n========================================\n\nCode:\n```text\n// main.ts\nconst handler ...;\nmodule.exports.handler = handler;\n```\n\n```text\nimport { ValidationPipe } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Callback, Context, Handler } from 'aws-lambda';\nimport serverlessExpress from '@vendia/serverless-express';\nimport { AppModule } from './app.module';\n\nlet server: Handler;\n\nasync function bootstrap(): Promise<Handler> {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(\n    new ValidationPipe({\n      whitelist: true,\n    }),\n  );\n  await app.init();\n\n  const expressApp = app.getHttpAdapter().getInstance();\n  return serverlessExpress({ app: expressApp });\n}\n\nexport const handler: Handler = async (event: any, context: Context, callback: Callback) => {\n  server = server ?? (await bootstrap());\n  return server(event, context, callback);\n};\n```\n\n```yaml\nservice:\n  name: serverless-example\n\nplugins:\n  - serverless-offline\n\nprovider:\n  name: aws\n  runtime: nodejs12.x\n\nfunctions:\n  main:\n    handler: dist/main.handler\n    events:\n      - http:\n          method: ANY\n          path: /\n      - http:\n          method: ANY\n          path: '{proxy+}'\n```\n\n```js\nreturn {\n  ...options,\n  externals: [],\n  output: {\n    ...options.output,\n    libraryTarget: 'commonjs2',\n  },\n  // ... the rest of the configuration\n};\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": false,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false,\n    \"esModuleInterop\": true\n  }\n}\n```\n\n```text\n\"build\": \"nest build --webpack && sed -i 's/exports.handler = handler;/module.exports.handler = handler;/g' dist/main.js\",\n```\n\n```text\nFailure: offline: handler 'handler' in [..] is not a function\n```\n\n```text\nmain.js\n```\n\n```text\nexports.handler = handler;\n```\n\n```text\nmodule.exports.handler = handler;\n```\n\n```text\nmain.ts\n```\n\n```text\nmain.ts\n```\n\n```text\nserverless.yml\n```\n\n```text\nmodule.exports.handler = handler\n```\n\n```text\nexports.handler = handler\n```\n\n```text\n\"build\": \"nest build --webpack && sed -i 's/exports.handler = handler;/module.exports.handler = handler;/g' dist/main.js\",\n\"build:mac\": \"nest build --webpack && sed -i '' 's~exports.handler = handler;~module.exports.handler = handler;~g' dist/main.js\",\n```\n\n```text\nexports.handler\n```\n\n```text\nmodule.exports.handler\n```\n\n```text\nmain.js\n```\n\n```text\nsed\n```\n\n```text\npackage.json\n```\n\n```text\nsed\n```\n\n```js\nmodule.exports = (options) => {\n  return {\n    ...options,\n    output: {\n      ...options.output,\n      libraryTarget: 'commonjs2',\n    },\n  };\n};\n```\n\n```yaml\n...\n\nfunctions:\n  example:\n    handler: \"./dist/apps/example/main.js.handler\"\n...\n```\n\n```text\nlibraryTarget\n```\n\n```text\ncommonjs2\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nlibraryTarget\n```\n\n```text\ncommonjs2\n```\n\n```text\nserverless.yml\n```\n\n```text\nmain.js.handler\n```\n\n```text\nentrypoint\n```\n\n```text\ndist/apps/example/main.js.entrypoint\n```\n\n```text\n\"compilerOptions\": {  \n  \"module\": \"commonjs\",\n},\n```\n\n```text\n...\nexports.main = main;\n```\n\n========================================\n\nComments:\n- since `exports === module.exports` then it should work fine with both, right?\n- But it doesn't. :\\\n- I did a quick test from a brand new project and I'm not experiencing this issue. What version of Nest are you running? AFAIK, this is a pretty new feature and might require Nest8\n- I am getting the same error. Did you manage to find a fix? @Stan\n- Anyone got fix .. using nest8\n- same here im using nx workspace with nest8 serverless-plugin-typescript it compiles properly but w/o module.export\n- Didn't do anything for me.\n- it is working solution with `\"module\": \"commonjs\",` or one have to remove it ?","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":400,"estimatedTokens":2033}}701{"id":"stack-60059940","source":"stackoverflow","questionId":60059940,"title":"Graphql Apollo upload in Nestjs returns invalid value {}","tags":["graphql","nestjs","apollo-server"],"text":"Title: Graphql Apollo upload in Nestjs returns invalid value {}\nTags: graphql, nestjs, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI tried adding an upload argument to a GraphQL endpoint using `graphql-upload`'s `GraphQLUpload` scalar:\n\n```\nimport { FileUpload, GraphQLUpload } from 'graphql-upload'\n\n@Mutation(() => Image, { nullable: true })\nasync addImage(@Args({name: 'image', type: () => GraphQLUpload}) image: FileUpload): Promise {\n// do stuff...\n}\n```\n\nAnd this worked initially. A few runs later however, and it started returning the following error:\n\n```\n\"Variable \\\"$image\\\" got invalid value {}; Expected type Upload. Upload value invalid.\"\n```\n\nTried testing with Insomnia client and curl:\n\n```\ncurl localhost:8000/graphql \\\n -F operations='{ \"query\": \"mutation ($image: Upload!) { addImage(image: $image) { id } }\", \"variables\": { \"image\": null } }'\n -F map='{ \"0\": [\"variables.image\"] }'\n -F 0=@/path/to/image\n```\n\n========================================\n\nTop Answer:\nUse `import {GraphQLUpload} from \"apollo-server-express\"`\n\nnot **import GraphQLUpload from 'graphql-upload'**\n\nhttps://i.sstatic.net/yGFr7.png\n\n========================================\n\nCode:\n```js\nimport { FileUpload, GraphQLUpload } from 'graphql-upload'\n\n@Mutation(() => Image, { nullable: true })\nasync addImage(@Args({name: 'image', type: () => GraphQLUpload}) image: FileUpload): Promise<Image | undefined> {\n// do stuff...\n}\n```\n\n```text\n\"Variable \\\"$image\\\" got invalid value {}; Expected type Upload. Upload value invalid.\"\n```\n\n```sh\ncurl localhost:8000/graphql \\\n  -F operations='{ \"query\": \"mutation ($image: Upload!) { addImage(image: $image) { id } }\", \"variables\": { \"image\": null } }'\n  -F map='{ \"0\": [\"variables.image\"] }'\n  -F 0=@/path/to/image\n```\n\n```text\ngraphql-upload\n```\n\n```text\nGraphQLUpload\n```\n\n```js\nimport { Scalar } from '@nestjs/graphql'\nimport FileType from 'file-type'\nimport { GraphQLError } from 'graphql'\nimport { FileUpload } from 'graphql-upload'\nimport { isUndefined } from 'lodash'\n\n@Scalar('Upload')\nexport class Upload {\n  description = 'File upload scalar type'\n\n  async parseValue(value: Promise<FileUpload>) {\n    const upload = await value\n    const stream = upload.createReadStream()\n    const fileType = await FileType.fromStream(stream)\n\n    if (isUndefined(fileType)) throw new GraphQLError('Mime type is unknown.')\n\n    if (fileType?.mime !== upload.mimetype)\n      throw new GraphQLError('Mime type does not match file content.')\n\n    return upload\n  }\n}\n```\n\n```js\nimport { UnsupportedMediaTypeException } from '@nestjs/common'\nimport { Scalar } from '@nestjs/graphql'\nimport { ValueNode } from 'graphql'\nimport { FileUpload, GraphQLUpload } from 'graphql-upload'\n\nexport type CSVParseProps = {\n  file: FileUpload\n  promise: Promise<FileUpload>\n}\n\nexport type CSVUpload = Promise<FileUpload | Error>\nexport type CSVFile = FileUpload\n\n@Scalar('CSV', () => CSV)\nexport class CSV {\n  description = 'CSV upload type.'\n  supportedFormats = ['text/csv']\n\n  parseLiteral(arg: ValueNode) {\n    const file = GraphQLUpload.parseLiteral(arg, (arg as any).value)\n\n    if (\n      file.kind === 'ObjectValue' &&\n      typeof file.filename === 'string' &&\n      typeof file.mimetype === 'string' &&\n      typeof file.encoding === 'string' &&\n      typeof file.createReadStream === 'function'\n    )\n      return Promise.resolve(file)\n\n    return null\n  }\n\n  // If this is `async` then any error thrown\n  // hangs and doesn't return to the user. However,\n  // if a non-promise is returned it fails reading the\n  // stream later. We can't evaluate the `sync`\n  // version of the file either as there's a data race (it's not\n  // always there). So we return the `Promise` version\n  // for usage that gets parsed after return...\n  parseValue(value: CSVParseProps) {\n    return value.promise.then((file) => {\n      if (!this.supportedFormats.includes(file.mimetype))\n        return new UnsupportedMediaTypeException(\n          `Unsupported file format. Supports: ${this.supportedFormats.join(\n            ' '\n          )}.`\n        )\n\n      return file\n    })\n  }\n\n  serialize(value: unknown) {\n    return GraphQLUpload.serialize(value)\n  }\n}\n```\n\n```js\n@Field(() => CSV)\nfile!: CSVUpload\n```\n\n```js\n// returns either the file or error to throw\nconst fileRes = await file\n\nif (isError(fileRes)) throw fileRes\n```\n\n```text\napollo-server-core\n```\n\n```text\ngraphql-upload\n```\n\n```text\ngraphql-upload\n```\n\n```text\nparseValue\n```\n\n```text\n.csv\n```\n\n```text\nArgsType\n```\n\n```js\nimport * as FileType from 'file-type'\nimport { GraphQLError, GraphQLScalarType } from 'graphql'\nimport { Readable } from 'stream'\n\nexport interface FileUpload {\n  filename: string\n  mimetype: string\n  encoding: string\n  createReadStream: () => Readable\n}\n\nexport const GraphQLUpload = new GraphQLScalarType({\n  name: 'Upload',\n  description: 'The `Upload` scalar type represents a file upload.',\n  async parseValue(value: Promise<FileUpload>): Promise<FileUpload> {\n    const upload = await value\n    const stream = upload.createReadStream()\n    const fileType = await FileType.fromStream(stream)\n\n    if (fileType?.mime !== upload.mimetype)\n      throw new GraphQLError('Mime type does not match file content.')\n\n    return upload\n  },\n  parseLiteral(ast): void {\n    throw new GraphQLError('Upload literal unsupported.', ast)\n  },\n  serialize(): void {\n    throw new GraphQLError('Upload serialization unsupported.')\n  },\n})\n```\n\n```text\ngraphql-upload\n```\n\n```text\nimport {GraphQLUpload} from \"apollo-server-express\"\n```\n\n```text\nimport { GraphQLUpload, FileUpload } from \"graphql-upload\";\n\n  @Mutation(() => Boolean)\n  async docUpload(\n    @Arg('userID') userid: number,\n    @Arg('file', () => GraphQLUpload)\n    file: FileUpload\n  ) {\n    const { filename, createReadStream } = file;\n    console.log(userid, file, filename, createReadStream);\n    return true\n  }\n```\n\n```text\n{\n    file: '/user/mim/desktop/t.txt'\n}\n```\n\n========================================\n\nComments:\n- @xadm thanks for the reply. The spec here: github.com/jaydenseric/graphql-multipart-request-spec mentions these should be null, is this not the case?\n- it worked ... node.js errors/warnings? restart?\n- @xadm `GraphQLError: Upload value invalid. at GraphQLScalarType.parseValue (&#47;path&#47;to&#47;project&#47;nest&#47;node_modules&#47;graphql-upload&#47;lib&#47;Graph&zwnj;&#8203;QLUpload.js:66:11)`. It worked for me initially (about an hour), then the error came and I'm not sure what changed if anything.\n- Can you explain a little further how did you get your mutation working? I'm running into the same error\n- Is your `apollo-server-core` package at latest? If so, it includes `graphql-upload` in it's dependencies and has the middleware handling file uploads already.\n- Sorry for the late reply `@Mutation(() => File) async uploadFile( @Args({ name: 'input', type: () => GraphQLUpload }) fileInput: FileUpload, ): Promise { const url = await this.filesService.create(fileInput) return { url, success: true } }` Where GraphQLUpload and FileUpload are imported from my previous code and File type is just the schema that you are going to return\n- This errors for me when I upload a file: RangeError: Maximum call stack size exceeded at ReadStream.open\"\n- It might be exposed now, but at the time the type wasn't exposed (i.e. `FileUpload`). Hence the dependency and import :)\n- Sure @willsquire. Youโ€™re comment from 12th Feb guide me. Thank you for that. After few hours trying to solve the issue, you gave me the rights tips!\n- Why this answer not at the top?!\n- I had issue just with the docker and this worked for me. you are from the future\n- apollo-server-express no longer includes `GraphQLUpload`.\n- Apollo Server no longer supports uploads out of the box.","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":272,"estimatedTokens":1936}}702{"id":"stack-75375378","source":"stackoverflow","questionId":75375378,"title":"I cannot use Websocket package on NestJS","tags":["javascript","node.js","websocket","nestjs"],"text":"Title: I cannot use Websocket package on NestJS\nTags: javascript, node.js, websocket, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to work with websockets on Nestjs, i install the dependencies\n\n`yarn add @nestjs/websockets @nestjs/platform-socket.io`\n\nI generated a example resource for the websockets\n\n`nest g res messagesWs --no-spec`\n\nThen this message shows up in my terminal\n\nTypeError: this.metadataScanner.getAllMethodNames is not a function\n\nThis is a capture from the problem\n\nWhat can i do?\nPD: sorry for my bad english\n\nI search for that function getAllMethodNames but i didn't get anything\n\n========================================\n\nTop Answer:\n`@nestjs/core` and `@nestjs/websockets` versions should always be **in sync**. For example, if the latest version of your locally installed `@nestjs/websockets` package is 9.3.6, then you have to make sure that `@nestjs/core` is also on 9.3.6.\n\nOnce you fix this up, the error will go away.\n\n========================================\n\nCode:\n```text\nyarn add @nestjs/websockets @nestjs/platform-socket.io\n```\n\n```text\nnest g res messagesWs --no-spec\n```\n\n```text\n\"@nestjs/platform-socket.io\": \"9.3.6\", \"@nestjs/websockets\": \"9.3.6\"\n```\n\n```text\n\"@nestjs/platform-socket.io\": \"9.1.6\", \"@nestjs/websockets\": \"9.1.6\"\n```\n\n```text\n\"@nestjs/platform-socket.io\": \"^7.6.15\",\n\"@nestjs/websockets\": \"^7.6.15\",\n```\n\n```text\nnode_modules\n```\n\n```text\npackage.json\n```\n\n```text\n^\n```\n\n```text\n@nestjs/core\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\n@nestjs/core\n```\n\n```text\n@nestjs/core\n```\n\n```text\npnpm-lock.yaml\n```\n\n```text\n@nestjs/platform-socket.io\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\n@nestjs/core\n```\n\n```text\npnpm up\n```\n\n========================================\n\nComments:\n- Could you the messageWs file and the module you added it to, please.\n- Thanks, i tried with 9.1.6 version and its working\n- I assume there's no way to express such a constraint in the package file? So you have to resort to specifying exact versions in the package.json file?","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":113,"estimatedTokens":513}}703{"id":"stack-76466982","source":"stackoverflow","questionId":76466982,"title":"Getting 'secretOrPrivateKey must have a value' error in NestJS JWT authentication","tags":["node.js","typescript","jwt","nestjs"],"text":"Title: Getting 'secretOrPrivateKey must have a value' error in NestJS JWT authentication\nTags: node.js, typescript, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm encountering an error in my NestJS application when using JWT authentication with the @nestjs/jwt package. The error message I'm receiving is \"secretOrPrivateKey must have a value.\" I have followed the official documentation and made sure to configure the JwtModule with the secret key, but the error persists.\n\nHere's the relevant code in my application:\n\n```\n// auth.module.ts:\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { EmailService } from 'src/email/email.service';\nimport { UserService } from 'src/user/user.service';\nimport { JwtModule, JwtService } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\n\n@Module({\n imports: [\n JwtModule.register({\n global: true,\n secret: jwtConstants.secret,\n secretOrPrivateKey: jwtConstants.secret,\n signOptions: { expiresIn: '60s' },\n })\n ],\n providers: [AuthService, UserService, JwtService, EmailService],\n controllers: [AuthController]\n})\nexport class AuthModule {}\n\n// constants.ts:\nexport const jwtConstants = {\n secret: process.env.JWT_SECRET\n}\n\n//auth.service.ts:\nimport { ForbiddenException, Injectable } from '@nestjs/common'\nimport { PrismaService } from 'src/prisma/prisma.service'\nimport { CheckNewPasswordCode, RquestNewPasswordDto, SignInDto, SignUpDto, UpdatePasswordDto, UpdatePrivilegesDto } from './dto'\nimport { UserService } from 'src/user/user.service'\nimport { JwtService } from '@nestjs/jwt'\n\n@Injectable()\nexport class AuthService {\n constructor(private userService: UserService,\n private jwtService: JwtService) { }\n\n async signUp(dto: SignUpDto) {\n const user = await this.userService.signUp(dto)\n const payload = { sub: user.email, username: user.name }\n\n return {\n access_token: await this.jwtService.signAsync(payload),\n }\n }\n\n async signIn(dto: SignInDto) {\n const user = await this.userService.signIn(dto)\n const payload = { sub: user.email, username: user.name }\n\n return {\n access_token: await this.jwtService.signAsync(payload),\n }\n }\n}\n```\n\nI have also checked the following points:\n\nI confirmed that the JWT_SECRET environment variable is correctly set and accessible within my application. I even printed its value in the AuthModule to verify its retrieval.\n\nI have installed the jsonwebtoken package as a dependency in my project.\n\nDespite these efforts, I'm still encountering the same error. Can someone please help me identify what could be causing this issue and provide guidance on how to resolve it?\n\nPlease let me know if any additional information is needed.\n\n========================================\n\nTop Answer:\nThere are errors in the official documentation.\nmodify here:\n\n```\nreturn {\n //access_token: await this.jwtService.signAsync(payload),\n access_token: await this.jwtService.signAsync(payload, { secret: your.secret }),//\n}\n```\n\n========================================\n\nCode:\n```text\n// auth.module.ts:\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { EmailService } from 'src/email/email.service';\nimport { UserService } from 'src/user/user.service';\nimport { JwtModule, JwtService } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\n\n@Module({\n  imports: [\n    JwtModule.register({\n      global: true,\n      secret: jwtConstants.secret,\n      secretOrPrivateKey: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    })\n  ],\n  providers: [AuthService, UserService, JwtService, EmailService],\n  controllers: [AuthController]\n})\nexport class AuthModule {}\n\n// constants.ts:\nexport const jwtConstants = {\n    secret: process.env.JWT_SECRET\n}\n\n\n//auth.service.ts:\nimport { ForbiddenException, Injectable } from '@nestjs/common'\nimport { PrismaService } from 'src/prisma/prisma.service'\nimport { CheckNewPasswordCode, RquestNewPasswordDto, SignInDto, SignUpDto, UpdatePasswordDto, UpdatePrivilegesDto } from './dto'\nimport { UserService } from 'src/user/user.service'\nimport { JwtService } from '@nestjs/jwt'\n\n@Injectable()\nexport class AuthService {\n    constructor(private userService: UserService,\n        private jwtService: JwtService) { }\n\n    async signUp(dto: SignUpDto) {\n        const user = await this.userService.signUp(dto)\n        const payload = { sub: user.email, username: user.name }\n\n        return {\n            access_token: await this.jwtService.signAsync(payload),\n        }\n    }\n\n    async signIn(dto: SignInDto) {\n        const user = await this.userService.signIn(dto)\n        const payload = { sub: user.email, username: user.name }\n\n        return {\n            access_token: await this.jwtService.signAsync(payload),\n        }\n    }\n}\n```\n\n```text\n// I've changed my providers in auth.module.ts from this\nproviders: [AuthService, UserService, EmailService, JwtService]\n// to this\nproviders: [AuthService, UserService, EmailService]\n```\n\n```js\nconst token = await this.jwtService.signAsync(\n  {\n    foundUser,\n  },\n  {\n    secret: this.configService.get('JWT_CONFIG.secret'),\n  },\n);\nres.header('authorization', 'bearer' + token);\n```\n\n```text\nreturn {\n    //access_token: await this.jwtService.signAsync(payload),\n    access_token: await this.jwtService.signAsync(payload, { secret: your.secret }),//\n}\n```\n\n```none\nSECRET_KEY=\"your secret key here\"\n```\n\n```text\n.env\n```\n\n```text\n${process.env.MY_SECRET}\n```\n\n```text\nConfigModule.forRoot({\n      isGlobal: true, \n      envFilePath: 'PATH_TO_YOUR_ENV', //replace with your env path\n    }),\n```\n\n========================================\n\nComments:\n- Before the `@Module()` does logging `jwtConstants.secret` provide you with the correct value? Is this the only place you register the `AuthService` (it should be but I'm double checking)\n- `JwtModule.register({ global: true, secret: (() => {console.log(jwtConstants.secret); return jwtConstants.secret})()` This is how i'm logging. And yes, it is the value it was supposed to be.\n- My only guess at the moment is that you have `AuthService` in another `providers` array somewhere which is invalidating the original secret passed to the `JwtModule`. Without a reproduction or access to your code it's gonna be hard to tell\n- I wish there was more explanation for this behavior. it works though\n- Thank you, I carefully followed the official documentation and couldn't understand where this error could have come from. It's surprising that it hasn't been corrected in the meantime\n- Making that changes to the code in the question would result in a syntax error.\n- @Quentin I think he means ` `$process.env.MY_SECRET}` ` with template literals. I just tested it, and it works fine!","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":213,"estimatedTokens":1704}}704{"id":"stack-65766885","source":"stackoverflow","questionId":65766885,"title":"How to create Seed in Nestjs?","tags":["nestjs","seeding"],"text":"Title: How to create Seed in Nestjs?\nTags: nestjs, seeding\nSource: Stack Overflow\n\nQuestion:\nI have my application with this directory structure.\n\n```\nApp\n|-- src\n |-- modules\n |-- user\n |-- role\n |-- company\n |-- ...\n |-- app.module.ts\n |-- main.js (Application Bootstrap)\n |-- seed.js\n |-- ...other files\n```\n\nI created a file with the following content:\n\n`seed.ts`\n\nhttps://i.sstatic.net/oz9NO.png\n\nI want to insert data at the beginning of the application to complete with data some tables of my databases that are needed for the application to work.\n\nThanks for the help!\n\n========================================\n\nCode:\n```sh\nApp\n|-- src\n    |-- modules\n        |-- user\n        |-- role\n        |-- company\n        |-- ...\n        |-- app.module.ts\n        |-- main.js (Application Bootstrap)\n        |-- seed.js\n    |-- ...other files\n```\n\n```text\nseed.ts\n```\n\n```text\n@Injectable()\nexport class AppService implements OnApplicationBootstrap{\n  onApplicationBootstrap(): any {\n  // add a functionality to check if the data already exists, if not add it manually\n  }\n}\n```\n\n```text\nqueryRunner.manager.insert()\n```\n\n```text\nAppService\n```\n\n```text\nOnApplicationBootstrap\n```\n\n========================================\n\nComments:\n- Please don't post pictures, but rather code snippets here on StackOverflow. Code snippets can be copied and checked locally while screenshots and pictures can't be. Also, what's wrong with above? What is it not doing that you want it to? Do you get any errors? Does something just not happen? There's not really much of a question or problem at the moment\n- probably the best and reliable answer out there! Thanks alot!\n- It will be triggered on every change in the codebase , wont it create a extra overhead while bootstraping..","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":442}}705{"id":"stack-60569737","source":"stackoverflow","questionId":60569737,"title":"NestJS TypeORM for MongoDB Crashing After Insert","tags":["node.js","mongodb","typescript","nestjs"],"text":"Title: NestJS TypeORM for MongoDB Crashing After Insert\nTags: node.js, mongodb, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIโ€™m having this weird behavior in NestJS and TypeORM for MongoDB. \n\nWhen I create a new entity with `this.repo.save(newEntity);`, the data is saved to MongoDB. But, I also get the error `cannot read property โ€œcreateValueMap()โ€ of undefined.`.\n\nIs there a solution to this?\n\n========================================\n\nTop Answer:\nWhat solved the problem in my code was the `@ObjectIdColumn` decorator. I hope this might help someone.\n\n```\nimport { BaseEntity, Column, Entity, ObjectID, ObjectIdColumn } from \"typeorm\";\nimport { TaskStatus } from \"./tasks-status.enum\";\n\n@Entity()\nexport class Task extends BaseEntity {\n @ObjectIdColumn()\n _id: ObjectID;\n\n @Column()\n title: string;\n\n @Column()\n description: string;\n\n @Column()\n status: TaskStatus;\n}\n```\n\n========================================\n\nCode:\n```text\nthis.repo.save(newEntity);\n```\n\n```text\ncannot read property โ€œcreateValueMap()โ€ of undefined.\n```\n\n```text\nimport { ObjectID } from 'mongodb'\nexport const toObjectId = (value: string | ObjectID): ObjectID => {\n  return typeof value === 'string' ? new ObjectID(value) : value\n}\n```\n\n```text\nTypeOrm\n```\n\n```text\nObjectID\n```\n\n```text\nimport { BaseEntity, Column, Entity, ObjectID, ObjectIdColumn } from \"typeorm\";\nimport { TaskStatus } from \"./tasks-status.enum\";\n\n@Entity()\nexport class Task extends BaseEntity {\n    @ObjectIdColumn()\n    _id: ObjectID;\n\n    @Column()\n    title: string;\n\n    @Column()\n    description: string;\n\n    @Column()\n    status: TaskStatus;\n}\n```\n\n```text\n@ObjectIdColumn\n```\n\n========================================\n\nComments:\n- I was using a primaryColumn decorator before, and changed to this option worked for me! thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":90,"estimatedTokens":449}}706{"id":"stack-62814208","source":"stackoverflow","questionId":62814208,"title":"How to handle multiple middlewares in NEST JS for specific/different request methods?","tags":["node.js","middleware","nestjs","nestjs-config"],"text":"Title: How to handle multiple middlewares in NEST JS for specific/different request methods?\nTags: node.js, middleware, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\n**Explaining my code below:** There are two middleware AuthenticationMiddleware, RequestFilterMiddleware which intervene ALL request methods.\n\n**My question** is how to make `RequestFilterMiddleware` middleware only for GET method and `AuthenticationMiddleware` middleware for ALL request methods\n\n**app.module.ts**\n\n```\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(AuthenticationMiddleware, RequestFilterMiddleware)\n .forRoutes({ path: '/**', method: RequestMethod.ALL });\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(AuthenticationMiddleware, RequestFilterMiddleware)\n      .forRoutes({ path: '/**', method: RequestMethod.ALL });\n  }\n}\n```\n\n```text\nRequestFilterMiddleware\n```\n\n```text\nAuthenticationMiddleware\n```\n\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(AuthenticationMiddleware)\n      .forRoutes({ path: '/**', method: RequestMethod.ALL });\n    consumer\n      .apply(RequestFilterMiddleware)\n      .forRoutes({ path: '/**', method: RequestMethod.GET });\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":54,"estimatedTokens":358}}707{"id":"stack-63386366","source":"stackoverflow","questionId":63386366,"title":"Using Timestamp with nestjs is not updated when update","tags":["mongodb","timestamp","nestjs"],"text":"Title: Using Timestamp with nestjs is not updated when update\nTags: mongodb, timestamp, nestjs\nSource: Stack Overflow\n\nQuestion:\nAm using NestJs for a backend project and am trying to use timestamps to show update and create date but nothing shows!\n\n```\n@Schema()\nexport class Camera extends Document{\n \n// @Prop({required: true, unique: true})\n @Prop({required: true})\n facility_name: string;\n\n @Prop({required: true, unique : true})\n camera_id: string;\n \n @Prop({required: true})\n camera_location: string;\n\n @Prop({required: true})\n camera_type: string;\n\n @Prop({default : false})\n is_deleted : boolean;\n\n @Prop()\n timestamps: true;\n\n}\n\nexport const cameraSchema = SchemaFactory.createForClass(Camera); }\n```\n\nHow can I use timestamps with this tpye of frmawork as it doesn't show any date!!\n\n========================================\n\nCode:\n```text\n@Schema()\nexport class Camera extends Document{\n \n//   @Prop({required: true, unique: true})\n  @Prop({required: true})\n  facility_name: string;\n\n  @Prop({required: true, unique : true})\n  camera_id: string;\n  \n  @Prop({required: true})\n  camera_location: string;\n\n  @Prop({required: true})\n  camera_type: string;\n\n  @Prop({default : false})\n  is_deleted : boolean;\n\n  @Prop()\n  timestamps: true;\n\n}\n\nexport const cameraSchema = SchemaFactory.createForClass(Camera); }\n```\n\n```text\n@Schema({\n  timestamps: true,\n})\n```\n\n```text\n{\n  \"_id\": \"5fc3fab191c59905a0931df2\",\n  \"content\": \"Lorem ipsum dolor sit amet\",\n  \"createdAt\": \"2020-11-29T19:46:57.199Z\",\n  \"updatedAt\": \"2020-11-29T19:46:57.199Z\",\n  \"__v\": 0\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":83,"estimatedTokens":391}}708{"id":"stack-57439410","source":"stackoverflow","questionId":57439410,"title":"How nestjs configures path aliases in a project","tags":["nestjs"],"text":"Title: How nestjs configures path aliases in a project\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI configured the path alias in tsconfig.json of the nestjs project, but there was an error while running.\n\nI tried to configure like Angular, but there was an error in nestjs\n\nThis is my tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es6\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"paths\": {\n \"~auth/*\": [\"src/auth/*\"]\n }\n },\n \"exclude\": [\"node_modules\"]\n}\n```\n\nUse it like this\n\n```\nimport { userLoginJwt } from '~auth/jwt-names'\n```\n\nStartup error\n\n```\n$ npm run start:dev\n[0] internal/modules/cjs/loader.js:584\n[0] throw err;\n[0] ^\n[0]\n[0] Error: Cannot find module 'src/auth/jwt-names'\n```\n\nSorry, I emphasize here that running `npm run start` works fine, but running `npm run start:dev` can lead to unexpected situations.\n\n========================================\n\nTop Answer:\n**TL;DR;**\n\n- Update your `package.json`\n\n`\"start:dev\": \"nest start --watch --exec 'node -r tsconfig-paths/register -r ts-node/register ./src/main.ts'\"`\n\n- Use `npm run start:dev`\n\n========================================\n\nCode:\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es6\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"paths\": {\n      \"~auth/*\": [\"src/auth/*\"]\n    }\n  },\n  \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\nimport { userLoginJwt } from '~auth/jwt-names'\n```\n\n```text\n$ npm run start:dev\n[0] internal/modules/cjs/loader.js:584\n[0]     throw err;\n[0]     ^\n[0]\n[0] Error: Cannot find module 'src/auth/jwt-names'\n```\n\n```text\nnpm run start\n```\n\n```text\nnpm run start:dev\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es6\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./src\",\n    \"incremental\": true,\n    \"paths\": {\n      \"~auth/*\": [\"auth/*\"]\n    }\n  },\n  \"exclude\": [\"node_modules\"]\n}\n```\n\n```js\n// tsconfig-paths-bootstrap.js\n\nconst tsConfig = require('./tsconfig.json');\nconst tsConfigPaths = require('tsconfig-paths');\n\ntsConfigPaths.register({\n  baseUrl: tsConfig.compilerOptions.outDir,\n  paths: tsConfig.compilerOptions.paths,\n});\n```\n\n```text\n{\n  \"watch\": [\"dist\"],\n  \"ext\": \"js\",\n  \"exec\": \"node  -r ./tsconfig-paths-bootstrap.js dist/main.js\"\n}\n```\n\n```text\nimport { userLoginJwt } from '~auth/jwt-names';\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\ntsconfig\n```\n\n```text\nbaseUrl\n```\n\n```text\nsrc\n```\n\n```text\noutDir\n```\n\n```text\ndist\n```\n\n```text\nsrc\n```\n\n```text\npackage.json\n```\n\n```text\n\"start:dev\": \"nest start --watch --exec 'node -r tsconfig-paths/register -r ts-node/register ./src/main.ts'\"\n```\n\n```text\nnpm run start:dev\n```\n\n```json\n\"moduleResolution\": \"node\",\n\"baseUrl\": \"src\",\n\"paths\": {\n  \"@lib/*\": [\"lib/*\"],\n  \"@models/*\": [\"models/*\"],\n  \"@plugins/*\": [\"plugins/*\"],\n  \"@routes/*\": [\"routes/*\"],\n  \"@services/*\": [\"services/*\"],\n  \"@api\": [\"api/index\"]\n}\n```\n\n```text\n\"paths\": {\n  \"~auth/*\": [\"src/auth/*\"]\n}\n```\n\n```text\n\"paths\": {\n  \"@auth/*\": [\"src/auth/*\"]\n}\n```\n\n```text\n\"paths\": {\n    \"*\": [\n       \"./*\"\n     ]\n   },\n```\n\n```json\n{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"entryFile\": \"my-proj-name/src/main.js\", //<-- Added this line\n  \"compilerOptions\": {\n    \"deleteOutDir\": true\n  }\n}\n```\n\n```text\ntsconfig.json\n```\n\n```text\nentryFile\n```\n\n```text\nnest-cli.json\n```\n\n========================================\n\nComments:\n- That's good general advice but NestJS seems to force you to use \"./\" for baseURL so this is not an option\n- Nestjs has updated the template and the above code will not work for the new version. For the new version, set the `paths` field directly in `tsconfig.json`.\n- This is the best answer because it scales to any project and there is a good and clear medium post ๐Ÿ‘ I recommend reading also alexjover.com/blog/&hellip; in order to add aliases to your Jest settings as well. In Jest it can be done in the package.json\n- I would argue that tilda is better, now a lot of npm modules are using @ as well, it's easy to get confused if it's a local file or from npm\n- Everyone has a different preference, the docs say no prefix, so i would in retrospect go with what the docs say. typescriptlang.org/tsconfig#paths however @ is the convention i have seen / been working with for a while.","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":265,"estimatedTokens":1205}}709{"id":"stack-52895598","source":"stackoverflow","questionId":52895598,"title":"multiInject in Nest.js","tags":["javascript","node.js","nestjs","inversifyjs"],"text":"Title: multiInject in Nest.js\nTags: javascript, node.js, nestjs, inversifyjs\nSource: Stack Overflow\n\nQuestion:\nIn Inversify.js there is `multiInject` decorator that allow us to inject multiple objects as array. All objects' dependencies in this array resolved as well.\n\nIs there any way to achieve this in Nest.js?\n\n========================================\n\nTop Answer:\nJust a minor tweak to the great solution by @kim-kern you can use that solution but avoid a small bit of overhead for adding new entries ...\n\nreplace\n\n```\nproviders: [\n Cat,\n Dog,\n {\n provide: 'MyAnimals',\n useFactory: (cat, dog) => [cat, dog],\n inject: [Cat, Dog],\n },\n ],\n```\n\nwith\n\n```\nproviders: [\n Cat,\n Dog,\n {\n provide: 'MyAnimals',\n useFactory: (...animals: Animal[]) => animals,\n inject: [Cat, Dog],\n },\n ],\n```\n\nIt's only minor but instead of having to add a new one in **3** places for every new addition it's down to **2**. Adds up when you have a few and reduces chance of error.\n\nAlso the nest team are working on making this easier an you can track via this github issue: https://github.com/nestjs/nest/issues/770\n\n========================================\n\nCode:\n```text\nmultiInject\n```\n\n```text\nexport interface Animal {\n  makeSound(): string;\n}\n\n@Injectable()\nexport class Cat implements Animal {\n  makeSound(): string {\n    return 'Meow!';\n  }\n}\n\n@Injectable()\nexport class Dog implements Animal {\n  makeSound(): string {\n    return 'Woof!';\n  }\n}\n```\n\n```text\nproviders: [\n    Cat,\n    Dog,\n    {\n      provide: 'MyAnimals',\n      useFactory: (cat, dog) => [cat, dog],\n      inject: [Cat, Dog],\n    },\n  ],\n```\n\n```text\nconstructor(@Inject('MyAnimals') private animals: Animal[]) {\n  }\n\n@Get()\nasync get() {\n  return this.animals.map(a => a.makeSound()).join(' and ');\n}\n```\n\n```text\n@Injectable()\nexport class Dog implements Animal {\n  constructor(private toy: Toy) {\n  }\n  makeSound(): string {\n    this.toy.play();\n    return 'Woof!';\n  }\n}\n```\n\n```text\nmultiInject\n```\n\n```text\n@Injectable\n```\n\n```text\nAnimal\n```\n\n```text\nCat\n```\n\n```text\nDog\n```\n\n```text\nAnimal\n```\n\n```text\nAnimal\n```\n\n```text\nDog\n```\n\n```text\nToy\n```\n\n```text\nToy\n```\n\n```text\nproviders: [\n    Cat,\n    Dog,\n    {\n      provide: 'MyAnimals',\n      useFactory: (cat, dog) => [cat, dog],\n      inject: [Cat, Dog],\n    },\n  ],\n```\n\n```text\nproviders: [\n    Cat,\n    Dog,\n    {\n      provide: 'MyAnimals',\n      useFactory: (...animals: Animal[]) => animals,\n      inject: [Cat, Dog],\n    },\n  ],\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":170,"estimatedTokens":615}}710{"id":"stack-74815121","source":"stackoverflow","questionId":74815121,"title":"Why is hot reloading not working in my NestJS/Docker-Compose multistage project?","tags":["docker","visual-studio-code","docker-compose","nestjs","hot-reload"],"text":"Title: Why is hot reloading not working in my NestJS/Docker-Compose multistage project?\nTags: docker, visual-studio-code, docker-compose, nestjs, hot-reload\nSource: Stack Overflow\n\nQuestion:\nHot reloading is not working. The API is not being updated after changes in the code are saved. Here is the code:\n\nhttps://codesandbox.io/s/practical-snowflake-c4j6fh\n\nWhen bulding (docker-compose up -V --build) I get the following messages on terminal:\n\n\r\n\r\n\n```\n2022-12-16 09:29:53 redis | 1:C 16 Dec 2022 12:29:53.411 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo2022-12-16 09:29:53 redis | 1:C 16 Dec 2022 12:29:53.411 # Redis version=7.0.6, bits=64, commit=00000000, modified=0, pid=1, just started2022-12-16 09:29:53 redis | 1:C 16 Dec 2022 12:29:53.411 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf2022-12-16 09:29:53 redis | 1:M 16 Dec 2022 12:29:53.411 * monotonic clock: POSIX clock_gettime2022-12-16 09:29:53 redis | 1:M 16 Dec 2022 12:29:53.411 * Running mode=standalone, port=6379.2022-12-16 09:29:53 redis | 1:M 16 Dec 2022 12:29:53.411 # Server initialized2022-12-16 09:29:53 redis | 1:M 16 Dec 2022 12:29:53.411 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.2022-12-16 09:29:53 redis | 1:M 16 Dec 2022 12:29:53.412 * Ready to accept connections2022-12-16 09:29:53 postgres | The files belonging to this database system will be owned by user \"postgres\".2022-12-16 09:29:53 postgres | This user must also own the server process.2022-12-16 09:29:53 postgres | 2022-12-16 09:29:53 postgres | The database cluster will be initialized with locale \"en_US.utf8\".2022-12-16 09:29:53 postgres | The default database encoding has accordingly been set to \"UTF8\".2022-12-16 09:29:53 postgres | The default text search configuration will be set to \"english\".2022-12-16 09:29:53 postgres | 2022-12-16 09:29:53 postgres | Data page checksums are disabled.2022-12-16 09:29:53 postgres | 2022-12-16 09:29:53 postgres | fixing permissions on existing directory /var/lib/postgresql/data ... ok2022-12-16 09:29:53 postgres | creating subdirectories ... ok2022-12-16 09:29:53 postgres | selecting dynamic shared memory implementation ... posix2022-12-16 09:29:53 postgres | selecting default max_connections ... 1002022-12-16 09:29:53 postgres | selecting default shared_buffers ... 128MB2022-12-16 09:29:53 postgres | selecting default time zone ... Etc/UTC2022-12-16 09:29:53 postgres | creating configuration files ... ok2022-12-16 09:29:53 postgres | running bootstrap script ... ok2022-12-16 09:29:54 postgres | performing post-bootstrap initialization ... ok2022-12-16 09:29:54 postgres | initdb: warning: enabling \"trust\" authentication for local connections2022-12-16 09:29:54 postgres | You can change this by editing pg_hba.conf or using the option -A, or2022-12-16 09:29:54 postgres | --auth-local and --auth-host, the next time you run initdb.2022-12-16 09:29:54 postgres | syncing data to disk ... ok2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | Success. You can now start the database server using:2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | pg_ctl -D /var/lib/postgresql/data -l logfile start2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | waiting for server to start....2022-12-16 12:29:54.305 UTC [48] LOG: starting PostgreSQL 12.13 (Debian 12.13-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.311 UTC [48] LOG: listening on Unix socket \"/var/run/postgresql/.s.PGSQL.5432\"2022-12-16 09:29:54 store-backend-api-1 | 2022-12-16 09:29:54 store-backend-api-1 | > store-backend@0.0.1 start:dev2022-12-16 09:29:54 store-backend-api-1 | > nest start --watch2022-12-16 09:29:54 store-backend-api-1 | 2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.338 UTC [49] LOG: database system was shut down at 2022-12-16 12:29:54 UTC2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.345 UTC [48] LOG: database system is ready to accept connections2022-12-16 09:29:54 postgres | done2022-12-16 09:29:54 postgres | server started2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.434 UTC [48] LOG: received fast shutdown request2022-12-16 09:29:54 postgres | waiting for server to shut down....2022-12-16 12:29:54.444 UTC [48] LOG: aborting any active transactions2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.445 UTC [48] LOG: background worker \"logical replication launcher\" (PID 55) exited with exit code 12022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.445 UTC [50] LOG: shutting down2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.482 UTC [48] LOG: database system is shut down2022-12-16 09:29:54 postgres | done2022-12-16 09:29:54 postgres | server stopped2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | PostgreSQL init process complete; ready for start up.2022-12-16 09:29:54 postgres | 2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.552 UTC [1] LOG: starting PostgreSQL 12.13 (Debian 12.13-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.552 UTC [1] LOG: listening on IPv4 address \"0.0.0.0\", port 54322022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.552 UTC [1] LOG: listening on IPv6 address \"::\", port 54322022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.563 UTC [1] LOG: listening on Unix socket \"/var/run/postgresql/.s.PGSQL.5432\"2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.592 UTC [67] LOG: database system was shut down at 2022-12-16 12:29:54 UTC2022-12-16 09:29:54 postgres | 2022-12-16 12:29:54.600 UTC [1] LOG: database system is ready to accept connections\n```\n\n\r\n\r\n\r\n\nAnd then the previous messages disappear and the following ones are shown:\n\n\r\n\r\n\n```\n[12:29:55 PM] Starting compilation in watch mode...2022-12-16 09:29:55 store-backend-api-1 | 2022-12-16 09:29:58 store-backend-api-1 | [12:29:58 PM] Found 0 errors. Watching for file changes.2022-12-16 09:29:58 store-backend-api-1 | 2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [NestFactory] Starting Nest application...2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] TypeOrmModule dependencies initialized +65ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] ConfigHostModule dependencies initialized +1ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] AppModule dependencies initialized +0ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +49ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [InstanceLoader] UserModule dependencies initialized +1ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [RoutesResolver] AppController {/api}: +7ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [RouterExplorer] Mapped {/api, GET} route +4ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [RouterExplorer] Mapped {/api/test, GET} route +0ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [RoutesResolver] UserController {/api/users}: +1ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [RouterExplorer] Mapped {/api/users, POST} route +1ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [RouterExplorer] Mapped {/api/users, GET} route +1ms2022-12-16 09:29:59 store-backend-api-1 | [Nest] 29 - 12/16/2022, 12:29:59 PM LOG [NestApplication] Nest application successfully started +3ms\n```\n\n========================================\n\nTop Answer:\n### Add this to tsconfig.json.\n\n```\n\"watchOptions\": {\n // Use native file system events for files and directories\n \"watchFile\": \"priorityPollingInterval\",\n \"watchDirectory\": \"dynamicprioritypolling\",\n // Poll files for updates more frequently\n // when they're updated a lot.\n \"fallbackPolling\": \"dynamicPriority\",\n // Don't coalesce watch notification\n \"synchronousWatchDirectory\": true,\n // Finally, two additional settings for reducing the amount of possible\n // files to track work from these directories\n \"excludeDirectories\": [\"**/node_modules\", \"dist\"]\n }\n```\n\n========================================\n\nCode:\n```html\n2022-12-16 09:29:53 redis                | 1:C 16 Dec 2022 12:29:53.411 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo</br>2022-12-16 09:29:53 redis                | 1:C 16 Dec 2022 12:29:53.411 # Redis version=7.0.6, bits=64, commit=00000000, modified=0, pid=1, just started</br>2022-12-16 09:29:53 redis                | 1:C 16 Dec 2022 12:29:53.411 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf</br>2022-12-16 09:29:53 redis                | 1:M 16 Dec 2022 12:29:53.411 * monotonic clock: POSIX clock_gettime</br>2022-12-16 09:29:53 redis                | 1:M 16 Dec 2022 12:29:53.411 * Running mode=standalone, port=6379.</br>2022-12-16 09:29:53 redis                | 1:M 16 Dec 2022 12:29:53.411 # Server initialized</br>2022-12-16 09:29:53 redis                | 1:M 16 Dec 2022 12:29:53.411 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can can also cause failures without low memory condition, see https://github.com/</br>jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.</br>2022-12-16 09:29:53 redis                | 1:M 16 Dec 2022 12:29:53.412 * Ready to accept connections</br>2022-12-16 09:29:53 postgres             | The files belonging to this database system will be owned by user \"postgres\".</br>2022-12-16 09:29:53 postgres             | This user must also own the server process.</br>2022-12-16 09:29:53 postgres             | </br>2022-12-16 09:29:53 postgres             | The database cluster will be initialized with locale \"en_US.utf8\".</br>2022-12-16 09:29:53 postgres             | The default database encoding has accordingly been set to \"UTF8\".</br>2022-12-16 09:29:53 postgres             | The default text search configuration will be set to \"english\".</br>2022-12-16 09:29:53 postgres             | </br>2022-12-16 09:29:53 postgres             | Data page checksums are disabled.</br>2022-12-16 09:29:53 postgres             | </br>2022-12-16 09:29:53 postgres             | fixing permissions on existing directory /var/lib/postgresql/data ... ok</br>2022-12-16 09:29:53 postgres             | creating subdirectories ... ok</br>2022-12-16 09:29:53 postgres             | selecting dynamic shared memory implementation ... posix</br>2022-12-16 09:29:53 postgres             | selecting default max_connections ... 100</br>2022-12-16 09:29:53 postgres             | selecting default shared_buffers ... 128MB</br>2022-12-16 09:29:53 postgres             | selecting default time zone ... Etc/UTC</br>2022-12-16 09:29:53 postgres             | creating configuration files ... ok</br>2022-12-16 09:29:53 postgres             | running bootstrap script ... ok</br>2022-12-16 09:29:54 postgres             | performing post-bootstrap initialization ... ok</br>2022-12-16 09:29:54 postgres             | initdb: warning: enabling \"trust\" authentication for local connections</br>2022-12-16 09:29:54 postgres             | You can change this by editing pg_hba.conf or using the option -A, or</br>2022-12-16 09:29:54 postgres             | --auth-local and --auth-host, the next time you run initdb.</br>2022-12-16 09:29:54 postgres             | syncing data to disk ... ok</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | Success. You can now start the database server using:</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             |     pg_ctl -D /var/lib/postgresql/data -l logfile start</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | waiting for server to start....2022-12-16 12:29:54.305 UTC [48] LOG:  starting PostgreSQL 12.13 (Debian 12.13-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.311 UTC [48] LOG:  listening on Unix socket \"/var/run/postgresql/.s.PGSQL.5432\"</br>2022-12-16 09:29:54 store-backend-api-1  | </br>2022-12-16 09:29:54 store-backend-api-1  | > store-backend@0.0.1 start:dev</br>2022-12-16 09:29:54 store-backend-api-1  | > nest start --watch</br>2022-12-16 09:29:54 store-backend-api-1  | </br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.338 UTC [49] LOG:  database system was shut down at 2022-12-16 12:29:54 UTC</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.345 UTC [48] LOG:  database system is ready to accept connections</br>2022-12-16 09:29:54 postgres             |  done</br>2022-12-16 09:29:54 postgres             | server started</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.434 UTC [48] LOG:  received fast shutdown request</br>2022-12-16 09:29:54 postgres             | waiting for server to shut down....2022-12-16 12:29:54.444 UTC [48] LOG:  aborting any active transactions</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.445 UTC [48] LOG:  background worker \"logical replication launcher\" (PID 55) exited with exit code 1</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.445 UTC [50] LOG:  shutting down</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.482 UTC [48] LOG:  database system is shut down</br>2022-12-16 09:29:54 postgres             |  done</br>2022-12-16 09:29:54 postgres             | server stopped</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | PostgreSQL init process complete; ready for start up.</br>2022-12-16 09:29:54 postgres             | </br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.552 UTC [1] LOG:  starting PostgreSQL 12.13 (Debian 12.13-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.552 UTC [1] LOG:  listening on IPv4 address \"0.0.0.0\", port 5432</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.552 UTC [1] LOG:  listening on IPv6 address \"::\", port 5432</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.563 UTC [1] LOG:  listening on Unix socket \"/var/run/postgresql/.s.PGSQL.5432\"</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.592 UTC [67] LOG:  database system was shut down at 2022-12-16 12:29:54 UTC</br>2022-12-16 09:29:54 postgres             | 2022-12-16 12:29:54.600 UTC [1] LOG:  database system is ready to accept connections</br>\n```\n\n```html\n[12:29:55 PM] Starting compilation in watch mode...</br>2022-12-16 09:29:55 store-backend-api-1  | </br>2022-12-16 09:29:58 store-backend-api-1  | [12:29:58 PM] Found 0 errors. Watching for file changes.</br>2022-12-16 09:29:58 store-backend-api-1  | </br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [NestFactory] Starting Nest application...</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +65ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] ConfigHostModule dependencies initialized +1ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] AppModule dependencies initialized +0ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] ConfigModule dependencies initialized +1ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +49ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [InstanceLoader] UserModule dependencies initialized +1ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [RoutesResolver] AppController {/api}: +7ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [RouterExplorer] Mapped {/api, GET} route +4ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [RouterExplorer] Mapped {/api/test, GET} route +0ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [RoutesResolver] UserController {/api/users}: +1ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [RouterExplorer] Mapped {/api/users, POST} route +1ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [RouterExplorer] Mapped {/api/users, GET} route +1ms</br>2022-12-16 09:29:59 store-backend-api-1  | [Nest] 29  - 12/16/2022, 12:29:59 PM     LOG [NestApplication] Nest application successfully started +3ms\n```\n\n```text\n###################\n# BUILD FOR LOCAL DEVELOPMENT\n###################\n\nFROM node:18-alpine As development\nUSER root\n# Create app directory\nWORKDIR /usr/src/app\n\n# Copy application dependency manifests to the container image.\n# A wildcard is used to ensure copying both package.json AND package-lock.json (when available).\n# Copying this first prevents re-running npm install on every code change.\nCOPY package*.json ./\n\n# Install app dependencies using the `npm ci` command instead of `npm install`\nRUN npm ci\n\n# Bundle app source\nCOPY  . .\nRUN npm  run build\n\n# Use the node user from the image (instead of the root user)\nUSER node\n```\n\n```text\n\"watchOptions\": {\n    // Use native file system events for files and directories\n    \"watchFile\": \"priorityPollingInterval\",\n    \"watchDirectory\": \"dynamicprioritypolling\",\n    // Poll files for updates more frequently\n    // when they're updated a lot.\n    \"fallbackPolling\": \"dynamicPriority\",\n    // Don't coalesce watch notification\n    \"synchronousWatchDirectory\": true,\n    // Finally, two additional settings for reducing the amount of possible\n    // files to track  work from these directories\n    \"excludeDirectories\": [\"**/node_modules\", \"dist\"]\n  }\n```\n\n```text\n\"watchOptions\": {\n    // Use a dynamic polling instead of systemโ€™s native events for file changes.\n    \"watchFile\": \"dynamicPriorityPolling\",\n    \"watchDirectory\": \"dynamicPriorityPolling\",\n    \"excludeDirectories\": [\"**/node_modules\", \"dist\"]\n  }\n```\n\n```text\n\"start:dev\": \"nest start --tsc --watch\",\n```\n\n========================================\n\nComments:\n- Unfortunately it didn't work for me. I made this project based on the following tutorial. The tutorial has a repository. The live reload of the tutorial repository works for me. The problem doesn't seem to be related to docker files, package.json or dependency versions. tomray.dev/nestjs-docker-compose-postgres.\n- Please give some more information. Your host system, Linux, Windows? Os version. And if possible post the error logs you get into. I tried it on Ubuntu 22.04. It is just a normal docker-compose and dockerfile. Did you destroy containers and volumes before? docker compose up --build?\n- Host system is Windows 10 Pro Version 21H2. There's no visible errors. It make the build, the api works. Just don't update on changes (when a file is saved).\n- I'm using 'docker-compose up --build -V -d' or 'docker-compose up --build -V' (works on the tutorial repository). I also tried (several times) to remove containers, images and volumes manually through Docker Desktop.\n- If you update your question with all error messages you get, i will try to help you. Please also once the container starts, post the logs from nestjs. I took your repo yesterday and noticed that there are some other errors in the code and fixed them during the test.\n- I updated it with all logs I have.\n- I suspecting there's a file permission issue, but in the project files itself, not in Dockerfile comands: stackoverflow.com/a/74829258/3788133\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- It works but do you know if this has impact on prod environment?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.463Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":131,"estimatedTokens":5613}}711{"id":"stack-57972166","source":"stackoverflow","questionId":57972166,"title":"How to set .env variables in a module import / configuration","tags":["javascript","node.js","typescript","dependency-injection","nestjs"],"text":"Title: How to set .env variables in a module import / configuration\nTags: javascript, node.js, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use a `.env` file in my app.\n\nI created two file for that (one module and one service) : \n\n`config.module.ts`\n\n```\nimport {Module} from '@nestjs/common';\nimport {ConfigService} from './config.service';\n\n@Module({\n providers: [{\n provide: ConfigService,\n useValue: new ConfigService(`${process.env.NODE_ENV || 'development'}.env`),\n }],\n exports: [ConfigService],\n})\n\nexport class ConfigModule {}\n```\n\n`config.service.ts`\n\n```\nimport * as dotenv from 'dotenv';\nimport * as fs from 'fs';\n\nexport class ConfigService {\n private readonly envConfig: {[key: string]: string};\n\n constructor(filePath: string) {\n // stock the file\n this.envConfig = dotenv.parse(fs.readFileSync(filePath));\n }\n\n // get specific key in .env file\n get(key: string): string {\n return this.envConfig[key];\n }\n\n}\n```\n\nThe problem is that in my main module I want to connect to `mongo` but I do not know how I can recover my variables as the module is declared in:\n\n Actually it's a class that gives me the infos\n\n`root.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { EnvService } from './env';\nimport { HelloModule } from './module/hello.module';\nimport { ContentModule } from './module/content.module';\nimport { CategoriesModule } from './module/categories.module';\nimport { AuthorModule } from './module/author.module';\n\nconst env = new EnvService().getEnv();\n\n@Module({\n imports: [\n // connect to the mongodb database\n MongooseModule.forRoot(`mongodb://${env.db_user}:${env.db_pass}@${env.db_uri}:${env.db_name}/${env.db_name}`, env.db_option),\n // ping module\n HelloModule,\n // data module\n ContentModule,\n CategoriesModule,\n AuthorModule,\n ],\n})\n\nexport class RootModule {}\n```\n\n========================================\n\nCode:\n```text\nimport {Module} from '@nestjs/common';\nimport {ConfigService} from './config.service';\n\n@Module({\n    providers: [{\n        provide: ConfigService,\n        useValue: new ConfigService(`${process.env.NODE_ENV || 'development'}.env`),\n    }],\n    exports: [ConfigService],\n})\n\nexport class ConfigModule {}\n```\n\n```text\nimport * as dotenv from 'dotenv';\nimport * as fs from 'fs';\n\nexport class ConfigService {\n    private readonly envConfig: {[key: string]: string};\n\n    constructor(filePath: string) {\n        // stock the file\n        this.envConfig = dotenv.parse(fs.readFileSync(filePath));\n    }\n\n    // get specific key in .env file\n    get(key: string): string {\n        return this.envConfig[key];\n    }\n\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { EnvService } from './env';\nimport { HelloModule } from './module/hello.module';\nimport { ContentModule } from './module/content.module';\nimport { CategoriesModule } from './module/categories.module';\nimport { AuthorModule } from './module/author.module';\n\nconst env = new EnvService().getEnv();\n\n@Module({\n    imports: [\n        // connect to the mongodb database\n        MongooseModule.forRoot(`mongodb://${env.db_user}:${env.db_pass}@${env.db_uri}:${env.db_name}/${env.db_name}`, env.db_option),\n        // ping module\n        HelloModule,\n        // data module\n        ContentModule,\n        CategoriesModule,\n        AuthorModule,\n    ],\n})\n\nexport class RootModule {}\n```\n\n```text\n.env\n```\n\n```text\nconfig.module.ts\n```\n\n```text\nconfig.service.ts\n```\n\n```text\nmongo\n```\n\n```text\nroot.module.ts\n```\n\n```text\nMongooseModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    uri: `mongodb://${configService.get(db_user)}:${configService.get(db_pass)}@${configService.get(db_uri)}:${configService.get(db_port)}/${configService.get(db_name)}`,\n  }),\n  inject: [ConfigService],\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":175,"estimatedTokens":981}}712{"id":"stack-65238786","source":"stackoverflow","questionId":65238786,"title":"Return data from response within an observable in Nestjs","tags":["typescript","observable","nestjs"],"text":"Title: Return data from response within an observable in Nestjs\nTags: typescript, observable, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm new to Nestjs, Typescript and basically backend development. And I'm working on a simple Weather app, where I fetch weather data from Open Weather API.\nI'm using Nest built-in `HttpModule` which is wrapping Axios within, then using `HttpService` to make a GET request to Open weather. The request is returning an Observable which is totally news to me.\nHow do I extract the actual response data from the observable in the `Injectable service` and return it to the `Controller`?\n\nHere's my weather.service.ts\n\n```\nimport { Injectable, HttpService } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n constructor(private httpService: HttpService) {}\n\n getWeather() {\n let obs = this.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a');\n \n console.log('just before subscribe');\n \n obs.subscribe((x) => {\n let {weather} = x.data;\n console.log(weather);\n })\n console.log('After subscribe');\n \n // TODO: Should extract and return response data f\n // return;\n }\n}\n```\n\nAnd this is weather.controller.ts\n\n```\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get()\n getWeather() {\n const res = this.appService.getWeather();\n return res;\n }\n}\n```\n\nAlso can someone clarify what are the missing types in my code?\n\n========================================\n\nTop Answer:\nTry this to return the value,by converting the observable to promise.\n\ngetProductList() {\nreturn firstValueFrom(this.workflowService.getProductList()).then(res=>{return res.data});\n}\n\n========================================\n\nCode:\n```text\nimport { Injectable, HttpService } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n  constructor(private httpService: HttpService) {}\n\n  getWeather() {\n    let obs = this.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a');\n    \n    console.log('just before subscribe');\n    \n    obs.subscribe((x) => {\n        let {weather} = x.data;\n        console.log(weather);\n    })\n    console.log('After subscribe');\n    \n    // TODO: Should extract and return response data f\n    // return;\n  }\n}\n```\n\n```text\nimport { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get()\n  getWeather() {\n    const res = this.appService.getWeather();\n    return res;\n  }\n}\n```\n\n```text\nHttpModule\n```\n\n```text\nHttpService\n```\n\n```text\nInjectable service\n```\n\n```text\nController\n```\n\n```js\nimport { Injectable, HttpService } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n  constructor(private httpService: HttpService) {}\n\n  getWeather() {\n    return this.httpService.get('https://api.openweathermap.org/data/2.5/weather?q=cairo&appid=c9661625b3eb09eed099288fbfad560a').pipe(\n      map(response => response.data)\n    );\n   \n  }\n}\n```\n\n```text\nRxJS Observables\n```\n\n```text\nmap\n```\n\n```text\nrxjs/operators\n```\n\n```text\nArray.prototype.map\n```\n\n```text\nController\n```\n\n```text\nthis.appService.getWeather()\n```\n\n```text\n.toPromise()\n```\n\n```text\nasync/await\n```\n\n```text\ntoPromise()\n```\n\n```text\nlastValueFrom(observable)\n```\n\n```text\nfirstValueFrom(observable)\n```\n\n========================================\n\nComments:\n- Thank you, I already figured it out and did convert it `toPromise()` which made it easier to use async/await\n- As of mid 2022, toPromise() is deprecated. RxJS recommends using either lastValueFrom() or firstValueFrom(). rxjs.dev/deprecations/to-promise","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":188,"estimatedTokens":962}}713{"id":"stack-69463692","source":"stackoverflow","questionId":69463692,"title":"NestJs Using Environment Configuration on @Cron decorator","tags":["javascript","node.js","nestjs","node-cron"],"text":"Title: NestJs Using Environment Configuration on @Cron decorator\nTags: javascript, node.js, nestjs, node-cron\nSource: Stack Overflow\n\nQuestion:\nI am building a nestJs application, with scheduling and configuration. I want to be able to configure my Cron with my environment variable but it does not seems to work.\n\napp.module.ts :\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot(),\n ScheduleModule.forRoot(),\n SchedulingModule,\n ...\n ],\n})\nexport class AppModule {}\n```\n\nscheduling.service.ts (from my SchedulingModule) :\n\n```\n@Cron(process.env.CRON_VALUE)\nscheduledJob() {\n this.logger.log('Scheduled : Job');\n ...\n}\n```\n\n.env :\n\n```\n...\nCRON_VALUE=0 4 * * *\n...\n```\n\nApparently at the moment the value is checked it's empty. I got the following error :\n\n```\n(node:55016) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_isAMomentObject' of undefined\n at new CronTime (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:42:50)\n at new CronJob (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:527:19)\n at /Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/@nestjs/schedule/dist/scheduler.orchestrator.js:56:29 \n ...\n```\n\n========================================\n\nTop Answer:\nTo fix this problem you should load the config on your service again:\n\n```\nrequire('dotenv').config();\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    ScheduleModule.forRoot(),\n    SchedulingModule,\n    ...\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n@Cron(process.env.CRON_VALUE)\nscheduledJob() {\n  this.logger.log('Scheduled : Job');\n  ...\n}\n```\n\n```text\n...\nCRON_VALUE=0 4 * * *\n...\n```\n\n```text\n(node:55016) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_isAMomentObject' of undefined\n    at new CronTime (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:42:50)\n    at new CronJob (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:527:19)\n    at /Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/@nestjs/schedule/dist/scheduler.orchestrator.js:56:29 \n    ...\n```\n\n```text\nconstructor(private schedulerRegistry: SchedulerRegistry) {}\n\nonModuleInit() {\n  const job = new CronJob(process.env. CRON_VALUE, () => {\n    // What you want to do here\n  });\n\n  this.schedulerRegistry.addCronJob(name, job);\n  job.start();\n}\n```\n\n```text\nrequire('dotenv').config();\n```\n\n```text\nimport * as dotenv from 'dotenv';\n\nconst getCronInterval = () => {\n  dotenv.config();\n\n  return process.env.FETCH_AND_SEND_DATA_CRON_INTERVAL;\n};\n\n@Injectable()\nexport class AppService {\n  constructor(\n    private readonly service: MyService,\n  ) {}\n\n  @Cron(getCronInterval()) // Adjust the cron schedule as needed\n  async doSomething() {\n    ....\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to pass configs from config service to Nest.js decorator?\n- Is there a \"nestjs\" way to do that ?\n- @Youba Unfortunately there is not, this is a limitation of its Config system because it evaluates `.env` AFTER all the imports and decorators are resolved. You have to manually ensure that .env is populated before other files are imported in order to have dynamic decorator values\n- Yes, you can't either pass a value from config service to a decorators, moreover you can't load the config from main.js when we working with Crons\n- I hope at least this solution works for you ^^\n- @Youba what about from your app.module?\n- @Youba Thanks for sharing your solution. That's what I ended up doing; adding it into app.module.ts (so that it will also work doing testing). I am amazed by Nest.js and how fun it most of the time is to work with, however, equally amazed at how \"dumb\" they made the ConfigModule.\n- If the project uses the NestJS config module to the .env variables in all nestjs components, this module might have logic (e.g you load the .env.dev only if .env.local doesnt exist) - if you use require('dotenv').config() - the current file won't have the same .env file as the rest of the nestjs which is defined by the config module","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":143,"estimatedTokens":1075}}714{"id":"stack-60390967","source":"stackoverflow","questionId":60390967,"title":"NestJS redirect HTTP to HTTPS / force SSL","tags":["typescript","security","https","nestjs"],"text":"Title: NestJS redirect HTTP to HTTPS / force SSL\nTags: typescript, security, https, nestjs\nSource: Stack Overflow\n\nQuestion:\nBuilding a NestJS Application I want to route ALL incoming traffic through https without inconvenience for the user.\n\nSo far there are two ways I know, both doesn't fit my requirements. \n\nSet up two servers for http and https and than redirect traffic per route/api endpoint, which is really not DRY and cannot be best practice. Doc redirect\n\nBy only creating the https server, the user would always be forced to type the https address manually what I don't want. Doc https\n\nIdeally I would assume a solution where https is checked and forced the very first moment some one is hitting the server by just typing `example.com`. I think this would best be done in `main.ts` of my NestJS application.\n\n========================================\n\nTop Answer:\nFor my use case, I see no reason to bloat the server with reverse proxy layer while node http servers are fully featured. Since question is related to NestJS, here I present simple native solution, using Nest middleware. Of course, u will have to also the NestJS documentation on hosting two servers, which is again fairly simple.\n\n```\nimport { HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class HttpsRedirectMiddleware implements NestMiddleware\n{\n use(req: Request, res: Response, next: () => void)\n {\n if (!req.secure)\n {\n const httpsUrl = `https://${req.hostname}${req.originalUrl}`;\n res.redirect(HttpStatus.PERMANENT_REDIRECT, httpsUrl);\n }\n else\n {\n next();\n }\n }\n}\n```\n\nWe simply ask on request object whether conneciton is secure, if not, we incite browser to permanently redirect to same url, but this time prefixed with `https://`.\nThe middleware class above is then to be registered for all routes within `configure()` method of `AppModule`.\n\n```\nconfigure(consumer: MiddlewareConsumer)\n{\n consumer.apply(HttpsRedirectMiddleware).forRoutes(\"*\");\n}\n```\n\n========================================\n\nCode:\n```text\nexample.com\n```\n\n```text\nmain.ts\n```\n\n```text\nserver {\n       listen         80;\n       server_name    example1.com example2.com;\n       return         301 https://$host$request_uri;\n}\n\nserver {\n       listen         443 ssl;\n       server_name    example1.com example2.com;\n       ...\n}\n```\n\n```text\nimport { HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response } from \"express\";\n\n@Injectable()\nexport class HttpsRedirectMiddleware implements NestMiddleware\n{\n    use(req: Request, res: Response, next: () => void)\n    {\n        if (!req.secure)\n        {\n            const httpsUrl = `https://${req.hostname}${req.originalUrl}`;\n            res.redirect(HttpStatus.PERMANENT_REDIRECT, httpsUrl);\n        }\n        else\n        {\n            next();\n        }\n    }\n}\n```\n\n```text\nconfigure(consumer: MiddlewareConsumer)\n{\n    consumer.apply(HttpsRedirectMiddleware).forRoutes(\"*\");\n}\n```\n\n```text\nhttps://\n```\n\n```text\nconfigure()\n```\n\n```text\nAppModule\n```\n\n```js\nimport enforce from 'express-sslify';\n\nasync bootstrap() {\n    // create your app\n\n    // Must be the FIRST middleware applied\n    // Must add in the 'trustProtoHeader' option\n    // (I only add this for production, but you can do whatever suits you)\n    if (process.env.NODE_ENV === 'production') {\n        app.use(enforce.HTTPS({ trustProtoHeader: true });\n    }\n\n    // other stuff\n}\n```\n\n```text\nnpm install express-sslify --save\n```\n\n```text\nmain.ts\n```\n\n```text\nhttps\n```\n\n========================================\n\nComments:\n- You can do this easily on nginx level. Is this solution good enough to you?\n- I am not familiar with nginx, right now I am serving my nestjs build via `node main.js`, nothing fancy. I am open for changes if they provide benefits.\n- So basically I could do the same thing with an Apache Server? I already have one set up.\n- Yes, this two solutions are very similar. You can define redirect on apache as well.\n- Is the port (80, 8080 or sth. like this) already included in `req.hostname`?\n- @BennyCode the port is not included in req.hostname\n- Just a warning for Heroku users, this won't work.\n- THANK YOU - this should have more upvotes","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":158,"estimatedTokens":1065}}715{"id":"stack-59624156","source":"stackoverflow","questionId":59624156,"title":"NestJs request and response interceptor unit testing","tags":["jestjs","nestjs"],"text":"Title: NestJs request and response interceptor unit testing\nTags: jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to log the incoming requests and outgoing responses for my API. I created a request interceptor and a response interceptor as described here\n\nhttps://docs.nestjs.com/interceptors\n\nSo the request interceptor only logs the request object\n\n```\n@Injectable()\nexport class RequestInterceptor implements NestInterceptor {\n private readonly logger: Logger = new Logger(RequestInterceptor.name, true);\n\n public intercept(context: ExecutionContext, next: CallHandler): Observable {\n const { originalUrl, method, params, query, body } = context.switchToHttp().getRequest();\n \n this.logger.debug({ originalUrl, method, params, query, body }, this.intercept.name);\n \n return next.handle();\n }\n}\n```\n\nand the response interceptor waits for the outgoing response and logs the status code and response object later on\n\n```\n@Injectable()\nexport class ResponseInterceptor implements NestInterceptor {\n private readonly logger: Logger = new Logger(ResponseInterceptor.name, true);\n\n public intercept(context: ExecutionContext, next: CallHandler): Observable {\n const { statusCode } = context.switchToHttp().getResponse();\n\n return next.handle().pipe(\n tap((responseData: any) =>\n this.logger.debug({ statusCode, responseData }, this.intercept.name),\n ),\n );\n }\n}\n```\n\nI would like to test them but unfortunately have almost no experience in testing. I tried to start with the request interceptor and came up with this\n\n```\nconst executionContext: any = {\n switchToHttp: jest.fn().mockReturnThis(),\n getRequest: jest.fn().mockReturnThis(),\n};\n\nconst nextCallHander: CallHandler = {\n handle: jest.fn(),\n};\n\ndescribe('RequestInterceptor', () => {\n let interceptor: RequestInterceptor;\n\n beforeEach(() => {\n interceptor = new RequestInterceptor();\n });\n\n describe('intercept', () => {\n it('should fetch the request object', (done: any) => {\n const requestInterception: Observable = interceptor.intercept(executionContext, nextCallHander);\n\n requestInterception.subscribe({\n next: value => {\n // ... ??? ...\n },\n error: error => {\n throw error;\n },\n complete: () => {\n done();\n },\n });\n });\n });\n});\n```\n\nI currently don't know what to pass into the next callback but when I try to run the test as it is it says that the requestInterception variable is undefined. So the test fails before reaching the next callback. So the error message I get is\n\nTypeError: Cannot read property 'subscribe' of undefined\n\nI also tried to test the response interceptor and came up with this\n\n```\nconst executionContext: any = {\n switchToHttp: jest.fn().mockReturnThis(),\n getResponse: jest.fn().mockReturnThis()\n};\n\nconst nextCallHander: CallHandler = {\n handle: jest.fn()\n};\n\ndescribe(\"ResponseInterceptor\", () => {\n let interceptor: ResponseInterceptor;\n\n beforeEach(() => {\n interceptor = new ResponseInterceptor();\n });\n\n describe(\"intercept\", () => {\n it(\"should fetch the statuscode and response data\", (done: any) => {\n const responseInterception: Observable = interceptor.intercept(\n executionContext,\n nextCallHander\n );\n\n responseInterception.subscribe({\n next: value => {\n // ...\n },\n error: error => {\n throw error;\n },\n complete: () => {\n done();\n }\n });\n });\n });\n});\n```\n\nThis time I get an error at the interceptor\n\nTypeError: Cannot read property 'pipe' of undefined\n\nWould some mind helping me to test those two interceptors properly?\n\nThanks in advance\n\n========================================\n\nCode:\n```ts\n@Injectable()\nexport class RequestInterceptor implements NestInterceptor {\n  private readonly logger: Logger = new Logger(RequestInterceptor.name, true);\n\n  public intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const { originalUrl, method, params, query, body } = context.switchToHttp().getRequest();\n    \n    this.logger.debug({ originalUrl, method, params, query, body }, this.intercept.name);\n    \n    return next.handle();\n  }\n}\n```\n\n```ts\n@Injectable()\nexport class ResponseInterceptor implements NestInterceptor {\n  private readonly logger: Logger = new Logger(ResponseInterceptor.name, true);\n\n  public intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const { statusCode } = context.switchToHttp().getResponse();\n\n    return next.handle().pipe(\n      tap((responseData: any) =>\n        this.logger.debug({ statusCode, responseData }, this.intercept.name),\n      ),\n    );\n  }\n}\n```\n\n```ts\nconst executionContext: any = {\n  switchToHttp: jest.fn().mockReturnThis(),\n  getRequest: jest.fn().mockReturnThis(),\n};\n\nconst nextCallHander: CallHandler<any> = {\n  handle: jest.fn(),\n};\n\ndescribe('RequestInterceptor', () => {\n  let interceptor: RequestInterceptor;\n\n  beforeEach(() => {\n    interceptor = new RequestInterceptor();\n  });\n\n  describe('intercept', () => {\n    it('should fetch the request object', (done: any) => {\n      const requestInterception: Observable<any> = interceptor.intercept(executionContext, nextCallHander);\n\n      requestInterception.subscribe({\n        next: value => {\n          // ... ??? ...\n        },\n        error: error => {\n          throw error;\n        },\n        complete: () => {\n          done();\n        },\n      });\n    });\n  });\n});\n```\n\n```ts\nconst executionContext: any = {\n  switchToHttp: jest.fn().mockReturnThis(),\n  getResponse: jest.fn().mockReturnThis()\n};\n\nconst nextCallHander: CallHandler<any> = {\n  handle: jest.fn()\n};\n\ndescribe(\"ResponseInterceptor\", () => {\n  let interceptor: ResponseInterceptor;\n\n  beforeEach(() => {\n    interceptor = new ResponseInterceptor();\n  });\n\n  describe(\"intercept\", () => {\n    it(\"should fetch the statuscode and response data\", (done: any) => {\n      const responseInterception: Observable<any> = interceptor.intercept(\n        executionContext,\n        nextCallHander\n      );\n\n      responseInterception.subscribe({\n        next: value => {\n          // ...\n        },\n        error: error => {\n          throw error;\n        },\n        complete: () => {\n          done();\n        }\n      });\n    });\n  });\n});\n```\n\n```js\nconst context = {\n  switchToHttp: jest.fn(() => ({\n    getRequest: () => ({\n      originalUrl: '/',\n      method: 'GET',\n      params: undefined,\n      query: undefined,\n      body: undefined,\n    }),\n    getResponse: () => ({\n      statusCode: 200,\n    }),\n  })),\n  // method I needed recently so I figured I'd add it in\n  getType: jest.fn(() => 'http')\n}\n```\n\n```js\nconst next = {\n  handle: () => of()\n}\n```\n\n```js\nconst next = {\n  handle: jest.fn(() => of(myDataObject)),\n}\n```\n\n```js\ndescribe('ResponseInterceptor', () => {\n  let interceptor: ResponseInterceptor;\n  let loggerSpy = jest.spyOn(Logger.prototype, 'debug');\n\n  beforeEach(() => {\n    interceptor = new ResponseInterceptor();\n  });\n\n  afterEach(() => {\n    loggerSpy.resetMock();\n  });\n\n  describe('intercept', () => {\n    it('should fetch the request object', (done: any) => {\n      const responseInterceptor: Observable<any> = interceptor.intercept(executionContext, nextCallHander);\n\n      responseInterceptor.subscribe({\n        next: value => {\n          // expect the logger to have two parameters, the data, and the intercept function name\n          expect(loggerSpy).toBeCalledWith({statusCode: 200, responseData: value}, 'intercept');\n        },\n        error: error => {\n          throw error;\n        },\n        complete: () => {\n          // only logging one request\n          expect(loggerSpy).toBeCalledTimes(1);\n          done();\n        },\n      });\n    });\n  });\n});\n```\n\n```text\nExecutionContext\n```\n\n```text\nnext\n```\n\n```text\nExecutionContext\n```\n\n```text\nswitchToHttp()\n```\n\n```text\nswitchToHttp()\n```\n\n```text\ngetResponse()\n```\n\n```text\ngetRequest()\n```\n\n```text\ngetRequest()\n```\n\n```text\ngetResponse()\n```\n\n```text\nres.statusCode\n```\n\n```text\nreq.originalUrl\n```\n\n```text\ncontext\n```\n\n```text\nCallHandler\n```\n\n```text\nCallHandler\n```\n\n```text\nhandle()\n```\n\n```text\nnext\n```\n\n```text\nnext.handle()\n```\n\n```text\nexecutionContext\n```\n\n```text\ncallHandler\n```\n\n```text\nRequestInterceptor\n```\n\n```text\ncomplete\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":400,"estimatedTokens":2023}}716{"id":"stack-62486153","source":"stackoverflow","questionId":62486153,"title":"Get data from observable grpc service in nestjs,","tags":["node.js","angular","grpc","nestjs","grpc-node"],"text":"Title: Get data from observable grpc service in nestjs,\nTags: node.js, angular, grpc, nestjs, grpc-node\nSource: Stack Overflow\n\nQuestion:\nI want to use gRPC service to communicate between my microservices. but when getting a response from Grpc service, before return a method, I want to do some modification and functionality.\n\nsample project: https://github.com/nestjs/nest/tree/master/sample/04-grpc\n\nlike this:\n\n```\n@Get(':id') \ngetById(@Param('id') id: string): Observable {\n const res: Observable = this.heroService.findOne({ id: +id }); \n console.log(res); res.name = res.name + 'modify string'; \n return res;\n}\n```\n\nbut show below message in console.log instead of the original response.\n\n```\nObservable { _isScalar: false, _subscribe: [Function] }\n```\n\n========================================\n\nTop Answer:\nYour can use map operator to transform the emitted value.\n\nIn the below code, you are adding string `modify string` to `name`.\n\n```\n@Get(':id')\n getById(@Param('id') id: string): Observable {\n return this.heroService\n .findOne({ id: +id })\n .pipe(map(item => ({ ...item, name: `${item.name}modify string` })));\n }\n```\n\nIf any time, you want to log emitted values or perform side effects in an Observable stream, you can use tap operator\n\n```\n@Get(':id')\n getById(@Param('id') id: string): Observable {\n return this.heroService\n .findOne({ id: +id })\n .pipe(tap(item => console.log(item)));\n }\n```\n\n========================================\n\nCode:\n```text\n@Get(':id') \ngetById(@Param('id') id: string): Observable<Hero> {\n  const res: Observable<Hero> = this.heroService.findOne({ id: +id }); \n  console.log(res); res.name = res.name + 'modify string'; \n  return res;\n}\n```\n\n```text\nObservable { _isScalar: false, _subscribe: [Function] }\n```\n\n```text\n@Get(':id') \nasync getById(@Param('id') id: string): Promise<Hero> {\n\n  const res:Hero = await lastValueFrom(this.heroService.findOne({ id: +id }));\n  \n  res.name = res.name + 'modify string'; \n  return res;\n}\n```\n\n```text\nObservable\n```\n\n```text\nPromise\n```\n\n```text\nlastValueFrom\n```\n\n```text\nObservable\n```\n\n```text\n@Get(':id')\n  getById(@Param('id') id: string): Observable<Hero> {\n    return this.heroService\n      .findOne({ id: +id })\n      .pipe(map(item => ({ ...item, name: `${item.name}modify string` })));\n  }\n```\n\n```text\n@Get(':id')\n  getById(@Param('id') id: string): Observable<Hero> {\n    return this.heroService\n      .findOne({ id: +id })\n      .pipe(tap(item => console.log(item)));\n  }\n```\n\n```text\nmodify string\n```\n\n```text\nname\n```\n\n========================================\n\nComments:\n- This is now replaced with firstValueFrom and lastValueFrom. Will be removed in v8. Details: rxjs.dev/deprecations/to-promise\n- @Nils: True, feel free to edit my answer :)\n- It tells me that the \"Suggested edit queue is full\". (I also did not know I could edit answers, thanks :)\n- github.com/yukukotani/protoc-gen-nestjs/blob/&hellip; In shortly you need to write `stream` keyword before your return type in proto files.","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":129,"estimatedTokens":749}}717{"id":"stack-60531318","source":"stackoverflow","questionId":60531318,"title":"Deleting the columns from the typeorm entities","tags":["postgresql","nestjs","typeorm"],"text":"Title: Deleting the columns from the typeorm entities\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am pretty new to the NestJS/typeorm system. So while working, I created an `Episode` entity and added some fields. Then I updated the entity to remove and update some fields. But after running the application, it still has the deleted columns ( checked it on pgAdmin ). The migrations are not updated to delete the columns. Is there any way to do it?\n\n========================================\n\nCode:\n```text\nEpisode\n```\n\n```text\nrm -rf dist\n```\n\n========================================\n\nComments:\n- Do you have `synchronize:true` set in your TypeORM configuration?\n- Yes. It adds new columns added to the entity, but does not remove the deleted ones.\n- TypeORM has a really bad issue with caching columns and not deleting them. Usual remedy is `rm -rf dist` (or the windows equivalent) and start the server again\n- Thank You very much. It worked.\n- I'll just comment here that his works on NestJS, in case someone searches for it.","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":26,"estimatedTokens":264}}718{"id":"stack-59087179","source":"stackoverflow","questionId":59087179,"title":"How update entity if exist or create if not exist entity","tags":["javascript","sql","nestjs","typeorm"],"text":"Title: How update entity if exist or create if not exist entity\nTags: javascript, sql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere are my entities.\n\n```\n// user\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic email: string;\n\n@Column({ type: 'varchar', nullable: false })\npublic password: string;\n\n@OneToOne(() => Token, (token: Token) => token.user)\npublic token: Token;\n```\n\n```\n// token\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic uuid: string;\n\n@Column({ type: 'integer', nullable: false })\npublic userId: number;\n\n@OneToOne(() => User, (user: User) => user.hash, { cascade: ['insert', 'remove'] })\n@JoinColumn({ name: 'userId' })\npublic user: User;\n```\n\nThis is how I save current in my database.\n\n```\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const token = this.tokenRepository.create(tokenDto);\n return await this.tokenRepository.save(token);\n}\n```\n\nWhen I first save my token to the database, all of it is saved.\n\nWhen I save a second time, I get an error.\n\nER_DUP_ENTRY: Duplicate entry '36' for key 'REL_d417e5d35f2434afc4bd48cb4d'\n\nI read in the documentation about the save method. But why I get the error, I can not understand. I expect the record to be updated. Why are my token details not updated?\n\nI understand how to do this using sql.\n\n```\nINSERT INTO \"Tokens\" (UUID, USERID)\n VALUES ('d93ab036-768c-420a-98d6-2f80c79e6ae7', 36)\n ON CONFLICT (USERID) \n DO UPDATE SET UUID = 'd93ab036-768c-420a-98d6-2f80c79e6ae7', \n USERID = 36'\n```\n\nAfter some experiments, I noticed that when I specify the token id, then saving or updating is successful.\n\n```\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const a = {\n id: 15,\n uuid: '343443443444444444444444',\n userId: 36,\n };\n const token = this.tokenRepository.create(a);\n return await this.tokenRepository.save(token);\n}\n```\n\nBut if I didnโ€™t indicate the id of the token, I get an error.\n\n```\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const a = {\n // id: 15,\n uuid: '343443443444444444444444',\n userId: 36,\n };\n const token = this.tokenRepository.create(a);\n return await this.tokenRepository.save(token);\n}\n```\n\nER_DUP_ENTRY: Duplicate entry '36' for key 'REL_d417e5d35f2434afc4bd48cb4d'\n\nI searched and found some examples.\n\nTypeORM upsert - create if not exist\n\nhttps://github.com/typeorm/typeorm/issues/3342\n\nThey say that the value must be a primary key or a unique value. But my userId field is an index, and is also unique.\n\nhttps://i.sstatic.net/2oZ8r.png\n\nWhat options can be, why is my token not updated?\n\n========================================\n\nTop Answer:\nIt isn't saying that there is a duplicate entry in the table already, it is saying that there is already one entry in there with that value for the primary key and it is refusing to insert a second for that reason.\n\nYou will find one matching row, and that your code at the point of the error is trying to insert a second.\n\nDealing with duplicates on insert:\n\nIf you try INSERT a duplicate values for a primary key (or a unique index) you will always get that error. There are a couple of ways around it: check before you insert and either do an update (if something might have changed) or just don't do anything.\n\n========================================\n\nCode:\n```js\n// user\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic email: string;\n\n@Column({ type: 'varchar', nullable: false })\npublic password: string;\n\n@OneToOne(() => Token, (token: Token) => token.user)\npublic token: Token;\n```\n\n```js\n// token\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic uuid: string;\n\n@Column({ type: 'integer', nullable: false })\npublic userId: number;\n\n@OneToOne(() => User, (user: User) => user.hash, { cascade: ['insert', 'remove'] })\n@JoinColumn({ name: 'userId' })\npublic user: User;\n```\n\n```js\nprivate async savePayload(tokenDto: CreateTokenDto) {\n    const token = this.tokenRepository.create(tokenDto);\n    return await this.tokenRepository.save(token);\n}\n```\n\n```sql\nINSERT INTO \"Tokens\" (UUID, USERID)\n    VALUES ('d93ab036-768c-420a-98d6-2f80c79e6ae7', 36)\n        ON CONFLICT (USERID) \n            DO UPDATE SET UUID = 'd93ab036-768c-420a-98d6-2f80c79e6ae7', \n                USERID = 36'\n```\n\n```js\nprivate async savePayload(tokenDto: CreateTokenDto) {\n    const a = {\n        id: 15,\n        uuid: '343443443444444444444444',\n        userId: 36,\n    };\n    const token = this.tokenRepository.create(a);\n    return await this.tokenRepository.save(token);\n}\n```\n\n```js\nprivate async savePayload(tokenDto: CreateTokenDto) {\n    const a = {\n        // id: 15,\n        uuid: '343443443444444444444444',\n        userId: 36,\n    };\n    const token = this.tokenRepository.create(a);\n    return await this.tokenRepository.save(token);\n}\n```\n\n```js\nconst values = {\n    uuid: '343443443444444444444444',\n    userId: 36\n}\n\nawait connection.createQueryBuilder()\n            .insert()\n            .into(Tokens)\n            .values(post2)\n            .onConflict(`(\"userId\") DO UPDATE SET UUID = :uuid`)\n            .setParameter(\"title\", values.uuid)\n            .execute();\n```\n\n```js\n@Column({ type: 'varchar', nullable: false })\npublic uuid: string;\n\n@PrimaryColumn()\npublic userId: number;\n\n@OneToOne(() => User, (user: User) => user.hash, { cascade: ['insert', 'remove'] })\n@JoinColumn({ name: 'userId' })\npublic user: User;\n```\n\n```text\nRepository<T>.save()\n```\n\n```text\nsave()\n```\n\n```text\nid\n```\n\n```text\nsave()\n```\n\n```text\nid\n```\n\n```text\nsave()\n```\n\n```text\nuserId\n```\n\n```text\nsave()\n```\n\n```text\n@PrimaryGeneratedId\n```\n\n```text\n@PrimaryColumn\n```\n\n```js\nasync CreateNewRole(data: any): Promise<Role | any> {\n    try {\n      const entity = await this.roleRepository.create(data);\n      const role = await this.roleRepository.save(entity);\n      this.trackingService.create(data.user);\n      return {\n        success: true,\n        role,\n      };\n    } catch (e) {\n      //  code == 23505 means duplication key\n      if (parseInt(e.code) === 23505) {\n        console.log('error : ', e.detail);\n        return {\n          success: false,\n          message: ROLE_ERROR_MESSAGES.ROLE_IS_FOUND,\n        };\n      } else {\n        return {\n          success: false,\n        };\n      }\n    }\n  }\n\n  async UpdateRole(data: any, id: number): Promise<Role | any> {\n    try {\n      await this.roleRepository.update(id, { ...data.payload });\n      this.trackingService.create(data.user);\n      // todo this need to be refactored !!\n      // return back the updated entity\n      const role = await this.roleRepository.find({ id });\n      console.log('role updated ', role);\n      return {\n        role,\n        success: true,\n      };\n    } catch (e) {\n      if (parseInt(e.code) === 23505) {\n        console.log('error : ', e.detail);\n        return {\n          success: false,\n          message: ROLE_ERROR_MESSAGES.ROLE_IS_FOUND,\n        };\n      } else {\n        return {\n          success: false,\n        };\n      }\n    }\n  }\n```\n\n========================================\n\nComments:\n- Yes, the second option works as I expected. This is the most complete answer. thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":320,"estimatedTokens":1812}}719{"id":"stack-68839194","source":"stackoverflow","questionId":68839194,"title":"How to use environment variables in ClientsModule?","tags":["nestjs","nestjs-config"],"text":"Title: How to use environment variables in ClientsModule?\nTags: nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use environment variables in the ClientsModule as such:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([Process]),\n ClientsModule.register([\n {\n name: 'PROCESS_SERVICE',\n transport: Transport.RMQ,\n options: {\n queue: process.env.RMQ_PRODUCER_QUEUE_NAME,\n urls: [process.env.RMQ_PRODUCER_URL],\n queueOptions: { durable: true },\n },\n },\n ]),\n```\n\nAnd I've also tried this:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\nimport { ConfigService } from '@nestjs/config';\n\nconst configService = new ConfigService();\nconst rmqProcessUrl = configService.get('RMQ_PRODUCER_URL');\nconst rmqProcessQueue = configService.get('RMQ_PRODUCER_QUEUE');\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([Process]),\n ClientsModule.register([\n {\n name: 'PROCESSES_SERVICE',\n transport: Transport.RMQ,\n options: {\n queue: rmqProcessQueue,\n urls: [rmqProcessUrl],\n queueOptions: { durable: true },\n },\n },\n ]),\n```\n\nBut in both occasions the following error appears:\n\nTypeError: metatype is not a constructor\n\nIt works as intended when I use the values directly. I have also tried importing and using\n\n```\nexport const rmqServiceName = process.env.RMQ_PRODUCER_QUEUE_NAME\n```\n\nand\n\n```\nexport const rmqServiceName = process.env.RMQ_PRODUCER_URL\n```\n\nbut that also results in the same error.\n\nSo how can I get access to the `.env` variables in the `@ClientsModule`?\nIs there a workaround that I'm missing?\n\n========================================\n\nTop Answer:\nI discovered the solutions here is implementation in my module file\n\n```\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ envFilePath: '.env' }), // Configure ConfigModule\n ClientsModule.register([\n {\n name: 'SERVICE_A',\n transport: Transport.TCP,\n options: (configService: ConfigService) => ({\n host: configService.get('SERVICE_A_HOST') as string,\n port: Number(configService.get('SERVICE_A_PORT')),\n }),\n },\n {\n name: 'SERVICE_B',\n transport: Transport.TCP,\n options: (configService: ConfigService) => ({\n host: configService.get('SERVICE_B_HOST') as string,\n port: Number(configService.get('SERVICE_B_PORT')),\n }),\n },\n ]),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n========================================\n\nCode:\n```js\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([Process]),\n    ClientsModule.register([\n      {\n        name: 'PROCESS_SERVICE',\n        transport: Transport.RMQ,\n        options: {\n          queue: process.env.RMQ_PRODUCER_QUEUE_NAME,\n          urls: [process.env.RMQ_PRODUCER_URL],\n          queueOptions: { durable: true },\n        },\n      },\n    ]),\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\nimport { ConfigService } from '@nestjs/config';\n\nconst configService = new ConfigService();\nconst rmqProcessUrl = configService.get<string>('RMQ_PRODUCER_URL');\nconst rmqProcessQueue = configService.get<string>('RMQ_PRODUCER_QUEUE');\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([Process]),\n    ClientsModule.register([\n      {\n        name: 'PROCESSES_SERVICE',\n        transport: Transport.RMQ,\n        options: {\n          queue: rmqProcessQueue,\n          urls: [rmqProcessUrl],\n          queueOptions: { durable: true },\n        },\n      },\n    ]),\n```\n\n```js\nexport const rmqServiceName = process.env.RMQ_PRODUCER_QUEUE_NAME\n```\n\n```js\nexport const rmqServiceName = process.env.RMQ_PRODUCER_URL\n```\n\n```text\n.env\n```\n\n```text\n@ClientsModule\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([Process]),\n    ClientsModule.registerAsync([\n      {\n        name: 'PROCESSES_SERVICE',\n        imports: [ConfigModule],\n        useFactory: async (configService: ConfigService) => ({\n          transport: Transport.RMQ,\n          options: {\n            queue: configService.get<string>('RMQ_PRODUCER_QUEUE'),\n            urls: [configService.get<string>('RMQ_PRODUCER_URL')],\n            queueOptions: { durable: configService.get<boolean>('RMQ_PRODUCER_QUEUE_DURABLE') },\n          },\n        }),\n        inject: [ConfigService],\n      },\n    ]),\n```\n\n```text\nnestjs/config\n```\n\n```text\nConfigModule\n```\n\n```text\napp.module.ts\n```\n\n```text\nasync\n```\n\n```text\nClientsModule.register\n```\n\n```text\napp.module.ts\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ClientsModule, Transport } from '@nestjs/microservices';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({ envFilePath: '.env' }), // Configure ConfigModule\n    ClientsModule.register([\n      {\n        name: 'SERVICE_A',\n        transport: Transport.TCP,\n        options: (configService: ConfigService) => ({\n          host: configService.get('SERVICE_A_HOST') as string,\n          port: Number(configService.get('SERVICE_A_PORT')),\n        }),\n      },\n      {\n        name: 'SERVICE_B',\n        transport: Transport.TCP,\n        options: (configService: ConfigService) => ({\n          host: configService.get('SERVICE_B_HOST') as string,\n          port: Number(configService.get('SERVICE_B_PORT')),\n        }),\n      },\n    ]),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n```\n\n========================================\n\nComments:\n- read the docs docs.nestjs.com/microservices/basics#client","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":274,"estimatedTokens":1588}}720{"id":"stack-68028356","source":"stackoverflow","questionId":68028356,"title":"nullable array of nullable values in nestjs code first graphql","tags":["graphql","nestjs","code-first"],"text":"Title: nullable array of nullable values in nestjs code first graphql\nTags: graphql, nestjs, code-first\nSource: Stack Overflow\n\nQuestion:\nHow can I get a field of type array that allows nullable values when using the code-first approach in nestjs graphql.\n\nThe example shows that\n\n```\n@Field(type => [String])\n ingredients: string[];\n```\n\ngenerates `[String!]!` in the `schema.gql` file. How can I get just `[String]`? using `{nullable: true}` gives me `[String!]`\n\nI was hoping to find some type of utility or parameter in the `@Field` decorator, but It seems it isn't\n\n========================================\n\nCode:\n```text\n@Field(type => [String])\n  ingredients: string[];\n```\n\n```text\n[String!]!\n```\n\n```text\nschema.gql\n```\n\n```text\n[String]\n```\n\n```text\n{nullable: true}\n```\n\n```text\n[String!]\n```\n\n```text\n@Field\n```\n\n```text\n@Field(type => [Post])\nposts: Post[];\n```\n\n```js\n@Field(type => [Post], { nullable: 'items' })\nposts: Post[];`\n```\n\n```text\n@Field(() => [String], { nullable: 'itemsAndList' })\n```\n\n========================================\n\nComments:\n- Hehe, shame on me. It's clear in the docs. I guess I was a little too lazy. I hope the wording of the question helps other lazy people in the future :)\n- As a lazy person that found this helpful, thank you! ๐ŸŽ‰\n- @Jay do have any idea about nullable just `List`? I want my list to be nullable but not its items.\n- @e.hadid probably it's better to return an empty array instead of `null`","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":71,"estimatedTokens":364}}721{"id":"stack-63838754","source":"stackoverflow","questionId":63838754,"title":"Nest.js Can't resolve circular dependency on TestingModule","tags":["typescript","backend","nestjs"],"text":"Title: Nest.js Can't resolve circular dependency on TestingModule\nTags: typescript, backend, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have built a new module and service for a Nest app, it has a circular dependency that resolves successfully when I run the application, but when I run the tests, my mockedModule (TestingModule) can't resolve the dependency for the new service I created.\n\nExample of the \"LimitsService\" created with a circular dependency with \"MathService\":\n\n```\n@Injectable()\nexport class LimitsService {\n constructor(\n private readonly listService: ListService,\n @Inject(forwardRef(() => MathService))\n private readonly mathService: MathService,\n ) {}\n\n async verifyLimit(\n user: User,\n listId: string,\n ): Promise {\n ...\n this.mathService.doSomething()\n }\n \n async someOtherMethod(){...}\n}\n```\n\nMathService calls LimitService.someOtherMethod in one of its methods.\n\nThis is how the testing module for \"MathService\" is setup (everything worked fine before without \"LimitsService\"):\n\n```\nconst limitsServiceMock = {\n verifyLimit: jest.fn(),\n someOtherMethod: jest.fn()\n};\n\nconst listServiceMock = {\n verifyLimit: jest.fn(),\n someOtherMethod: jest.fn()\n};\n\ndescribe('Math Service', () => {\n\n let mathService: MathService;\n let limitsService: LimitsService;\n let listService: ListService;\n let httpService: HttpService;\n\n beforeEach(async () => {\n const mockModule: TestingModule = await Test.createTestingModule({\n imports: [HttpModule],\n providers: [\n MathService,\n ConfigService,\n {\n provide: LimitsService,\n useValue: limitsServiceMock\n },\n {\n provide: ListService,\n useValue: listServiceMock\n },\n ],\n }).compile();\n \n httpService = mockModule.get(HttpService);\n limitsService = mockModule.get(LimitsService);\n listService = mockModule.get(ListService);\n mathService= mockModule.get(MathService);\n \n });\n\n...tests\n```\n\nBut when I run the test file, I get:\n\n\"Nest can't resolve dependencies of the MathService (...). Please make sure that the argument dependency at index [x] is available in the RootTestModule context.\"\n\nI have tried commenting out \"mathService\" from \"LimitsService\" and it works when I do that,but I need mathService.\n\nI have also tried importing \"LimitsModule\" instead of providing \"LimitsService\" with forwardRef() and then getting \"LimitsService\" from mockModule but that threw the same error.\n\nWhat is the proper way of importing my \"LimitsService\" into the mockModule?\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LimitsService {\n      constructor(\n        private readonly listService: ListService,\n        @Inject(forwardRef(() => MathService))\n        private readonly mathService: MathService,\n      ) {}\n\n      async verifyLimit(\n        user: User,\n        listId: string,\n      ): Promise<void> {\n         ...\n         this.mathService.doSomething()\n      }\n     \n      async someOtherMethod(){...}\n}\n```\n\n```text\nconst limitsServiceMock = {\n  verifyLimit: jest.fn(),\n  someOtherMethod: jest.fn()\n};\n\nconst listServiceMock = {\n  verifyLimit: jest.fn(),\n  someOtherMethod: jest.fn()\n};\n\ndescribe('Math Service', () => {\n\n  let mathService: MathService;\n  let limitsService: LimitsService;\n  let listService: ListService;\n  let httpService: HttpService;\n\n\n  beforeEach(async () => {\n    const mockModule: TestingModule = await Test.createTestingModule({\n      imports: [HttpModule],\n      providers: [\n        MathService,\n        ConfigService,\n        {\n          provide: LimitsService,\n          useValue: limitsServiceMock\n        },\n        {\n          provide: ListService,\n          useValue: listServiceMock\n        },\n      ],\n    }).compile();\n    \n    httpService = mockModule.get(HttpService);\n    limitsService = mockModule.get(LimitsService);\n    listService = mockModule.get(ListService);\n    mathService= mockModule.get(MathService);\n    \n });\n\n...tests\n```\n\n```text\njest.mock('@Limits/limits.service');\n```\n\n```text\ndescribe('Math Service', () => {\n\n  let mockLimitsService : LimitsService;\n\n  let mathService: MathService;\n  let listService: ListService;\n  let httpService: HttpService;\n\n\n  beforeEach(async () => {\n    const mockModule: TestingModule = await Test.createTestingModule({\n      imports: [HttpModule],\n      providers: [\n        MathService,\n        ConfigService,\n        LimitsService,\n        {\n          provide: ListService,\n          useValue: listServiceMock\n        },\n      ],\n    }).compile();\n\n    mockLimitsService = mockModule.get(LimitsService);\n\n    httpService = mockModule.get(HttpService);\n    listService = mockModule.get(ListService);\n    mathService= mockModule.get(MathService);\n    \n });\n```\n\n========================================\n\nComments:\n- It seems that LimitsService requires two dependencies, ie, ListService and MathService. However in your code you're not providing ListService as providers. Maybe you can add ListService into your providers list and try again.\n- My mistake when I added the example, in my code I do have ListService listed as a provider\n- Hey, I've run into the same problem! Where is listServiceMock defined though?\n- Hey, that would be defined as: `const listServiceMock = { verifyLimit: jest.fn(), someOtherMethod: jest.fn() };`\n- goddamn this solution helped me too, thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":204,"estimatedTokens":1315}}722{"id":"stack-61578856","source":"stackoverflow","questionId":61578856,"title":"(node:18560) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'typeFn' of undefined","tags":["mongodb","typescript","mongoose","graphql","nestjs"],"text":"Title: (node:18560) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'typeFn' of undefined\nTags: mongodb, typescript, mongoose, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am getting this error when I am trying to resolve a field(blocks) with the `@ResolveField()` decorator.\n\n**page.resolver.ts**\n\n```\nimport {\n Resolver,\n Query,\n Mutation,\n Args,\n ResolveField,\n Parent,\n} from '@nestjs/graphql';\nimport { PageService } from './page.service';\nimport { PageType } from './type/page.type';\nimport { CreatePageInput } from './input/create-page.input';\nimport { BlockService } from '../block/block.service';\nimport { Page } from './page.interface';\n\n@Resolver('Page')\nexport class PageResolver {\n constructor(\n private readonly pageService: PageService,\n private readonly blockService: BlockService,\n ) {}\n\n @Query(() => [PageType])\n pages() {\n return this.pageService.getAllPages();\n }\n\n @Query(() => [PageType])\n async page(@Args('id') id: string) {\n return this.pageService.getPage(id);\n }\n\n @Mutation(() => PageType)\n createPage(@Args('createPageInput') createPageInput: CreatePageInput) {\n return this.pageService.createPage(createPageInput);\n }\n\n @ResolveField()\n blocks(@Parent() page: Page) {\n return this.blockService.getManyBlocks(page.blockIds);\n }\n}\n```\n\n**page.interface.ts**\n\n```\nimport { Document } from 'mongoose';\n\nexport interface Page extends Document {\n readonly id: string;\n readonly name: string;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly createdBy: string;\n readonly updatedBy: string;\n readonly blockIds: string[];\n}\n```\n\n========================================\n\nCode:\n```text\nimport {\n  Resolver,\n  Query,\n  Mutation,\n  Args,\n  ResolveField,\n  Parent,\n} from '@nestjs/graphql';\nimport { PageService } from './page.service';\nimport { PageType } from './type/page.type';\nimport { CreatePageInput } from './input/create-page.input';\nimport { BlockService } from '../block/block.service';\nimport { Page } from './page.interface';\n\n@Resolver('Page')\nexport class PageResolver {\n  constructor(\n    private readonly pageService: PageService,\n    private readonly blockService: BlockService,\n  ) {}\n\n  @Query(() => [PageType])\n  pages() {\n    return this.pageService.getAllPages();\n  }\n\n  @Query(() => [PageType])\n  async page(@Args('id') id: string) {\n    return this.pageService.getPage(id);\n  }\n\n  @Mutation(() => PageType)\n  createPage(@Args('createPageInput') createPageInput: CreatePageInput) {\n    return this.pageService.createPage(createPageInput);\n  }\n\n  @ResolveField()\n  blocks(@Parent() page: Page) {\n    return this.blockService.getManyBlocks(page.blockIds);\n  }\n}\n```\n\n```text\nimport { Document } from 'mongoose';\n\nexport interface Page extends Document {\n  readonly id: string;\n  readonly name: string;\n  readonly createdAt: Date;\n  readonly updatedAt: Date;\n  readonly createdBy: string;\n  readonly updatedBy: string;\n  readonly blockIds: string[];\n}\n```\n\n```text\n@ResolveField()\n```\n\n```text\n@Resolver(() => PageType)\n```\n\n```text\n() => PageType\n```\n\n```text\n@Resolver()\n```\n\n========================================\n\nComments:\n- I'm pretty sure if you are using `@ResolveField()` you need to use a function in the `@Resolver()` decorator, e.g. `@Resolver(() => Page)`\n- Thanks, It's solved after using `@Resolver(() => PageType)`","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":151,"estimatedTokens":828}}723{"id":"stack-74246552","source":"stackoverflow","questionId":74246552,"title":"error TS2688: Cannot find type definition file for 'ioredis'","tags":["javascript","nestjs","tsconfig","ioredis"],"text":"Title: error TS2688: Cannot find type definition file for 'ioredis'\nTags: javascript, nestjs, tsconfig, ioredis\nSource: Stack Overflow\n\nQuestion:\nI have a project with nestJS. But in when trying to add some module it show error.\n\n```\nerror TS2688: Cannot find type definition file for 'ioredis'.\n The file is in the program because:\n Entry point for implicit type library 'ioredis'\n```\n\nand this is my tsconfig\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": false,\n \"noImplicitAny\": false,\n \"removeComments\": true,\n \"noLib\": false,\n \"allowSyntheticDefaultImports\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"allowJs\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\", \n \"paths\": {\n \"@core/*\": [\"src/core/*\"],\n \"@main/*\": [\"src/main/*\"],\n \"@migrations/*\": [\"src/migrations/*\"],\n \"@modules/*\": [\"src/modules/*\"],\n \"@shared/*\": [\"src/shared/*\"]\n },\n \"incremental\": true\n },\n \"exclude\": [\n \"node_modules\", \"dist\"\n ]\n}\n```\n\nHow to resolve the error ?\n\n========================================\n\nCode:\n```text\nerror TS2688: Cannot find type definition file for 'ioredis'.\n  The file is in the program because:\n    Entry point for implicit type library 'ioredis'\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"module\": \"commonjs\",\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"removeComments\": true,\n        \"noLib\": false,\n        \"allowSyntheticDefaultImports\": true,\n        \"emitDecoratorMetadata\": true,\n        \"experimentalDecorators\": true,\n        \"target\": \"es2017\",\n        \"sourceMap\": true,\n        \"allowJs\": true,\n        \"outDir\": \"./dist\",\n        \"baseUrl\": \"./\",   \n        \"paths\": {\n            \"@core/*\": [\"src/core/*\"],\n            \"@main/*\": [\"src/main/*\"],\n            \"@migrations/*\": [\"src/migrations/*\"],\n            \"@modules/*\": [\"src/modules/*\"],\n            \"@shared/*\": [\"src/shared/*\"]\n        },\n        \"incremental\": true\n    },\n    \"exclude\": [\n        \"node_modules\", \"dist\"\n    ]\n}\n```\n\n```bash\nnpm install --save-dev @types/ioredis@4.28.10\n```\n\n```bash\nnpm install --save ioredis@4.28.5\nnpm install --save-dev @types/ioredis@4.28.10\n```\n\n```text\nioredis@4\n```\n\n```text\n@types/ioredis\n```\n\n```text\nioredis@5\n```\n\n```text\n@nestjs/bull\n```\n\n```text\nbull\n```\n\n```text\nioredis@5\n```\n\n```text\nioredis\n```\n\n```text\nbull\n```\n\n```text\nioredis@5\n```\n\n========================================\n\nComments:\n- What is your version of `ioredis`? It should come with types ready to use\n- Saved me couple of hours. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":138,"estimatedTokens":638}}724{"id":"stack-65577974","source":"stackoverflow","questionId":65577974,"title":"How to use NestJS Reflector inside a Custom Decorator?","tags":["javascript","node.js","nestjs"],"text":"Title: How to use NestJS Reflector inside a Custom Decorator?\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using a `@SetMetaData('version', 'v2')` to set versioning for a http method in a controller.\nThen I have a custom `@Get()` decorator to add the version as a postfix to the controller route.\n\nSo that, I would be able to use `/api/cats/v2/firstfive`, when I have\n\n```\n@SetMetaData('version', 'v2')\n@Get('firstfive')\n```\n\nBut I don't see a clear way to inject Reflector to my custom @Get decorator.\n\nMy Get decorator is as follows,\n\n```\nimport { Get as _Get } from '@nestjs/common';\nexport function Get(path?: string) {\n version = /*this.reflector.get('version') or something similar */\n return applyDecorators(_Get(version+path));\n}\n```\n\nPlease Help me out here!\nThanks!\n\n========================================\n\nCode:\n```text\n@SetMetaData('version', 'v2')\n@Get('firstfive')\n```\n\n```text\nimport { Get as _Get } from '@nestjs/common';\nexport function Get(path?: string) {\n  version = /*this.reflector.get('version') or something similar */\n  return applyDecorators(_Get(version+path));\n}\n```\n\n```text\n@SetMetaData('version', 'v2')\n```\n\n```text\n@Get()\n```\n\n```text\n/api/cats/v2/firstfive\n```\n\n```js\nexport function Get(path: string): MethodDecorator {\n  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const version = Reflect.getMetadata('version', target, propertyKey);\n    Reflect.defineMetadata(PATH_METADATA, version + path, descriptor.value);\n    Reflect.defineMetadata(METHOD_METADATA, RequestMethod.GET, descriptor.value);\n    return descriptor;\n  }\n}\n```\n\n```text\nthis.reflector\n```\n\n```text\n@Get()\n```\n\n```text\nReflect.getOwnMetadata()\n```\n\n```text\nPATH_METHOD\n```\n\n```text\nMETHOD_METADATA\n```\n\n```text\n@nestjs/common/constants\n```\n\n```text\nRequestMethod\n```\n\n```text\n@nestjs/common/enums\n```\n\n```text\n@Get()\n```\n\n```text\n@SetMetadata()\n```\n\n```text\n@SetVersion()\n```\n\n```text\n@Get()\n```\n\n========================================\n\nComments:\n- I have added @SetMetadata() on either side for debugging but in above @Get decorator `Reflect.getMetadata('version', target, propertyKey.value);` gives undefined. Any fixes?\n- I was able to get it working after a few changes. They are as follows: - Use `Reflect.metadata` instead of `SetMetadata` - Change Get return type to `MethodDecorator` - Use `propertyKey` instead of `propertyKey.value` All else seem to work. Thanks! Once you make these change I can accept the answer.\n- Is possible to use this method to get metadata from class?\n- Sure, you just need to know the metadata key","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":124,"estimatedTokens":651}}725{"id":"stack-55048217","source":"stackoverflow","questionId":55048217,"title":"How to iterate over @Query() object in Nest js","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: How to iterate over @Query() object in Nest js\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there any way, how to iterate over object which we got in controller by `@Query()` anotations?\n\nWe have dynamic count and name of query parameters in GET, so we need to take whole `@Query()` object and iterate over them to know what paramas we exactly have.\n\nBut if I want to iterate over that object I got error that object is not iterable.\n\nAny idea how to do that?\n\n========================================\n\nTop Answer:\nIn nest controller, use `@Query()` / `@Body()` / \n`@Headers()` decorator without argument \nwill return a key-value javascript object.\n\nfor example:\n\n```\n// request url: http://example.com/path-foo/path-bar?qf=1&qb=2\n\n @Post(':foo/:bar')\n async function baz(@Query() query,@Param() param) {\n const keys = Object.keys(query); // ['qf', 'qb']\n const vals = Object.values(query); // ['1', '2']\n const pairs = Object.entries(query); // [['qf','1'],['qb','2']]\n const params = Object.entries(param); // [['foo','path-foo'],['bar','path-bar']]\n // these are all iterate able array\n // so you can use any Array's built-in function\n // e.g. for / forEach / map / filter ...\n }\n```\n\nreference: \n\nObject\n\nObject.keys()\n\nObject.values()\n\nObject.entries()\n\n```\n// sample object\n const obj = {\n foo: 'this is foo',\n bar: 'this is bar',\n baz: 'this is baz',\n };\n\n Object.keys(obj);\n Object.values(obj);\n Object.entries(obj);\n\n /**\n * return iterable array:\n *\n * ['foo', 'bar', 'baz']\n *\n * ['this is foo', 'this is bar', 'this is baz']\n *\n * [\n * ['foo', 'this is foo']\n * ['bar', 'this is bar']\n * ['baz', 'this is baz']\n * ]\n */\n```\n\n========================================\n\nCode:\n```text\n@Query()\n```\n\n```text\n@Query()\n```\n\n```text\n@Get()\ngetHello(@Query() query) {\n  for (const queryKey of Object.keys(query)) {\n    console.log(`${queryKey}: ${query[queryKey]}`);\n  }\n}\n```\n\n```text\nObject.keys()\n```\n\n```text\n// request url: http://example.com/path-foo/path-bar?qf=1&qb=2\n\n    @Post(':foo/:bar')\n    async function baz(@Query() query,@Param() param) {\n        const keys = Object.keys(query); // ['qf', 'qb']\n        const vals = Object.values(query); // ['1', '2']\n        const pairs = Object.entries(query); // [['qf','1'],['qb','2']]\n        const params = Object.entries(param); // [['foo','path-foo'],['bar','path-bar']]\n        // these are all iterate able array\n        // so you can use any Array's built-in function\n        // e.g. for / forEach / map / filter ...\n    }\n```\n\n```text\n// sample object\n    const obj = {\n      foo: 'this is foo',\n      bar: 'this is bar',\n      baz: 'this is baz',\n    };\n\n    Object.keys(obj);\n    Object.values(obj);\n    Object.entries(obj);\n\n    /**\n     * return iterable array:\n     *\n     * ['foo', 'bar', 'baz']\n     *\n     * ['this is foo', 'this is bar', 'this is baz']\n     *\n     * [\n     *     ['foo', 'this is foo']\n     *     ['bar', 'this is bar']\n     *     ['baz', 'this is baz']\n     * ]\n     */\n```\n\n```text\n@Query()\n```\n\n```text\n@Body()\n```\n\n```text\n@Headers()\n```\n\n========================================\n\nComments:\n- You could also use `Object.entries` - `for (const [queryKey, queryValue] of Object.entries(query)) {}`.\n- Please provide an explanation with your answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":157,"estimatedTokens":822}}726{"id":"stack-67496417","source":"stackoverflow","questionId":67496417,"title":"How to do unit testing for guard in nest?","tags":["typescript","unit-testing","jestjs","nestjs"],"text":"Title: How to do unit testing for guard in nest?\nTags: typescript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'v done unit testing for controllers and services like this:\n\n```\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\ndescribe('CatsController', () => {\n let catsController: CatsController;\n let catsService: CatsService;\n\n beforeEach(() => {\n catsService = new CatsService();\n catsController = new CatsController(catsService);\n });\n\n describe('findAll', () => {\n it('should return an array of cats', async () => {\n const result = ['test'];\n jest.spyOn(catsService, 'findAll').mockImplementation(() => result);\n\n expect(await catsController.findAll()).toBe(result);\n });\n });\n});\n```\n\nbut I hava a global guard, this guard is independent of any controller or service, I do not know how to write the .spec file. PLZ\n\n========================================\n\nCode:\n```text\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\ndescribe('CatsController', () => {\n let catsController: CatsController;\n let catsService: CatsService;\n\n beforeEach(() => {\n   catsService = new CatsService();\n   catsController = new CatsController(catsService);\n });\n\n describe('findAll', () => {\n   it('should return an array of cats', async () => {\n     const result = ['test'];\n     jest.spyOn(catsService, 'findAll').mockImplementation(() => result);\n\n     expect(await catsController.findAll()).toBe(result);\n   });\n });\n});\n```\n\n```js\nimport { ExecutionContext, Injectable, CanActivate, UnauthorizedException } from '@nestjs/common';\nimport type { Request } from 'express';\n\n@Injectable()\nexport class AuthenticatedGuard implements CanActivate {\n  canActivate(context: ExecutionContext): true | never {\n    const req = context.switchToHttp().getRequest<Request>();\n    const isAuthenticated = req.isAuthenticated();\n    if (!isAuthenticated) {\n      throw new UnauthorizedException();\n    }\n    return isAuthenticated;\n  }\n}\n```\n\n```js\nimport { createMock } from '@golevelup/ts-jest';\nimport { ExecutionContext, UnauthorizedException } from '@nestjs/common';\n\nimport { AuthenticatedGuard } from '@/common/guards';\n\ndescribe('AuthenticatedGuard', () => {\n  let authenticatedGuard: AuthenticatedGuard;\n\n  beforeEach(() => {\n    authenticatedGuard = new AuthenticatedGuard();\n  });\n\n  it('should be defined', () => {\n    expect(authenticatedGuard).toBeDefined();\n  });\n\n  describe('canActivate', () => {\n    it('should return true when user is authenticated', () => {\n      const mockContext = createMock<ExecutionContext>();\n      mockContext.switchToHttp().getRequest.mockReturnValue({\n        // method attached to `req` instance by Passport lib\n        isAuthenticated: () => true,\n      });\n\n      const canActivate = authenticatedGuard.canActivate(mockContext);\n\n      expect(canActivate).toBe(true);\n    });\n\n    it('should thrown an Unauthorized (HTTP 401) error when user is not authenticated', () => {\n      const mockContext = createMock<ExecutionContext>();\n      mockContext.switchToHttp().getRequest.mockReturnValue({\n        // method attached to `req` instance by Passport lib\n        isAuthenticated: () => false,\n      });\n\n      const callCanActivate = () => authenticatedGuard.canActivate(mockContext);\n\n      expect(callCanActivate).toThrowError(UnauthorizedException);\n    });\n  });\n});\n```\n\n```text\nauthenticated.guard.spec.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.464Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":125,"estimatedTokens":864}}727{"id":"stack-57388095","source":"stackoverflow","questionId":57388095,"title":"Mongoose is undefined when using import syntax and not when using require","tags":["javascript","typescript","mongoose","ecmascript-6","nestjs"],"text":"Title: Mongoose is undefined when using import syntax and not when using require\nTags: javascript, typescript, mongoose, ecmascript-6, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo I have my module written as such\n\n```\nimport mongoose from 'mongoose';\n\nexport class MyModule {\n constructor(){\n //do\n }\n\n create(str){\n mongoose.connect(str); //cannot find property 'connect' of undefined\n }\n\n}\n```\n\nWhen using the import syntax, I get the `cannot find property 'connect' of undefined` error; it works as intended when using require.\n\nWeirdly enough, importing individual properties via import syntax works as intended,\n\n```\nimport { connect } from 'mongoose'\n```\n\nbut I need access to the entire ORM for some other reasons.\n\nWhy is it like so? Am I doing something wrong? To be fair, I don't have much experience in ES6 module system, TypeScript and Node.js so I might be missing something here.\n\nI'm running this on Node.js with NestJS, on a typescript file.\n\n========================================\n\nTop Answer:\nIn your `tsconfig.json` file, you can set\n\n```\n\"allowSyntheticDefaultImports\": true,\n\"esModuleInterop\": true\n```\n\nThis will allow you to use the syntax\n\n```\nimport mongoose from 'mongoose';\n```\n\n========================================\n\nCode:\n```text\nimport mongoose from 'mongoose';\n\nexport class MyModule {\n   constructor(){\n       //do\n   }\n\n   create(str){\n      mongoose.connect(str); //cannot find property 'connect' of undefined\n   }\n\n}\n```\n\n```text\nimport { connect } from 'mongoose'\n```\n\n```text\ncannot find property 'connect' of undefined\n```\n\n```text\nconst mongoose = require('mongoose');\n```\n\n```text\nimport * as mongoose from `mongoose`;\n```\n\n```text\nimport {connect} from `mongoose`;\n```\n\n```text\nimport * as mongoose from 'mongoose';\n```\n\n```text\nimport * as mongoose from 'mongoose';\n\nexport class MyModule {\n\n   constructor(){\n       //do\n   }\n\n   create(str){\n      mongoose.connect(str);\n   }\n}\n```\n\n```text\nimport mongoose from `mongoose`\n```\n\n```text\nimport { connect } from `mongoose`\n```\n\n```text\nimport * as mongoose from `mongoose`\n```\n\n```text\n@types/mongoose\n```\n\n```text\nmongoose\n```\n\n```text\n\"allowSyntheticDefaultImports\": true,\n\"esModuleInterop\": true\n```\n\n```text\nimport mongoose from 'mongoose';\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Has it installed `mongoose` in the `node_modules`? was there any error in npm installation?\n- To be clear, when you replace the first line of your code example with `const mongoose = require('mongoose');` it works? Are you executing this code with Node.js?\n- @nivendha Yea, I have it in my package.json already and it's also existing in the node_modules folder\n- @PatrickHund Yes and yes, and I'm using NestJS as a framework\n- Import syntax mandates the file extension so `import mongoose from 'mongoose.js'`. Also, you cannot mix and match import and require syntax. Commonjs (nodejs) modules **must** use `require` and cannot use `import`. ES6 modules **must** use `import` and cannot user `require`. There is a possibility of writing modules that export both but not all do (in fact most don't)\n- `import * as mongoose from 'mongoose';` try this\n- The reason for this is that the ES standards committee, being mostly browser developers, have defined the behavior of ES6 module loading that is not compatible with nodejs old module system\n- @slebetman `import mongoose from 'mongoose.js'` doesn't seem to work.\n- @BinitGhetiya `import * as mongoose from 'mongoose';` works amazingly! I think I also found the problem upon using this. It seems like Mongoose does not have a default export as reported by VS Code after installing `@types&#47;mongoose`, that being the case, doing `import mongoose` explicitly will not work.\n- Are you using babel js for ES6\n- @HamidRazaNoori Either that or is a Typescript compiler thing\n- @AbanaClara I have added answer please mark it correct Thanks :)\n- Note that this is a Typescript specific syntax and breaks the ES6 standards. For now it works but in the future when Typescript re-aligns with ES6 this may break (or it may not, depends on what Microsoft wants to do with the language they invented). See: stackoverflow.com/questions/29596714/&hellip;\n- Unfortunately this does not work as an acceptable answer to my problem (those useful for future readers). I have personally written an answer with a decent explanation and mention your handle instead.\n- @AbanaClara No worries :), hope you got your answer.\n- Wow this is definitely good info. I wish this answer came when this post was hot.","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":161,"estimatedTokens":1140}}728{"id":"stack-59607560","source":"stackoverflow","questionId":59607560,"title":"NestJs - TypeORM configuration works but not with ConfigService","tags":["nestjs","typeorm"],"text":"Title: NestJs - TypeORM configuration works but not with ConfigService\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to create a REST API with NestJs and TypeORM. In my **app.module.ts** I load the TypeORM module\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'api',\n entities: [`${__dirname}/**/*.entity.{ts,js}`],\n synchronize: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\nand it's working fine for now. I would like to load the configuration from an external .env file so from the docs\n\nhttps://docs.nestjs.com/techniques/database#async-configuration\n\nand from here\n\nNestJS Using ConfigService with TypeOrmModule\n\nI created a .env file in the root project directory with the following content\n\n```\nDATABASE_TYPE = postgres\nDATABASE_HOST = localhost\nDATABASE_PORT = 5432\nDATABASE_USERNAME = postgres\nDATABASE_PASSWORD = postgres\nDATABASE_NAME = api\nDATABASE_SYNCHRONIZE = true\n```\n\nNext I update my code to\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n type: configService.get('DATABASE_TYPE'),\n host: configService.get('DATABASE_HOST'),\n port: configService.get('DATABASE_PORT'),\n username: configService.get('DATABASE_USERNAME'),\n password: configService.get('DATABASE_PASSWORD'),\n database: configService.get('DATABASE_NAME'),\n entities: [`${__dirname}/**/*.entity.{ts,js}`],\n synchronize: configService.get('DATABASE_SYNCHRONIZE'),\n }),\n inject: [ConfigService],\n }),\n ],\n})\nexport class AppModule {}\n```\n\nUnfortunately I get this error on startup\n\n```\n[Nest] 28257 - 01/06/2020, 7:19:20 AM [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService at index [0] is available in the TypeOrmCoreModule context.\n\nPotential solutions:\n- If ConfigService is a provider, is it part of the current TypeOrmCoreModule?\n- If ConfigService is exported from a separate @Module, is that module imported within TypeOrmCoreModule?\n @Module({\n imports: [ /* the Module containing ConfigService */ ]\n })\n +1ms\n```\n\nWhen I log the configuration in my **main.ts** within the **bootstrap** function I get a correct configuration from the .env file.\n\nHow can I fix the error?\n\n========================================\n\nTop Answer:\ncode translation of @ Jay McDoniel explanation\n\ntypeorm.config.ts\n\n```\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport { LoggerOptions } from 'typeorm';\n\nexport default class TypeOrmConfig {\n static getOrmConfig(configService: ConfigService): TypeOrmModuleOptions {\n return {\n type: 'postgres',\n host: configService.get('DB_HOST') || 'localhost',\n port: configService.get('DB_PORT') || 5432,\n username: configService.get('DB_USERNAME'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize:configService.get('TYPEORM_SYNCHRONIZE') || false,\n logging: configService.get('TYPEORM_LOGGING') || false\n };\n }\n}\n\nexport const typeOrmConfigAsync: TypeOrmModuleAsyncOptions = {\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService): Promise => TypeOrmConfig.getOrmConfig(configService),\n inject: [ConfigService]\n};\n```\n\napp.module.ts\n\n```\nimport { LoginModule } from './login/login.module';\nimport * as redisStore from 'cache-manager-redis-store';\nimport { ServiceModule } from './service/service.module';\nimport { UserModule } from './user/user.module';\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { RedisCacheModule } from './redis-cache/redis-cache.module';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n UserModule,\n ServiceModule,\n LoginModule,\n RedisCacheModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nnestjsconfigmoduletypeorm\n\nReference video\nReference code\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'postgres',\n      host: 'localhost',\n      port: 5432,\n      username: 'postgres',\n      password: 'postgres',\n      database: 'api',\n      entities: [`${__dirname}/**/*.entity.{ts,js}`],\n      synchronize: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nDATABASE_TYPE = postgres\nDATABASE_HOST = localhost\nDATABASE_PORT = 5432\nDATABASE_USERNAME = postgres\nDATABASE_PASSWORD = postgres\nDATABASE_NAME = api\nDATABASE_SYNCHRONIZE = true\n```\n\n```text\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    TypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        type: configService.get<any>('DATABASE_TYPE'),\n        host: configService.get<string>('DATABASE_HOST'),\n        port: configService.get<number>('DATABASE_PORT'),\n        username: configService.get<string>('DATABASE_USERNAME'),\n        password: configService.get<string>('DATABASE_PASSWORD'),\n        database: configService.get<string>('DATABASE_NAME'),\n        entities: [`${__dirname}/**/*.entity.{ts,js}`],\n        synchronize: configService.get<boolean>('DATABASE_SYNCHRONIZE'),\n      }),\n      inject: [ConfigService],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n[Nest] 28257   - 01/06/2020, 7:19:20 AM   [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService at index [0] is available in the TypeOrmCoreModule context.\n\nPotential solutions:\n- If ConfigService is a provider, is it part of the current TypeOrmCoreModule?\n- If ConfigService is exported from a separate @Module, is that module imported within TypeOrmCoreModule?\n  @Module({\n    imports: [ /* the Module containing ConfigService */ ]\n  })\n +1ms\n```\n\n```text\nConfigModule\n```\n\n```text\nisGlobal: true\n```\n\n```text\nConfigModule.forRoot()\n```\n\n```text\nTypeormModule.forRootAsync()\n```\n\n```text\nMyConfigModule\n```\n\n```text\nimports\n```\n\n```text\nConfigModule\n```\n\n```text\nexports\n```\n\n```text\nCofnigModule\n```\n\n```text\nConfigModule.forRoot()\n```\n\n```text\nMyConfigModule\n```\n\n```text\nAppModule\n```\n\n```text\nimports: [ConfigModule]\n```\n\n```text\nimports: [MyConfigModule]\n```\n\n```text\nTypeormModule.forRootAsync()\n```\n\n```js\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport { LoggerOptions } from 'typeorm';\n\nexport default class TypeOrmConfig {\n  static getOrmConfig(configService: ConfigService): TypeOrmModuleOptions {\n    return {\n      type: 'postgres',\n      host: configService.get('DB_HOST') || 'localhost',\n      port: configService.get('DB_PORT') || 5432,\n      username: configService.get('DB_USERNAME'),\n      password: configService.get('DB_PASSWORD'),\n      database: configService.get('DB_NAME'),\n      entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n      synchronize:configService.get<boolean>('TYPEORM_SYNCHRONIZE') || false,\n      logging: configService.get<LoggerOptions>('TYPEORM_LOGGING') || false\n    };\n  }\n}\n\nexport const typeOrmConfigAsync: TypeOrmModuleAsyncOptions = {\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService): Promise<TypeOrmModuleOptions> => TypeOrmConfig.getOrmConfig(configService),\n  inject: [ConfigService]\n};\n```\n\n```js\nimport { LoginModule } from './login/login.module';\nimport * as redisStore from 'cache-manager-redis-store';\nimport { ServiceModule } from './service/service.module';\nimport { UserModule } from './user/user.module';\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { RedisCacheModule } from './redis-cache/redis-cache.module';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n    UserModule,\n    ServiceModule,\n    LoginModule,\n    RedisCacheModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- add your configService file please\n- @ Selmi sorry, I don't have a ConfigService file. I just have to inject it, as you can see in the docs docs.nestjs.com/techniques/configuration","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":345,"estimatedTokens":2234}}729{"id":"stack-77254434","source":"stackoverflow","questionId":77254434,"title":"Swagger UI not sending Authorization header despite configuration in NestJS","tags":["nestjs","swagger-ui","nestjs-config","nestjs-swagger"],"text":"Title: Swagger UI not sending Authorization header despite configuration in NestJS\nTags: nestjs, swagger-ui, nestjs-config, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI am facing an issue with Swagger UI in my NestJS application where it's not sending the Authorization header with the requests. I have set up JWT authentication and when I test the endpoints using cURL or Postman by including the Authorization header manually, everything works fine. However, when I use Swagger UI after logging in through the \"Authorize\" button on the top right corner of the Swagger UI page, the Authorization header is not included in the request, resulting in a 401 Unauthorized response from the server.\nhttps://i.sstatic.net/ealik.png\nhttps://i.sstatic.net/NcURW.png\n\nHere's how I have configured Swagger in my main.ts file:\n\n```\n// src/main.ts\n\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const config = new DocumentBuilder()\n .setTitle('My Project API')\n .setDescription('API description for My Project')\n .setVersion('1.0')\n .addTag('myproject')\n .addBearerAuth(\n {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n description: 'Input your JWT token',\n name: 'Authorization',\n in: 'header',\n },\n 'access-token',\n )\n .build();\n const document = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup('api', app, document, {\n swaggerOptions: {\n security: [{ 'access-token': [] }],\n },\n });\n await app.listen(3000);\n}\nbootstrap();\n```\n\nAnd here's my questions.controller.ts file:\n\n```\n// src/questions/questions.controller.ts\n\nimport {\n Controller,\n Post,\n Body,\n UseGuards,\n ValidationPipe,\n UsePipes,\n} from '@nestjs/common';\nimport { QuestionsService } from './questions.service';\nimport { CreateQuestionDto } from './dto/create-question.dto';\nimport { QuestionEntity } from './question.entity';\nimport { AuthGuard } from '@nestjs/passport';\nimport { BlockSymbolsPipe } from 'src/pipes/block-symbols.pipe';\nimport { ApiBearerAuth } from '@nestjs/swagger';\n\n@Controller('questions')\n@ApiBearerAuth()\n@UseGuards(AuthGuard('jwt'))\n@UsePipes(new BlockSymbolsPipe())\nexport class QuestionsController {\n constructor(private questionsService: QuestionsService) {}\n\n @Post()\n createQuestion(\n @Body(ValidationPipe) createQuestionDto: CreateQuestionDto,\n ): Promise {\n return this.questionsService.createQuestion(createQuestionDto);\n }\n}\n```\n\nI am currently using NestJS version 10, \"@nestjs/swagger\" version \"^7.1.12\", and \"swagger-ui-express\" version \"^5.0.0\" with Ubuntu.\n\nIn Postman, I have to include the token with each request manually. However, in Swagger UI, it seems to be a global setting. Once I log in using the \"Authorize\" button at the top right of the Swagger UI page, I don't see any option to include or not include the token for individual requests. It's supposed to send the token automatically with all requests requiring authorization, but it's not doing that in my case.\n\n========================================\n\nTop Answer:\nI had this issue in my **nestjs** project. If you are using **DocumentBuilder** from **@nestjs/swagger**, you can encounter this issue.\n\nThis is the code before I fixed the problem:\n\n```\nconst options = new DocumentBuilder()\n .setTitle('NestJS API')\n .setVersion('0.0.1')\n .setDescription('The NestJS API description')\n .addBearerAuth({\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n in: 'header',\n name: 'Authorization',\n description: 'Enter your Bearer token',\n })\n .build();\n```\n\nI added **.addSecurityRequirements('bearer')** property and the problem was fixed.\n\nCode example:\n\n```\nconst options = new DocumentBuilder()\n .setTitle('NestJS API')\n .setVersion('0.0.1')\n .setDescription('The NestJS API description')\n .addBearerAuth({\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n in: 'header',\n name: 'Authorization',\n description: 'Enter your Bearer token',\n })\n .addSecurityRequirements('bearer')\n .build();\n```\n\n========================================\n\nCode:\n```text\n// src/main.ts\n\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const config = new DocumentBuilder()\n    .setTitle('My Project API')\n    .setDescription('API description for My Project')\n    .setVersion('1.0')\n    .addTag('myproject')\n    .addBearerAuth(\n      {\n        type: 'http',\n        scheme: 'bearer',\n        bearerFormat: 'JWT',\n        description: 'Input your JWT token',\n        name: 'Authorization',\n        in: 'header',\n      },\n      'access-token',\n    )\n    .build();\n  const document = SwaggerModule.createDocument(app, config);\n  SwaggerModule.setup('api', app, document, {\n    swaggerOptions: {\n      security: [{ 'access-token': [] }],\n    },\n  });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n// src/questions/questions.controller.ts\n\nimport {\n  Controller,\n  Post,\n  Body,\n  UseGuards,\n  ValidationPipe,\n  UsePipes,\n} from '@nestjs/common';\nimport { QuestionsService } from './questions.service';\nimport { CreateQuestionDto } from './dto/create-question.dto';\nimport { QuestionEntity } from './question.entity';\nimport { AuthGuard } from '@nestjs/passport';\nimport { BlockSymbolsPipe } from 'src/pipes/block-symbols.pipe';\nimport { ApiBearerAuth } from '@nestjs/swagger';\n\n@Controller('questions')\n@ApiBearerAuth()\n@UseGuards(AuthGuard('jwt'))\n@UsePipes(new BlockSymbolsPipe())\nexport class QuestionsController {\n  constructor(private questionsService: QuestionsService) {}\n\n  @Post()\n  createQuestion(\n    @Body(ValidationPipe) createQuestionDto: CreateQuestionDto,\n  ): Promise<QuestionEntity> {\n    return this.questionsService.createQuestion(createQuestionDto);\n  }\n}\n```\n\n```text\n'access-token'\n```\n\n```text\n'bearer'\n```\n\n```text\naddBearerAuth\n```\n\n```text\nsecurity\n```\n\n```text\nBearer\n```\n\n```text\nBearer\n```\n\n```text\nconst options = new DocumentBuilder()\n  .setTitle('NestJS API')\n  .setVersion('0.0.1')\n  .setDescription('The NestJS API description')\n  .addBearerAuth({\n    type: 'http',\n    scheme: 'bearer',\n    bearerFormat: 'JWT',\n    in: 'header',\n    name: 'Authorization',\n    description: 'Enter your Bearer token',\n  })\n  .build();\n```\n\n```text\nconst options = new DocumentBuilder()\n  .setTitle('NestJS API')\n  .setVersion('0.0.1')\n  .setDescription('The NestJS API description')\n  .addBearerAuth({\n    type: 'http',\n    scheme: 'bearer',\n    bearerFormat: 'JWT',\n    in: 'header',\n    name: 'Authorization',\n    description: 'Enter your Bearer token',\n  })\n  .addSecurityRequirements('bearer')\n  .build();\n```\n\n========================================\n\nComments:\n- Yes, I tried that before and just tried it again just to be sure. Unfortunately the same result: { \"message\": \"Unauthorized\", \"statusCode\": 401 }\n- In the 'SwaggerOptions' you need to configure the security options as well, you need to tell it that you are using Bearer token as 'OpenApi' security.\n- What exactly is missing from my main.ts file that I provided? I configured everything there.\n- It works thanks.\n- Also to use the authorization in one particular endpoint you must to include the @ApiBearerAuth(). FYI\n- Please add some more explaination/detail to your answer, your current answer is a bit confusing to understand.","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":272,"estimatedTokens":1869}}730{"id":"stack-65769384","source":"stackoverflow","questionId":65769384,"title":"Models vs DTO in NestJS","tags":["nestjs","dto","data-transfer-objects"],"text":"Title: Models vs DTO in NestJS\nTags: nestjs, dto, data-transfer-objects\nSource: Stack Overflow\n\nQuestion:\nI am completely new to NestJS. I have seen that in NestJS, a model is created to specify the details of data, e.g. when creating a simple task manager, when we want to specify what a single task will look like, we specify it in the model (example below):\n\n```\nexport interface Task {\n id: string;\n title: string;\n description: string;\n status: TaskStatus;\n}\n\nexport enum TaskStatus {\n OPEN = 'OPEN',\n IN_PROGRESS = 'IN_PROGRESS',\n DONE = 'DONE',\n}\n```\n\nHowever, I later came across DTOs, where once again the shape of data is described. My understanding is that DTOs are used when transferring data, i.e. it describes the kind of data that you will post or get.\n\nMy question is that when I am already using DTOs to describe the shape of data, why use Models at all?\n\nAlso, I read that with DTOs we can have a single source of truth and in case we realise that the structure of data needs to change, we won't have to specify it separately in the controller and service files, however, this still means we will have to update the Model?\n\n========================================\n\nCode:\n```text\nexport interface Task {\n  id: string;\n  title: string;\n  description: string;\n  status: TaskStatus;\n}\n\nexport enum TaskStatus {\n  OPEN = 'OPEN',\n  IN_PROGRESS = 'IN_PROGRESS',\n  DONE = 'DONE',\n}\n```\n\n========================================\n\nComments:\n- You are correct. Never the less, I hate duplicating same data structure code, therefor I made a script that creates DTOs and schema from the same source.","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":50,"estimatedTokens":402}}731{"id":"stack-71997235","source":"stackoverflow","questionId":71997235,"title":"why nestjs swargger string array not working","tags":["swagger","nestjs"],"text":"Title: why nestjs swargger string array not working\nTags: swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nexport class AdministratorLoginDto {\n @ApiProperty()\n userName: number[];\n}\n```\n\nI set userName with number[], but i get the openapi is string[].\n\nI set userName with number[], but i get the openapi json is string[].\n\n```\n{\n \"AdministratorLoginDto\": {\n \"type\": \"object\",\n \"properties\": {\n \"userName\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\" // question: why this type is not number?\n }\n }\n },\n \"required\": [\n \"userName\"\n ]\n }\n}\n```\n\nThank you!\n\n========================================\n\nCode:\n```js\nexport class AdministratorLoginDto {\n  @ApiProperty()\n  userName: number[];\n}\n```\n\n```json\n{\n  \"AdministratorLoginDto\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"userName\": {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\" // question: why this type is not number?\n        }\n      }\n    },\n    \"required\": [\n      \"userName\"\n    ]\n  }\n}\n```\n\n```js\nexport class AdministratorLoginDto {\n  @ApiProperty({\n     type: Number,\n     isArray: true,\n  })\n  userName: number[];\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":75,"estimatedTokens":282}}732{"id":"stack-71183677","source":"stackoverflow","questionId":71183677,"title":"When I run nest.js, I get a Missing \"driver\" option error","tags":["graphql","nestjs","prisma"],"text":"Title: When I run nest.js, I get a Missing \"driver\" option error\nTags: graphql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using nest.js, prisma, and graphql.\n\nWhen I run the npm run start:dev command, I get an error.\n\nIf anyone knows how to solve this, please let me know.\n\nERROR [GraphQLModule] Missing\n\"driver\" option. In the latest version of \"@nestjs/graphql\" package\n(v10) a new required configuration property called \"driver\" has been\nintroduced. Check out the official documentation for more details on\nhow to migrate (https://docs.nestjs.com/graphql/migration-guide).\nExample:\n\nGraphQLModule.forRoot({\ndriver: ApolloDriver,\n})\n\n```\napp.module.ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\nimport { DonationsModule } from './donations/donations.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: false,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```\ngenerate-typings.ts\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n typePaths: ['./src/**/*.graphql'],\n path: join(process.cwd(), 'src/graphql.ts'),\n outputAs: 'class',\n watch: true,\n});\n```\n\nfix\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n driver: ApolloDriver,\n autoSchemaFile: true,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n========================================\n\nTop Answer:\nAlso don't forget to import\n\n```\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\n```\n\n========================================\n\nCode:\n```text\napp.module.ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\nimport { DonationsModule } from './donations/donations.module';\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      playground: false,\n      plugins: [ApolloServerPluginLandingPageLocalDefault()],\n      typePaths: ['./**/*.graphql'],\n    }),\n    DonationsModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\ngenerate-typings.ts\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n  typePaths: ['./src/**/*.graphql'],\n  path: join(process.cwd(), 'src/graphql.ts'),\n  outputAs: 'class',\n  watch: true,\n});\n```\n\n```text\n@Module({\n  imports: [\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n      autoSchemaFile: true,\n      plugins: [ApolloServerPluginLandingPageLocalDefault()],\n      typePaths: ['./**/*.graphql'],\n    }),\n    DonationsModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n```\n\n```text\n@Module({\n  imports: [\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n    }),\n  ],\n})\n```\n\n```text\nGraphQLModule\n```\n\n```text\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\n```\n\n========================================\n\nComments:\n- I rewrote it as above. (fix) The following error occurs at the location import { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';.\n- Cannot find module '@nestjs/apollo' or corresponding type declaration. ts(2307)\n- Have you installed @nestjs/apollo? @yuturo","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":168,"estimatedTokens":993}}733{"id":"stack-58359414","source":"stackoverflow","questionId":58359414,"title":"How e2e with guard nestjs","tags":["javascript","node.js","typescript","jestjs","nestjs"],"text":"Title: How e2e with guard nestjs\nTags: javascript, node.js, typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to e2e an endpoint called `/users` with nestjs but I got an error. I have doubts how to make the test pass with a guard.\n\nFirst error\n\n Nest can't resolve dependencies of the UserModel (?). Please make sure\n that the argument DatabaseConnection at index [0] is available in the\n MongooseModule context.\n\nSecond error\n\n expected 200 \"OK\", got 401 \"Unauthorized\"\n\nApp.module\n\n```\n@Module({\n imports: [\n MongooseModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n uri: configService.mongoUri,\n useNewUrlParser: true,\n }),\n inject: [ConfigService],\n }),\n GlobalModule,\n UsersModule,\n AuthModule,\n PetsModule,\n RestaurantsModule,\n ConfigModule,\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(TokenDataMiddleware)\n .forRoutes({ path: '*', method: RequestMethod.ALL });\n }\n}\n```\n\nUsersService\n\n```\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectModel('User') private readonly userModel: Model,\n private readonly utilsService: UtilsService,\n private readonly configService: ConfigService,\n ) { }\nasync getAllUsers(): Promise {\n const users = this.userModel.find().lean().exec();\n return users;\n }\n}\n```\n\nController\n\n```\n@Controller('users')\nexport class UsersController {\n constructor(private readonly usersService: UsersService, private readonly utilsService: UtilsService) { }\n @Get()\n @ApiBearerAuth()\n @UseGuards(JwtAuthGuard)\n async users() {\n const users = await this.usersService.getAllUsers();\n return users;\n }\n```\n\ne2e file\n\n```\ndescribe('UsersController (e2e)', () => {\n let app: INestApplication;\n beforeAll(async () => {\n const testAppModule: TestingModule = await Test.createTestingModule({\n imports: [AppModule, GlobalModule,\n UsersModule,\n AuthModule,\n PetsModule,\n RestaurantsModule,\n ConfigModule],\n providers: [],\n }).compile();\n\n app = testAppModule.createNestApplication();\n await app.init();\n });\n\n it('GET all users from API', async () => {\n // just mocked users;\n const users = getAllUsersMock.buildList(2);\n const response = await request(app.getHttpServer())\n .get('/users')\n .expect(200);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    MongooseModule.forRootAsync({\n      imports: [ConfigModule],\n      useFactory: async (configService: ConfigService) => ({\n        uri: configService.mongoUri,\n        useNewUrlParser: true,\n      }),\n      inject: [ConfigService],\n    }),\n    GlobalModule,\n    UsersModule,\n    AuthModule,\n    PetsModule,\n    RestaurantsModule,\n    ConfigModule,\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(TokenDataMiddleware)\n      .forRoutes({ path: '*', method: RequestMethod.ALL });\n  }\n}\n```\n\n```text\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectModel('User') private readonly userModel: Model<UserDocument>,\n    private readonly utilsService: UtilsService,\n    private readonly configService: ConfigService,\n  ) { }\nasync getAllUsers(): Promise<UserDocument[]> {\n    const users = this.userModel.find().lean().exec();\n    return users;\n  }\n}\n```\n\n```text\n@Controller('users')\nexport class UsersController {\n    constructor(private readonly usersService: UsersService, private readonly utilsService: UtilsService) { }\n    @Get()\n    @ApiBearerAuth()\n    @UseGuards(JwtAuthGuard)\n    async users() {\n        const users = await this.usersService.getAllUsers();\n        return users;\n    }\n```\n\n```text\ndescribe('UsersController (e2e)', () => {\n  let app: INestApplication;\n  beforeAll(async () => {\n    const testAppModule: TestingModule = await Test.createTestingModule({\n      imports: [AppModule, GlobalModule,\n        UsersModule,\n        AuthModule,\n        PetsModule,\n        RestaurantsModule,\n        ConfigModule],\n      providers: [],\n    }).compile();\n\n    app = testAppModule.createNestApplication();\n    await app.init();\n  });\n\n  it('GET all users from API', async () => {\n    // just mocked users;\n    const users = getAllUsersMock.buildList(2);\n    const response = await request(app.getHttpServer())\n      .get('/users')\n      .expect(200);\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n```\n\n```text\n/users\n```\n\n```text\nawait Test.createTestingModule({\n      imports: [AppModule],\n    }).compile()\n      .overrideProvider(HttpService)\n      .useValue(httpServiceMock);\n```\n\n```text\nconst loginResponse = await request(app.getHttpServer())\n  .post('/auth/login')\n  .send({ username: 'user', password: '123456' })\n  .expect(201);\n// store the jwt token for the next request\nconst { jwt } = loginResponse.body;\n\nawait request(app.getHttpServer())\n  .get('/users')\n  // use the jwt to authenticate your request\n  .set('Authorization', 'Bearer ' + jwt)\n  .expect(200)\n  .expect(res => expect(res.body.users[0])\n    .toMatchObject({ username: 'user' }));\n```\n\n```text\nAppModule\n```\n\n```text\noverrideProvider\n```\n\n```text\nforRoot\n```\n\n```text\nMongooseModule\n```\n\n```text\nAppModule\n```\n\n========================================\n\nComments:\n- Hi thanks for you answer, I update the question with your changes(it works) but keep my question about mock jwt token for pass JwtAuthGuard. thanks !\n- @anthonywillismu&#241;oz See my edit. The 401 error is as expected since your API is protected. It's actually good to test that unauthenticated requests cannot access your API. For testing the protected resource, you have to set the Authorization header, see the example. Also, you do not need to import all your modules. *Only* import the AppModule. It itself will import all other modules.\n- @Kim Kern What is httpServiceMock? I faced the same problem and cannot understand it\n- @MegaRoks Have a look at this thread on how to create a mock: stackoverflow.com/a/55366343/4694994","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":264,"estimatedTokens":1522}}734{"id":"stack-54250910","source":"stackoverflow","questionId":54250910,"title":"How can I change the property name of a serialized entity with toJSON?","tags":["node.js","typescript","serialization","nestjs","class-transformer"],"text":"Title: How can I change the property name of a serialized entity with toJSON?\nTags: node.js, typescript, serialization, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI want to serialize a property with a different name than it has in the entity.\n\n```\n@Entity()\nexport class MyEntity {\n // This should be serialized with name_column in JSON\n @Column()\n name: string\n}\n```\n\nWhen I call `classToPlain` I want the property `name` to be serialized to `name_column`:\n\n```\nclassToPlain(myEntity)\n// returns: {name: 'my name'}\n// should be: {name_column: 'my name'}\n```\n\n========================================\n\nTop Answer:\nPrevious answer only works if you're directly calling `classToPlain` on the model entity.\n\nIf you have a separate DTO class, you'll be calling `plainToClass` and then `classToPlain`, which will cause it to be either blank or keep the original name.\n\nAnother approach you could take to change the name is exposing a getter function instead:\n\n```\n@Expose({ toClassOnly: true })\nname: string;\n\n@Expose({ toPlainOnly: true })\nget column_name(): string {\n return this.name;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class MyEntity {\n  // This should be serialized with name_column in JSON\n  @Column()\n  name: string\n}\n```\n\n```text\nclassToPlain(myEntity)\n// returns: {name: 'my name'}\n// should be: {name_column: 'my name'}\n```\n\n```text\nclassToPlain\n```\n\n```text\nname\n```\n\n```text\nname_column\n```\n\n```text\n@Expose({ name: \"name_column\" })\nname: string;\n```\n\n```text\njson-typescript-mapper\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Expose\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\n@Expose({ toClassOnly: true })\nname: string;\n\n@Expose({ toPlainOnly: true })\nget column_name(): string {\n   return this.name;\n}\n```\n\n```text\nclassToPlain\n```\n\n```text\nplainToClass\n```\n\n```text\nclassToPlain\n```\n\n```text\n@Expose({ name: \"name_column\" })\nname: string;\n```\n\n```text\ninstanceToPlain(new MyEntity({\n  name: 'Harry'\n}));\n```\n\n```text\n@Expose()\n```\n\n```text\ninstanceToPlain\n```\n\n```text\nclassToPlain\n```\n\n```text\ninstanceToPlain\n```\n\n```text\n@Expose\n```\n\n```text\nname_column\n```\n\n========================================\n\nComments:\n- Please post your code as text, explain the error, see minimal reproducible example for more guidance.","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":159,"estimatedTokens":588}}735{"id":"stack-68851646","source":"stackoverflow","questionId":68851646,"title":"Vincit/Objection.js returns \"cannot read property '$relation' of undefined\" when using .withGraphFetched()","tags":["typescript","nestjs","knex.js","objection.js"],"text":"Title: Vincit/Objection.js returns \"cannot read property '$relation' of undefined\" when using .withGraphFetched()\nTags: typescript, nestjs, knex.js, objection.js\nSource: Stack Overflow\n\nQuestion:\nI am currently setting up Objection.js with NestJS and am having trouble using any sort of graph fetch or save methods. Relevant models:\n\n### resource-group.model.ts\n\n```\nimport { BaseModel } from './base.model';\nimport { Model } from 'objection';\nimport { ResourceGroupTypeModel } from './resource-group-type.model';\nimport { CollectionModel } from './collection.model';\nimport { AttributeModel } from './attribute.model';\nimport { ResourceModel } from './resource.model';\n\nexport class ResourceGroupModel extends BaseModel {\n static tableName = 'resource_group';\n\n typeId: number;\n title: string;\n groupId: string;\n collectionId?: number;\n defaultResourceId?: number;\n isDeleted: boolean;\n\n static relationMappings = {\n attributes: {\n modelClass: AttributeModel,\n relation: Model.ManyToManyRelation,\n join: {\n from: 'resource_group.id',\n through: {\n from: 'resourcegroup_attribute.resource_group_id',\n to: 'resourcegroup_attribute.attribute_id'\n },\n to: 'attribute.id',\n },\n },\n }\n}\n```\n\n### attribute.model.ts\n\n```\nimport { BaseModel } from './base.model';\nimport { Model } from 'objection';\n\nexport class AttributeModel extends BaseModel {\n static tableName = 'attribute'\n\n name: string;\n value: string;\n isSystem: boolean;\n\n static relationMappings = {\n resourceGroups: {\n modelClass: `${__dirname}/resource-group.model.js`,\n relation: Model.ManyToManyRelation,\n join: {\n from: 'attribute.id',\n through: {\n from: 'resourcegroup_attribute.attribute_id',\n to: 'resourcegroup_attribute.resource_group_id',\n },\n to: 'resource_group.id',\n },\n },\n }\n}\n```\n\n### resource-group.service.ts\n\n```\nimport { Injectable, Inject } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { EntityService } from '../abstract';\nimport { ResourceGroup } from '../entities';\nimport { Repository } from 'typeorm';\nimport { ModelClass } from 'objection';\nimport { ResourceGroupModel } from '../db/models/resource-group.model';\n\n@Injectable()\nexport class ResourceGroupService extends EntityService {\n constructor(\n @InjectRepository(ResourceGroup)\n protected readonly repository: Repository,\n @Inject(ResourceGroupModel)\n protected readonly model: ModelClass,\n ) {\n super(repository);\n }\n\n test() {\n return this.model\n .query()\n // .findById(25); // this line works fine\n\n .withGraphFetched(['attributes']) // these two lines do not\n .where({id: 25});\n }\n}\n```\n\nAnybody have any ideas of what's going on? I've looked through the source code but it appears to be an issue in my code, maybe in one of my models.\n\n========================================\n\nCode:\n```js\nimport { BaseModel } from './base.model';\nimport { Model } from 'objection';\nimport { ResourceGroupTypeModel } from './resource-group-type.model';\nimport { CollectionModel } from './collection.model';\nimport { AttributeModel } from './attribute.model';\nimport { ResourceModel } from './resource.model';\n\nexport class ResourceGroupModel extends BaseModel {\n  static tableName = 'resource_group';\n\n  typeId: number;\n  title: string;\n  groupId: string;\n  collectionId?: number;\n  defaultResourceId?: number;\n  isDeleted: boolean;\n\n  static relationMappings = {\n    attributes: {\n      modelClass: AttributeModel,\n      relation: Model.ManyToManyRelation,\n      join: {\n        from: 'resource_group.id',\n        through: {\n          from: 'resourcegroup_attribute.resource_group_id',\n          to: 'resourcegroup_attribute.attribute_id'\n        },\n        to: 'attribute.id',\n      },\n    },\n  }\n}\n```\n\n```js\nimport { BaseModel } from './base.model';\nimport { Model } from 'objection';\n\nexport class AttributeModel extends BaseModel {\n  static tableName = 'attribute'\n\n  name: string;\n  value: string;\n  isSystem: boolean;\n\n  static relationMappings = {\n    resourceGroups: {\n      modelClass: `${__dirname}/resource-group.model.js`,\n      relation: Model.ManyToManyRelation,\n      join: {\n        from: 'attribute.id',\n        through: {\n          from: 'resourcegroup_attribute.attribute_id',\n          to: 'resourcegroup_attribute.resource_group_id',\n        },\n        to: 'resource_group.id',\n      },\n    },\n  }\n}\n```\n\n```js\nimport { Injectable, Inject } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { EntityService } from '../abstract';\nimport { ResourceGroup } from '../entities';\nimport { Repository } from 'typeorm';\nimport { ModelClass } from 'objection';\nimport { ResourceGroupModel } from '../db/models/resource-group.model';\n\n@Injectable()\nexport class ResourceGroupService extends EntityService<ResourceGroup> {\n  constructor(\n    @InjectRepository(ResourceGroup)\n    protected readonly repository: Repository<ResourceGroup>,\n    @Inject(ResourceGroupModel)\n    protected readonly model: ModelClass<ResourceGroupModel>,\n  ) {\n    super(repository);\n  }\n\n  test() {\n    return this.model\n      .query()\n      // .findById(25);                 // this line works fine\n\n      .withGraphFetched(['attributes']) // these two lines do not\n      .where({id: 25});\n  }\n}\n```\n\n```js\nreturn this.model\n      .query()\n      .withGraphFetched(['attributes'])\n      .where({id: 25});\n```\n\n```js\nreturn this.model\n      .query()\n      .withGraphFetched('[attributes]') // square brackets are inside the string itself\n      .where({id: 25});\n```\n\n```text\nresource-group.service.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":223,"estimatedTokens":1372}}736{"id":"stack-72287494","source":"stackoverflow","questionId":72287494,"title":"Using enums from prisma in nestJS graphQL models","tags":["enums","graphql","nestjs","prisma"],"text":"Title: Using enums from prisma in nestJS graphQL models\nTags: enums, graphql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nMy object that is supposed to be returned:\n\n```\n@ObjectType()\nexport class User {\n @Field(() => String)\n email: string\n\n @Field(() => [Level])\n level: Level[]\n}\n```\n\nLevel is an enum generated by prisma, defined in schema.prisma:\n\n```\nenum Level {\n EASY\n MEDIUM\n HARD\n}\n```\n\nNow I'm trying to return this User object in my GraphQL Mutation:\n\n```\n@Mutation(() => User, { name: 'some-endpoint' })\n```\n\nWhen running this code, I'm getting the following error:\n\n```\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the \"Level\". Make sure your class is decorated with an appropriate decorator.\n```\n\nWhat am I doing wrong here? Can't enums from prisma be used as a field?\n\n========================================\n\nTop Answer:\nYou're probably missing the registration of the enum type in GraphQL:\n\n```\n// user.model.ts\nregisterEnumType(Level, { name: \"Level\" });\n```\n\n========================================\n\nCode:\n```js\n@ObjectType()\nexport class User {\n  @Field(() => String)\n  email: string\n\n  @Field(() => [Level])\n  level: Level[]\n}\n```\n\n```text\nenum Level {\n  EASY\n  MEDIUM\n  HARD\n}\n```\n\n```js\n@Mutation(() => User, { name: 'some-endpoint' })\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the \"Level\". Make sure your class is decorated with an appropriate decorator.\n```\n\n```text\nimport { Level } from '@prisma/client'\n\n@ObjectType()\nexport class User {\n  @Field(() => String)\n  email: string\n\n  @Field(() => Level)\n  level: Level\n}\n\nregisterEnumType(Level, {\n  name: 'Level',\n});\n```\n\n```text\nregisterEnumType\n```\n\n```text\n@Field(() => Enum)\n```\n\n```text\n// user.model.ts\nregisterEnumType(Level, { name: \"Level\" });\n```\n\n```text\nenum Role {\n  USER = 'USER',\n  ADMIN = 'ADMIN',\n}\n\nregisterEnumType(Role, {\n  name: 'Role',\n});\n\nexport class CreateUserInput {\n@IsEnum(Role)\n@Field(() => Role, { nullable: true })\nrole?: Role;\n}\n```\n\n```text\nasync create(createUserInput: CreateUserInput): Promise<User> {\n    return this.prisma.user.create({\n      data: {\n        ...createUserInput,\n      },\n    });\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":138,"estimatedTokens":555}}737{"id":"stack-72207189","source":"stackoverflow","questionId":72207189,"title":"NestJS Exception filter messes up error array if it comes from ValidationPipe","tags":["node.js","typescript","nestjs","httpexception"],"text":"Title: NestJS Exception filter messes up error array if it comes from ValidationPipe\nTags: node.js, typescript, nestjs, httpexception\nSource: Stack Overflow\n\nQuestion:\nSo I use the ValidationPipe to validate my DTOs in NestJS, like this:\n\n```\n// auth.dto.ts\nexport class AuthDto {\n @IsEmail()\n @IsNotEmpty()\n email: string;\n}\n```\n\nWithout the Exception filter the error message works as intended. I leave the email field empty and I receive an array of error messages:\n\n```\n// Response - Message array, but no wrapper\n{\n \"statusCode\": 400,\n \"message\": [\n \"email should not be empty\",\n \"email must be an email\"\n ],\n \"error\": \"Bad Request\"\n}\n```\n\nPerfect. Now I want to implement a wrapper for the error messages, so I create a new filter and add it to to bootstrap:\n\n```\n// main.ts\nasync function bootstrap() {\n // ...\n app.useGlobalFilters(new GlobalExceptionFilter());\n}\nbootstrap();\n```\n\n```\n// global-exception.filter.ts\nimport {\n ArgumentsHost,\n Catch,\n ExceptionFilter,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\nimport { Response } from 'express';\nimport { IncomingMessage } from 'http';\n\nexport const getStatusCode = (exception: T): number => {\n return exception instanceof HttpException\n ? exception.getStatus()\n : HttpStatus.INTERNAL_SERVER_ERROR;\n};\n\nexport const getErrorMessage = (exception: T): string => {\n return exception instanceof HttpException\n ? exception.message\n : String(exception);\n};\n\n@Catch()\nexport class GlobalExceptionFilter implements ExceptionFilter {\n catch(exception: T, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n const statusCode = getStatusCode(exception);\n const message = getErrorMessage(exception);\n\n response.status(statusCode).json({\n error: {\n timestamp: new Date().toISOString(),\n path: request.url,\n statusCode,\n message,\n },\n });\n }\n}\n```\n\nIt works great for most of my errors:\n\n```\n// Response - Good format (wrapped), single message expected\n{\n \"error\": {\n \"timestamp\": \"2022-05-11T19:54:59.093Z\",\n \"path\": \"/auth/signup\",\n \"statusCode\": 400,\n \"message\": \"Email already in use\"\n }\n}\n```\n\nBut when I get a ValidationError from the ValidationPipe it should give me an array or messages like before, but it gives this message instead:\n\n```\n// Response - Wrapper: check, single message instead of array\n{\n \"error\": {\n \"timestamp\": \"2022-05-11T19:59:17.282Z\",\n \"path\": \"/auth/signup\",\n \"statusCode\": 400,\n \"message\": \"Bad Request Exception\" // it should be \"message\": [\"not empty\", \"must be email\"]\n }\n}\n```\n\nThe exception object in my exception filter has a response field which contains the message array:\n\n```\n// HttpException object inside the filter class\n{\n response: {\n statusCode: 400,\n message: [ 'email should not be empty', 'email must be an email' ],\n error: 'Bad Request'\n },\n status: 400\n}\n```\n\nBut `exception.response.message` doesn't work, because the field is private and TypeScript throws an error:\n`Property 'response' is private and only accessible within class 'HttpException'.`\n\nDoes any of you know how could I reach the message array, so I could format my error response properly?\n\nEDIT: Sorry for the long post!\n\n========================================\n\nTop Answer:\nAs you are using `@Catch` decorator, you could get a `HttpException` or not, so we need to evaluate it.\n\nLet's create an interface to \"parse\" Nest.js built-in `HttpException` class response:\n\n```\nexport interface HttpExceptionResponse {\n statusCode: number;\n message: any;\n error: string;\n}\n```\n\nNow we can process it:\n\n```\nexport const getErrorMessage = (exception: T): any => {\n\n if(exception instanceof HttpException) {\n\n const errorResponse = exception.getResponse();\n const errorMessage = (errorResponse as HttpExceptionResponse).message || exception.message;\n\n return errorMessage;\n } else {\n return String(exception);\n }\n};\n```\n\n`exception.getResponse()` can be a string or an object, that's because we handle it as `message: any` of course.\n\n========================================\n\nCode:\n```js\n// auth.dto.ts\nexport class AuthDto {\n  @IsEmail()\n  @IsNotEmpty()\n  email: string;\n}\n```\n\n```json\n// Response - Message array, but no wrapper\n{\n  \"statusCode\": 400,\n  \"message\": [\n    \"email should not be empty\",\n    \"email must be an email\"\n  ],\n  \"error\": \"Bad Request\"\n}\n```\n\n```js\n// main.ts\nasync function bootstrap() {\n  // ...\n  app.useGlobalFilters(new GlobalExceptionFilter());\n}\nbootstrap();\n```\n\n```js\n// global-exception.filter.ts\nimport {\n  ArgumentsHost,\n  Catch,\n  ExceptionFilter,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\nimport { Response } from 'express';\nimport { IncomingMessage } from 'http';\n\nexport const getStatusCode = <T>(exception: T): number => {\n  return exception instanceof HttpException\n    ? exception.getStatus()\n    : HttpStatus.INTERNAL_SERVER_ERROR;\n};\n\nexport const getErrorMessage = <T>(exception: T): string => {\n  return exception instanceof HttpException\n    ? exception.message\n    : String(exception);\n};\n\n@Catch()\nexport class GlobalExceptionFilter<T> implements ExceptionFilter {\n  catch(exception: T, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<IncomingMessage>();\n    const statusCode = getStatusCode<T>(exception);\n    const message = getErrorMessage<T>(exception);\n\n    response.status(statusCode).json({\n      error: {\n        timestamp: new Date().toISOString(),\n        path: request.url,\n        statusCode,\n        message,\n      },\n    });\n  }\n}\n```\n\n```json\n// Response - Good format (wrapped), single message expected\n{\n  \"error\": {\n    \"timestamp\": \"2022-05-11T19:54:59.093Z\",\n    \"path\": \"/auth/signup\",\n    \"statusCode\": 400,\n    \"message\": \"Email already in use\"\n  }\n}\n```\n\n```json\n// Response - Wrapper: check, single message instead of array\n{\n  \"error\": {\n    \"timestamp\": \"2022-05-11T19:59:17.282Z\",\n    \"path\": \"/auth/signup\",\n    \"statusCode\": 400,\n    \"message\": \"Bad Request Exception\" // it should be \"message\": [\"not empty\", \"must be email\"]\n  }\n}\n```\n\n```js\n// HttpException object inside the filter class\n{\n  response: {\n    statusCode: 400,\n    message: [ 'email should not be empty', 'email must be an email' ],\n    error: 'Bad Request'\n  },\n  status: 400\n}\n```\n\n```text\nexception.response.message\n```\n\n```text\nProperty 'response' is private and only accessible within class 'HttpException'.\n```\n\n```text\nexport interface HttpExceptionResponse {\n    statusCode: number;\n    message: any;\n    error: string;\n}\n```\n\n```text\nexport const getErrorMessage = <T>(exception: T): any => {\n\n  if(exception instanceof HttpException) {\n\n    const errorResponse = exception.getResponse();\n    const errorMessage = (errorResponse as HttpExceptionResponse).message || exception.message;\n\n    return errorMessage;\n  } else {\n    return String(exception);\n  }\n};\n```\n\n```text\n@Catch\n```\n\n```text\nHttpException\n```\n\n```text\nHttpException\n```\n\n```text\nexception.getResponse()\n```\n\n```text\nmessage: any\n```\n\n========================================\n\nComments:\n- Try `exception[\"response\"][\"message\"]`. This bypasses the `private` restriction\n- Great tip! It works!\n- @TobiasS. : This works fine with the solution you provided but any idea how we can make it work in case of using I18nValidationPipe() since I need to provide internationalization? I am using something like this : @UsePipes(new I18nValidationPipe({ whitelist: true, transform: true })) And doing this in the GlobalExceptionFilter class we are getting only exception. response","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":340,"estimatedTokens":1888}}738{"id":"stack-69581669","source":"stackoverflow","questionId":69581669,"title":"TypeORM in NestJS can not connect to MongoDB","tags":["mongodb","express","nestjs","typeorm"],"text":"Title: TypeORM in NestJS can not connect to MongoDB\nTags: mongodb, express, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI install the mongodb software on my own Ubuntu server and I get the mongo string just like this `mongodb://xxx:pass@42.212.159.109:27017`,when I type this string in my local terminal and use `mongosh mongodb://xxx:pass@42.212.159.109:27017`, it works fine and the connection is success. But when I use this mongodb string in my nestjs project, when I run `npm run start`, the terminal output `MongoServerError: Authentication failed.`\n\n### app.module.ts\n\n```\nTypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => {\n const username = configService.get('MONGO_USER');\n const password = configService.get('MONGO_PASS');\n const database = configService.get('MONGO_DATABASE');\n const host = configService.get('MONGO_HOST');\n const port = configService.get('MONGO_PORT');\n return {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n },\n```\n\nThe mongodb version is 4.1.3, TypeOrm version is 0.2.38.\nDoes anyone know what is the problem and how to solve it? Thank u.\n\n========================================\n\nTop Answer:\nMaybe you should try to use the Database URL connection string instead of host, port, username, password, ...\n\nSo instead of using this\n\n```\nreturn {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n entities: ...\n ...\n}\n```\n\nyou should use this\n\n```\nreturn {\n type: \"mongodb\",\n url: configService.get(\"DATABASE_URL\"),\n entities: ...\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: async (configService: ConfigService) => {\n        const username = configService.get('MONGO_USER');\n        const password = configService.get('MONGO_PASS');\n        const database = configService.get('MONGO_DATABASE');\n        const host = configService.get('MONGO_HOST');\n        const port = configService.get('MONGO_PORT');\n        return {\n          type: 'mongodb',\n          host,\n          port,\n          username,\n          password,\n          database,\n          entities: [__dirname + '/**/*.entity{.ts,.js}'],\n          synchronize: true,\n        };\n      },\n```\n\n```text\nmongodb://xxx:pass@42.212.159.109:27017\n```\n\n```text\nmongosh mongodb://xxx:pass@42.212.159.109:27017\n```\n\n```text\nnpm run start\n```\n\n```text\nMongoServerError: Authentication failed.\n```\n\n```text\nreturn {\n      type: 'mongodb',\n      host,\n      port,\n      username,\n      password,\n      database,\n      authSource: 'admin',\n      entities: [__dirname + '/**/*.entity{.ts,.js}'],\n      synchronize: true,\n    };\n```\n\n```text\nreturn {\n    type: 'mongodb',\n    host,\n    port,\n    username,\n    password,\n    database,\n    entities: ...\n    ...\n}\n```\n\n```text\nreturn {\n    type: \"mongodb\",\n    url: configService.get(\"DATABASE_URL\"),\n    entities: ...\n    ...\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.465Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":143,"estimatedTokens":772}}739{"id":"stack-60525544","source":"stackoverflow","questionId":60525544,"title":"How to serialize a nest js response with class-transformer while getting data with Typegoose?","tags":["serialization","response","nestjs","class-transformer","typegoose"],"text":"Title: How to serialize a nest js response with class-transformer while getting data with Typegoose?\nTags: serialization, response, nestjs, class-transformer, typegoose\nSource: Stack Overflow\n\nQuestion:\nI have been trying to work through the NestJs example for the Serialization Section for Mongodb using Typegoose using the class-transformer library. The example given at https://docs.nestjs.com/techniques/serialization only shows how to use serialization in TypeORM. I followed the same process for Typegoose. Here is what I have tried so far.\n\n```\n// cat.domain.ts\n\nimport { prop } from '@typegoose/typegoose';\n\nexport class Cat {\n @prop()\n name: string;\n\n @prop()\n age: number;\n\n @prop()\n breed: string;\n}\n\n// cats.service.ts\n\n@Injectable()\nexport class CatsService {\n constructor(\n @InjectModel(Cat) private readonly catModel: ReturnModelType,\n ) {}\n\n findAll(): Observable {\n return from(this.catModel.find().exec());\n }\n\n findOne(id: string): Observable {\n return from(this.catModel.findById(id).exec());\n }\n ...\n}\n\n// cat.response.ts\n\nimport { ObjectId } from 'mongodb';\nimport { Exclude, Transform } from 'class-transformer';\n\nexport class CatResponse {\n @Transform(value => value.toString(), { toPlainOnly: true })\n _id?: ObjectId;\n\n name: string;\n\n age: number;\n\n @Exclude()\n breed: string;\n\n constructor(partial: Partial) {\n Object.assign(this, partial);\n }\n}\n\n// cats.controller.ts\n\n@Controller('cats')\n@UseInterceptors(ClassSerializerInterceptor)\nexport class CatsController {\n constructor(private readonly catsService: CatsService) {}\n\n @Get()\n findAll(): Observable {\n return this.catsService.findAll();\n }\n\n @Get(':id')\n findOne(@Param() params: FindOneParamsDto): Observable {\n return this.catsService.findOne(params.id);\n }\n ...\n}\n```\n\nI tried running the API call on Get() with id but instead of the `breed` being excluded from the response I have been getting the following response.\n\n```\n{\n \"$__\": {\n \"strictMode\": true,\n \"selected\": {},\n \"getters\": {},\n \"_id\": {\n \"_bsontype\": \"ObjectID\",\n \"id\": {\n \"type\": \"Buffer\",\n \"data\": [\n 94,\n 93,\n 76,\n 66,\n 116,\n 204,\n 248,\n 112,\n 147,\n 216,\n 167,\n 205\n ]\n }\n },\n \"wasPopulated\": false,\n \"activePaths\": {\n \"paths\": {\n \"_id\": \"init\",\n \"name\": \"init\",\n \"age\": \"init\",\n \"breed\": \"init\",\n \"__v\": \"init\"\n },\n \"states\": {\n \"ignore\": {},\n \"default\": {},\n \"init\": {\n \"_id\": true,\n \"name\": true,\n \"age\": true,\n \"breed\": true,\n \"__v\": true\n },\n \"modify\": {},\n \"require\": {}\n },\n \"stateNames\": [\n \"require\",\n \"modify\",\n \"init\",\n \"default\",\n \"ignore\"\n ]\n },\n \"pathsToScopes\": {},\n \"cachedRequired\": {},\n \"$setCalled\": [],\n \"emitter\": {\n \"_events\": {},\n \"_eventsCount\": 0,\n \"_maxListeners\": 0\n },\n \"$options\": {\n \"skipId\": true,\n \"isNew\": false,\n \"willInit\": true\n }\n },\n \"isNew\": false,\n \"_doc\": {\n \"_id\": {\n \"_bsontype\": \"ObjectID\",\n \"id\": {\n \"type\": \"Buffer\",\n \"data\": [\n 94,\n 93,\n 76,\n 66,\n 116,\n 204,\n 248,\n 112,\n 147,\n 216,\n 167,\n 205\n ]\n }\n },\n \"name\": \"Sylver\",\n \"age\": 14,\n \"breed\": \"Persian Cat\",\n \"__v\": 0\n },\n \"$locals\": {},\n \"$op\": null,\n \"$init\": true\n}\n```\n\nCan anyone help me with how to serialize response properly?\n\n========================================\n\nTop Answer:\n### For people trying to nestjs documentation & using mongoose but `ClassSerializerInterceptor` not working.\n\nPosting a solution for using class-transformer withe mongoose below which can be helpful for others, it uses custom interceptor that you can see in the nest documentation. https://docs.nestjs.com/interceptors\n\n```\nHow the folder structure would be: \n \nsrc\nโ””โ”€โ”€ cats\n โ”œโ”€โ”€ dto\n โ”‚ โ””โ”€โ”€ cats-response.dto.ts\n โ”œโ”€โ”€ interceptor\n โ”‚ โ””โ”€โ”€ cats.interceptor.ts\n โ”œโ”€โ”€ schemas\n โ”‚ โ””โ”€โ”€ cat.schema.ts\n โ”œโ”€โ”€ cats.controller.ts\n โ””โ”€โ”€ cats.service.ts\n```\n\nWe will create a dto for cat response called `CatsResponseDto` in `cats-response.dto.ts` & in it exclude the `breed` property from response using Exclude() decorator. By using Dto for response we will create the instance of `CatsResponseDto`\n\nWe will create custom interceptor for cats response called `CatsInterceptor` in `cats.interceptor.ts`. You can generate it using nest cli, the command is `nest g interceptor cats`\n\n**cats-response.dto.ts**\n\nCreate `CatsResponseDto` to be used in our custom interceptor.\n\n```\nimport { Expose, Exclude } from 'class-transformer'\n\nexport class CatsResponseDto {\n\n @Expose()\n name: string;\n\n @Expose()\n age: number;\n\n // Exclude decorator to exclude it from our response.\n @Exclude()\n breed: string;\n\n}\n```\n\n**cats.interceptor.ts**\n\nCreate out custom `CatsInterceptor`\n\nNote: plainToClass has been deprecated & now called plainToInstance, I only got to know when used it on my Ide and it prompted. The official documentation yet not updated. https://github.com/typestack/class-transformer#plaintoclass\n\nThe changelog does mention about it.\n\nhttps://github.com/typestack/class-transformer/blob/develop/CHANGELOG.md#041-breaking-change---2021-11-20\n\n```\nimport { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { plainToInstance } from 'class-transformer'\nimport { map, Observable } from 'rxjs';\nimport { CatsResponseDto } from '../dto/cats-response.dto'\n\n@Injectable()\nexport class CatsInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, handler: CallHandler): Observable {\n \n return handler.handle().pipe(\n map((data: any) => {\n \n // run something before the response is sent out.\n // Please note that plainToClass is deprecated & is now called plainToInstance\n \n return plainToInstance(CatsResponseDto, data, {\n \n // By using excludeExtraneousValues we are ensuring that only properties decorated with Expose() decorator are included in response.\n \n excludeExtraneousValues: true,\n\n })\n })\n );\n\n }\n}\n```\n\nOur cat schema must have been defined like below (for reference) in `cat.schema.ts` or similar as per mongoose documentation.\n\n**cat.schema.ts**\n\n```\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\n\nexport type CatDocument = Cat & Document;\n\n@Schema({ timestamps: true })\nexport class Cat {\n\n // no Id defined here as its automatically added by mongoose unless we explicitly provide option to turn it OFF in schema options. \n \n @Prop({ required: true })\n name: string;\n\n @Prop({ required: true })\n age: number;\n\n @Prop({ required: true })\n breed: string;\n\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\nNow bind our custom interceptor `CatsInterceptor` in `cats.controller.ts`\n\n**cats.controller.ts**\n\n```\nimport { Cat } from './schemas/cat.schema';\nimport { CatsInterceptor } from './interceptor/cats.interceptor';\nimport { CatsService } from './cats.service.ts'\n\n@Controller('cats')\nexport class CatsController {\n constructor(private readonly catsService: CatsService) {}\n\n @Get()\n findAll(): Promise {\n return this.catsService.findAll();\n }\n\n @UseInterceptors(CatsInterceptor)\n @Get(':id')\n findOne(@Param() params: FindOneParamsDto): Promise {\n return this.catsService.findOne(params.id);\n }\n ...\n}\n```\n\n**RESULT**: when calling /cats/{id} response would exclude breed.\n\nrelated issue:\nclass serialization not working in nestjs\n\n========================================\n\nCode:\n```text\n// cat.domain.ts\n\nimport { prop } from '@typegoose/typegoose';\n\nexport class Cat {\n  @prop()\n  name: string;\n\n  @prop()\n  age: number;\n\n  @prop()\n  breed: string;\n}\n\n\n// cats.service.ts\n\n@Injectable()\nexport class CatsService {\n  constructor(\n    @InjectModel(Cat) private readonly catModel: ReturnModelType<typeof Cat>,\n  ) {}\n\n  findAll(): Observable<Cat[]> {\n    return from(this.catModel.find().exec());\n  }\n\n  findOne(id: string): Observable<Cat> {\n    return from(this.catModel.findById(id).exec());\n  }\n  ...\n}\n\n// cat.response.ts\n\nimport { ObjectId } from 'mongodb';\nimport { Exclude, Transform } from 'class-transformer';\n\nexport class CatResponse {\n  @Transform(value => value.toString(), { toPlainOnly: true })\n  _id?: ObjectId;\n\n  name: string;\n\n  age: number;\n\n  @Exclude()\n  breed: string;\n\n  constructor(partial: Partial<CatResponse>) {\n    Object.assign(this, partial);\n  }\n}\n\n// cats.controller.ts\n\n@Controller('cats')\n@UseInterceptors(ClassSerializerInterceptor)\nexport class CatsController {\n  constructor(private readonly catsService: CatsService) {}\n\n  @Get()\n  findAll(): Observable<CatResponse[]> {\n    return this.catsService.findAll();\n  }\n\n  @Get(':id')\n  findOne(@Param() params: FindOneParamsDto): Observable<CatResponse> {\n    return this.catsService.findOne(params.id);\n  }\n  ...\n}\n```\n\n```text\n{\n    \"$__\": {\n        \"strictMode\": true,\n        \"selected\": {},\n        \"getters\": {},\n        \"_id\": {\n            \"_bsontype\": \"ObjectID\",\n            \"id\": {\n                \"type\": \"Buffer\",\n                \"data\": [\n                    94,\n                    93,\n                    76,\n                    66,\n                    116,\n                    204,\n                    248,\n                    112,\n                    147,\n                    216,\n                    167,\n                    205\n                ]\n            }\n        },\n        \"wasPopulated\": false,\n        \"activePaths\": {\n            \"paths\": {\n                \"_id\": \"init\",\n                \"name\": \"init\",\n                \"age\": \"init\",\n                \"breed\": \"init\",\n                \"__v\": \"init\"\n            },\n            \"states\": {\n                \"ignore\": {},\n                \"default\": {},\n                \"init\": {\n                    \"_id\": true,\n                    \"name\": true,\n                    \"age\": true,\n                    \"breed\": true,\n                    \"__v\": true\n                },\n                \"modify\": {},\n                \"require\": {}\n            },\n            \"stateNames\": [\n                \"require\",\n                \"modify\",\n                \"init\",\n                \"default\",\n                \"ignore\"\n            ]\n        },\n        \"pathsToScopes\": {},\n        \"cachedRequired\": {},\n        \"$setCalled\": [],\n        \"emitter\": {\n            \"_events\": {},\n            \"_eventsCount\": 0,\n            \"_maxListeners\": 0\n        },\n        \"$options\": {\n            \"skipId\": true,\n            \"isNew\": false,\n            \"willInit\": true\n        }\n    },\n    \"isNew\": false,\n    \"_doc\": {\n        \"_id\": {\n            \"_bsontype\": \"ObjectID\",\n            \"id\": {\n                \"type\": \"Buffer\",\n                \"data\": [\n                    94,\n                    93,\n                    76,\n                    66,\n                    116,\n                    204,\n                    248,\n                    112,\n                    147,\n                    216,\n                    167,\n                    205\n                ]\n            }\n        },\n        \"name\": \"Sylver\",\n        \"age\": 14,\n        \"breed\": \"Persian Cat\",\n        \"__v\": 0\n    },\n    \"$locals\": {},\n    \"$op\": null,\n    \"$init\": true\n}\n```\n\n```text\nbreed\n```\n\n```js\nimport { plainToInstance } from \"class-transformer\";\n\n    @Controller('cats')\n    @UseInterceptors(ClassSerializerInterceptor)\n    export class CatsController {\n      constructor(private readonly catsService: CatsService) {}\n    \n      @Get()\n      findAll(): Observable<CatResponse[]> {\n        const cats = this.catsService.findAll();\n        // transforming the Model to CatResponse class...\n        const catResponses = cats.map(cat => classToPlain(new CatResponse(cat.toJSON())))\n        return catResponses;\n      }\n    \n      @Get(':id')\n      findOne(@Param() params: FindOneParamsDto): Observable<CatResponse> {\n        const cat = this.catsService.findOne(params.id);\n        const catResponse = plainToInstance(new CatResponse(cat.toJSON()));\n        return \n      }\n      ...\n    }\n```\n\n```text\ncats.controller.ts\n```\n\n```text\nHow the folder structure would be:  \n  \nsrc\nโ””โ”€โ”€ cats\n    โ”œโ”€โ”€ dto\n    โ”‚   โ””โ”€โ”€ cats-response.dto.ts\n    โ”œโ”€โ”€ interceptor\n    โ”‚   โ””โ”€โ”€ cats.interceptor.ts\n    โ”œโ”€โ”€ schemas\n    โ”‚   โ””โ”€โ”€ cat.schema.ts\n    โ”œโ”€โ”€ cats.controller.ts\n    โ””โ”€โ”€ cats.service.ts\n```\n\n```js\nimport { Expose, Exclude } from 'class-transformer'\n\nexport class CatsResponseDto {\n\n  @Expose()\n  name: string;\n\n  @Expose()\n  age: number;\n\n  // Exclude decorator to exclude it from our response.\n  @Exclude()\n  breed: string;\n\n}\n```\n\n```js\nimport { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { plainToInstance } from 'class-transformer'\nimport { map, Observable } from 'rxjs';\nimport { CatsResponseDto } from '../dto/cats-response.dto'\n\n@Injectable()\nexport class CatsInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, handler: CallHandler): Observable<any> {\n    \n    return handler.handle().pipe(\n      map((data: any) => {\n        \n        // run something before the response is sent out.\n        // Please note that plainToClass is deprecated & is now called plainToInstance\n        \n        return plainToInstance(CatsResponseDto, data, {\n        \n        // By using excludeExtraneousValues we are ensuring that only properties decorated with Expose() decorator are included in response.\n          \n        excludeExtraneousValues: true,\n\n        })\n      })\n    );\n\n  }\n}\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\n\nexport type CatDocument = Cat & Document;\n\n@Schema({ timestamps: true })\nexport class Cat {\n\n  // no Id defined here as its automatically added by mongoose unless we explicitly provide option to turn it OFF in schema options.  \n    \n  @Prop({ required: true })\n  name: string;\n\n  @Prop({ required: true })\n  age: number;\n\n  @Prop({ required: true })\n  breed: string;\n\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\n```js\nimport { Cat } from './schemas/cat.schema';\nimport { CatsInterceptor } from './interceptor/cats.interceptor';\nimport { CatsService } from './cats.service.ts'\n\n@Controller('cats')\nexport class CatsController {\n  constructor(private readonly catsService: CatsService) {}\n\n  @Get()\n  findAll(): Promise<Cat[]> {\n    return this.catsService.findAll();\n  }\n\n  @UseInterceptors(CatsInterceptor)\n  @Get(':id')\n  findOne(@Param() params: FindOneParamsDto): Promise<Cat> {\n    return this.catsService.findOne(params.id);\n  }\n  ...\n}\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nCatsResponseDto\n```\n\n```text\ncats-response.dto.ts\n```\n\n```text\nbreed\n```\n\n```text\nCatsResponseDto\n```\n\n```text\nCatsInterceptor\n```\n\n```text\ncats.interceptor.ts\n```\n\n```text\nnest g interceptor cats\n```\n\n```text\nCatsResponseDto\n```\n\n```text\nCatsInterceptor\n```\n\n```text\ncat.schema.ts\n```\n\n```text\nCatsInterceptor\n```\n\n```text\ncats.controller.ts\n```\n\n========================================\n\nComments:\n- how would u suggest I exclude items from my response? I was thinking of doing something similar to that like create a Transform Interceptor along with a custom decorator and check for the decorator in the interceptor but that seems like a lot of work and I m not that experienced yet. Is there an easier way to do it?\n- when it is some value like \"password\" you can set \"select: false\" as an `@prop` option and it is by default not included in any query without explicitly selecting it again, otherwise transform it to an POJO (either by `.toJSON` or `.lean`) and filtering out anything that you dont want (blacklist / whitelist)\n- How to serialize a nest js response with class-transformer while getting data with MONGOOSE?\n- link in the answer says \"404 Not found\".\n- @RollerCosta, i have updated the links\n- what about _id ?\n- id is the id of the cat that you are trying to get.","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":727,"estimatedTokens":3886}}740{"id":"stack-62351708","source":"stackoverflow","questionId":62351708,"title":"Nestjs how to clear ( reset ) all cache","tags":["javascript","typescript","caching","cron","nestjs"],"text":"Title: Nestjs how to clear ( reset ) all cache\nTags: javascript, typescript, caching, cron, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm building an API and the data get updated every day at 3 am and need to clear all cached endpoints whatever is! \n\nI'm using the `CacheModule` and the decorator `@UserInterceptor(CacheInterceptor)` to cache whatever I need in the controller. \n\nthere a `Cron` function that runs every day at 3 am to update the content, I need to know what the code should put in that method to clear all cache.\n\n========================================\n\nTop Answer:\nAccording to the official NestJs docs (July 2022), they offer a .reset() method to \"clear the entire cache\". This examples assumes you're using the naming convention in their docs, where cacheManager is the locally scoped & injected CACHE_MANAGER from @nestjs/common and \"Cache\" from cache-manager package.\n\n```\n// inside the class constructor\nconstructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}\n// and then inside a class method\nawait this.cacheManager.reset();\n```\n\nReference: https://docs.nestjs.com/techniques/caching\n\n========================================\n\nCode:\n```text\nCacheModule\n```\n\n```text\n@UserInterceptor(CacheInterceptor)\n```\n\n```text\nCron\n```\n\n```text\nconstructor(@Inject(CACHE_MANAGER) protected readonly cacheManager) {}\n```\n\n```text\nconst keys = await this.cacheManager.keys()\nawait this.cacheManager.del(keys)\n```\n\n```text\n// inside the class constructor\nconstructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}\n// and then inside a class method\nawait this.cacheManager.reset();\n```\n\n========================================\n\nComments:\n- `reset()` has been removed in the latest version of cache-manager however you can use `clear()` instead npmjs.com/package/cache-manager#clear","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":60,"estimatedTokens":453}}741{"id":"stack-50590068","source":"stackoverflow","questionId":50590068,"title":"Does NestJS comes with security practices already?","tags":["node.js","security","nestjs","typeorm","nodejs-server"],"text":"Title: Does NestJS comes with security practices already?\nTags: node.js, security, nestjs, typeorm, nodejs-server\nSource: Stack Overflow\n\nQuestion:\nDoes NestJS handles some security practices out of the box?. If not, what recommendations can you to secure a NestJS application besides helmet? I see in the NestJS middleware docs an example using the helmet dependency.\n\nWhen using TypeORM, SQL injection is covered?\n\n========================================\n\nTop Answer:\n**NestJS** follows mostly the same security rules as the **Node.js** server and **Express**.\n\n**NestJS has an dedicated security section** in its documentation that addresses these topics:\n\n- Authentication\n\n- Authorization\n\n- Encryption and Hashing\n\n- Helmet\n\n- CORS\n\n- CSRF Protection\n\n- Rate limiting\n\n**When it comes to protecting against SQL Injection, I think sanitize input and parameterized statements are the most important.**\n\nOverall, however, it is most important that **programmers do not cause security holes through code and architecture, but with good security practices and as administrators to expose to production hardened services with the least privileges**. It is important to educate ourselves in this area all the time.","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":33,"estimatedTokens":304}}742{"id":"stack-60704316","source":"stackoverflow","questionId":60704316,"title":"Run NestJS script from command line","tags":["typescript","command","nestjs"],"text":"Title: Run NestJS script from command line\nTags: typescript, command, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to be able to run a script that parses an XML file using NestJS framework for a proof-of-concept, but I'm not sure how to do it.\n\nI created a `scripts` directory inside `/src` and placed my `script.ts` with an initial console.log there. How can I run commands within that file? Should I change the script.ts file to plain javascript instead of typescript and then run node myscript.ts? What is the correct approach for this manner?\n\n========================================\n\nTop Answer:\nYou can add a `bin` property to your `package.json` with the name of the command you want to give, and the js file associated with the command. From there, if you were to run \"commandName\", you *should* get the command to properly run (after building from Typescript to JavaScript of course). As an example, you can see this. The original command file is written in Typescript, given a shebang of `#!/usr/bin/env node` to allow for `node` to be used as the script runner, and then compiled into JavaScript with the rest of the library. From there, I just run `ogma ` and let the script take care of the rest. \n\nFor you, adding in Nest will be a step on top of this, but still pretty easy to manage as you'll have the entry file use the `NestFactory` to create the application and then pass the expected data into some sort of handler as described briefly here. Feel free to comment if you have any other questions.\n\n========================================\n\nCode:\n```text\nscripts\n```\n\n```text\n/src\n```\n\n```text\nscript.ts\n```\n\n```text\nnpx ts-node my-file.ts\n```\n\n```text\nts-node\n```\n\n```text\nbin\n```\n\n```text\npackage.json\n```\n\n```text\n#!/usr/bin/env node\n```\n\n```text\nnode\n```\n\n```text\nogma <file_name>\n```\n\n```text\nNestFactory\n```\n\n========================================\n\nComments:\n- Found a more thorough answer here: stackoverflow.com/questions/65250657/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":67,"estimatedTokens":493}}743{"id":"stack-72131909","source":"stackoverflow","questionId":72131909,"title":"NestJS TypeORM Optional Query not working","tags":["node.js","swagger","nestjs","typeorm"],"text":"Title: NestJS TypeORM Optional Query not working\nTags: node.js, swagger, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a problem that is I have set Query Params to optional, but it's not reflecting optional in swagger,\n\nHere is my code:\n\n```\n@Get('pagination')\n @ApiOperation({ summary: 'Get Activity Post Pagination Enabled' })\n public async getActivityPostPagination(\n @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,\n @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,\n @Query('user_id') user_id?: string,\n @Query('badge_id') badge_id?: string,\n @Query('title') title?: string,\n ) {\n //code here\n }\n```\n\nBut is swagger, it shows like this:\n\nhttps://i.sstatic.net/jNHAz.png\n\nThe page and limit and not optional, but for other query parameters must be optional, what Am I missing here?\n\nThank you\n\n========================================\n\nCode:\n```text\n@Get('pagination')\n  @ApiOperation({ summary: 'Get Activity Post Pagination Enabled' })\n  public async getActivityPostPagination(\n    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,\n    @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,\n    @Query('user_id') user_id?: string,\n    @Query('badge_id') badge_id?: string,\n    @Query('title') title?: string,\n  ) {\n    //code here\n  }\n```\n\n```text\n@Get('pagination')\n  @ApiOperation({ summary: 'Get Activity Post Pagination Enabled' })\n  @ApiQuery({ name: 'user_id', required: false, type: String })\n  @ApiQuery({ name: 'badge_id', required: false, type: String })\n  public async getActivityPostPagination(\n    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,\n    @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,\n    @Query('user_id') user_id?: string,\n    @Query('badge_id') badge_id?: string,\n    @Query('title') title?: string,\n  ) {\n    //code here\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":473}}744{"id":"stack-59814737","source":"stackoverflow","questionId":59814737,"title":"How to use moment in nestjs application","tags":["javascript","node.js","typescript","momentjs","nestjs"],"text":"Title: How to use moment in nestjs application\nTags: javascript, node.js, typescript, momentjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use momentjs in a nestjs app, and also be able to test my services. \nSo I provided momentjs as below in my module\n\n```\nproviders: [\n {\n provide: 'MomentWrapper',\n useFactory: async () => moment(),\n scope: Scope.REQUEST,\n },\n ],\n```\n\nand in my service \n\n```\nconstructor(\n @Inject('MomentWrapper') private momentWrapper: moment.Moment\n )\n```\n\nThen I have a method like this\n\n```\nprivate calculateNextRun(every: number, period: SchedulePeriod): string {\n const currentDate = this.momentWrapper.tz('America/Toronto');\n let nextDate = null;\n\n nextDate = currentDate.add(every, period);\n console.log(currentDate.format(), nextDate.format(), every, period, );\n\n return nextDate.toISOString();\n }\n```\n\nThis method will be called in a loop, and supposed to get the current date and add some days/weeks/.. to it and return it.\n\nThe issue is it keeps the old value so each time it goes into the method is not starting from current date\n\nconsole output\n\n```\n2020-01-25T16:39:19-05:00 2020-01-25T16:39:19-05:00 6 d\n2020-02-15T16:39:19-05:00 2020-02-15T16:39:19-05:00 3 w\n2020-02-16T16:39:19-05:00 2020-02-16T16:39:19-05:00 1 d\n```\n\nIf you see first date, which is `currentDate` keep changing\n\nIs there any way to overcome this issue, **without** creating a new service like this\n\n```\nimport * as moment from 'moment-timezone';\n@Injectable()\nexport class MomentService {\n moment(): moment.Moment {\n return moment();\n }\n}\n```\n\n========================================\n\nTop Answer:\nThis works fine for me:\n\n```\n// in some *.service.ts\nimport * as moment from 'moment';\n\n{ userIsRegistredOn: moment()}\n```\n\n========================================\n\nCode:\n```text\nproviders: [\n    {\n      provide: 'MomentWrapper',\n      useFactory: async () => moment(),\n      scope: Scope.REQUEST,\n    },\n  ],\n```\n\n```text\nconstructor(\n        @Inject('MomentWrapper') private momentWrapper: moment.Moment\n    )\n```\n\n```text\nprivate calculateNextRun(every: number, period: SchedulePeriod): string {\n        const currentDate = this.momentWrapper.tz('America/Toronto');\n        let nextDate = null;\n\n        nextDate = currentDate.add(every, period);\n        console.log(currentDate.format(), nextDate.format(), every, period, );\n\n        return nextDate.toISOString();\n    }\n```\n\n```text\n2020-01-25T16:39:19-05:00 2020-01-25T16:39:19-05:00 6 d\n2020-02-15T16:39:19-05:00 2020-02-15T16:39:19-05:00 3 w\n2020-02-16T16:39:19-05:00 2020-02-16T16:39:19-05:00 1 d\n```\n\n```text\nimport * as moment from 'moment-timezone';\n@Injectable()\nexport class MomentService {\n    moment(): moment.Moment {\n        return moment();\n    }\n}\n```\n\n```text\ncurrentDate\n```\n\n```text\nproviders: [\n    {\n      provide: 'MomentWrapper',\n      useValue: moment\n    },\n  ],\n```\n\n```text\nmoment\n```\n\n```text\nmoment()\n```\n\n```text\n// in some *.service.ts\nimport * as moment from 'moment';\n\n\n{ userIsRegistredOn: moment()}\n```\n\n========================================\n\nComments:\n- Does it work when you define your provider as `useValue: moment` and then call `this.momentWrapper().tz(...`?\n- @KimKern I changed it to what you asked, anyway I get syntax error for `this.momentWrapper()` , BUT if I use my old syntax with your changes, seems it's working\n- @KimKern please post it as answer to accept\n- This is a typescript issue importing the package see the answer below stackoverflow.com/a/71943285/8255981\n- could you please the reference that how to inject the `moment` in `service.ts` file\n- could you please the complete example of the code? FYI: typo `import from`","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":163,"estimatedTokens":913}}745{"id":"stack-63170241","source":"stackoverflow","questionId":63170241,"title":"Nestjs/TypeORM - How to implement custom search by column","tags":["node.js","nestjs","typeorm"],"text":"Title: Nestjs/TypeORM - How to implement custom search by column\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am playing around with NestJs using TypeORM along with MySQL.\n\nI have went via documentation, and I have made basic CRUD app running locally.\nI have built in searches (via Repository) by id, but I would need to implement search by custom column as well.\n\nFor example I have this entity:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n username: string;\n\n @Column()\n first_name: string;\n\n @Column()\n last_Name: string;\n\n @Column()\n gender: string;\n```\n\nAnd in my repository, I have these built in methods:\n\n```\nasync findAll(): Promise {\n return this.usersRepository.find();\n }\n\n findOne(id: string): Promise {\n return this.usersRepository.findOne(id);\n }\n```\n\nAnd it works just fine, as expected. I would need another custom search, so I can search also by username, how can I achieve that?\nI would need something like this:\n\n```\nfindByUsername(username: string): Promise {\n return this.usersRepository.findByUsername(username);\n }\n```\n\nI assume I have to implement custom query, but I have no clue where to do it :(\n\n========================================\n\nTop Answer:\nYou can use this code\n\n```\nfindByName(user_name: string): Promise {\n return this.usersRepository.findOne({ user_name }); \n}\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  username: string;\n\n  @Column()\n  first_name: string;\n\n  @Column()\n  last_Name: string;\n\n  @Column()\n  gender: string;\n```\n\n```text\nasync findAll(): Promise<User[]> {\n    return this.usersRepository.find();\n  }\n\n  findOne(id: string): Promise<User> {\n    return this.usersRepository.findOne(id);\n  }\n```\n\n```text\nfindByUsername(username: string): Promise<User> {\n    return this.usersRepository.findByUsername(username);\n  }\n```\n\n```js\nfindByUsername(username: string): Promise<User | undefined> {\n    return this.usersRepository.findOne({ username }); \n}\n```\n\n```text\nfindByUsername(username: string): Promise<User | undefined> {\n    const user = getRepository(User)\n      .createQueryBuilder(\"user\")\n      .where(\"user.username = :username\", { username: username })\n      .getOne();\n\n    return user;\n  }\n```\n\n```text\nconst firstUser = await connection\n    .getRepository(User)\n    .createQueryBuilder(\"user\")\n    .where(\"user.id = :id\", { id: 1 })\n    .getOne();\n```\n\n```text\nfindByName(user_name: string): Promise<User> {\n    return this.usersRepository.findOne({ user_name }); \n}\n```\n\n```text\nasync getUserByName(username: string){\n    return await this.userRepository.findOneBy({name: username });\n}\n```\n\n========================================\n\nComments:\n- How can we compare if string is non case sensitive?\n- Do you happen to know where is this documented? I would like to read about it a bit.\n- not sure where i read it before :) but you can check the typescript definition files of the TypeOrm.\n- Can you please provide at least some explanation","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":147,"estimatedTokens":768}}746{"id":"stack-70378974","source":"stackoverflow","questionId":70378974,"title":"How to use rxjs/Observables inside Nestjs Application w/o Controller","tags":["axios","rxjs","nestjs"],"text":"Title: How to use rxjs/Observables inside Nestjs Application w/o Controller\nTags: axios, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nNestjs suggests to use the `HttpModule`, imported from `@nestjs/axios` to perform requests to external APIs.\nI understand that the `HttpService` transforms the responses into `Observables`.\n\n### Goal\n\nRequest data from an external API and use the data inside the application.\n\n### Problem\n\nI fail to understand how to actually retrieve the data from the request. I read in some other answers, that if you return the observable from a `Controller`, Nestjs will automatically handle it for you and return the data to the client. That's great, however, I am not using it inside a `Controller`. I need the data to be available inside the application.\n\nI have a service:\n\n```\n@Injectable()\nexport class ExampleService {\n\n // constructor\n\n getData(): Observable> {\n return this.httpService.get(`http://some-url.com`);\n }\n\n}\n```\n\nHow would use `getData()` within the application logic to get to the data returned by the `Observable` ? And would it be better, in that case, to use a plain axios request with `Promises` and not use the `HttpModule` ?\n\nThe only solution I found so far is using `subscribe` :\n\n```\nthis.httpService.get(`http://some-url.com`)\n.subscribe((value) => {\n console.log(value);\n});\n```\n\nWhich seems to be would end up in a callback hell, compared to all the fancy `async ... awaits`.\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class ExampleService {\n\n  // constructor\n\n  getData(): Observable<AxiosResponse<any[]>> {\n    return this.httpService.get(`http://some-url.com`);\n  }\n\n}\n```\n\n```js\nthis.httpService.get(`http://some-url.com`)\n.subscribe((value) => {\n  console.log(value);\n});\n```\n\n```text\nHttpModule\n```\n\n```text\n@nestjs/axios\n```\n\n```text\nHttpService\n```\n\n```text\nObservables\n```\n\n```text\nController\n```\n\n```text\nController\n```\n\n```text\ngetData()\n```\n\n```text\nObservable\n```\n\n```text\nPromises\n```\n\n```text\nHttpModule\n```\n\n```text\nsubscribe\n```\n\n```text\nasync ... awaits\n```\n\n```ts\nstream1().subscribe(value1 => \n  stream2(value1).subscribe(value2 => {\n    /* Do something with value2 */\n  })\n)\n```\n\n```ts\nstream1().pipe(\n  mergeMap(value1 => stream2(value1))\n).subscribe(value2 => {\n  /* Do something with value2 */\n})\n```\n\n```ts\na_value = 5\n// convert with:\nlist_values = [a_value]\n```\n\n```ts\nlist_values = [1,2,3,4,5]\n// convert with:\nvalue = list_values[0] || 0\n// or\nvalue = list_values[list_values.length - 1] || 100\n// or\nvalue = sum(list_values)\n```\n\n```ts\nfirstValueFrom(\n  this.httpService.get(`http://some-url.com`)\n).then(value => {\n  /* Do something with value */\n});\n\n// or with await as syntactic sugar\n\nvalue = await lastValueFrom(\n  this.httpService.get(`http://some-url.com`)\n);\n/* Do something with value */\n```\n\n```text\npromise\n```\n\n```text\n.then\n```\n\n```text\nasync/await\n```\n\n```text\n.then\n```\n\n```text\nfirstValueFrom\n```\n\n```text\nlastValueFrom\n```\n\n========================================\n\nComments:\n- you can call `getData` and subscribe to it . `this.service.getData().subscribe`\n- This would be the same as calling `httpService.get().subscribe` which I already included in my question.\n- Thanks for the very informative answer @MrkSef ! This gives me a better idea on how to approach this. I definitely check out `firstValueFrom` , like you said, these are probably enough for http requests.","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":192,"estimatedTokens":853}}747{"id":"stack-56129216","source":"stackoverflow","questionId":56129216,"title":"How to make waiting for the completion of actions, then receive a new message?","tags":["node.js","rabbitmq","microservices","nestjs"],"text":"Title: How to make waiting for the completion of actions, then receive a new message?\nTags: node.js, rabbitmq, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm creating microservice by nestjs, transfer throw rabbitmq.\nHow to make microservice receive messages from queue in turn waiting for complete of the previous one.\n\n- main.ts\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Transport } from '@nestjs/microservices';\n\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(AppModule, {\n transport: Transport.RMQ,\n options: {\n urls: [`amqp://localhost:5672`],\n queue: 'rmq_queue',\n queueOptions: { durable: false },\n prefetchCount: 1,\n },\n });\n\n await app.listenAsync();\n}\n\nbootstrap();\n```\n\n- app.controller.ts\n\n```\nimport { Controller, Logger } from '@nestjs/common';\nimport { EventPattern } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n @EventPattern('hello')\n async handleHello(): Promise {\n Logger.log('-handle-');\n await (new Promise(resolve => setTimeout(resolve, 5000)));\n Logger.log('---hello---');\n }\n}\n```\n\n- client.js\n\n```\nconst { ClientRMQ } = require('@nestjs/microservices');\n\n(async () => {\n const client = new ClientRMQ({\n urls: ['amqp://localhost:5672'],\n queue: 'rmq_queue',\n queueOptions: { durable: false },\n });\n\n await client.connect();\n\n for (let i = 0; i https://github.com/heySasha/nest-rmq\n\nActual output:\n\n```\n[Nest] 9560 - 05/14/2019, 1:53 PM -handle- +2ms\n[Nest] 9560 - 05/14/2019, 1:53 PM -handle- +9ms\n[Nest] 9560 - 05/14/2019, 1:53 PM -handle- +12ms\n[Nest] 9560 - 05/14/2019, 1:54 PM ---hello--- +4967ms\n[Nest] 9560 - 05/14/2019, 1:54 PM ---hello--- +2ms\n[Nest] 9560 - 05/14/2019, 1:54 PM ---hello--- +1ms\n```\n\nBut i expect:\n\n```\n[Nest] 9560 - 05/14/2019, 1:53 PM -handle- +2ms\n[Nest] 9560 - 05/14/2019, 1:54 PM ---hello--- +5067ms\n[Nest] 9560 - 05/14/2019, 1:53 PM -handle- +2ms\n[Nest] 9560 - 05/14/2019, 1:54 PM ---hello--- +5067ms\n[Nest] 9560 - 05/14/2019, 1:53 PM -handle- +2ms\n[Nest] 9560 - 05/14/2019, 1:54 PM ---hello--- +5067ms\n```\n\n========================================\n\nTop Answer:\nWhat you want to have is usually accomplished with consumer acknowledgments. You can read about them here. In short, your consumer (in your case Nest.js microservice), that has prefetch count set to 1, will receive a new message only after it acknowledges a previous one. If you are familiar with AWS SQS, this operation is similar to deleting message from the queue.\n\nNest.js uses amqplib under the hood for communicating with RabbitMQ. Consumer acknowledgment policy is established during channel creation - you can see there's a `noAck` option. However, the channel is created with `noAck` set to `true` - you can check it here, which means that it's the listener who automatically acknowledges messages when they are passed to your `@EventHandler` method. You can verify that with RabbitMQ management plugin, that provides handy UI and ability to check non acked messages in flight.\n\nI failed to find any useful info about that both in Nest.js sources and docs. But this might give you a hint.\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Transport } from '@nestjs/microservices';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice(AppModule, {\n    transport: Transport.RMQ,\n    options: {\n      urls: [`amqp://localhost:5672`],\n      queue: 'rmq_queue',\n      queueOptions: { durable: false },\n      prefetchCount: 1,\n    },\n  });\n\n  await app.listenAsync();\n}\n\nbootstrap();\n```\n\n```text\nimport { Controller, Logger } from '@nestjs/common';\nimport { EventPattern } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n  @EventPattern('hello')\n  async handleHello(): Promise<void> {\n    Logger.log('-handle-');\n    await (new Promise(resolve => setTimeout(resolve, 5000)));\n    Logger.log('---hello---');\n  }\n}\n```\n\n```text\nconst { ClientRMQ } = require('@nestjs/microservices');\n\n(async () => {\n  const client = new ClientRMQ({\n    urls: ['amqp://localhost:5672'],\n    queue: 'rmq_queue',\n    queueOptions: { durable: false },\n  });\n\n  await client.connect();\n\n  for (let i = 0; i < 3; i++) {\n    client.emit('hello', 0).subscribe();\n  }\n})();\n```\n\n```text\n[Nest] 9560   - 05/14/2019, 1:53 PM   -handle- +2ms\n[Nest] 9560   - 05/14/2019, 1:53 PM   -handle- +9ms\n[Nest] 9560   - 05/14/2019, 1:53 PM   -handle- +12ms\n[Nest] 9560   - 05/14/2019, 1:54 PM   ---hello--- +4967ms\n[Nest] 9560   - 05/14/2019, 1:54 PM   ---hello--- +2ms\n[Nest] 9560   - 05/14/2019, 1:54 PM   ---hello--- +1ms\n```\n\n```text\n[Nest] 9560   - 05/14/2019, 1:53 PM   -handle- +2ms\n[Nest] 9560   - 05/14/2019, 1:54 PM   ---hello--- +5067ms\n[Nest] 9560   - 05/14/2019, 1:53 PM   -handle- +2ms\n[Nest] 9560   - 05/14/2019, 1:54 PM   ---hello--- +5067ms\n[Nest] 9560   - 05/14/2019, 1:53 PM   -handle- +2ms\n[Nest] 9560   - 05/14/2019, 1:54 PM   ---hello--- +5067ms\n```\n\n```text\nimport { isString, isUndefined } from '@nestjs/common/utils/shared.utils';\nimport { Observable } from 'rxjs';\nimport { CustomTransportStrategy, RmqOptions, Server } from '@nestjs/microservices';\nimport {\n    CONNECT_EVENT, DISCONNECT_EVENT, DISCONNECTED_RMQ_MESSAGE, NO_MESSAGE_HANDLER,\n    RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT,\n    RQM_DEFAULT_PREFETCH_COUNT,\n    RQM_DEFAULT_QUEUE, RQM_DEFAULT_QUEUE_OPTIONS,\n    RQM_DEFAULT_URL,\n} from '@nestjs/microservices/constants';\n\nlet rqmPackage: any = {};\n\nexport class ServerRMQ extends Server implements CustomTransportStrategy {\n    private server: any = null;\n    private channel: any = null;\n    private readonly urls: string[];\n    private readonly queue: string;\n    private readonly prefetchCount: number;\n    private readonly queueOptions: any;\n    private readonly isGlobalPrefetchCount: boolean;\n\n    constructor(private readonly options: RmqOptions['options']) {\n        super();\n        this.urls = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL];\n        this.queue =\n            this.getOptionsProp(this.options, 'queue') || RQM_DEFAULT_QUEUE;\n        this.prefetchCount =\n            this.getOptionsProp(this.options, 'prefetchCount') ||\n            RQM_DEFAULT_PREFETCH_COUNT;\n        this.isGlobalPrefetchCount =\n            this.getOptionsProp(this.options, 'isGlobalPrefetchCount') ||\n            RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT;\n        this.queueOptions =\n            this.getOptionsProp(this.options, 'queueOptions') ||\n            RQM_DEFAULT_QUEUE_OPTIONS;\n\n        this.loadPackage('amqplib', ServerRMQ.name, () => require('amqplib'));\n        rqmPackage = this.loadPackage(\n            'amqp-connection-manager',\n            ServerRMQ.name,\n            () => require('amqp-connection-manager'),\n        );\n    }\n\n    public async listen(callback: () => void): Promise<void> {\n        await this.start(callback);\n    }\n\n    public close(): void {\n        if (this.channel) {\n            this.channel.close();\n        }\n\n        if (this.server) {\n            this.server.close();\n        }\n    }\n\n    public async start(callback?: () => void) {\n        this.server = this.createClient();\n        this.server.on(CONNECT_EVENT, (_: any) => {\n            this.channel = this.server.createChannel({\n                json: false,\n                setup: (channel: any) => this.setupChannel(channel, callback),\n            });\n        });\n        this.server.on(DISCONNECT_EVENT, (err: any) => {\n            this.logger.error(DISCONNECTED_RMQ_MESSAGE);\n        });\n    }\n\n    public createClient<T = any>(): T {\n        const socketOptions = this.getOptionsProp(this.options, 'socketOptions');\n        return rqmPackage.connect(this.urls, socketOptions);\n    }\n\n    public async setupChannel(channel: any, callback: () => void) {\n        await channel.assertQueue(this.queue, this.queueOptions);\n        await channel.prefetch(this.prefetchCount, this.isGlobalPrefetchCount);\n        channel.consume(\n            this.queue,\n            (msg: any) => this.handleMessage(msg)\n                .then(() => this.channel.ack(msg)) // Ack message after complete\n                .catch(err => {\n                    // error handling\n                    this.logger.error(err);\n                    return this.channel.ack(msg);\n                }),\n            { noAck: false },\n        );\n        callback();\n    }\n\n    public async handleMessage(message: any): Promise<void> {\n        const { content, properties } = message;\n        const packet = JSON.parse(content.toString());\n        const pattern = isString(packet.pattern)\n            ? packet.pattern\n            : JSON.stringify(packet.pattern);\n\n        if (isUndefined(packet.id)) {\n            return this.handleEvent(pattern, packet);\n        }\n\n        const handler = this.getHandlerByPattern(pattern);\n\n        if (!handler) {\n            const status = 'error';\n\n            return this.sendMessage(\n                { status, err: NO_MESSAGE_HANDLER },\n                properties.replyTo,\n                properties.correlationId,\n            );\n        }\n\n        const response$ = this.transformToObservable(\n            await handler(packet.data),\n        ) as Observable<any>;\n\n        const publish = <T>(data: T) =>\n            this.sendMessage(data, properties.replyTo, properties.correlationId);\n\n        if (response$) {\n            this.send(response$, publish);\n        }\n\n    }\n\n    public sendMessage<T = any>(\n        message: T,\n        replyTo: any,\n        correlationId: string,\n    ): void {\n        const buffer = Buffer.from(JSON.stringify(message));\n        this.channel.sendToQueue(replyTo, buffer, { correlationId });\n    }\n}\n```\n\n```text\nServerRMQ\n```\n\n```text\nsetupChannel()\n```\n\n```text\nnoAck: false\n```\n\n```text\nthis.handleMessage(msg)\n```\n\n```text\nthis.channel.ack(msg)\n```\n\n```text\nnoAck\n```\n\n```text\nnoAck\n```\n\n```text\ntrue\n```\n\n```text\n@EventHandler\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Transport } from '@nestjs/microservices';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice(AppModule, {\n    transport: Transport.RMQ,\n    options: {\n      urls: [`amqp://localhost:5672`],\n      queue: 'rmq_queue',\n      queueOptions: { durable: false },\n      noAck: false,\n      prefetchCount: 1,\n    },\n  });\n\n  await app.listenAsync();\n}\n\nbootstrap();\n```\n\n```text\nimport { Controller, Logger } from '@nestjs/common';\nimport {  Ctx, EventPattern, RmqContext } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n  @EventPattern('hello')\n  async handleHello(@Ctx() context: RmqContext): Promise<void> {\n    Logger.log('-handle-');\n    await (new Promise(resolve => setTimeout(resolve, 5000)));\n    Logger.log('---hello---');\n\n    const channel = context.getChannelRef();\n    const originalMsg = context.getMessage();\n    channel.ack(originalMsg);\n  }\n}\n```\n\n```text\nnoAck: false\n```\n\n```text\ncontext\n```\n\n```text\nack\n```\n\n========================================\n\nComments:\n- Do you want to achieve a synchronous call to that endpoint?\n- Thank you! I think, that need to create Custom Transport, docs.nestjs.com/microservices/custom-transport.\n- @AleksandrYatsenko sounds like a solution. I'm gonna be a bit selfish and leave a link here to my npm package, that can actually be very useful in your case. If you find that it fits your needs, enjoy: npmjs.com/package/nabbitmq\n- i think channel.ack should be before setimeout or any other action , so rabbitMQ no that someone handling this message","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":411,"estimatedTokens":2909}}748{"id":"stack-53087389","source":"stackoverflow","questionId":53087389,"title":"nestjs Gateways emit an event to all connected sockets","tags":["nestjs"],"text":"Title: nestjs Gateways emit an event to all connected sockets\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nHow to issue an event to all connected sockets?\n\n```\nexport class EventsGateway {\n\n @SubscribeMessage('message')\n\n async onEvent(client, data) {\n // The following is the use of `socket.io` to issue events to all connected sockets.\n // io.emit('message', data);\n }\n }\n```\n\nHow do I perform this in nestjs?\n\n========================================\n\nCode:\n```text\nexport class EventsGateway {\n\n      @SubscribeMessage('message')\n\n       async onEvent(client, data) {\n        // The following is the use of `socket.io` to issue events to all connected sockets.\n        // io.emit('message', data);\n      }\n    }\n```\n\n```ts\nimport WebSocketServer from '@nestjs/websockets'\n\nexport class EventsGateway {\n  @WebSocketServer() server;\n\n  @SubscribeMessage('message')\n  onEvent(client: any, payload: any): Observable<WsResponse<any>> | any {\n    this.server.emit('message', payload);\n  }\n}\n```\n\n```text\nWebSocketServer\n```\n\n========================================\n\nComments:\n- This is a good question that many people may be searching if they can't quite find the appropriate documentation or don't understand the abstractions they're working with, not sure why it received any down votes.\n- While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":58,"estimatedTokens":389}}749{"id":"stack-58084087","source":"stackoverflow","questionId":58084087,"title":"Starting nestjs in production mode","tags":["nestjs"],"text":"Title: Starting nestjs in production mode\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using akveo backend bundle that I bought, and while everything seems to be working fine in development mode starting in production gives me following errors, I am new to nestjs itself. \nAnyone know what's going here?\n\n```\nnode_modules/@nestjs/core/adapters/http-adapter.d.ts:5:31 - error TS2420: Class 'AbstractHttpAdapter' incorrectly implements interface 'HttpServer'.\n Property 'status' is missing in type 'AbstractHttpAdapter' but required in type 'HttpServer'.\n\n5 export declare abstract class AbstractHttpAdapter implements HttpServer {\n~~~~~~~~~~~~~~~~~~~\n\n node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts:26:5\n 26 status(response: any, statusCode: number): any;\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n 'status' is declared here.\n\n node_modules/@nestjs/core/application-config.d.ts:2:39 - error TS2307: Cannot find module '@nestjs/common/interfaces/configuration-provider.interface'.\n\n 2 import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface';\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n node_modules/@nestjs/core/guards/guards-context-creator.d.ts:3:39 - error TS2307: Cannot find module '@nestjs/common/interfaces/configuration-provider.interface'.\n\n3 import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface';\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n node_modules/@nestjs/core/interceptors/interceptors-context-creator.d.ts:2:39 - error TS2307: Cannot find module '@nestjs/common/interfaces/configuration-provider.interface'.\n\n2 import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface';\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n node_modules/@nestjs/core/nest-application.d.ts:24:5 - error TS2416: Property 'getHttpAdapter' in type 'NestApplication' is not assignable to the same property in base type 'INestApplication'.\n Type '() => AbstractHttpAdapter' is not assignable to type '() => HttpServer'.\n Property 'status' is missing in type 'AbstractHttpAdapter' but required in type 'HttpServer'.\n\n24 getHttpAdapter(): AbstractHttpAdapter;\n~~~~~~~~~~~~~~\n\n node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts:26:5\n26 status(response: any, statusCode: number): any;\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n 'status' is declared here.\n\n Found 5 errors.\n```\n\nI am using `tsc -p tsconfig.build.json` command to build it with `tsconfig.build.json`:\n\n```\n{\n \"extends\": \"./tsconfig.json\",\n \"exclude\": [\"node_modules\", \"test\", \"**/*spec.ts\"]\n}\n```\n\nand `tsconfig.json`:\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es6\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\"\n },\n \"exclude\": [\"node_modules\"]\n}\n```\n\nI expect that this config should compile typescript code to javascript which then I would run with `node dist/main.js` command. Which it actually does. But I am worried about the typescript compiler errors.\n\n========================================\n\nCode:\n```text\nnode_modules/@nestjs/core/adapters/http-adapter.d.ts:5:31 - error TS2420: Class 'AbstractHttpAdapter<TServer, TRequest, TResponse>' incorrectly implements interface 'HttpServer<TRequest, TResponse>'.\n    Property 'status' is missing in type 'AbstractHttpAdapter<TServer, TRequest, TResponse>' but required in type 'HttpServer<TRequest, TResponse>'.\n\n5 export declare abstract class AbstractHttpAdapter<TServer = any, TRequest = any, TResponse = any> implements HttpServer<TRequest, TResponse> {\n~~~~~~~~~~~~~~~~~~~\n\n    node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts:26:5\n    26     status(response: any, statusCode: number): any;\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    'status' is declared here.\n\n    node_modules/@nestjs/core/application-config.d.ts:2:39 - error TS2307: Cannot find module '@nestjs/common/interfaces/configuration-provider.interface'.\n\n    2 import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface';\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    node_modules/@nestjs/core/guards/guards-context-creator.d.ts:3:39 - error TS2307: Cannot find module '@nestjs/common/interfaces/configuration-provider.interface'.\n\n3 import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface';\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    node_modules/@nestjs/core/interceptors/interceptors-context-creator.d.ts:2:39 - error TS2307: Cannot find module '@nestjs/common/interfaces/configuration-provider.interface'.\n\n2 import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface';\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    node_modules/@nestjs/core/nest-application.d.ts:24:5 - error TS2416: Property 'getHttpAdapter' in type 'NestApplication' is not assignable to the same property in base type 'INestApplication'.\n    Type '() => AbstractHttpAdapter<any, any, any>' is not assignable to type '() => HttpServer<any, any>'.\n    Property 'status' is missing in type 'AbstractHttpAdapter<any, any, any>' but required in type 'HttpServer<any, any>'.\n\n24     getHttpAdapter(): AbstractHttpAdapter;\n~~~~~~~~~~~~~~\n\n    node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts:26:5\n26     status(response: any, statusCode: number): any;\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    'status' is declared here.\n\n\n    Found 5 errors.\n```\n\n```text\n{\n    \"extends\": \"./tsconfig.json\",\n    \"exclude\": [\"node_modules\", \"test\", \"**/*spec.ts\"]\n}\n```\n\n```text\n{\n    \"compilerOptions\": {\n        \"module\": \"commonjs\",\n        \"declaration\": true,\n        \"removeComments\": true,\n        \"emitDecoratorMetadata\": true,\n        \"experimentalDecorators\": true,\n        \"target\": \"es6\",\n        \"sourceMap\": true,\n        \"outDir\": \"./dist\",\n        \"baseUrl\": \"./\"\n    },\n    \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\ntsc -p tsconfig.build.json\n```\n\n```text\ntsconfig.build.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\nnode dist/main.js\n```\n\n```text\n\"@nestjs/common\": \"6.6.0\",  // notice the core/common does not match, it should be bumped\n   \"@nestjs/core\": \"6.6.2\",\n```\n\n```text\npackage.json\n```\n\n```text\n@nest\n```\n\n```text\ncore\n```\n\n========================================\n\nComments:\n- Please paste your errors in StackOverflow. The picture is hard to read and discourages others from helping. What start commands are you using? How are you building your project? How are you testing the deployment? Where are you trying to deploy to (if you are deploying your server currently)?\n- Sorry, I'll keep that in mind in the future. I've edited the question.\n- It turned out that this indeed was, the problem. Although now I am having with nestjs not been able to resolve mongoose @InjectModel dependencies. But this is another issue.\n- Also had this exact same issue where `@nestjs&#47;platform-express` was a different version to `@nestjs&#47;core`. Once syncing them up, the error went away. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":190,"estimatedTokens":1820}}750{"id":"stack-51194226","source":"stackoverflow","questionId":51194226,"title":"supertest e2e with nestjs: request is not a function","tags":["node.js","e2e-testing","supertest","nestjs"],"text":"Title: supertest e2e with nestjs: request is not a function\nTags: node.js, e2e-testing, supertest, nestjs\nSource: Stack Overflow\n\nQuestion:\nI try to introduce e2e tests for my simple NestJS backend services. I am providing a custom userService and a custom UserRepository mocked with sinon.\n\nThis is my **user.e2e-spec.ts** file:\n\n```\nimport * as request from 'supertest';\nimport * as sinon from 'sinon';\nimport { Test } from '@nestjs/testing';\nimport { INestApplication } from '@nestjs/common';\nimport { UserService } from '../../src/user/user.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from '../../src/user/user.entity';\nimport { TestUtil } from '../../src/utils/TestUtil';\nimport { createFakeUser } from '../../src/user/test/userTestUtil';\n\nlet sandbox: sinon.SinonSandbox;\nlet testUtil;\n\ndescribe('User', () => {\n let app: INestApplication;\n const fakeUser = createFakeUser();\n const userService = { findOne: () => fakeUser };\n\n beforeAll(async () => {\n sandbox = sinon.createSandbox();\n testUtil = new TestUtil(sandbox);\n const module = await Test.createTestingModule({\n providers: [\n {\n provide: UserService,\n useValue: userService,\n },\n {\n provide: getRepositoryToken(User),\n useValue: testUtil.getMockRepository().object,\n },\n ],\n }).compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n it(`/GET user`, () => {\n return request(app.getHttpServer())\n .get('/user/:id')\n .expect(200)\n .expect({\n data: userService.findOne(),\n });\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\nand this is my **user.controller.ts**:\n\n```\nimport { ApiBearerAuth, ApiUseTags } from '@nestjs/swagger';\nimport { Controller, Get, Param } from '@nestjs/common';\nimport { UserService } from './user.service';\nimport { User } from './user.entity';\n\n@ApiUseTags('Users')\n@ApiBearerAuth()\n@Controller('user')\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n\n @Get('/:id')\n findOne(@Param('id') id: number): Promise {\n return this.userService.find(id);\n }\n}\n```\n\nI wrote a bunch of Unit tests with the same pattern and it works. Have no clue what is wrong with this e2e supertest.\n\nThanks for your help!\n\n**UPDATE**:\nThis is the error message I get:\n\n```\nTypeError: request is not a function\n at Object.it (/Users/florian/Development/Houzy/nestjs-backend/e2e/user/user.e2e-spec.ts:40:16)\n at Object.asyncFn (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/jasmine_async.js:124:345)\n at resolve (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:46:12)\n at new Promise ()\n at mapper (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:34:499)\n at promise.then (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:74:39)\n at \n```\n\n========================================\n\nCode:\n```js\nimport * as request from 'supertest';\nimport * as sinon from 'sinon';\nimport { Test } from '@nestjs/testing';\nimport { INestApplication } from '@nestjs/common';\nimport { UserService } from '../../src/user/user.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from '../../src/user/user.entity';\nimport { TestUtil } from '../../src/utils/TestUtil';\nimport { createFakeUser } from '../../src/user/test/userTestUtil';\n\nlet sandbox: sinon.SinonSandbox;\nlet testUtil;\n\ndescribe('User', () => {\n    let app: INestApplication;\n    const fakeUser = createFakeUser();\n    const userService = { findOne: () => fakeUser };\n\n    beforeAll(async () => {\n        sandbox = sinon.createSandbox();\n        testUtil = new TestUtil(sandbox);\n        const module = await Test.createTestingModule({\n            providers: [\n                {\n                    provide: UserService,\n                    useValue: userService,\n                },\n                {\n                    provide: getRepositoryToken(User),\n                    useValue: testUtil.getMockRepository().object,\n                },\n            ],\n        }).compile();\n\n        app = module.createNestApplication();\n        await app.init();\n    });\n\n    it(`/GET user`, () => {\n        return request(app.getHttpServer())\n            .get('/user/:id')\n            .expect(200)\n            .expect({\n                data: userService.findOne(),\n            });\n    });\n\n    afterAll(async () => {\n        await app.close();\n    });\n});\n```\n\n```ts\nimport { ApiBearerAuth, ApiUseTags } from '@nestjs/swagger';\nimport { Controller, Get, Param } from '@nestjs/common';\nimport { UserService } from './user.service';\nimport { User } from './user.entity';\n\n@ApiUseTags('Users')\n@ApiBearerAuth()\n@Controller('user')\nexport class UserController {\n    constructor(private readonly userService: UserService) {}\n\n    @Get('/:id')\n    findOne(@Param('id') id: number): Promise<User> {\n        return this.userService.find(id);\n    }\n}\n```\n\n```none\nTypeError: request is not a function\n    at Object.it (/Users/florian/Development/Houzy/nestjs-backend/e2e/user/user.e2e-spec.ts:40:16)\n    at Object.asyncFn (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/jasmine_async.js:124:345)\n    at resolve (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:46:12)\n    at new Promise (<anonymous>)\n    at mapper (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:34:499)\n    at promise.then (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:74:39)\n    at <anonymous>\n```\n\n```text\nimport request from 'supertest';\n```\n\n```text\nit(`/GET user`, () => {\n        return request(app.getHttpServer())\n            .get('/user/1') // pass here id, not a string\n            .expect(200)\n            .expect({\n                data: userService.findOne(),\n        });\n});\n```\n\n```text\n@Get('/:id')\n    findOne(@Param('id') id: number): Promise<User> {\n        return this.userService.find(id);\n }\n```\n\n========================================\n\nComments:\n- Also, include more info. Such as error message, what you have tried etc.\n- Thanks for your help but I still get the same error.\n- @FlorianR&#252;egg changed answer. Update your request import in tests.\n- Thanks a lot, that was the problem!","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":218,"estimatedTokens":1592}}751{"id":"stack-67798146","source":"stackoverflow","questionId":67798146,"title":"Provide explicit type for the mutation GraphQL","tags":["graphql","nestjs"],"text":"Title: Provide explicit type for the mutation GraphQL\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a mutation which will accept list of products. But doing so GraphQL is throwing error for **createMultipleProducts** method. Not sure what is the mistake here.\n\n```\nimport { Inject } from \"@nestjs/common\";\nimport { Args, Mutation, Query, Resolver } from \"@nestjs/graphql\";\nimport { ClientProxy } from \"@nestjs/microservices\";\nimport { ProductRequest } from \"src/types/ms-product/product.request.type\";\nimport { ProductResponse } from \"src/types/ms-product/product.response.type\";\n@Resolver(of => ProductResponse)\nexport class ProductResolver {\n\n constructor(\n @Inject('SERVICE__PRODUCT') private readonly clientServiceProduct: ClientProxy\n ) {}\n\n @Mutation(returns => ProductResponse)\n async createProduct(@Args('data') product: ProductRequest): Promise {\n const PATTERN = {cmd: 'ms-product-create'};\n const PAYLOAD = product;\n return this.clientServiceProduct.send(PATTERN, PAYLOAD)\n .toPromise()\n .then((response: ProductResponse) => {\n return response;\n })\n .catch((error) => {\n return error;\n })\n }\n\n @Mutation(returns => [ProductResponse])\n async createMultipleProducts(@Args('data') products: [ProductRequest]): Promise> {\n try {\n const PROMISES = products.map(async (product: ProductRequest) => {\n const PATTERN = {cmd: 'ms-product-create'};\n const PAYLOAD = product;\n return await this.clientServiceProduct.send(PATTERN, PAYLOAD).toPromise();\n });\n \n return await Promise.all(PROMISES);\n } catch (error) {\n throw new Error(error);\n }\n }\n\n @Query(returns => ProductResponse)\n async readProduct(@Args('data') id: string) {\n return {}\n }\n}\n```\n\nI'm getting this error:\n\n```\nUnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure you are providing an explicit type for the \"createMultipleProducts\" (parameter at index [0]) of the \"ProductResolver\" class.\n```\n\n========================================\n\nTop Answer:\nNew format 2022\n\n```\n@Query(returns => ProductResponse)\n async readProduct(@Args('data', () => String ) id: string) {\n return {}\n }\n```\n\n========================================\n\nCode:\n```text\nimport { Inject } from \"@nestjs/common\";\nimport { Args, Mutation, Query, Resolver } from \"@nestjs/graphql\";\nimport { ClientProxy } from \"@nestjs/microservices\";\nimport { ProductRequest } from \"src/types/ms-product/product.request.type\";\nimport { ProductResponse } from \"src/types/ms-product/product.response.type\";\n@Resolver(of => ProductResponse)\nexport class ProductResolver {\n\n  constructor(\n    @Inject('SERVICE__PRODUCT') private readonly clientServiceProduct: ClientProxy\n  ) {}\n\n  @Mutation(returns => ProductResponse)\n  async createProduct(@Args('data') product: ProductRequest): Promise<ProductResponse> {\n    const PATTERN = {cmd: 'ms-product-create'};\n    const PAYLOAD = product;\n    return this.clientServiceProduct.send(PATTERN, PAYLOAD)\n    .toPromise()\n    .then((response: ProductResponse) => {\n      return response;\n    })\n    .catch((error) => {\n      return error;\n    })\n  }\n\n  @Mutation(returns => [ProductResponse])\n  async createMultipleProducts(@Args('data') products: [ProductRequest]): Promise<Array<ProductResponse>> {\n    try {\n      const PROMISES = products.map(async (product: ProductRequest) => {\n        const PATTERN = {cmd: 'ms-product-create'};\n        const PAYLOAD = product;\n        return await this.clientServiceProduct.send(PATTERN, PAYLOAD).toPromise();\n      });\n  \n      return await Promise.all(PROMISES);\n    } catch (error) {\n      throw new Error(error);\n    }\n  }\n\n  @Query(returns => ProductResponse)\n  async readProduct(@Args('data') id: string) {\n    return {}\n  }\n}\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure you are providing an explicit type for the \"createMultipleProducts\" (parameter at index [0]) of the \"ProductResolver\" class.\n```\n\n```js\n@Mutation(returns => [ProductResponse])\nasync createMultipleProducts(@Args({ name: 'data', type: () => [ProductRequest] }) products: ProductRequest[]): Promise<Array<ProductResponse>> {\n  ...\n}\n```\n\n```text\n@Query(returns => ProductResponse)\n  async readProduct(@Args('data', () => String ) id: string) {\n    return {}\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":143,"estimatedTokens":1058}}752{"id":"stack-59718680","source":"stackoverflow","questionId":59718680,"title":"How do I configure a custom nestjs pipe?","tags":["typescript","nestjs"],"text":"Title: How do I configure a custom nestjs pipe?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've got the most basic pipe that I would like to use on a method of a custom provider. The pipe looks as follows:\n\n```\n@Injectable()\nexport class DateTransformPipe implements PipeTransform {\n transform(value: any, metadata: ArgumentMetadata) {\n console.log('Inside the DateTransformPipe pipe...');\n return value;\n }\n}\n```\n\nAnd here is the class where I would like to use it:\n\n```\n@Injectable()\nexport class MyProvider {\n\n @UsePipes(new DateTransformPipe())\n private getDataFor(onDate: Date): string {\n console.log(onDate);\n return 'Some Stuff'\n }\n}\n```\n\nThe pipe is in a special directory `src/helpers/pipes`. The problem here is that the pipe's transform method is not called at all...I don't seem to figure out why.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class DateTransformPipe implements PipeTransform {\n  transform(value: any, metadata: ArgumentMetadata) {\n    console.log('Inside the DateTransformPipe pipe...');\n    return value;\n  }\n}\n```\n\n```text\n@Injectable()\nexport class MyProvider {\n\n    @UsePipes(new DateTransformPipe())\n    private getDataFor(onDate: Date): string {\n      console.log(onDate);\n        return 'Some Stuff'\n    }\n}\n```\n\n```text\nsrc/helpers/pipes\n```\n\n```js\n@Controller('cats')\nclass CatController {\n    @Post()\n    @UsePipes(new DateTransformPipe())\n    async create(@Body() createCatDto: CreateCatDto) {\n    this.catsService.create(createCatDto);\n    }\n}\n```\n\n```text\ngetDataFor\n```\n\n```text\nMyProvider\n```\n\n========================================\n\nComments:\n- Are you using this pipe with a controller/resolver/gateway or with a service?\n- @JayMcDoniel Well yeah that class can be technically considered a service, it's just a provider.\n- yeah, service/provider. Looks like cojak's answer had what you needed. I was trying to determine the use before making assumptions\n- If I needed to use the pipes logic with providers methods, what's the alternatives do I have?","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":88,"estimatedTokens":512}}753{"id":"stack-76959313","source":"stackoverflow","questionId":76959313,"title":"NestJS Repository gives error 'No metadata for \"TaskRepository\" was found.'","tags":["nestjs","typeorm","repository-pattern","nestjs-typeorm"],"text":"Title: NestJS Repository gives error 'No metadata for \"TaskRepository\" was found.'\nTags: nestjs, typeorm, repository-pattern, nestjs-typeorm\nSource: Stack Overflow\n\nQuestion:\nGitHub link to project:\nnestjs-task-management\n\nError Log:\n\n```\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [NestFactory] Starting Nest application...\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] AppModule dependencies initialized +115ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +182ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TasksModule dependencies initialized +2ms \n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [RoutesResolver] TasksController {/tasks}: +28ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [RouterExplorer] Mapped {/tasks/:id, GET} route +5ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [NestApplication] Nest application successfully started +4ms\n[Nest] 15824 - 23/08/2023, 12:03:53 ERROR [ExceptionsHandler] No metadata for \"TaskRepository\" was found.\nEntityMetadataNotFoundError: No metadata for \"TaskRepository\" was found.\n at DataSource.getMetadata (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\data-source\\DataSource.ts:444:30)\n at Repository.get metadata [as metadata] (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:53:40)\n at Repository.findOne (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:577:42)\n at TasksService.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.service.ts:37:50)\n at TasksController.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.controller.ts:24:30)\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (node:internal/process/task_queues:95:5)\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\nModules:\n\n```\n\"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/typeorm\": \"^10.0.0\",\n \"typeorm\": \"^0.3.17\"\n```\n\ntypeorm.config.ts:\n\n```\nimport { TypeOrmModuleOptions } from \"@nestjs/typeorm\";\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'root',\n database: 'taskmanagement',\n entities: [__dirname + '/../**/*.entity.{js,ts}'],\n synchronize: true,\n};\n```\n\ntasks.module.ts:\n\n```\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { TasksController } from './tasks.controller';\nimport { TasksService } from './tasks.service';\nimport { TaskRepository } from './task.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([TaskRepository])],\n controllers: [TasksController],\n providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\ntask.entity.ts:\n\n```\nimport { TaskStatus } from \"./task-status.enum\";\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity()\nexport class Task {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column()\n description: string;\n\n @Column()\n status: TaskStatus;\n}\n```\n\ntask.repository.ts:\n\n```\nimport { Repository } from 'typeorm';\nimport { Task } from './task.entity';\n\nexport class TaskRepository extends Repository {\n // Your custom repository methods can go here\n}\n```\n\ntasks.service.ts:\n\n```\nimport { TaskRepository } from './task.repository';\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Task } from './task.entity';\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {};\n async getTaskById(id: number): Promise {\n const record = await this.taskRepository.findOne({ where: { id } });\n if (!record) {\n throw new NotFoundException();\n }\n return record;\n }\n}\n```\n\nI tried using an older version of TypeORM but that was introducing new errors and I want to learn doing this using the up-to-date methods.\n\nI only get this error when I hit the endpoint using Postman and I have been trying to fix this since yesterday and was unable to find any similar issues. One was to use `entities: [__dirname + '/../**/*.entity.{js,ts}'],` in the typeorm config file where I was using `autoLoadEntities: true` instead so I tried that too but didn't change anything.\n\nI don't understand where and how I have to provide metadata to the repository.\n\nI thank you guys in advance for any help here.\n\n========================================\n\nTop Answer:\nI resolved this by reverting @nestjs/typeorm to version 8.0.0 (`yarn upgrade @nestjs/typeorm@8.0.0`) and downgrading typeorm to version 0.2.32 (`yarn upgrade typeorm@0.2.32`).\n\n========================================\n\nCode:\n```text\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [NestFactory] Starting Nest application...\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [InstanceLoader] AppModule dependencies initialized +115ms\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +182ms\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [InstanceLoader] TasksModule dependencies initialized +2ms  \n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [RoutesResolver] TasksController {/tasks}: +28ms\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [RouterExplorer] Mapped {/tasks/:id, GET} route +5ms\n[Nest] 15824  - 23/08/2023, 11:22:29     LOG [NestApplication] Nest application successfully started +4ms\n[Nest] 15824  - 23/08/2023, 12:03:53   ERROR [ExceptionsHandler] No metadata for \"TaskRepository\" was found.\nEntityMetadataNotFoundError: No metadata for \"TaskRepository\" was found.\n    at DataSource.getMetadata (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\data-source\\DataSource.ts:444:30)\n    at Repository.get metadata [as metadata] (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:53:40)\n    at Repository.findOne (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:577:42)\n    at TasksService.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.service.ts:37:50)\n    at TasksController.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.controller.ts:24:30)\n    at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n    at processTicksAndRejections (node:internal/process/task_queues:95:5)\n    at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n    at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\n\"@nestjs/common\": \"^9.0.0\",\n    \"@nestjs/core\": \"^9.0.0\",\n    \"@nestjs/typeorm\": \"^10.0.0\",\n    \"typeorm\": \"^0.3.17\"\n```\n\n```text\nimport { TypeOrmModuleOptions } from \"@nestjs/typeorm\";\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n    type: 'postgres',\n    host: 'localhost',\n    port: 5432,\n    username: 'postgres',\n    password: 'root',\n    database: 'taskmanagement',\n    entities: [__dirname + '/../**/*.entity.{js,ts}'],\n    synchronize: true,\n};\n```\n\n```text\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { TasksController } from './tasks.controller';\nimport { TasksService } from './tasks.service';\nimport { TaskRepository } from './task.repository';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([TaskRepository])],\n  controllers: [TasksController],\n  providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\nimport { TaskStatus } from \"./task-status.enum\";\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity()\nexport class Task {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    title: string;\n\n    @Column()\n    description: string;\n\n    @Column()\n    status: TaskStatus;\n}\n```\n\n```text\nimport { Repository } from 'typeorm';\nimport { Task } from './task.entity';\n\nexport class TaskRepository extends Repository<Task> {\n  // Your custom repository methods can go here\n}\n```\n\n```text\nimport { TaskRepository } from './task.repository';\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Task } from './task.entity';\n\n@Injectable()\nexport class TasksService {\n    constructor(\n        @InjectRepository(TaskRepository)\n        private taskRepository: TaskRepository,\n    ) {};\n    async getTaskById(id: number): Promise<Task> {\n        const record = await this.taskRepository.findOne({ where: { id } });\n        if (!record) {\n            throw new NotFoundException();\n        }\n        return record;\n    }\n}\n```\n\n```text\nentities: [__dirname + '/../**/*.entity.{js,ts}'],\n```\n\n```text\nautoLoadEntities: true\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([TaskRepository])],\n  controllers: [TasksController],\n  providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\nimport { Task } from './task.entity';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Task])],\n  controllers: [TasksController],\n  providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\n@Injectable()\nexport class TasksService {\n    constructor(\n        @InjectRepository(TaskRepository)\n        private taskRepository: TaskRepository,\n    ) {};\n}\n```\n\n```text\nimport { MongoRepository } from 'typeorm'\n\nimport { Task } from './task.entity'\n\n@Injectable()\nexport class TasksService {\n    constructor(\n        @InjectRepository(Task)\n        private taskRepository: MongoRepository<Task>,\n    ) {};\n}\n```\n\n```text\nTaskRepository\n```\n\n```text\nTask\n```\n\n```text\ntask.entity.ts\n```\n\n```text\nTaskService\n```\n\n```text\nTask\n```\n\n```text\nTaskRepository\n```\n\n```text\nTaskRepository\n```\n\n```text\nyarn upgrade @nestjs/typeorm@8.0.0\n```\n\n```text\nyarn upgrade typeorm@0.2.32\n```\n\n========================================\n\nComments:\n- Found solutions here: stackoverflow.com/questions/72549668/&hellip; stackoverflow.com/questions/72957962/&hellip;\n- I tried that but it gives this error: `ERROR [ExceptionHandler] Nest can't resolve dependencies of the TasksService (?). Please make sure that the argument TaskRepository at index [0] is available in the TasksModule context.` and if I use `imports: [TypeOrmModule.forFeature([Task]), TypeOrmModule.forFeature([TaskRepository])],` instead, I get the same error as before.\n- @SAIFALI Updated my answer. Can you check?\n- thanks for the update, it works fine now but now I'm using MongoRepository instead of a custom built repository, I'll try using my custom repository later though and check how I can get it to work, thanks.\n- I actually got my custom repository working too, I just replaced: `private taskRepository: MongoRepository,` with: `private taskRepository: TaskRepository,` And in my repository file I replaced: `export class TasksRepository extends Repository {}` with: `export class TasksRepository extends Repository {}` Not sure if it's the right way but I got it working with my custom repository.","metadata":{"transformedAt":"2026-08-18T18:33:02.466Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":356,"estimatedTokens":2943}}754{"id":"stack-75021981","source":"stackoverflow","questionId":75021981,"title":"NestJS / Typescript error TS2304 - Cannot find name 'Get'","tags":["typescript","nestjs"],"text":"Title: NestJS / Typescript error TS2304 - Cannot find name 'Get'\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am getting this error to compile a file.\n\n[ERROR] 17:58:11 โจฏ Unable to compile TypeScript: src/main.ts(5,6):\nerror TS2304: Cannot find name 'Get'.\n\nThis is is my `main.ts` file\n\n```\nimport {Controller, Module } from \"@nestjs/common\";\nimport {NestFactory} from \"@nestjs/core\";\n@Controller()\nclass AppController {\n @Get()\n getRootRoute() {\n return \"Hi, there!\";\n }\n}\n\n@Module({\n controllers: [AppController]\n})\nclass AppModule {}\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n await app.listen(3000);\n}\nbootstrap()\n```\n\n========================================\n\nTop Answer:\nu neeed to import {Get} the dependencies from @nestjs/common\n\n========================================\n\nCode:\n```text\nimport {Controller, Module } from \"@nestjs/common\";\nimport {NestFactory} from \"@nestjs/core\";\n@Controller()\nclass AppController {\n    @Get()\n    getRootRoute() {\n        return \"Hi, there!\";\n    }\n}\n\n@Module({\n    controllers: [AppController]\n})\nclass AppModule {}\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n\n    await app.listen(3000);\n}\nbootstrap()\n```\n\n```text\nmain.ts\n```\n\n```text\nGet\n```\n\n```text\n@nestjs/common\n```\n\n========================================\n\nComments:\n- Have you imported `Get` ?\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":85,"estimatedTokens":409}}755{"id":"stack-73898438","source":"stackoverflow","questionId":73898438,"title":"Does the Nestjs controller method have to be async if it returns a promise?","tags":["asynchronous","controller","nestjs"],"text":"Title: Does the Nestjs controller method have to be async if it returns a promise?\nTags: asynchronous, controller, nestjs\nSource: Stack Overflow\n\nQuestion:\nVery simple general question:\n\n```\n@Controller('something')\nclass SomeController {\n @Get()\n foobar() {\n return foo() // this returns a promise\n }\n}\n```\n\nSo in such a case, do I have to make the `foobar()` controller method async?\nMy understanding is that this is not necessary. NestJS will resolve the returned promise automatically. Making the method async is only needed if I wanna `await` inside.\n\nIs this correct?\n\n========================================\n\nCode:\n```text\n@Controller('something')\nclass SomeController {\n  @Get()\n  foobar() {\n     return foo() // this returns a promise\n  }\n}\n```\n\n```text\nfoobar()\n```\n\n```text\nawait\n```\n\n```text\nasync\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":46,"estimatedTokens":204}}756{"id":"stack-64593582","source":"stackoverflow","questionId":64593582,"title":"NestJS Fastify Authentication","tags":["passport.js","nestjs","fastify","nestjs-fastify"],"text":"Title: NestJS Fastify Authentication\nTags: passport.js, nestjs, fastify, nestjs-fastify\nSource: Stack Overflow\n\nQuestion:\nSo I replaced ExpressJS with Fastify, but my problem is Nest-Passport doesn't support fastify, do we have an alternative for Nest-Passport? or any solutions on how to secure RestAPI in nestJS using a token?\n\n========================================\n\nTop Answer:\nI dont kown if this is the correct manner. But if I change the default jwt extractor\n\n`ExtractJwt.fromAuthHeaderAsBearerToken`\n\n(described within the doc ) by a custom one it works.\n\n```\nconst fromFastifyAuthHeaderAsBearerToken = (request: FastifyRequest): string => {\nconst auth = request.headers['authorization'];\nconst token = auth?.split(' ')[1];\nreturn token;\n}\n```\n\n========================================\n\nCode:\n```text\n@nestjs/jwt\n```\n\n```text\njsonwebtoken\n```\n\n```text\nconst fromFastifyAuthHeaderAsBearerToken = (request: FastifyRequest): string => {\nconst auth = request.headers['authorization'];\nconst token = auth?.split(' ')[1];\nreturn token;\n}\n```\n\n```text\nExtractJwt.fromAuthHeaderAsBearerToken\n```\n\n```js\napp.getHttpAdapter()\n        .getInstance()\n        .addHook('onRequest', (request, reply, done) => {\n            reply.setHeader = function (key, value) {\n                return this.raw.setHeader(key, value);\n            };\n            reply.end = function () {\n                this.raw.end();\n            };\n            request.res = reply;\n            done();\n        });\n```\n\n========================================\n\nComments:\n- This would be the correct link github.com/mikenicholson/&hellip;\n- You can also use it like in code like JWT strategy `jwtFromRequest: (request: fastify.FastifyRequest) => { console.log('As it is if not signed', request?.cookies?.Authentication); console.log('After unsigning the cookie', request?.unsignCookie(request.cookies?.Authentication)); }`","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":67,"estimatedTokens":473}}757{"id":"stack-67340588","source":"stackoverflow","questionId":67340588,"title":"NestJS - How to register dynamic module provider multiple times using different configuration?","tags":["node.js","typescript","nestjs"],"text":"Title: NestJS - How to register dynamic module provider multiple times using different configuration?\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a knex module which is implemented like this:\n\n```\nimport { DynamicModule, Module } from '@nestjs/common';\nimport { Knex, knex } from 'knex';\nimport { WINSTON_MODULE_PROVIDER } from 'nest-winston';\nimport { Logger } from 'winston';\n\nexport const KNEX_MODULE = 'KNEX_MODULE';\n\n@Module({})\nexport class KnexModule {\n static register(options: Knex.Config): DynamicModule {\n return {\n module: KnexModule,\n providers: [\n {\n inject: [WINSTON_MODULE_PROVIDER],\n provide: KNEX_MODULE,\n useFactory: (logger: Logger) => {\n logger.info('Creating new knex instance', {\n context: KnexModule.name,\n tags: ['instance', 'knex', 'create'],\n });\n return knex(options);\n },\n },\n ],\n exports: [KNEX_MODULE],\n };\n }\n}\n```\n\nMy application requires access to multiple databases, I know I can do that by creating multiple knex instances. So I tried to register the module twice, passing different configurations. However, the module only registered once. The second register call seems to be reusing the existing object instead of creating a new knex instance.\n\nWhat is the correct way to generate multiple providers, depending on the configuration passed? The closest thing I found is the forFeature functions in typeORM and Sequelize\n\n========================================\n\nCode:\n```js\nimport { DynamicModule, Module } from '@nestjs/common';\nimport { Knex, knex } from 'knex';\nimport { WINSTON_MODULE_PROVIDER } from 'nest-winston';\nimport { Logger } from 'winston';\n\nexport const KNEX_MODULE = 'KNEX_MODULE';\n\n@Module({})\nexport class KnexModule {\n  static register(options: Knex.Config): DynamicModule {\n    return {\n      module: KnexModule,\n      providers: [\n        {\n          inject: [WINSTON_MODULE_PROVIDER],\n          provide: KNEX_MODULE,\n          useFactory: (logger: Logger) => {\n            logger.info('Creating new knex instance', {\n              context: KnexModule.name,\n              tags: ['instance', 'knex', 'create'],\n            });\n            return knex(options);\n          },\n        },\n      ],\n      exports: [KNEX_MODULE],\n    };\n  }\n}\n```\n\n```js\nimport { DynamicModule, Module } from '@nestjs/common';\nimport { Knex, knex } from 'knex';\nimport { WINSTON_MODULE_PROVIDER } from 'nest-winston';\nimport { Logger } from 'winston';\n\nexport const KNEX_MODULE = 'KNEX_MODULE';\n\n@Module({})\nexport class KnexModule {\n  static register(token: string, options: Knex.Config): DynamicModule {\n    return {\n      module: KnexModule,\n      providers: [\n        {\n          inject: [WINSTON_MODULE_PROVIDER],\n          provide: token,\n          useFactory: (logger: Logger) => {\n            logger.info('Creating new knex instance', {\n              context: KnexModule.name,\n              tags: ['instance', 'knex', 'create'],\n            });\n            return knex(options);\n          },\n        },\n      ],\n      exports: [token],\n    };\n  }\n}\n```\n\n```js\n@Module({\n  imports: [KnexModule.register(CatRepository.KNEX_TOKEN, knexConfigs)],\n  providers: [CatRepository, CatService],\n  controllers: [CatController],\n  exports: [CatService],\n})\nexport class CatModule {}\n```\n\n```js\n@Injectable()\nexport class CatRepository implements Repository<Cat> {\n  // eslint-disable-next-line no-useless-constructor\n  public static KNEX_TOKEN = 'KNEX_CATS_TOKEN';\n\n  // eslint-disable-next-line no-useless-constructor\n  constructor(\n    @Inject(CatRepository.KNEX_TOKEN)\n    protected knex: Knex,\n  ) {}\n\n  ...\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":135,"estimatedTokens":895}}758{"id":"stack-63460693","source":"stackoverflow","questionId":63460693,"title":"Typescript: meaning of ? and ! in class properties","tags":["typescript","nestjs","typeorm"],"text":"Title: Typescript: meaning of ? and ! in class properties\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\n@Column({ name: 'device_kind', type: 'int2', nullable: false })\ndeviceKind?: number;\n```\n\nCan anyone explain this code? I didn't understand why they added the '?' mark. and some of them has '!' instead of question mark.\nWhat do they mean?\n\n========================================\n\nCode:\n```text\n@Column({ name: 'device_kind', type: 'int2', nullable: false })\ndeviceKind?: number;\n```\n\n```js\ntype Foo = {\n  prop1?: number\n}\n```\n\n```js\nclass Foo {\n  // Typescript does not complain about `a` because we set it in the constructor\n  public a: number;\n\n  // Typescript will complain about `b` because we forgot it.\n  public b: number;\n\n  // Typescript will not complain about `c` because we told it not to.\n  public c!: number;\n\n  // Typescript will not complain about `d` because it's optional and is\n  // allowed to be undefined.\n  public d?: number;\n\n  constructor() {\n    this.a = 5;\n  }\n\n}\n```\n\n```text\nprop1\n```\n\n```text\n!\n```\n\n```text\nc!\n```\n\n```text\nd?\n```\n\n```text\nd\n```\n\n```text\nnumber\n```\n\n```text\nundefined\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":76,"estimatedTokens":287}}759{"id":"stack-61796828","source":"stackoverflow","questionId":61796828,"title":"Fastify & NestJS - How to set response headers in interceptor","tags":["header","nestjs","fastify"],"text":"Title: Fastify & NestJS - How to set response headers in interceptor\nTags: header, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set the response headers in my interceptor, and have had no luck with any method I've found yet. I've tried:\n\n```\nconst request = context.switchToHttp().getRequest();\n const response = context.switchToHttp().getResponse();\n \n return next.handle();\n```\n\n- `request.res.headers['my-header'] = 'xyz'`\n\n- `response.header('my-header', 'xyz')`\n\n- `response.headers['my-header'] = 'xyz'`\n\n- `response.header['my-header'] = 'xyz'`\n\nwith no luck. The first option says that res is undefined, the second \"Cannot read property 'Symbol(fastify.reply.headers)' of undefined\", and the others just do nothing.\n\n========================================\n\nCode:\n```text\nconst request = context.switchToHttp().getRequest();\n const response = context.switchToHttp().getResponse();\n <snippet of code from below>\n return next.handle();\n```\n\n```text\nrequest.res.headers['my-header'] = 'xyz'\n```\n\n```text\nresponse.header('my-header', 'xyz')\n```\n\n```text\nresponse.headers['my-header'] = 'xyz'\n```\n\n```text\nresponse.header['my-header'] = 'xyz'\n```\n\n```js\n@Injectable()\nexport class HeaderInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next.handle().pipe(\n      tap(() => {\n        const res = context.switchToHttp().getResponse<FastifyReply<ServerResponse>>();\n        res.header('foo', 'bar');\n      })\n    );\n  }\n}\n```\n\n```js\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [\n    AppService,\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: HeaderInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```sh\nโ–ถ curl http://localhost:3000 -v\n* Rebuilt URL to: http://localhost:3000/\n*   Trying 127.0.0.1...\n* TCP_NODELAY set\n* Connected to localhost (127.0.0.1) port 3000 (#0)\n> GET / HTTP/1.1\n> Host: localhost:3000\n> User-Agent: curl/7.54.0\n> Accept: */*\n> \n< HTTP/1.1 200 OK\n< foo: bar\n< content-type: text/plain; charset=utf-8\n< content-length: 12\n< Date: Thu, 14 May 2020 14:09:22 GMT\n< Connection: keep-alive\n< \n* Connection #0 to host localhost left intact\nHello World!%\n```\n\n```text\nFastifyAdapter\n```\n\n```text\nmain.ts\n```\n\n```text\n.getResponse<FastifyReply<ServerResponse>>()\n```\n\n```text\ncurl\n```\n\n```text\nfoo: bar\n```\n\n```text\nresponse.headers('my-header', 'xyz)\n```\n\n```text\nnest new\n```\n\n========================================\n\nComments:\n- I realise I was doing something wrong, response.headers does indeed work. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":133,"estimatedTokens":643}}760{"id":"stack-75156037","source":"stackoverflow","questionId":75156037,"title":"How to mock readonly property in nodejs using jest","tags":["javascript","node.js","typescript","jestjs","nestjs"],"text":"Title: How to mock readonly property in nodejs using jest\nTags: javascript, node.js, typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have the following class which has a chunk defined as an array and multiple objects get pushed into this array `this.chunk`.\n\n**SearchController.ts**\n\n```\n@Injectable()\nexport class SearchController {\n private chunk: any[] = [];\n readonly CHUNK_SIZE: number = 100;\n\n public async post(names) {\n\n this.chunk.push(names);\n\n if (this.chunk.length >= this.CHUNK_SIZE) {\n return true;\n }\n return false;\n\n }\n}\n```\n\nI want to be able to either mock the CHUNK_SIZE to a number equal to 1 or maybe be able to change the value of the `chunk.length`\n\nBelow is my test\n\nSearchController.test.ts\n\n```\nit('should return true for chunk_size 1', async () => {\n\n const actual = await queue.post({action: 'UPDATE'});\n\n expect(actual).toBeTruthy();\n });\n```\n\nI have tried using jest.spyOn() but it didn't work.\nWhat am I missing?\n\nWould really appreciate if anyone can help. thanks.\n\n========================================\n\nTop Answer:\nMy technique for such cases is to create a derived test-specific class:\n\n```\nclass SearchControllerTest extends SearchController {\n override readonly CHUNK_SIZE = 1; // property cannot be private in parent class\n}\n```\n\nโ€ฆ and then mock the *SearchController.ts* module with the new class. If necessary, I use `jest.requireActual()` to get the true value of the module.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class SearchController {\n  private chunk: any[] = [];\n  readonly CHUNK_SIZE: number = 100;\n\n  public async post(names) {\n\n    this.chunk.push(names);\n\n    if (this.chunk.length >= this.CHUNK_SIZE) {\n        return true;\n    }\n    return false;\n\n  }\n}\n```\n\n```text\nit('should return true for chunk_size 1', async () => {\n\n    const actual = await queue.post({action: 'UPDATE'});\n\n\n    expect(actual).toBeTruthy();\n  });\n```\n\n```text\nthis.chunk\n```\n\n```text\nchunk.length\n```\n\n```js\nObject.defineProperty(<instanceOfController>, 'CHUNK_SIZE', { value: <anyRandomValue>, writable: false });\n```\n\n```js\nit('should return true for chunk_size 1', async () => {\n  Object.defineProperty(queue, 'CHUNK_SIZE', { value: 1, writable: false });\n\n  const actual = await queue.post({ action: 'UPDATE' });\n  expect(actual).toBeTruthy();\n});\n```\n\n```text\nit\n```\n\n```text\nclass SearchControllerTest extends SearchController {\n  override readonly CHUNK_SIZE = 1; // property cannot be private in parent class\n}\n```\n\n```text\njest.requireActual()\n```\n\n```text\n(queue as any)['CHUNK_SIZE'] = 1\n```\n\n```text\nany\n```\n\n```text\n['someprop']\n```\n\n```text\nObject.defineProperty(queue, \"CHUNK_SIZE\", {\n  get: () => 1,\n})\n```\n\n```text\nit('should return true for chunk_size 1', async () => {\n  Object.defineProperty(queue, \"CHUNK_SIZE\", { get: () => 1 })\n\n  const actual = await queue.post({ action: 'UPDATE' });\n\n  expect(actual).toBeTruthy();\n});\n```\n\n```text\nreadonly\n```\n\n```text\nObject.defineProperty()\n```\n\n```text\nenumerable\n```\n\n```text\nconfigurable\n```\n\n========================================\n\nComments:\n- SearchController['CHUNK_SIZE'] is it?\n- @deko_39 what do you mean?\n- use SearchController['CHUNK_SIZE'] = xxx in the testing code when you need to mock that property\n- @deko_39 I can't, because CHUNK_SIZE is readonly `Cannot assign to 'CHUNK_SIZE' because it is a read-only property.`","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":179,"estimatedTokens":846}}761{"id":"stack-78000339","source":"stackoverflow","questionId":78000339,"title":"NestJS VS AdonisJS","tags":["node.js","typescript","nestjs","backend","adonis.js"],"text":"Title: NestJS VS AdonisJS\nTags: node.js, typescript, nestjs, backend, adonis.js\nSource: Stack Overflow\n\nQuestion:\nI am about to embark on a new project. So far, I have been working with ExpressJS for my backend, but I find that I am reinventing the wheel a bit too much. Since I always strive to improve my projects, I find myself spending a lot of time on technology decisions and project structure to ensure that it is clean and scalable. Therefore, I plan to switch to Nest JS or Adonis JS, as they are rather opinionated frameworks that require a certain structure and specific tools in their core.\n\nMy inclination leans more towards Adonis JS than Nest, and I would like to know if there are any members who have experience in this area or who could provide me with other information or remarks that could influence my choice of technology? (knowing that the backend of the new project I will be working on will be complex)\n\nThank you.\n\n========================================\n\nCode:\n```text\nAnd commonly this is also correct, but you still remain with your issue\n```\n\n```text\nDo i need all of this?\n```\n\n```text\nCan i handle all this complexity?\n```\n\n```text\nblack box\n```\n\n```text\nless popular\n```\n\n```text\nless community\n```\n\n```text\nless help\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":41,"estimatedTokens":314}}762{"id":"stack-79099679","source":"stackoverflow","questionId":79099679,"title":"Is there a way to configure NestJs --watch mode to not clear the terminal?","tags":["nestjs"],"text":"Title: Is there a way to configure NestJs --watch mode to not clear the terminal?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen running a new NestJs application in --watch mode I had noticed that it clears my terminal right before logging in stdout \"Starting compilation in watch mode...\".\n\nI know it is using some form of escape sequence, either `\\ec` or `\\0033\\0143` (essentially `ESC+c`) but I need so badly for that not to happen. I need the terminal not to clear.\n\nIs there a way in any form of the NestJs configuration where I can disable this?\n\nI'm running a concurrent process of multiple stdout and its clearing all of my processes for its own logs. within the concurrent process I've tried transforming the output to remove the escape characters. First, it feels a bit excessive to go down this approach as I should be able to stop NestJs from doing it in the first place.\n\n========================================\n\nCode:\n```text\n\\ec\n```\n\n```text\n\\0033\\0143\n```\n\n```text\nESC+c\n```\n\n```none\n{\n  \"compilerOptions\": {\n    \"preserveWatchOutput\": true\n  }\n}\n```\n\n```text\n--preserveWatchOutput\n```\n\n```text\ntsconfig.json\n```\n\n```text\nv.10.4.5\n```\n\n========================================\n\nComments:\n- You should have seen what AI was recommending. Thank you for this straightforward solution. Perfect for monorepos","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":52,"estimatedTokens":332}}763{"id":"stack-72810663","source":"stackoverflow","questionId":72810663,"title":"Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'","tags":["node.js","nestjs","typeorm","node-mongodb-native","node.js-typeorm"],"text":"Title: Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'\nTags: node.js, nestjs, typeorm, node-mongodb-native, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nUsing **mongodb** by **typeorm** with **nestjs** - create crud rest api\n\nWhen trying to get data by **findone()** with '**id**' . getting below error\n\nTS2345: Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'.\n\nObject literal may only specify known properties, and 'id' does not exist in type 'FindOneOptions'.\n\nCode:\n\n```\nconst result = await this.sellerRepository.findOne({ id });\n```\n\n**Entity**\n\n```\n@Entity('seller')\nexport class Seller {\n @ObjectIdColumn()\n id: ObjectID;\n @Column({\n type: 'string',\n nullable: false,\n name: 'product_name',\n })\n productName: string;\n @Column({\n name: 'short_desc',\n })\n}\n\nasync findOne(id: string): Promise {\n const result = await this.sellerRepository.findOne({ id });\n return result;\n }\n```\n\nhttps://i.sstatic.net/zyD5G.png\n\n========================================\n\nTop Answer:\nYou should use findOneBy\n\n```\nfindOne(id: number): Promise {\n return this.usersRepository.findOneBy({ id: id });\n}\n```\n\n========================================\n\nCode:\n```text\nconst result = await this.sellerRepository.findOne({ id });\n```\n\n```text\n@Entity('seller')\nexport class Seller {\n  @ObjectIdColumn()\n  id: ObjectID;\n  @Column({\n    type: 'string',\n    nullable: false,\n    name: 'product_name',\n  })\n  productName: string;\n  @Column({\n    name: 'short_desc',\n  })\n}\n\nasync findOne(id: string): Promise<Seller> {\n    const result = await this.sellerRepository.findOne({ id });\n    return result;\n  }\n```\n\n```text\nimport { ObjectID } from 'mongodb';\n async findOne(id: string): Promise<Seller> {\n    const result = await this.sellerRepository.findOne(new ObjectID(id));\n    return result;\n  }\n```\n\n```text\nnew ObjectID(id)\n```\n\n```text\nimport { ObjectID } from 'mongodb';\n```\n\n```text\ndeclare module 'mongodb'\n```\n\n```text\nindex.d.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntypeRoots\n```\n\n```text\n\"typeRoots\": [ \"./typings\", \"./node_modules/@types/\" ]\n```\n\n```text\nfithOneBy({id})\n```\n\n```text\nfindOne(id)\n```\n\n```text\nfindOne(id: number): Promise<User> {\n   return this.usersRepository.findOneBy({ id: id });\n}\n```\n\n```text\nimport { FindOptionsWhere } from 'typeorm';\n```\n\n```text\nconst result = await this.sellerRepository.findOne({ id: id as FindOptionsWhere<Seller> });\n```\n\n```js\nconst prodId = await this.productEntity.findOne({\n  where: {\n    column_name_in_Entity: defined initializer\n  }\n})\n```\n\n========================================\n\nComments:\n- It's being discussed on github at github.com/typeorm/typeorm/issues/8939\n- Both tried but there is no use. I think typeorm gives this kind of error for mongodb\n- Are you sure the error remains the same?\n- yes..but got solution in another way..will post it...thank you for your response\n- Already tried with the above but did not work. It gives the same error message.","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":159,"estimatedTokens":749}}764{"id":"stack-64572885","source":"stackoverflow","questionId":64572885,"title":"NestJS (7.5.1) not watching assets in watch mode","tags":["nestjs","livereload"],"text":"Title: NestJS (7.5.1) not watching assets in watch mode\nTags: nestjs, livereload\nSource: Stack Overflow\n\nQuestion:\nFor some reason, the nest start --watch is not watching any non-typescript assets. Even though I've followed exactly what this doc said: https://docs.nestjs.com/cli/monorepo#assets I can't seem to figure this out. I've tried in standard mode and mono-repo mode to no success. I started a new project just to demonstrate what I'm seeing.\n\nNest --version: 7.5.1\n\nWhen running command: `npm run start:dev` I would expect to see that every time I update my html files, then I should see the \"incremental file change detected\" message and the app reloads but nothing is happening after the initial app load. On initial app load, the files do get copied to the dist folder so thats fine but I would expect that as I'm developing and updating these files, the app should also be reloading but it only seems to work for typescript files. Am I misunderstanding what this should be doing?\n\nHere's the nest-cli.json:\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\":{\n \"assets\": [\"**/*.html\"],\n \"watchAssets\": true\n }\n}\n```\n\nAny ideas??\n\n========================================\n\nTop Answer:\nAssets configuration works as described in documentation. VS Code wasnโ€™t registering file changes so I proved it by manually editing a file outside or the IDE and it works. Closing question\n\n========================================\n\nCode:\n```json\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\":{\n    \"assets\": [\"**/*.html\"],\n    \"watchAssets\": true\n  }\n}\n```\n\n```text\nnpm run start:dev\n```\n\n```text\n\"assets\": [\n  { \"include\": \"**/*.html\", \"watchAssets\": true }\n]\n```\n\n========================================\n\nComments:\n- Thanks but I had already tried that as well and it still didnโ€™t work.\n- Weird, it works fine for me. Is your project on github or something where I could take a closer look?\n- Ah I figured out the problem. It looks like its related to my IDE. I'm using Visual Studio Code and noticed that when I save my file in that IDE, its not triggering the change for some reason. I edited the html file in VIM and that indeed does trigger the watch to register that the file changed and it reloads correctly. Visual Studio Code appears to be saving my file to disk when I check diffs and timestamps to ensure but for some reason its not triggering the watch. Either way, Nest is working properly with the config above - thank you!\n- I`m running into same issue, did you found a way to make it works with VSCODE?","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":62,"estimatedTokens":648}}765{"id":"stack-58135998","source":"stackoverflow","questionId":58135998,"title":"How to use value which returned from controller? Testing controllers on NestJs","tags":["node.js","unit-testing","testing","nestjs","sequelize-typescript"],"text":"Title: How to use value which returned from controller? Testing controllers on NestJs\nTags: node.js, unit-testing, testing, nestjs, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nController and method for testing:\n\n```\nimport { Controller, Get, Response, HttpStatus, Param, Body, Post, Request, Patch, Delete, Res } from '@nestjs/common';\n@Controller('api/parts')\nexport class PartController {\n constructor(private readonly partsService: partsService) { }\n\n @Get()\n public async getParts(@Response() res: any) {\n const parts = await this.partsService.findAll();\n return res.status(HttpStatus.OK).json(parts);\n }\n}\n```\n\nAnd this is unit test which must test getParts method:\n\n```\ndescribe('PartsController', () => {\n let partsController: PartsController;\n let partsService: partsService;\n\n beforeEach(async () => {\n partsService = new partsService(Part);\n partsController= new PartsController(partsService);\n });\n\n describe('findAll', () => {\n it('should return an array of parts', async () => {\n const result = [{ name: 'TestPart' }] as Part[];\n\n jest.spyOn(partsService, 'findAll').mockImplementation(async () => result);\n\n const response = {\n json: (body?: any) => {\n expect(body).toBe(result);\n },\n status: (code: number) => response,\n };\n\n await partsController.getParts(response);\n });\n });\n});\n```\n\nThis test works correctly, but I think this is a bad solution. When I investigated this problem, I saw this option:\n\n```\nconst response = {\n json: (body?: any) => {},\n status: (code: number) => response,\n};\nexpect(await partsController.getParts(response)).toBe(result);\n```\n\nBut when I try it my test don't work, cause await partsController.getParts(response) // undefined\nSo what should I do to make my test look good?\n\nIn solution I use: nodeJS sequelize, nestJS, typescript\n\n========================================\n\nCode:\n```text\nimport { Controller, Get, Response, HttpStatus, Param, Body, Post, Request, Patch, Delete, Res } from '@nestjs/common';\n@Controller('api/parts')\nexport class PartController {\n  constructor(private readonly partsService: partsService) { }\n\n  @Get()\n  public async getParts(@Response() res: any) {\n    const parts = await this.partsService.findAll();\n    return res.status(HttpStatus.OK).json(parts);\n  }\n}\n```\n\n```text\ndescribe('PartsController', () => {\n  let partsController: PartsController;\n  let partsService: partsService;\n\n  beforeEach(async () => {\n    partsService = new partsService(Part);\n    partsController= new PartsController(partsService);\n  });\n\n  describe('findAll', () => {\n    it('should return an array of parts', async () => {\n      const result = [{ name: 'TestPart' }] as Part[];\n\n      jest.spyOn(partsService, 'findAll').mockImplementation(async () => result);\n\n      const response = {\n        json: (body?: any) => {\n          expect(body).toBe(result);\n        },\n        status: (code: number) => response,\n      };\n\n      await partsController.getParts(response);\n    });\n  });\n});\n```\n\n```text\nconst response = {\n  json: (body?: any) => {},\n  status: (code: number) => response,\n};\nexpect(await partsController.getParts(response)).toBe(result);\n```\n\n```js\ndescribe('Parts Controller', () => {\n    let partsController: PartsController;\n    let partsService: PartsService;\n\n    beforeEach(async () => {\n        // magic happens with the following line\n        const module = await Test.createTestingModule({\n            controllers: [\n                PartsController\n            ],\n            providers: [\n                PartsService\n                //... any other needed import goes here\n            ]\n        }).compile();\n\n        partsService = module.get<PartsService>(PartsService);\n        partsController = module.get<PartsController>(PartsController);\n    });\n\n    // The next 4 lines are optional and depends on whether you would need to perform these cleanings of the mocks or not after each tests within this describe section\n    afterEach(() => {\n        jest.restoreAllMocks();\n        jest.resetAllMocks();\n    });\n\n    it('should be defined', () => {\n        expect(partsController).toBeDefined();\n        expect(partsService).toBeDefined();\n    });\n\n    describe('findAll', () => {\n      it('should return an array of parts', async () => {\n        const result: Part[] = [{ name: 'TestPart' }];\n\n        jest.spyOn(partsService, 'findAll').mockImplementation(async (): Promise<Part[]> => Promise.resolve(result));\n\n        const response = {\n            json: (body?: any) => {},\n            status: (code: number) => HttpStatus.OK,\n        };\n\n        expect(await partsController.getParts(response)).toBe(result);\n      });\n    }); \n});\n```\n\n```js\nimport { Controller, Get, Response, HttpStatus, Param, Body, Post, Request, Patch, Delete, Res } from '@nestjs/common';\nimport { Response } from 'express';\n\n@Controller('api/parts')\nexport class PartController {\n  constructor(private readonly partsService: partsService) { }\n\n  @Get()\n  public async getParts(@Response() res: Response) { // <= see Response type from express being used here\n    const parts = await this.partsService.findAll();\n    return res.status(HttpStatus.OK).json(parts);\n  }\n}\n```\n\n========================================\n\nComments:\n- Is there any reason you want to inject the response and manage it your self instead of having Nest take care of it for you?\n- I am following your solution but I keep getting `Type '{ json: (body?: User[]) => void; status: (code: number) => HttpStatus; }' is missing the following properties from type 'Response': sendStatus, links, send, jsonp, and 78 more`. How would u avoid including the all the parameters of `Response` ?\n- @asus do you have a solutin on that\n- have you tried wrapping your mocked object with `as Response` so TypeScript won't cry about the missing props you eventually don't need for your test purposes ?\n- I was running into this as well, if you type the partial as `as any as Response` then you will get the type errors to go away. Got that from stackoverflow.com/questions/57964299/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":194,"estimatedTokens":1505}}766{"id":"stack-72686788","source":"stackoverflow","questionId":72686788,"title":"How to use EJS template engine with NestJS?","tags":["javascript","node.js","typescript","nestjs","ejs"],"text":"Title: How to use EJS template engine with NestJS?\nTags: javascript, node.js, typescript, nestjs, ejs\nSource: Stack Overflow\n\nQuestion:\nI would like to use EJS as my template engine in NestJS. With Express I can configure EJS in the main file like this:\n\n```\napp.set(\"view engine\", \"ejs\");\n```\n\nHow can I best implement this with NestJS? Nestjs does not ship with a `.set` method.\n\n========================================\n\nCode:\n```text\napp.set(\"view engine\", \"ejs\");\n```\n\n```text\n.set\n```\n\n```text\nnpm i ejs\n```\n\n```text\n// main.ts\nimport { NestFactory } from '@nestjs/core';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { join } from 'path';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(\n    AppModule,\n  );\n  /*\n     Here it's assumed that public and views are in the root directory,\n     alongside src. You can put them wherever you want, \n     just use the correct path if you use another folder.\n  */\n  app.useStaticAssets(join(__dirname, '..', 'public'));\n  app.setBaseViewsDir(join(__dirname, '..', 'views'));\n  app.setViewEngine('ejs');\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n// app.controller.ts\nimport { Get, Controller, Render } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  @Render('index')\n  root() {\n    return { message: 'Hello world!' };\n  }\n}\n```\n\n```text\n<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>App</title>\n  </head>\n  <body>\n    <%= message %>\n  </body>\n</html>\n```\n\n```text\napp.setViewEngine('ejs')\n```\n\n```text\nmain.ts\n```\n\n```text\npublic\n```\n\n```text\nviews\n```\n\n```text\nejs\n```\n\n```text\nindex.ejs\n```\n\n```text\nmessage\n```\n\n```text\nmessage\n```\n\n```text\nindex.ejs\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":115,"estimatedTokens":447}}767{"id":"stack-73189707","source":"stackoverflow","questionId":73189707,"title":"how to do Prisma soft delete with NestJS?","tags":["nestjs","prisma"],"text":"Title: how to do Prisma soft delete with NestJS?\nTags: nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI had tried to implement this method in my application. but I don't have depth knowledge of Prisma. Kindly explain that with some examples.\n\n========================================\n\nTop Answer:\nwith depracation of middleware now its done by using extensions, you can check this article I wrote https://medium.com/@erciliomarquesmanhica/implementing-soft-delete-in-prisma-using-client-extensions-a-step-by-step-guide-for-nestjs-51a9d0716831 but here is short version of it:\n\n**Step 1: Setting up Prisma**\n\nI assume you already did this, if not please this docs Prisma on Nestjs.\n\n**Step 2: Adding Soft Delete Field**\n\nNow that we have Prisma configured, we need to add the flag property on our models, this can be a boolean or date, usually people use date to also store when it was deleted. so in this step we will add the property deleted_at.\n\n**Step 3: Implementing Soft Delete Logic**\n\nSo if your did the step one correctly you endup with a PrismaService , so in order to add that soft delete logic to our prisma service we used to use middlwares, but it is depracated now, and we are currently doing it by adding client extensions .\n\nSo lets create those extensions then:\n\nCreate a file to hold your prisma extensions can call it prisma.extensions.ts\n\n```\nimport { Prisma } from '@prisma/client';\n \n //extension for soft delete\n export const softDelete = Prisma.defineExtension({\n name: 'softDelete',\n model: {\n $allModels: {\n async delete(\n this: M,\n where: Prisma.Args['where'],\n ): Promise> {\n const context = Prisma.getExtensionContext(this);\n \n return (context as any).update({\n where,\n data: {\n deleted_at: new Date(),\n },\n });\n },\n },\n },\n });\n \n //extension for soft delete Many\n export const softDeleteMany = Prisma.defineExtension({\n name: 'softDeleteMany',\n model: {\n $allModels: {\n async deleteMany(\n this: M,\n where: Prisma.Args['where'],\n ): Promise> {\n const context = Prisma.getExtensionContext(this);\n \n return (context as any).updateMany({\n where,\n data: {\n deleted_at: new Date(),\n },\n });\n },\n },\n },\n });\n \n //extension for filtering soft deleted rows from queries\n export const filterSoftDeleted = Prisma.defineExtension({\n name: 'filterSoftDeleted',\n query: {\n $allModels: {\n async $allOperations({ model, operation, args, query }) {\n if (\n operation === 'findUnique' ||\n operation === 'findFirst' ||\n operation === 'findMany'\n ) {\n args.where = { ...args.where, deleted_at: null };\n return query(args);\n }\n return query(args);\n },\n },\n },\n });\n```\n\nThese are pretty self explanatory extensions, if you are having problems understanding them I recommend you to go ready the docs client extensions, its pretty straight forward.\n\n**Step 4: Adding the extension to Prisma Service**\n\nSo this step can be a little bit confusing. why you would ask!\n\nFirst by intuition you will be tempeted to just go on PrismaService and add the extensions like this:\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\nimport {\n filterSoftDeleted,\n softDelete,\n softDeleteMany,\n} from './prisma.extension';\n\n@Injectable()\nexport class DatabaseService\n extends PrismaClient \n implements OnModuleInit\n{\n async onModuleInit() {\n await this.$connect();\n this.$extends(softDelete) //adding extensions\n .$extends(softDeleteMany)\n .$extends(filterSoftDeleted);\n }\n}\n```\n\nAnd I dont blame you, I first did it like this, and didnt work, why? because you need to add the extensions explicitly to the client. if its not clear dont worry, you will get it as we go.\n\nSo how do we actually add the extensions to the Prisma Service?\n\nWe will add the extension to PrismaService by extending a CustomPrismaClient of ours, which already has the extensions added. what I mean by that is that we will create a CustomPrismaClient and then extend it on our PrismaService.\n\nSo first lets create the CustomPrismaClient. create a file, can call it custom-prisma-client.ts and add these code:\n\n```\nimport { PrismaClient } from '@prisma/client';\nimport {\n filterSoftDeleted,\n softDelete,\n softDeleteMany,\n} from './prisma.extension';\n\n//function to give us a prismaClient with extensions we want\nexport const customPrismaClient = (prismaClient: PrismaClient) => {\n return prismaClient\n .$extends(softDelete) //here we add our created extensions\n .$extends(softDeleteMany)\n .$extends(filterSoftDeleted);\n};\n\n//Our Custom Prisma Client with the client set to the customPrismaClient with extension\nexport class PrismaClientExtended extends PrismaClient {\n customPrismaClient: CustomPrismaClient;\n\n get client() {\n if (!this.customPrismaClient)\n this.customPrismaClient = customPrismaClient(this);\n\n return this.customPrismaClient;\n }\n}\n\n//Create a type to our funtion\nexport type CustomPrismaClient = ReturnType;\n```\n\nSo I tried to add comments for increase your understanding, but basically we are creating a helper function that given a prismaClient it returns us that prismaClient with our extensions. and then we use that function on our PrismaClientExtended to set extensions.\n\nWIth that done, now all we need to do is extend our PrismaClientExtended class on PrismaService:\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\n\n@Injectable()\nexport class DatabaseService\n extends PrismaClientExtended // we now extending PrismaClientExtended\n implements OnModuleInit\n{\n async onModuleInit() {\n await this.$connect();\n }\n}\n```\n\n**Step 5: How to use it?**\n\nWell, I am adding this step because if you are like me, all my queries where done in some way that would no work with extensions, let me show you:\n\n```\nremove(id: number): Promise {\n return this.prismaService.posts.delete({\n where: {\n id: id,\n },\n });\n}\n```\n\nso this usually works fine, but remember we added our extensions to the client of our prismaService, thats why we need to use the client, and if you look closely the parameters already expects the where object, that why you send the object directy.\n\n```\nremove(id: number): Promise {\n return this.prismaService.client.posts.delete({\n id: id,\n });\n}\n```\n\ncompare these two closely, many people will rush these step and fail.\n\nthe same goes to the deleteMany method:\n\n```\nremoveAllPostsByUserId(id: number): Promise {\n return this.prismaService.client.posts.deleteMany({\n user_id: id,\n });\n}\n```\n\nand for the rest of queries you just need to use client, like this:\n\n```\nfindAll(): Promise {\n return this.prismaService.client.posts.findMany({\n include: { comments: true },\n });\n}\n```\n\n========================================\n\nCode:\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Post {\n  id      Int     @id @default(autoincrement())\n  title   String\n  content String?\n  user    User?   @relation(fields: [userId], references: [id])\n  userId  Int?\n  tags    Tag[]\n  views   Int     @default(0)\n  deleted Boolean @default(false)\n}\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n\nconst prisma = new PrismaClient({})\n\nasync function main() {\n  /***********************************/\n  /* SOFT DELETE MIDDLEWARE */\n  /***********************************/\n\n  prisma.$use(async (params, next) => {\n    // Check incoming query type\n    if (params.model == 'Post') {\n      if (params.action == 'delete') {\n        // Delete queries\n        // Change action to an update\n        params.action = 'update'\n        params.args['data'] = { deleted: true }\n      }\n      if (params.action == 'deleteMany') {\n        // Delete many queries\n        params.action = 'updateMany'\n        if (params.args.data != undefined) {\n          params.args.data['deleted'] = true\n        } else {\n          params.args['data'] = { deleted: true }\n        }\n      }\n    }\n    return next(params)\n  })\n```\n\n```text\nschema.prisma\n```\n\n```text\n{ deleted: true }\n```\n\n```text\nscript.ts\n```\n\n```text\nimport { Prisma } from '@prisma/client';\n    \n    //extension for soft delete\n    export const softDelete = Prisma.defineExtension({\n      name: 'softDelete',\n      model: {\n        $allModels: {\n          async delete<M, A>(\n            this: M,\n            where: Prisma.Args<M, 'delete'>['where'],\n          ): Promise<Prisma.Result<M, A, 'update'>> {\n            const context = Prisma.getExtensionContext(this);\n    \n            return (context as any).update({\n              where,\n              data: {\n                deleted_at: new Date(),\n              },\n            });\n          },\n        },\n      },\n    });\n    \n    //extension for soft delete Many\n    export const softDeleteMany = Prisma.defineExtension({\n      name: 'softDeleteMany',\n      model: {\n        $allModels: {\n          async deleteMany<M, A>(\n            this: M,\n            where: Prisma.Args<M, 'deleteMany'>['where'],\n          ): Promise<Prisma.Result<M, A, 'updateMany'>> {\n            const context = Prisma.getExtensionContext(this);\n    \n            return (context as any).updateMany({\n              where,\n              data: {\n                deleted_at: new Date(),\n              },\n            });\n          },\n        },\n      },\n    });\n    \n    //extension for filtering soft deleted rows from queries\n    export const filterSoftDeleted = Prisma.defineExtension({\n      name: 'filterSoftDeleted',\n      query: {\n        $allModels: {\n          async $allOperations({ model, operation, args, query }) {\n            if (\n              operation === 'findUnique' ||\n              operation === 'findFirst' ||\n              operation === 'findMany'\n            ) {\n              args.where = { ...args.where, deleted_at: null };\n              return query(args);\n            }\n            return query(args);\n          },\n        },\n      },\n    });\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\nimport {\n  filterSoftDeleted,\n  softDelete,\n  softDeleteMany,\n} from './prisma.extension';\n\n@Injectable()\nexport class DatabaseService\n  extends PrismaClient \n  implements OnModuleInit\n{\n  async onModuleInit() {\n    await this.$connect();\n    this.$extends(softDelete) //adding extensions\n      .$extends(softDeleteMany)\n      .$extends(filterSoftDeleted);\n  }\n}\n```\n\n```text\nimport { PrismaClient } from '@prisma/client';\nimport {\n  filterSoftDeleted,\n  softDelete,\n  softDeleteMany,\n} from './prisma.extension';\n\n//function to give us a prismaClient with extensions we want\nexport const customPrismaClient = (prismaClient: PrismaClient) => {\n  return prismaClient\n    .$extends(softDelete) //here we add our created extensions\n    .$extends(softDeleteMany)\n    .$extends(filterSoftDeleted);\n};\n\n//Our Custom Prisma Client with the client set to the customPrismaClient with extension\nexport class PrismaClientExtended extends PrismaClient {\n  customPrismaClient: CustomPrismaClient;\n\n  get client() {\n    if (!this.customPrismaClient)\n      this.customPrismaClient = customPrismaClient(this);\n\n    return this.customPrismaClient;\n  }\n}\n\n//Create a type to our funtion\nexport type CustomPrismaClient = ReturnType<typeof customPrismaClient>;\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\n\n@Injectable()\nexport class DatabaseService\n  extends PrismaClientExtended // we now extending PrismaClientExtended\n  implements OnModuleInit\n{\n  async onModuleInit() {\n    await this.$connect();\n  }\n}\n```\n\n```text\nremove(id: number): Promise<any> {\n  return this.prismaService.posts.delete({\n    where: {\n      id: id,\n    },\n  });\n}\n```\n\n```text\nremove(id: number): Promise<any> {\n  return this.prismaService.client.posts.delete({\n      id: id,\n  });\n}\n```\n\n```text\nremoveAllPostsByUserId(id: number): Promise<any> {\n  return this.prismaService.client.posts.deleteMany({\n    user_id: id,\n  });\n}\n```\n\n```text\nfindAll(): Promise<Posts[]> {\n  return this.prismaService.client.posts.findMany({\n    include: { comments: true },\n  });\n}\n```\n\n========================================\n\nComments:\n- What do you mean by `soft delete`? Once data in Prisma is deleted, it's permanently deleted. There is no concept of a soft delete unless you implement it at the database level. Please see the Stack Overflow \"How to Ask\" guide for how to ask a good question - stackoverflow.com/help/how-to-ask\n- @SheaHunterBelsky, it is a good question. In fact, there is documentation for it. Don't judge people too quickly! prisma.io/docs/concepts/components/prisma-client/middleware/&zwnj;&#8203;&hellip;\n- This comment was a year ago - My original comment meant to say that Prisma doesn't have this functionality, and it had to be added. At the time of my original comment, that documentation did not exist!\n- I found this package which handles more things github.com/olivierwilkinson/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":481,"estimatedTokens":3238}}768{"id":"stack-73374814","source":"stackoverflow","questionId":73374814,"title":"Swagger + Nest.js doesn't remove empty DTO and model","tags":["swagger","nestjs","swagger-ui"],"text":"Title: Swagger + Nest.js doesn't remove empty DTO and model\nTags: swagger, nestjs, swagger-ui\nSource: Stack Overflow\n\nQuestion:\nI was creating documentation for `Nest.js` API using `Swagger`. The problem is what I removed documentation from this DTO or model, in swagger UI docs I can see it as empty object.\n\nFor example:\n\n```\nimport { IsNotEmpty } from 'class-validator';\n\nexport class PostDto {\n @IsNotEmpty()\n readonly title: string;\n\n @IsNotEmpty()\n readonly content: string;\n\n @IsNotEmpty()\n readonly description: string;\n}\n```\n\nhttps://i.sstatic.net/wN9Mm.png\n\nAlso I was trying to change name of this entity, using incognito mode, reinstall `node_modules`, but it didn't work. If I change name of this entity, it also changes there. What's wrong?\n\nWhat I want to do, is by removing this documentation decorators, not to see those empty objects.\n\n========================================\n\nCode:\n```text\nimport { IsNotEmpty } from 'class-validator';\n\nexport class PostDto {\n  @IsNotEmpty()\n  readonly title: string;\n\n  @IsNotEmpty()\n  readonly content: string;\n\n  @IsNotEmpty()\n  readonly description: string;\n}\n```\n\n```text\nNest.js\n```\n\n```text\nSwagger\n```\n\n```text\nnode_modules\n```\n\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger\"]\n  }\n}\n```\n\n```text\n\"plugins\": [\n  {\n    \"name\": \"@nestjs/swagger\",\n    \"options\": {\n      \"classValidatorShim\": false,\n      \"introspectComments\": true\n    }\n  }\n]\n```\n\n```text\n@ApiProperty()\n```\n\n```text\nnest-cli.json\n```\n\n========================================\n\nComments:\n- What exactly are you trying to achieve? Are you trying to exclude a controller or an action from Swagger? docs.nestjs.com/openapi/decorators\n- I removed documentation from some DTOs and models, and I don't want to see it in UI docs as empty object.\n- According to the docs we need to remove the dist folder manually in case of dev mode. Just restarting didn't help. However, all other information was helpful.","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":96,"estimatedTokens":502}}769{"id":"stack-75589407","source":"stackoverflow","questionId":75589407,"title":"Using Nest JS Validation Pipe and class-transformer to get kebab-case query params","tags":["javascript","typescript","nestjs","class-validator","class-transformer"],"text":"Title: Using Nest JS Validation Pipe and class-transformer to get kebab-case query params\nTags: javascript, typescript, nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make use of Nest JS Validation Pipe to auto transform and validate my GET Request Query Params\n\ne.g\n\n`{{url}}/path?param-one=value&param-two=value`\n\nOn `app.module.ts`, I have the following code to set global validation pipe\n\n```\napp.useGlobalPipes(\n new ValidationPipe({\n transform: true,\n whitelist: true,\n forbidNonWhitelisted: true,\n }),\n );\n```\n\nAnd I have a DTO to do the validation\n\n```\nclass MyValidationDto {\n @IsString()\n paramOne: string\n\n @IsString()\n paramTwo: string\n}\n```\n\nAnd in my controller, I make use of the `MyValidationDto` class\n\n```\nclass MyController {\n ... stuff\n\n @Get('/path')\n async myFunction (Query() queryParams: MyValidationDto) { ...code }\n}\n```\n\nHowever, I'm not sure where to go to in order to parse the kebab case query keys `param-one` and `param-two` to the camelCase class properties `paramOne` and `paramTwo` in the validation DTO\n\nI've tried looking at Nest JS doc, `class-validator` doc and `class-transformer` doc, as well as search the highs and lows of internet to no luck. This should be a fairly common case so not sure where I'm going wrong here\n\nUnless this is not possible and I should be using the `Query()` decorator instead. Please advise :pray:\n\n========================================\n\nCode:\n```text\napp.useGlobalPipes(\n      new ValidationPipe({\n        transform: true,\n        whitelist: true,\n        forbidNonWhitelisted: true,\n      }),\n    );\n```\n\n```text\nclass MyValidationDto {\n   @IsString()\n   paramOne: string\n\n   @IsString()\n   paramTwo: string\n}\n```\n\n```text\nclass MyController {\n   ... stuff\n\n   @Get('/path')\n   async myFunction (Query() queryParams: MyValidationDto) { ...code }\n}\n```\n\n```text\n{{url}}/path?param-one=value&param-two=value\n```\n\n```text\napp.module.ts\n```\n\n```text\nMyValidationDto\n```\n\n```text\nparam-one\n```\n\n```text\nparam-two\n```\n\n```text\nparamOne\n```\n\n```text\nparamTwo\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nQuery()\n```\n\n```text\nexport class SomeDTO {\n  @IsString()\n  @Expose({ name: 'my-name' })\n  myName: string;\n  ..\n```\n\n```text\n@Injectable()\nexport class NormalizeQueryParamsPipe implements PipeTransform {\n  transform(value: RestaurantDTO, metadata: ArgumentMetadata) {\n    const normalizedQueryParams = {\n      ...value,\n      name: value['my-name'],\n    };\n\n    delete normalizedQueryParams['my-name'];\n    return normalizedQueryParams;\n  }\n}\n```\n\n```text\n// in main.ts:\n\napp.useGlobalPipes(new NormalizeQueryParamsPipe());\napp.useGlobalPipes(new ValidationPipe());\n\n// or: app.useGlobalPipes(new NormalizeQueryParamsPipe(), new ValidationPipe());\n```\n\n```text\n@Get()\n@UsePipes(new NormalizeQueryParamsPipe())\nasync getAll() {\n ..\n```\n\n```text\n@Expose()\n```\n\n```text\nplainToClass(camelcaseKeys(value), MyValidationDto)\n```\n\n```text\n'my-name'\n```\n\n```text\nmyName\n```\n\n```text\n@UsePipes()\n```\n\n========================================\n\nComments:\n- Thank you for this! As there is no direct way to do this, and this seems to be the least boilerplate-y solution, I've decided to go for this approach!","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":187,"estimatedTokens":810}}770{"id":"stack-74679050","source":"stackoverflow","questionId":74679050,"title":"Unit test Axios HttpService pipe in NestJS Middleware","tags":["typescript","axios","jestjs","rxjs","nestjs"],"text":"Title: Unit test Axios HttpService pipe in NestJS Middleware\nTags: typescript, axios, jestjs, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nThe middleware fetches a json document from a microservice endpoint and attaches it to the request.\n\nThe good path test is ok, but I can't get the bad path test to throw the ForbiddenException and prevent it from calling next().\n\nOutside of a Jest test, the middleware will block a request if it fails to fetch the json document.\n\nAny help is appreciated :)\n\nMiddleware:\n\n```\nimport { ForbiddenException, Injectable, NestMiddleware } from '@nestjs/common'\nimport { HttpService } from '@nestjs/axios'\nimport { NextFunction, Request, Response } from 'express'\nimport { catchError, firstValueFrom } from 'rxjs'\nimport { LoggerService } from '../logger.service'\n\n@Injectable()\nexport class MyMiddleware implements NestMiddleware {\n constructor(\n private logger: LoggerService,\n private httpService: HttpService,\n ) {}\n\n async use(req: Request, res: Response, next: NextFunction) {\n\n const response = await firstValueFrom(\n this.httpService\n .get('https://myservice/document-endpoint', {\n headers: {\n Cookie: req.headers['cookie'],\n },\n })\n .pipe(\n catchError((error: Error) => {\n this.logger.error(error.message);\n throw new ForbiddenException()\n }),\n ),\n )\n\n req.document = response.data.value\n next()\n }\n}\n```\n\nTests:\n\n'Bad path' test is the problem ... the nextFunction method is getting called and I can't manage to get it to throw the error.\n\n```\nimport { MyMiddleware } from './mymiddleware'\nimport { NextFunction, Request, Response } from 'express'\nimport { LoggerService } from '../logger/logger.service'\nimport { of } from 'rxjs'\nimport { createMock } from '@golevelup/nestjs-testing'\nimport { HttpService } from '@nestjs/axios'\nimport { AxiosResponse } from 'axios'\n\ndescribe('Authorization middleware', () => {\n let middleware: MyMiddleware\n let mockRequest: Partial\n let mockResponse: Partial\n let nextFunction: NextFunction = jest.fn()\n let mockHttpService = createMock()\n \n mockRequest = {\n headers: {\n cookie: 'idToken=asdasdasd'\n }\n\n beforeEach(async () => {\n mockResponse = {\n json: jest.fn(),\n }\n\n middleware = new MyMiddleware(new LoggerService(), mockHttpService)\n })\n\n test('bad path', async () => {\n jest.clearAllMocks()\n\n const mockDocumentResponse: AxiosResponse = {\n status: 404, \n statusText: '',\n headers: {},\n config: {},\n data: { error: 'Not Found' }\n }\n\n const httpSpy = jest.spyOn(mockHttpService, 'get')\n .mockReturnValue(of(mockDocumentResponse))\n\n await middleware.use(mockRequest as Request, mockResponse as Response, nextFunction)\n expect(nextFunction).toBeCalledTimes(0)\n })\n\n test('good path', async () => {\n jest.clearAllMocks()\n\n const mockDocumentResponse: AxiosResponse = {\n status: 200, \n statusText: '',\n headers: {},\n config: {},\n data: {\n value: 'example document',\n }\n }\n\n jest.spyOn(mockHttpService, 'get').mockImplementationOnce(() => of(mockDocumentResponse));\n await middleware.use(mockRequest as Request, mockResponse as Response, nextFunction)\n expect(nextFunction).toBeCalledTimes(1)\n })\n\n})\n```\n\n========================================\n\nCode:\n```text\nimport { ForbiddenException, Injectable, NestMiddleware } from '@nestjs/common'\nimport { HttpService } from '@nestjs/axios'\nimport { NextFunction, Request, Response } from 'express'\nimport { catchError, firstValueFrom } from 'rxjs'\nimport { LoggerService } from '../logger.service'\n\n@Injectable()\nexport class MyMiddleware implements NestMiddleware {\n  constructor(\n    private logger: LoggerService,\n    private httpService: HttpService,\n  ) {}\n\n  async use(req: Request, res: Response, next: NextFunction) {\n\n    const response = await firstValueFrom(\n      this.httpService\n        .get('https://myservice/document-endpoint', {\n          headers: {\n            Cookie: req.headers['cookie'],\n          },\n        })\n        .pipe(\n          catchError((error: Error) => {\n            this.logger.error(error.message);\n            throw new ForbiddenException()\n          }),\n        ),\n    )\n\n    req.document = response.data.value\n    next()\n  }\n}\n```\n\n```text\nimport { MyMiddleware } from './mymiddleware'\nimport { NextFunction, Request, Response } from 'express'\nimport { LoggerService } from '../logger/logger.service'\nimport { of } from 'rxjs'\nimport { createMock } from '@golevelup/nestjs-testing'\nimport { HttpService } from '@nestjs/axios'\nimport { AxiosResponse } from 'axios'\n\ndescribe('Authorization middleware', () => {\n  let middleware: MyMiddleware\n  let mockRequest: Partial<Request>\n  let mockResponse: Partial<Response>\n  let nextFunction: NextFunction = jest.fn()\n  let mockHttpService = createMock<HttpService>()\n  \n  mockRequest = {\n    headers: {\n      cookie: 'idToken=asdasdasd'\n    }\n\n  beforeEach(async () => {\n    mockResponse = {\n      json: jest.fn(),\n    }\n\n    middleware = new MyMiddleware(new LoggerService(), mockHttpService)\n  })\n\n  test('bad path', async () => {\n    jest.clearAllMocks()\n\n    const mockDocumentResponse: AxiosResponse = {\n      status: 404, \n      statusText: '',\n      headers: {},\n      config: {},\n      data: { error: 'Not Found' }\n    }\n\n    const httpSpy = jest.spyOn(mockHttpService, 'get')\n      .mockReturnValue(of(mockDocumentResponse))\n\n    await middleware.use(mockRequest as Request, mockResponse as Response, nextFunction)\n    expect(nextFunction).toBeCalledTimes(0)\n  })\n\n\n  test('good path', async () => {\n    jest.clearAllMocks()\n\n    const mockDocumentResponse: AxiosResponse = {\n      status: 200, \n      statusText: '',\n      headers: {},\n      config: {},\n      data: {\n        value: 'example document',\n      }\n    }\n\n    jest.spyOn(mockHttpService, 'get').mockImplementationOnce(() => of(mockDocumentResponse));\n    await middleware.use(mockRequest as Request, mockResponse as Response, nextFunction)\n    expect(nextFunction).toBeCalledTimes(1)\n  })\n\n})\n```\n\n```text\nimport { Observable, of } from 'rxjs'\n...\n\ntest('bad path', async () => {\n  jest.clearAllMocks()\n\n  const err = { response: 'resp', status: '500' }\n\n  // Instead of returning an error response, we simulate throwing an error.\n  const httpSpy = jest.spyOn(mockHttpService, 'get')\n    .mockImplementationOnce(() => new Observable(subscriber => subscriber.error(err)))\n\n  // Handle the expected ForbiddenException\n  await middleware.use(mockRequest as Request, mockResponse as Response, nextFunction)\n    .catch((error) => {\n      expect(error).toBeInstanceOf(ForbiddenException)\n      expect(nextFunction).toBeCalledTimes(0)\n    })\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":254,"estimatedTokens":1632}}771{"id":"stack-65794729","source":"stackoverflow","questionId":65794729,"title":"NestJS: Copying Assets not working on Linux","tags":["node.js","docker","dockerfile","nestjs","nestjs-config"],"text":"Title: NestJS: Copying Assets not working on Linux\nTags: node.js, docker, dockerfile, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI'm working on a NestJS project and copying my assets works fine on my Mac. However, once I dockerize it it won't work.\n\nnest-cli.json\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"assets\": [\n \"**/*.hbs\",\n \"**/*.css\",\n \"**/*.jpg\",\n \"**/*.png\",\n \"**/*.jpeg\"\n ],\n \"watchAssets\": true\n }\n}\n```\n\nDockerfile:\n\n```\nFROM mhart/alpine-node:latest\n\nRUN npm install pm2 -g\n\nCOPY backend /var/www/backend\nCOPY process.json /var/www\nWORKDIR /var/www\n\n#RUN npm i -g @nestjs/cli (tried with and w/out -> no difference)\nRUN cd ./backend && npm i --legacy-peer-deps && npm run build\n\n# Expose ports\nEXPOSE 80\n\nCMD [\"pm2-runtime\", \"./backend/main\"]\n```\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n}\n```\n\ntsconfig.build.json\n\n```\nnpm{\n \"extends\": \"./tsconfig.json\",\n \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n```\n\nI'm not getting any build errors and I've reproduced these steps manually on my mac and everything's being copied. When I go into the docker image and also run the buld step manually it works with no errors but again, no assets are being copied.\n\nI have my assets in different module & services folders and will want to keep it this way - so I'm not looking for a simply post build copy dir solution :)\n\nI've tried different linux dists. and Node version - I'm not sure what else to check\n\n========================================\n\nCode:\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"assets\": [\n      \"**/*.hbs\",\n      \"**/*.css\",\n      \"**/*.jpg\",\n      \"**/*.png\",\n      \"**/*.jpeg\"\n    ],\n    \"watchAssets\": true\n  }\n}\n```\n\n```text\nFROM mhart/alpine-node:latest\n\nRUN npm install pm2 -g\n\nCOPY backend /var/www/backend\nCOPY process.json /var/www\nWORKDIR /var/www\n\n#RUN npm i -g @nestjs/cli (tried with and w/out -> no difference)\nRUN cd ./backend && npm i --legacy-peer-deps && npm run build\n\n# Expose ports\nEXPOSE 80\n\nCMD [\"pm2-runtime\", \"./backend/main\"]\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true\n  }\n}\n```\n\n```text\nnpm{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n```\n\n```text\nFROM node:16-bullseye AS builder\nWORKDIR /usr/app\nCOPY package.json ./\nCOPY yarn.lock ./\nCOPY src ./\nCOPY nest-cli.json ./\nCOPY tsconfig.build.json ./\nCOPY tsconfig.json ./\nRUN yarn install\nRUN yarn build\n...\n```\n\n```text\n{\n  ...,\n  \"compilerOptions\": {\n    \"assets: [ \"modules/mails/templates/**/*.hbs\" ],\n    ...\n  }\n}\n```\n\n```text\nCOPY src ./src # Instead of 'COPY src ./'\n```\n\n```text\nyarn build\n```\n\n========================================\n\nComments:\n- Were you able to find the solution. I happen to face the same issue. In my case, the assets are copied to dist folder sometimes but not every time. If I get a docker container which does not have assets copied and execute an interactive terminal inside it and run npm run build, I see that the assets are copied as usual. In my mac, it never happens but I could reproduce this on Ubuntu 16.04.7 LTS (Xenial Xerus)\n- @ErangaHeshan Unfortunately, no. It \"might\" have something to do with the typescript version installed but I was never able to get it working regardless of what image and/or typescript version I'd use in my container. So I'm using npm:copyfiles as a buildstep now, as ugly as i is.... Example: copyfiles --up 1 src/**/*.hbs dist\n- I have the same issue. Random copying in dist on Ubuntu but on my mac everything is ok.\n- Unfortunately, I have no way of verifying this on my setup as I've long moved on but your explanation and fix makes sense to me - will accept this answer - thx!","metadata":{"transformedAt":"2026-08-18T18:33:02.467Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":183,"estimatedTokens":1081}}772{"id":"stack-64405853","source":"stackoverflow","questionId":64405853,"title":"NestJS + Mongoose: How to test for document(data).save()?","tags":["typescript","unit-testing","mongoose","jestjs","nestjs"],"text":"Title: NestJS + Mongoose: How to test for document(data).save()?\nTags: typescript, unit-testing, mongoose, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nSince I'm using some abstractions, the code here just receive an User, changes that to a Mongo format (aka adds a underslash to the id generated elsewhere), saves and then returns the saved User without the underslash on the id:\n\n```\nconstructor(\n @InjectModel('User')\n private readonly service: typeof Model\n ) { }\n\n async saveUser(user: User): Promise {\n const mongoUser = this.getMongoUser(user);\n const savedMongoUser = await new this.service(mongoUser).save();\n return this.toUserFormat(savedMongoUser);\n }\n```\n\nThe test I'm trying:\n\n```\nbeforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n MongoUserRepository,\n {\n provide: getModelToken('User'),\n useValue: { ... }, // all used functions with jest.fn()\n },\n ],\n }).compile();\n service = module.get(MongoUserRepository);\n model = module.get>(getModelToken('User'));\n });\n\n it('should save new user', async () => {\n jest.spyOn(model, 'save').mockReturnValue({\n save: jest.fn().mockResolvedValueOnce(mockMongoFormat)\n } as any);\n\n const foundMock = await service.saveUser(mockUserFormat);\n expect(foundMock).toEqual(mockUserFormat);\n });\n```\n\nThe problems:\n\n```\nNo overload matches this call.\n Overload 1 of 4, '(object: Model, method: \"model\" | \"remove\" | \"deleteOne\" | \"init\" | \"populate\" | \"replaceOne\" | \"update\" | \"updateOne\" | \"addListener\" | \"on\" | ... 45 more ... | \"where\"): SpyInstance', gave the following error.\n Argument of type '\"save\"' is not assignable to parameter of type '\"model\" | \"remove\" | \"deleteOne\" | \"init\" | \"populate\" | \"replaceOne\" | \"update\" | \"updateOne\" | \"addListener\" | \"on\" | \"once\" | \"removeListener\" | \"off\" | \"removeAllListeners\" | ... 41 more ... | \"where\"'.\n Overload 2 of 4, '(object: Model, method: \"collection\"): SpyInstance', gave the following error.\n Argument of type '\"save\"' is not assignable to parameter of type '\"collection\"'.ts(2769)\n```\n\nTrying to use \"new\" is also a no go:\n\n```\nNo overload matches this call.\n Overload 1 of 4, '(object: Model, method: \"find\" | \"watch\" | \"translateAliases\" | \"bulkWrite\" | \"model\" | \"$where\" | \"aggregate\" | \"count\" | \"countDocuments\" | ... 46 more ... | \"eventNames\"): SpyInstance', gave the following error.\n Argument of type '\"new\"' is not assignable to parameter of type '\"find\" | \"watch\" | \"translateAliases\" | \"bulkWrite\" | \"model\" | \"$where\" | \"aggregate\" | \"count\" | \"countDocuments\" | \"estimatedDocumentCount\" | \"create\" | \"createCollection\" | ... 43 more ... | \"eventNames\"'.\n Overload 2 of 4, '(object: Model, method: \"collection\"): SpyInstance', gave the following error.\n Argument of type '\"new\"' is not assignable to parameter of type '\"collection\"'.\n```\n\nI could probably change the implementation... but would really like to find out what to do in this situation... how should I mock that function?\n\n========================================\n\nCode:\n```text\nconstructor(\n    @InjectModel('User')\n    private readonly service: typeof Model\n  ) { }\n\n  async saveUser(user: User): Promise<User> {\n    const mongoUser = this.getMongoUser(user);\n    const savedMongoUser = await new this.service(mongoUser).save();\n    return this.toUserFormat(savedMongoUser);\n  }\n```\n\n```text\nbeforeEach(async () => {\n        const module: TestingModule = await Test.createTestingModule({\n          providers: [\n            MongoUserRepository,\n            {\n              provide: getModelToken('User'),\n              useValue: { ... }, // all used functions with jest.fn()\n            },\n          ],\n        }).compile();\n    service = module.get<MongoUserRepository>(MongoUserRepository);\n    model = module.get<Model<UserDocument>>(getModelToken('User'));\n  });\n\n  it('should save new user', async () => {\n    jest.spyOn(model, 'save').mockReturnValue({\n      save: jest.fn().mockResolvedValueOnce(mockMongoFormat)\n    } as any);\n\n    const foundMock = await service.saveUser(mockUserFormat);\n    expect(foundMock).toEqual(mockUserFormat);\n  });\n```\n\n```text\nNo overload matches this call.\n  Overload 1 of 4, '(object: Model<UserDocument, {}>, method: \"model\" | \"remove\" | \"deleteOne\" | \"init\" | \"populate\" | \"replaceOne\" | \"update\" | \"updateOne\" | \"addListener\" | \"on\" | ... 45 more ... | \"where\"): SpyInstance<...>', gave the following error.\n    Argument of type '\"save\"' is not assignable to parameter of type '\"model\" | \"remove\" | \"deleteOne\" | \"init\" | \"populate\" | \"replaceOne\" | \"update\" | \"updateOne\" | \"addListener\" | \"on\" | \"once\" | \"removeListener\" | \"off\" | \"removeAllListeners\" | ... 41 more ... | \"where\"'.\n  Overload 2 of 4, '(object: Model<UserDocument, {}>, method: \"collection\"): SpyInstance<Collection, [name: string, conn: Connection, opts?: any]>', gave the following error.\n    Argument of type '\"save\"' is not assignable to parameter of type '\"collection\"'.ts(2769)\n```\n\n```text\nNo overload matches this call.\n  Overload 1 of 4, '(object: Model<UserDocument, {}>, method: \"find\" | \"watch\" | \"translateAliases\" | \"bulkWrite\" | \"model\" | \"$where\" | \"aggregate\" | \"count\" | \"countDocuments\" | ... 46 more ... | \"eventNames\"): SpyInstance<...>', gave the following error.\n    Argument of type '\"new\"' is not assignable to parameter of type '\"find\" | \"watch\" | \"translateAliases\" | \"bulkWrite\" | \"model\" | \"$where\" | \"aggregate\" | \"count\" | \"countDocuments\" | \"estimatedDocumentCount\" | \"create\" | \"createCollection\" | ... 43 more ... | \"eventNames\"'.\n  Overload 2 of 4, '(object: Model<UserDocument, {}>, method: \"collection\"): SpyInstance<Collection, [name: string, conn: Connection, opts?: any]>', gave the following error.\n    Argument of type '\"new\"' is not assignable to parameter of type '\"collection\"'.\n```\n\n```text\nasync saveUser ( user: User ): Promise<User> {\n    const mongoUser = this.getMongoUser(user);\n    const savedMongoUser = await this.service.create( mongoUser );\n    return this.toUserFormat(savedMongoUser);\n}\n```\n\n```text\nit( 'should save new user', async () => {\n    jest.spyOn( model, 'create' ).mockImplementation(\n      jest.fn().mockResolvedValueOnce( mockMongoFormat )\n    );\n    const foundMock = await service.saveUser( mockUserFormat );\n    expect( foundMock ).toEqual( mockUserFormat );\n  } );\n```\n\n========================================\n\nComments:\n- How have you injected models/services in your test (probably through `beforeAll`)?\n- @GytisTG Yes, this would actually be the last test I need to pass. Even 'findOneAndUpdate' and 'findOneAndDelete' works.","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":149,"estimatedTokens":1640}}773{"id":"stack-64237525","source":"stackoverflow","questionId":64237525,"title":"How to dynamically connect to a database in nestjs?","tags":["typescript","sequelize.js","nestjs"],"text":"Title: How to dynamically connect to a database in nestjs?\nTags: typescript, sequelize.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have multiple databases that I want to connect. but just one of them have static name. for example the name of that database is `stores`, and in that I have a table that indicates the name of the other databases. now I want to change the connection provider after the first route being called. how can I do that?\n\nI tried to use the Dynamic modules, but I don't know how to use it.\n\n========================================\n\nCode:\n```text\nstores\n```\n\n```text\n@Injectable({ scope: Scope.REQUEST })\nexport class MongooseConfigService implements MongooseOptionsFactory {\n    constructor(\n        @Inject(REQUEST) private readonly request: Request,) {\n    }\n\n    createMongooseOptions(): MongooseModuleOptions {\n        return {\n            uri: request.params.uri, // Change this to whatever you want\n        };\n    }\n}\n```\n\n========================================\n\nComments:\n- Create your own Database module, and pass a database name to provider, or uri that you want to connect with, store somewhere these information with relations to the connection, like string -> connection, fe: Map with DB URI or DB Name with key as connection handler. Then you should be able to achieve your goal.\n- @cojack, thanks. but can you give an example on how to do that?","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":36,"estimatedTokens":347}}774{"id":"stack-59919546","source":"stackoverflow","questionId":59919546,"title":"Problem with e2e testing with NestJS TestingModule, GraphQL code first and TypeOrm","tags":["graphql","e2e-testing","nestjs"],"text":"Title: Problem with e2e testing with NestJS TestingModule, GraphQL code first and TypeOrm\nTags: graphql, e2e-testing, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm in struggle since few days with **e2e testing** my **NestJS** application using **GraphQL** code first approach and **TypeOrm**.\n\nI'm trying to create a **TestingModule** by injecting nestjs **GraphQLModule** with *autoSchemaFile* and I'm always getting the error \"*Schema must contain uniquely named types but contains multiple types named ...*\".\n\nHere a reproduction of my bug with minimal code:\n\n`character.entity.ts`:\n\n```\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\nimport { ObjectType, Field, ID } from 'type-graphql';\n\n@Entity()\n@ObjectType()\nexport class Character {\n @PrimaryGeneratedColumn()\n @Field(() => ID)\n id: string;\n\n @Column({ unique: true })\n @Field()\n name: string;\n}\n```\n\n`character.resolver.ts`:\n\n```\nimport { Query, Resolver } from '@nestjs/graphql';\nimport { Character } from './models/character.entity';\nimport { CharacterService } from './character.service';\n\n@Resolver(() => Character)\nexport class CharacterResolver {\n constructor(private readonly characterService: CharacterService) {}\n\n @Query(() => [Character], { name: 'characters' })\n async getCharacters(): Promise {\n return this.characterService.findAll();\n }\n}\n```\n\n`character.module.ts`:\n\n```\nimport { Module } from '@nestjs/common';\nimport { CharacterResolver } from './character.resolver';\nimport { CharacterService } from './character.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Character } from './models/character.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Character])],\n providers: [CharacterResolver, CharacterService],\n})\nexport class CharacterModule {}\n```\n\n`app.module.ts`:\n\n```\nimport { Module } from '@nestjs/common';\nimport { CharacterModule } from './character/character.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { GraphQLModule } from '@nestjs/graphql';\n\n@Module({\n imports: [TypeOrmModule.forRoot(), GraphQLModule.forRoot({ autoSchemaFile: 'schema.gql' }), CharacterModule],\n controllers: [],\n providers: [],\n})\nexport class AppModule {\n constructor(private readonly connection: Connection) {}\n}\n```\n\nand finally: `character.e2e-spec.ts`:\n\n```\nimport { INestApplication } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { CharacterModule } from '../src/character/character.module';\nimport { GraphQLModule } from '@nestjs/graphql';\n\ndescribe('CharacterResolver (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forRoot(),\n GraphQLModule.forRoot({ playground: false, autoSchemaFile: 'schema.gql' }),\n CharacterModule,\n ],\n }).compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n it('should create testing module', () => {\n expect(1).toBe(1);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\nAnd after running `npm run test:e2e`:\n\n```\nSchema must contain uniquely named types but contains multiple types named \"Character\".\n\n at typeMapReducer (../node_modules/graphql/type/schema.js:262:13)\n at Array.reduce ()\n at new GraphQLSchema (../node_modules/graphql/type/schema.js:145:28)\n at Function.generateFromMetadataSync (../node_modules/type-graphql/dist/schema/schema-generator.js:31:24)\n at Function. (../node_modules/type-graphql/dist/schema/schema-generator.js:16:33)\n at ../node_modules/tslib/tslib.js:110:75\n at Object.__awaiter (../node_modules/tslib/tslib.js:106:16)\n at Function.generateFromMetadata (../node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n```\n\nI don't find any other way to create a testing module with graphql code first approach on official doc or while googling... Am I missing something ?\n\n========================================\n\nCode:\n```js\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\nimport { ObjectType, Field, ID } from 'type-graphql';\n\n@Entity()\n@ObjectType()\nexport class Character {\n    @PrimaryGeneratedColumn()\n    @Field(() => ID)\n    id: string;\n\n    @Column({ unique: true })\n    @Field()\n    name: string;\n}\n```\n\n```js\nimport { Query, Resolver } from '@nestjs/graphql';\nimport { Character } from './models/character.entity';\nimport { CharacterService } from './character.service';\n\n@Resolver(() => Character)\nexport class CharacterResolver {\n    constructor(private readonly characterService: CharacterService) {}\n\n    @Query(() => [Character], { name: 'characters' })\n    async getCharacters(): Promise<Character[]> {\n        return this.characterService.findAll();\n    }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { CharacterResolver } from './character.resolver';\nimport { CharacterService } from './character.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Character } from './models/character.entity';\n\n@Module({\n    imports: [TypeOrmModule.forFeature([Character])],\n    providers: [CharacterResolver, CharacterService],\n})\nexport class CharacterModule {}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { CharacterModule } from './character/character.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { GraphQLModule } from '@nestjs/graphql';\n\n@Module({\n    imports: [TypeOrmModule.forRoot(), GraphQLModule.forRoot({ autoSchemaFile: 'schema.gql' }), CharacterModule],\n    controllers: [],\n    providers: [],\n})\nexport class AppModule {\n    constructor(private readonly connection: Connection) {}\n}\n```\n\n```js\nimport { INestApplication } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { CharacterModule } from '../src/character/character.module';\nimport { GraphQLModule } from '@nestjs/graphql';\n\ndescribe('CharacterResolver (e2e)', () => {\n    let app: INestApplication;\n\n    beforeAll(async () => {\n        const module: TestingModule = await Test.createTestingModule({\n            imports: [\n                TypeOrmModule.forRoot(),\n                GraphQLModule.forRoot({ playground: false, autoSchemaFile: 'schema.gql' }),\n                CharacterModule,\n            ],\n        }).compile();\n\n        app = module.createNestApplication();\n        await app.init();\n    });\n\n    it('should create testing module', () => {\n        expect(1).toBe(1);\n    });\n\n    afterAll(async () => {\n        await app.close();\n    });\n});\n```\n\n```text\nSchema must contain uniquely named types but contains multiple types named \"Character\".\n\n      at typeMapReducer (../node_modules/graphql/type/schema.js:262:13)\n          at Array.reduce (<anonymous>)\n      at new GraphQLSchema (../node_modules/graphql/type/schema.js:145:28)\n      at Function.generateFromMetadataSync (../node_modules/type-graphql/dist/schema/schema-generator.js:31:24)\n      at Function.<anonymous> (../node_modules/type-graphql/dist/schema/schema-generator.js:16:33)\n      at ../node_modules/tslib/tslib.js:110:75\n      at Object.__awaiter (../node_modules/tslib/tslib.js:106:16)\n      at Function.generateFromMetadata (../node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n```\n\n```text\ncharacter.entity.ts\n```\n\n```text\ncharacter.resolver.ts\n```\n\n```text\ncharacter.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\ncharacter.e2e-spec.ts\n```\n\n```text\nnpm run test:e2e\n```\n\n```text\n\"entities\": [\n    \"src/**/*.entity.js\"\n  ],\n  \"migrations\": [\n    \"src/migration/*.js\"\n  ],\n  \"cli\": {\n    \"migrationsDir\": \"src/migration\"\n  }\n```\n\n```text\normconfig.json\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- Just set this up today and found the same issue. No clue what's leading to it. I can confirm the error occurs at the point: `app.init()`","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":304,"estimatedTokens":1995}}775{"id":"stack-74526910","source":"stackoverflow","questionId":74526910,"title":"run nestjs application with yarn berry workspace monorepo","tags":["typescript","nestjs","monorepo","yarn-workspaces","yarn-berry"],"text":"Title: run nestjs application with yarn berry workspace monorepo\nTags: typescript, nestjs, monorepo, yarn-workspaces, yarn-berry\nSource: Stack Overflow\n\nQuestion:\nI want to configure monorepo with yarn berry workspaces.\nI create nest application with cli that `nest g application .` in packages/mono-api-server folder\nhere is my file tree\n\n```\n.\nโ”œโ”€โ”€ .pnp.cjs\nโ”œโ”€โ”€ .pnp.loader.mjs\nโ”œโ”€โ”€ .yarn\nโ”‚ย ย  โ”œโ”€โ”€ cache\nโ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ many zip files..\nโ”‚ย ย  โ”œโ”€โ”€ install-state.gz\nโ”‚ย ย  โ”œโ”€โ”€ plugins\nโ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ @yarnpkg\nโ”‚ย ย  โ”œโ”€โ”€ releases\nโ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ yarn-3.3.0.cjs\nโ”‚ย ย  โ””โ”€โ”€ unplugged\nโ”‚ย ย  โ”œโ”€โ”€ @nestjs-core-virtual-c9663b0b91\nโ”‚ย ย  โ”œโ”€โ”€ fsevents-patch-2882183fbf\nโ”‚ย ย  โ””โ”€โ”€ node-gyp-npm-9.3.0-21c41a4dfd\nโ”œโ”€โ”€ .yarnrc.yml\nโ”œโ”€โ”€ dist\nโ”‚ย ย  โ””โ”€โ”€ compiled files...\nโ”œโ”€โ”€ package.json\nโ”œโ”€โ”€ packages\nโ”‚ย ย  โ””โ”€โ”€ mono-api-server\nโ”‚ย ย  โ”œโ”€โ”€ .eslintrc.js\nโ”‚ย ย  โ”œโ”€โ”€ .prettierrc\nโ”‚ย ย  โ”œโ”€โ”€ README.md\nโ”‚ย ย  โ”œโ”€โ”€ nest-cli.json\nโ”‚ย ย  โ”œโ”€โ”€ package.json\nโ”‚ย ย  โ”œโ”€โ”€ src\nโ”‚ย ย  โ”œโ”€โ”€ tsconfig.build.json\nโ”‚ย ย  โ””โ”€โ”€ tsconfig.json\nโ”œโ”€โ”€ tsconfig.build.json\nโ”œโ”€โ”€ tsconfig.json\nโ””โ”€โ”€ yarn.lock\n```\n\nnest application starts well when *dist* folder is under the packages/mono-api-server\nbut i want to take it out to the root folder.\nso, i configure \"outDir\" tsconfig.json in the packages/mono-api-server\nfrom \"./dist\" to \"../../dist/mono-api-server\".\nThen it causes error below\n\n```\n/Users/cain/cain/monorepo/.pnp.cjs:17444\n Error.captureStackTrace(firstError);\n ^\nError: Your application tried to access @nestjs/core, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: @nestjs/core\nRequired by: /Users/cain/cain/monorepo/dist/mono-api-server/\n\nRequire stack:\n- /Users/cain/cain/monorepo/dist/mono-api-server/main.js\n at Function.require$$0.Module._resolveFilename (/Users/cain/cain/monorepo/.pnp.cjs:17444:13)\n......\n```\n\nI was suspicious that only @nestjs/core could not be loaded, so I tried importing something else on top of it such as lodash.\n\n```\nimport _ from 'lodash';\nconsole.log(\"hi\");\nimport { NestFactory } from '@nestjs/core';\n```\n\nand it works until it met `import { NestFactory } from '@nestjs/core';` and prints \"hi\"\n\nSo my assumption is since **@nestjs-core-virtual-c9663b0b91** is under the .yarn/unplugged folder, it should be configured separately.\n\nI guess the configure packagesExtension in .yarnrc.yml can be a solution. But i don't know how to set it up.\n\nAny one can help me to running nestjs application??\nupload package.json for reference.\n\n**package.json in packages/mono-api-server**\n\n```\n{\n \"name\": \"mono-api-server\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"prebuild\": \"rimraf dist\",\n \"build\": \"nest build\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"nest start\",\n \"start:dev\": \"nest start --watch\",\n \"start:debug\": \"nest start --debug --watch\",\n \"start:prod\": \"node dist/main\",\n \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/platform-express\": \"^9.0.0\",\n \"lodash\": \"^4.17.21\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^3.0.2\",\n \"rxjs\": \"^7.2.0\"\n },\n \"devDependencies\": {\n \"@nestjs/cli\": \"^9.0.0\",\n \"@nestjs/schematics\": \"^9.0.0\",\n \"@nestjs/testing\": \"^9.0.0\",\n \"@types/express\": \"^4.17.13\",\n \"@types/jest\": \"28.1.4\",\n \"@types/node\": \"^16.0.0\",\n \"@types/supertest\": \"^2.0.11\",\n \"@typescript-eslint/eslint-plugin\": \"^5.0.0\",\n \"@typescript-eslint/parser\": \"^5.0.0\",\n \"eslint\": \"^8.0.1\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"jest\": \"28.1.2\",\n \"prettier\": \"^2.3.2\",\n \"source-map-support\": \"^0.5.20\",\n \"supertest\": \"^6.1.3\",\n \"ts-jest\": \"28.0.5\",\n \"ts-loader\": \"^9.2.3\",\n \"ts-node\": \"^10.0.0\",\n \"tsconfig-paths\": \"4.0.0\",\n \"typescript\": \"~4.8.4\"\n }\n}\n```\n\n**package.json in root**\n\n```\n{\n \"packageManager\": \"yarn@3.3.0\",\n \"workspaces\": [\n \"packages/*\"\n ]\n}\n```\n\n========================================\n\nCode:\n```json\n.\nโ”œโ”€โ”€ .pnp.cjs\nโ”œโ”€โ”€ .pnp.loader.mjs\nโ”œโ”€โ”€ .yarn\nโ”‚ย ย  โ”œโ”€โ”€ cache\nโ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ many zip files..\nโ”‚ย ย  โ”œโ”€โ”€ install-state.gz\nโ”‚ย ย  โ”œโ”€โ”€ plugins\nโ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ @yarnpkg\nโ”‚ย ย  โ”œโ”€โ”€ releases\nโ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ yarn-3.3.0.cjs\nโ”‚ย ย  โ””โ”€โ”€ unplugged\nโ”‚ย ย      โ”œโ”€โ”€ @nestjs-core-virtual-c9663b0b91\nโ”‚ย ย      โ”œโ”€โ”€ fsevents-patch-2882183fbf\nโ”‚ย ย      โ””โ”€โ”€ node-gyp-npm-9.3.0-21c41a4dfd\nโ”œโ”€โ”€ .yarnrc.yml\nโ”œโ”€โ”€ dist\nโ”‚ย ย  โ””โ”€โ”€ compiled files...\nโ”œโ”€โ”€ package.json\nโ”œโ”€โ”€ packages\nโ”‚ย ย  โ””โ”€โ”€ mono-api-server\nโ”‚ย ย      โ”œโ”€โ”€ .eslintrc.js\nโ”‚ย ย      โ”œโ”€โ”€ .prettierrc\nโ”‚ย ย      โ”œโ”€โ”€ README.md\nโ”‚ย ย      โ”œโ”€โ”€ nest-cli.json\nโ”‚ย ย      โ”œโ”€โ”€ package.json\nโ”‚ย ย      โ”œโ”€โ”€ src\nโ”‚ย ย      โ”œโ”€โ”€ tsconfig.build.json\nโ”‚ย ย      โ””โ”€โ”€ tsconfig.json\nโ”œโ”€โ”€ tsconfig.build.json\nโ”œโ”€โ”€ tsconfig.json\nโ””โ”€โ”€ yarn.lock\n```\n\n```text\n/Users/cain/cain/monorepo/.pnp.cjs:17444\n      Error.captureStackTrace(firstError);\n            ^\nError: Your application tried to access @nestjs/core, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: @nestjs/core\nRequired by: /Users/cain/cain/monorepo/dist/mono-api-server/\n\nRequire stack:\n- /Users/cain/cain/monorepo/dist/mono-api-server/main.js\n    at Function.require$$0.Module._resolveFilename (/Users/cain/cain/monorepo/.pnp.cjs:17444:13)\n......\n```\n\n```js\nimport _ from 'lodash';\nconsole.log(\"hi\");\nimport { NestFactory } from '@nestjs/core';\n```\n\n```json\n{\n  \"name\": \"mono-api-server\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^9.0.0\",\n    \"@nestjs/core\": \"^9.0.0\",\n    \"@nestjs/platform-express\": \"^9.0.0\",\n    \"lodash\": \"^4.17.21\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^7.2.0\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^9.0.0\",\n    \"@nestjs/schematics\": \"^9.0.0\",\n    \"@nestjs/testing\": \"^9.0.0\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"28.1.4\",\n    \"@types/node\": \"^16.0.0\",\n    \"@types/supertest\": \"^2.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.0.0\",\n    \"@typescript-eslint/parser\": \"^5.0.0\",\n    \"eslint\": \"^8.0.1\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-prettier\": \"^4.0.0\",\n    \"jest\": \"28.1.2\",\n    \"prettier\": \"^2.3.2\",\n    \"source-map-support\": \"^0.5.20\",\n    \"supertest\": \"^6.1.3\",\n    \"ts-jest\": \"28.0.5\",\n    \"ts-loader\": \"^9.2.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"tsconfig-paths\": \"4.0.0\",\n    \"typescript\": \"~4.8.4\"\n  }\n}\n```\n\n```json\n{\n  \"packageManager\": \"yarn@3.3.0\",\n  \"workspaces\": [\n    \"packages/*\"\n  ]\n}\n```\n\n```text\nnest g application .\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\n```\n\n```text\ndist\n```\n\n```text\npackages/mono-api-server\n```\n\n```text\n@next/core\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":298,"estimatedTokens":1874}}776{"id":"stack-70230976","source":"stackoverflow","questionId":70230976,"title":"getting `sh: 1: exec: nest: not found` error deploying nestjs to google app engine","tags":["node.js","docker","google-app-engine","nestjs"],"text":"Title: getting `sh: 1: exec: nest: not found` error deploying nestjs to google app engine\nTags: node.js, docker, google-app-engine, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy my nestjs application to google app engine, but I get `sh: 1: exec: nest: not found` error\n\nmy package.json\n\n```\n\"main\": \"dist/main.js\",\n \"scripts\": {\n \"prebuild\": \"rimraf dist\",\n \"build\": \"nest build\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"nest start\",\n \"start:dev\": \"nest start --watch\",\n \"start:debug\": \"nest start --debug --watch\",\n \"start:prod\": \"node dist/main\",\n \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n \"gcp-build\": \"npm run build\",\n \"ae:deploy\": \"gcloud app deploy --quiet\",\n \"ae:browse\": \"gcloud app browse\",\n \"@nestjs/cli\": \"^8.0.0\",\n }\n```\n\nDockerFile\n\n```\nFROM node:14-alpine\n\nWORKDIR /usr/src/app\nENV NODE_ENV=production\n\nCOPY package*.json ./\n\nRUN npm install -g @nestjs/cli@8\n\nRUN npm install\n\nCOPY . ./\n\nRUN npm run build\n\nCMD [ \"npm\", \"run\", \"start:prod\" ]\n```\n\napp.yaml\n\n```\nruntime: nodejs14\nservice: default\n\ninstance_class: F1\n\nenv_variables:\n NODE_ENV: 'production'\n```\n\nCloudBuild.yaml\n\n```\nsteps:\n- name: \"gcr.io/cloud-builders/docker\"\n args:\n - build\n - \"--tag=gcr.io/cmor-baas-dev/kafka-connector:latest\"\n - \"--file=Dockerfile\"\n - . \nimages:\n- \"gcr.io/cmor-baas-dev/kafka-connector\"\ntimeout: 1800s\n```\n\nhttps://i.sstatic.net/RQax8.png\n\nhttps://i.sstatic.net/TiZ2c.png\n\nI think both Dockerfile and CloudBuild.yaml files are ignored (I am new to Google app engine, not sure do we need those files)\n\n### Update\n\nBased on here,\n\nAll dependencies that you define under the devDependencies field are\nignored and do not get installed for your app in App Engine.\n\nSo I moved `@nestjs/cli` to `dependencies` in my package.json, still same error\n\n========================================\n\nTop Answer:\nIf you came here looking for a solution because you are trying to deploy nestjs app on render.com and having this same issue, today is your lucky day.\n\nUninstall @nestjs/cli as devDependency and install dependency.\n\nSet start script to; \"start:prod\": \"node dist/main\"\n\nSet node version in package.json as:\n\n\"engines\": { \"node\": \"x.x.x\"//e.g \"18.16.0\" }\n\nThen push and deploy on render; it should work.\n\n========================================\n\nCode:\n```text\n\"main\": \"dist/main.js\",\n    \"scripts\": {\n        \"prebuild\": \"rimraf dist\",\n        \"build\": \"nest build\",\n        \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n        \"start\": \"nest start\",\n        \"start:dev\": \"nest start --watch\",\n        \"start:debug\": \"nest start --debug --watch\",\n        \"start:prod\": \"node dist/main\",\n        \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n        \"test\": \"jest\",\n        \"test:watch\": \"jest --watch\",\n        \"test:cov\": \"jest --coverage\",\n        \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n        \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n        \"gcp-build\": \"npm run build\",\n        \"ae:deploy\": \"gcloud app deploy --quiet\",\n        \"ae:browse\": \"gcloud app browse\",\n        \"@nestjs/cli\": \"^8.0.0\",\n    }\n```\n\n```text\nFROM node:14-alpine\n\nWORKDIR /usr/src/app\nENV NODE_ENV=production\n\nCOPY package*.json ./\n\nRUN npm install -g @nestjs/cli@8\n\nRUN npm install\n\nCOPY . ./\n\nRUN npm run build\n\nCMD [ \"npm\", \"run\", \"start:prod\" ]\n```\n\n```text\nruntime: nodejs14\nservice: default\n\ninstance_class: F1\n\nenv_variables:\n  NODE_ENV: 'production'\n```\n\n```text\nsteps:\n- name: \"gcr.io/cloud-builders/docker\"\n  args:\n  - build\n  - \"--tag=gcr.io/cmor-baas-dev/kafka-connector:latest\"\n  - \"--file=Dockerfile\"\n  - .  \nimages:\n- \"gcr.io/cmor-baas-dev/kafka-connector\"\ntimeout: 1800s\n```\n\n```text\nsh: 1: exec: nest: not found\n```\n\n```text\n@nestjs/cli\n```\n\n```text\ndependencies\n```\n\n```text\n\"start\": \"node dist/main.js\"\n```\n\n```text\n@nestjs/cli\n```\n\n```text\ndevDependency\n```\n\n```text\ndependency\n```\n\n========================================\n\nComments:\n- @PJoe see accepted answer below","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":210,"estimatedTokens":1075}}777{"id":"stack-74355633","source":"stackoverflow","questionId":74355633,"title":"CRON job executing twice at scheduled time (NestJS)","tags":["cron","nestjs","scheduled-tasks"],"text":"Title: CRON job executing twice at scheduled time (NestJS)\nTags: cron, nestjs, scheduled-tasks\nSource: Stack Overflow\n\nQuestion:\nI want to execute this cron function in my NestJs project :\n\n```\n@Cron('59 23 * * *')\nasync CashPendingCRON(){\n let stores = await this.storeRepository.find();\n for (let store of stores){\n await this.connection\n .createQueryBuilder()\n .insert()\n .into(CashPending)\n .values([\n { cashPending: store.cashPending, store: store }\n ])\n .execute()\n }\n```\n\nAs you can see the corn job is supposed to execute at 11:59 pm everyday. But it gets executed twice and the entries are logged in the DB two times. When I use intervals like 10 seconds (*/10 * * * * *) it gets called only once.\n\nPlease let me know if there is a fix or if I am doing something wrong.\n\nHere is how I added the ScheduleModule in the app.module.ts\n\n```\n@Module({\n imports: [\n ScheduleModule.forRoot(),\n ConfigModule.forRoot({\n load: [appConfig, devConfig, stagConfig],\n ignoreEnvFile: true,\n isGlobal: true,\n }),\n TypeOrmModule.forRoot(\n configService.getTypeOrmConfig(),\n ),\n TypeOrmModule.forFeature([\n User,\n Vendor,\n Store,\n Product,\n Category,\n Brand,\n AppVersion\n ]),\n JwtModule.registerAsync({\n imports: [ConfigModule],\n useFactory: async () => ({\n secret: process.env.TOKEN_KEY,\n }),\n inject: [ConfigService],\n }),\n UserModule,\n UserClusterModule,\n StoreModule,\n OperationManagerModule,\n UserBrandModule,\n UserCatalogueModule,\n UserPropertyModule,\n FileModule,\n BrandModule,\n CategoryModule,\n ProductsModule,\n WarehouseModule,\n SubCategoryModule,\n StoreStocksModule,\n WarehouseStockModule,\n RtvStocksModule,\n VendorModule,\n CustomerModule,\n W2sModule,\n S2sModule,\n W2wModule,\n BillerModule,\n WarehouseManagerModule,\n AuthModule,\n OrderModule,\n GRNModule,\n SKUTimelinesModule,\n BannerModule,\n OrderReturnModule,\n UtilModule,\n POModule,\n AppVersion,\n S2wModule,\n CashOutModule\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nPlease help. Thank you.\n\n========================================\n\nTop Answer:\nI faced this problem and informing the name property solved it for me:\n\n```\n@Cron(CronExpression.EVERY_10_SECONDS, { name: 'nameOfJob'})\n```\n\n========================================\n\nCode:\n```text\n@Cron('59 23 * * *')\nasync CashPendingCRON(){\n    let stores = await this.storeRepository.find();\n    for (let store of stores){\n        await this.connection\n        .createQueryBuilder()\n        .insert()\n        .into(CashPending)\n        .values([\n        { cashPending: store.cashPending, store: store }\n        ])\n        .execute()\n }\n```\n\n```text\n@Module({\n  imports: [\n    ScheduleModule.forRoot(),\n    ConfigModule.forRoot({\n      load: [appConfig, devConfig, stagConfig],\n      ignoreEnvFile: true,\n      isGlobal: true,\n    }),\n    TypeOrmModule.forRoot(\n      configService.getTypeOrmConfig(),\n    ),\n    TypeOrmModule.forFeature([\n      User,\n      Vendor,\n      Store,\n      Product,\n      Category,\n      Brand,\n      AppVersion\n    ]),\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      useFactory: async () => ({\n        secret: process.env.TOKEN_KEY,\n      }),\n      inject: [ConfigService],\n    }),\n    UserModule,\n    UserClusterModule,\n    StoreModule,\n    OperationManagerModule,\n    UserBrandModule,\n    UserCatalogueModule,\n    UserPropertyModule,\n    FileModule,\n    BrandModule,\n    CategoryModule,\n    ProductsModule,\n    WarehouseModule,\n    SubCategoryModule,\n    StoreStocksModule,\n    WarehouseStockModule,\n    RtvStocksModule,\n    VendorModule,\n    CustomerModule,\n    W2sModule,\n    S2sModule,\n    W2wModule,\n    BillerModule,\n    WarehouseManagerModule,\n    AuthModule,\n    OrderModule,\n    GRNModule,\n    SKUTimelinesModule,\n    BannerModule,\n    OrderReturnModule,\n    UtilModule,\n    POModule,\n    AppVersion,\n    S2wModule,\n    CashOutModule\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n  providers: [SchedulerService],\n  imports: [ScheduleModule.forRoot()],\n})\nexport class SchedulerModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Cron, CronExpression } from '@nestjs/schedule';\n\n@Injectable()\nexport class SchedulerService {\n  @Cron(CronExpression.EVERY_10_SECONDS)\n  handleExpiration() {\n    console.log(new Date());\n  }\n}\n```\n\n```text\n2022-12-21T14:04:00.005Z\n2022-12-21T14:04:10.004Z\n2022-12-21T14:04:20.009Z\n2022-12-21T14:04:30.004Z\n2022-12-21T14:04:40.011Z\n...\n```\n\n```text\nimports: [ScheduleModule.forRoot()]\n```\n\n```text\nScheduleModule.forRoot()\n```\n\n```text\n@Cron(CronExpression.EVERY_10_SECONDS, { name: 'nameOfJob'})\n```\n\n========================================\n\nComments:\n- Do you have the class that has this cron expression added to two `providers` arrays?\n- No the only place I have added the class(StoreService)to a ``` providers ``` array is its own module. Adding here for ref: `@Module({ imports: [ TypeOrmModule.forFeature([ User, ClusterManager, Store, Order, Biller, ReturnOrder ]), JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async () => ({ secret: process.env.TOKEN_KEY, }), inject: [ConfigService], }), ], controllers: [StoreController], providers: [ StoreService, ], }) export class StoreModule {}`\n- The code above it difficult to read, not sure how else to add it here. @JayMcDoniel\n- Any other way the cron in the class can be executed twice? because when I use intervals like 10 seconds (*/10 * * * * *) it gets called only once. This is a hard problem to crack. @JayMcDoniel\n- The only reason I can see it being added to the registry twice is due to being instantiated twice, but if using an interval it only happens once then I'm not sure. A way to reproduce this would be very helpful\n- yeah, when I call it every 10 seconds it is being executed once; every 24 hours, 2 times, haven't been able to solve this yet. @JayMcDoniel\n- I can't say that I can think of a reason that would happen. I would need some sort of reproduction to see it and diagnose\n- Ok I will try to a repo link in a bit.\n- Yep! Worked! Thanks, I had given up on this :p @Murilo\n- I had the same issue, I imported a guard in 3 places and the cron job ran 3 times, lol. Let's hope this fixes it.\n- ok so the rule is you have to create an entire module dedicated to cron jobs and make sure it isn't imported anywhere and have it import all of its dependencies.\n- what is 'nameOfJob'\n- It is available in the documentation at Nestjs Cron: [...] *Name: Useful for accessing and controlling a cron job once declared*.","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":255,"estimatedTokens":1635}}778{"id":"stack-59075112","source":"stackoverflow","questionId":59075112,"title":"NestJS - Use multiple MongoDB connections per module","tags":["node.js","mongodb","mongoose","nestjs","multiple-databases"],"text":"Title: NestJS - Use multiple MongoDB connections per module\nTags: node.js, mongodb, mongoose, nestjs, multiple-databases\nSource: Stack Overflow\n\nQuestion:\nIs there a way to connect multiple MongoDB connections per module?\n\napp.module.ts\n\n```\n@Module({\n imports: [\n MongooseModule.forRoot('mongodb://localhost/masterDB'),\n UserModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\nSimilarly, can we define another connection in another module which is a child of app.module?\n\nchild.module.ts\n\n```\n@Module({\n imports: [\n MongooseModule.forRoot('mongodb://localhost/childDB'),\n MongooseModule.forFeature([{ name: 'child', schema: ChildSchema }]),\n ],\n controllers: [ChildController],\n providers: [ChildService],\n})\nexport class ChildModule { }\n```\n\nOr any other way to access different databases at once.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\n[SOLVED March 2021]\n\nHere you'll find the solution:\n\nhttps://www.learmoreseekmore.com/2020/04/nestjs-multiple-mongodb-databases.html\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { studentSchema } from './schemas/myworld/student.schema';\nimport { animalSchema } from './schemas/wildlife/animal.schema';\n\n@Module({\n imports: [\n MongooseModule.forFeature([\n {\n name: 'Student',\n schema: studentSchema,\n collection: 'Student',\n \n },\n ],'myWorldDb'),\n MongooseModule.forFeature([\n {\n name: 'Animals',\n schema: animalSchema,\n collection: 'Animals'\n }\n ],'wildLifeDb'),\n MongooseModule.forRoot(\n 'mongodb+srv://:@cluster0-igk.mongodb.net/MyWorld?retryWrites=true&w=majority',\n {\n connectionName: 'myWorldDb'\n }\n ),\n MongooseModule.forRoot(\n 'mongodb+srv://:@cluster0-igk.mongodb.net/WildLife?retryWrites=true&w=majority',\n {\n connectionName: 'wildLifeDb'\n }\n )\n\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://localhost/masterDB'),\n    UserModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://localhost/childDB'),\n    MongooseModule.forFeature([{ name: 'child', schema: ChildSchema }]),\n  ],\n  controllers: [ChildController],\n  providers: [ChildService],\n})\nexport class ChildModule { }\n```\n\n```text\nimport * as mongoose from 'mongoose';\n\nexport const mongooseProviders = [\n  {\n    provide: 'MASTER_CONNECTION',\n    useFactory: (): Promise<typeof mongoose> =>\n    // This mongoose.connect never working for multples DB connection\n    // mongoose.connect('mongodb://localhost/masterDB'),\n    // Following is working fine and tested by me\n    mongoose.createConnection('mongodb://localhost/masterDB'),\n  },\n  {\n    provide: 'CHILD_CONNECTION',\n    useFactory: (): Promise<typeof mongoose> =>\n    // This mongoose.connect never working for multples DB connection\n    // mongoose.connect('mongodb://localhost/masterDB'),\n    // Following is working fine and tested by me\n      mongoose.createConnection('mongodb://localhost/ChildDB'),\n  },\n];\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { mongooseProviders } from './mongoose.providers';\n\n@Module({\n  providers: [...mongooseProviders],\n  exports: [...mongooseProviders],\n})\nexport class MongooseModule {}\n```\n\n```text\nimport { Connection } from 'mongoose';\nimport { ChildSchema } from './schemas/child/child.schema';\nimport { MasterSchema } from './schemas/master/master.schema';\n\nexport const modelProviders = [\n  {\n    provide: 'CHILD_MODEL',\n    useFactory: (connection: Connection) => connection.model('Child', ChildSchema),\n    inject: ['CHILD_CONNECTION'],\n  },\n  {\n    provide: 'MASTER_MODEL',\n    useFactory: (connection: Connection) => connection.model('Master', MasterSchema),\n    inject: ['MASTER_CONNECTION'],\n  },\n];\n```\n\n```text\n@Injectable\nexport Class ModelService {\n  constructor(@Inject('MASTER_MODEL') private masterModel: Model<Master>) {}\n...\n```\n\n```text\nimport * as mongoose from 'mongoose';\n\nexport const mongooseProviders = [\n  {\n    provide: 'MASTER_CONNECTION',\n    useFactory: async (): Promise<unknown> =>\n      await mongoose.createConnection('mongodb://localhost/masterDB'),\n  },\n  {\n    provide: 'CHILD_CONNECTION',\n    useFactory: async (): Promise<unknown> =>\n      await mongoose.createConnection('mongodb://localhost/childDB'),\n  },\n];\n```\n\n```text\nmongoose.connect\n```\n\n```text\nmongoose.createConnection\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { studentSchema } from './schemas/myworld/student.schema';\nimport { animalSchema } from './schemas/wildlife/animal.schema';\n\n@Module({\n  imports: [\n    MongooseModule.forFeature([\n      {\n        name: 'Student',\n        schema: studentSchema,\n        collection: 'Student',\n        \n      },\n    ],'myWorldDb'),\n    MongooseModule.forFeature([\n      {\n        name: 'Animals',\n        schema: animalSchema,\n        collection: 'Animals'\n      }\n    ],'wildLifeDb'),\n    MongooseModule.forRoot(\n      'mongodb+srv://<userName>:<password>@cluster0-igk.mongodb.net/MyWorld?retryWrites=true&w=majority',\n      {\n        connectionName: 'myWorldDb'\n      }\n    ),\n    MongooseModule.forRoot(\n      'mongodb+srv://<username>:<password>@cluster0-igk.mongodb.net/WildLife?retryWrites=true&w=majority',\n      {\n        connectionName: 'wildLifeDb'\n      }\n    )\n\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- Hi, this seems the right answer to the question, ill mark it as \"answered\". But these providers are a singleton, right? Can we have a dynamic connections name? e.g. I may have multiple dynamic children (tenants) database - childDB1, childDB2, childDB3 ... and so on.\n- yes you can you will have to use a custom provider for each conection docs.nestjs.com/fundamentals/custom-providers take a look at this\n- hey, I think my above comment was not clear. I have a situation - I have users collection in my MasterDB and for each user registered in the app I need to create and use ChildDB dynamically e.g. user1 in MasterDB will have its own user1DB which can be accessed by some particular modules only. How can I update the MongoDB uri for each of those modules?\n- just change it in the mongoose.providers.ts in its factory\n- Happy to be helpfull ^^\n- I get this error: ERROR [ExceptionHandler] Nest can't resolve dependencies of the TestService (?, AnimalsModel). Please make sure that the argument StudentModel at index [0] is available in the TestService context. Do you know why?\n- @JohnDoe_Scientist It has been a while but I found the same issue and figured out that you also need to specify the connectionName when you use the `@InjectModel`","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":258,"estimatedTokens":1723}}779{"id":"stack-69000952","source":"stackoverflow","questionId":69000952,"title":"How to generate pdf from docx - NodeJS + TypeScript","tags":["javascript","node.js","typescript","pdf-generation","nestjs"],"text":"Title: How to generate pdf from docx - NodeJS + TypeScript\nTags: javascript, node.js, typescript, pdf-generation, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to generate a PDF from a previously generated DOCX file in NodeJS. I'm using NestJS and TypeScript.\nI have tried many ways, but everything fails:\n\n- **@nativedocuments/docx-wasm**: NativeDocuments isn't working anymore.\n\n- **word2pdf**: Is archived at github, and unavailable at npm.\n**docx-pdf**: Generates an unstyled pdf. It removes my tables, indentation,\njustified text, etc.\n**libreoffice-convert**: Throws a window error: The\napplication cannot be started. The configuration file \"C:/Program\nFiles/LibreOffice/program/bootstrap.ini\" is corrupt (But LibreOffice software is working with no problem).\n\nDo you know some workaround to the problems I got with any of the previously mentioned docx to pdf alternatives? Or maybe some other alternative that I can use (For free, please)?\n\nThank you in advance!\n\n========================================\n\nTop Answer:\nI've had success using Puppeteer to render PDFs from HTML documents. If you could manage to transform your DOCX file into HTML, this might be a viable option. It looks like there are options available to do so, but I can't vouch for them.\n\n========================================\n\nCode:\n```text\nconst { exec } = require(\"child_process\");\n\nexec(\"libreoffice --headless file.xyz\", (error, stdout, stderr) => {\n    if (error) {\n        console.log(`error: ${error.message}`);\n        return;\n    }\n    if (stderr) {\n        console.log(`stderr: ${stderr}`);\n        return;\n    }\n    console.log(`stdout: ${stdout}`);\n});\n```\n\n```text\nexec\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":418}}780{"id":"stack-61952027","source":"stackoverflow","questionId":61952027,"title":"Configure swagger with Nestjs + Azure functions","tags":["azure","swagger","azure-functions","nestjs","nestjs-swagger"],"text":"Title: Configure swagger with Nestjs + Azure functions\nTags: azure, swagger, azure-functions, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI am trying to develop my nestjs using azure functions following this article:\nhttps://trilon.io/blog/deploy-nestjs-azure-functions\n\nI have configured Swagger in my application as follows:\n\n```\n...\nconst options = new DocumentBuilder()\n .setTitle('App title')\n .setDescription('App description')\n .setVersion('1.0')\n .addBearerAuth(\n {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n },\n 'authorization',\n )\n .addTag('freight')\n .build();\n\n const document = SwaggerModule.createDocument(app, options);\n SwaggerModule.setup('swagger', app, document);\n...\n```\n\nWhen I run the app in development, I can access my swagger UI by navigating to `/swagger`, however when I run `npm run build && func host start`, I receive `500` error, which also happens when I hit a non-existing route.\n\nAll other routes that are registered in the application work as expected.\n\n========================================\n\nTop Answer:\nI have solved the problem with the code below\n\nStep 01: config package.json\n\n`\"start:azure\": \"npm run build && func host start --port 3000\"`\n\nStep 02: config at main.azure.ts\n\n```\nimport { INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';\n\nexport async function createApp(): Promise {\n const app = await NestFactory.create(AppModule);\n\n app.setGlobalPrefix('api');\n\n // setup swagger\n const swaggerOptions = new DocumentBuilder()\n .setTitle('NestJS Azure Functions')\n .setDescription('NestJS Azure Functions')\n .setVersion('1.0')\n .addTag('nestjs')\n .build();\n\n const document = SwaggerModule.createDocument(app, swaggerOptions);\n SwaggerModule.setup('/docs', app, document, {\n useGlobalPrefix: true,\n });\n\n await app.init();\n await app.listen(3000);\n\n return app;\n}\n```\n\nStep 03: Now u can run `npm run start:azure` and u can route localhost:3000/api/docs\n\n========================================\n\nCode:\n```js\n...\nconst options = new DocumentBuilder()\n    .setTitle('App title')\n    .setDescription('App description')\n    .setVersion('1.0')\n    .addBearerAuth(\n      {\n        type: 'http',\n        scheme: 'bearer',\n        bearerFormat: 'JWT',\n      },\n      'authorization',\n    )\n    .addTag('freight')\n    .build();\n\n  const document = SwaggerModule.createDocument(app, options);\n  SwaggerModule.setup('swagger', app, document);\n...\n```\n\n```text\n/swagger\n```\n\n```text\nnpm run build && func host start\n```\n\n```text\n500\n```\n\n```text\nfunc host start --port 3000\n```\n\n```text\n...\n//config\nconst config = new DocumentBuilder()\n.setTitle('My Title')\n.setDescription('My Description')\n.setVersion('1.0')\n.setBasePath('api-docs')\n.build();\n\nconst document = SwaggerModule.createDocument(app, config);\n\nSwaggerModule.setup('api-docs', app, document, {\n  useGlobalPrefix: true,\n});\n\n// order matters here. \napp.init() \n// port that is used for swagger ui. Sync with Az Fx. \napp.listen(3000)\n```\n\n```text\nimport { INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';\n\nexport async function createApp(): Promise<INestApplication> {\n  const app = await NestFactory.create(AppModule);\n\n  app.setGlobalPrefix('api');\n\n  // setup swagger\n  const swaggerOptions = new DocumentBuilder()\n    .setTitle('NestJS Azure Functions')\n    .setDescription('NestJS Azure Functions')\n    .setVersion('1.0')\n    .addTag('nestjs')\n    .build();\n\n  const document = SwaggerModule.createDocument(app, swaggerOptions);\n  SwaggerModule.setup('/docs', app, document, {\n    useGlobalPrefix: true,\n  });\n\n  await app.init();\n  await app.listen(3000);\n\n  return app;\n}\n```\n\n```text\n\"start:azure\": \"npm run build && func host start --port 3000\"\n```\n\n```text\nnpm run start:azure\n```\n\n========================================\n\nComments:\n- Looks to be that either nest or swagger ui has a bug that requires the app.listen and azure function to run on same port. As well the setBasePath must be set to match the route in the .setup portion. Consider this a work around.\n- We did same steps but still not loading swagger for us.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but itโ€™d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who arenโ€™t as familiar with the syntax or struggling to understand the concepts. **Would you kindly edit your answer to include additional details for the benefit of the community?**","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":188,"estimatedTokens":1196}}781{"id":"stack-57692838","source":"stackoverflow","questionId":57692838,"title":"TypeOrm doesn't save entity with it's relation on update","tags":["postgresql","typescript","nestjs","typeorm"],"text":"Title: TypeOrm doesn't save entity with it's relation on update\nTags: postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nGiven the following relation:\n\n```\n@Entity({name: 'accounts'})\nexport class Account {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @OneToOne(type => Address, address => address.id)\n @JoinColumn({name: 'address_id'})\n address: Address;\n\n @Column()\n name: string;\n}\n```\n\nAnd the addres relation:\n\n```\n@Entity({name: 'addresses'})\nexport class Address {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({length: 45})\n country: string;\n}\n```\n\nWhen I get the `account` entity by this:\n\n```\n/**\n * Gets account by haccount ID with ALL relations\n * @param accountId The account ID\n */\n public async getAccountByAccountIdWithRelations(accountId: string): Promise {\n return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n }\n```\n\nI get the full `Account` entity with the `Address` relation in it.\n\nAnd then when I do the following:\n\n```\naccount.address.country = 'newcountry';\n```\n\nand do `this.save(account)` in `accountRepository` the address won't update at all!\n\n*When I do console log before the save, I see the `account` entity with the updated address, so this is something really strange!*\n\nWhy is it happening?\n\n**Note: All queries are done in a transaction; I dont know if it matters**\n\n========================================\n\nTop Answer:\nDoing that kind of update on sql is quite complicated and even with queryBuilder TypeORM doesn't support join updates (you can see it here). The relation selector is quite helpfull but I would advise you to use it when its really necesary and add a nullable field to get the Ids of the address and obtain the address on separate it makes the things a lot easier in cases you need to change that relation lets say when you want to change the whole address object. this would be the result in the relations:\n\n```\n@Entity({name: 'accounts'})\nexport class Account {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ nullable: true })\n address_id: string;\n\n @OneToOne(type => Address, address => address.id)\n @JoinColumn({name: 'address_id'})\n address: Address;\n\n @Column()\n name: string;\n}\n```\n\nAnd you can keep calling the relation as you did before with:\n\n```\npublic async getAccountByAccountIdWithRelations(accountId: string): Promise {\n return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n }\n```\n\nUsing this aproach would keep inserting and updating easy and it works also in the oneToMany => manyToOne Relations too\n\n========================================\n\nCode:\n```text\n@Entity({name: 'accounts'})\nexport class Account {\n\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @OneToOne(type => Address, address => address.id)\n  @JoinColumn({name: 'address_id'})\n  address: Address;\n\n  @Column()\n  name: string;\n}\n```\n\n```text\n@Entity({name: 'addresses'})\nexport class Address {\n\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column({length: 45})\n  country: string;\n}\n```\n\n```text\n/**\n   * Gets account by haccount ID with ALL relations\n   * @param accountId The account ID\n   */\n  public async getAccountByAccountIdWithRelations(accountId: string): Promise<Account> {\n    return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n  }\n```\n\n```text\naccount.address.country = 'newcountry';\n```\n\n```text\naccount\n```\n\n```text\nAccount\n```\n\n```text\nAddress\n```\n\n```text\nthis.save(account)\n```\n\n```text\naccountRepository\n```\n\n```text\naccount\n```\n\n```text\n@Entity()\n@Index([ 'studyId', 'teamId', 'enterdate' ])\nexport class DataMessage extends BaseEntity {\n    @PrimaryGeneratedColumn('increment') id: number;\n\n    @CreateDateColumn() enterdate: Date;\n    @UpdateDateColumn({ select: false })\n    updatedAt?: Date;\n    @Column() owner: string;\n    @Column() studyId: number;\n    @Column() teamId: number;\n    @Column() patient: string;\n    @Column() orderId: number;\n    @Column({ default: DataMessageStatus.OPEN })\n    status: DataMessageStatus;\n\n    @Column()\n    @Index()\n    resultId: number;\n\n    @OneToMany(() => DataMessageContent, (c) => c.message, { cascade: true })\n    contents: DataMessageContent[];\n}\n\n@Entity()\nexport class DataMessageContent extends BaseEntity {\n    @PrimaryGeneratedColumn('increment') id: number;\n\n    @CreateDateColumn() enterdate: Date;\n    @Column() owner: string;\n    @Column() role: UserRole;\n    @Column({ default: MessageStatus.UNREAD })\n    status: MessageStatus;\n\n    @Column() txt: string;\n\n    @ManyToOne(() => DataMessage, (m) => m.contents)\n    message: DataMessage;\n}\n```\n\n```text\n@Entity({name: 'accounts'})\nexport class Account {\n\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column({ nullable: true })\n  address_id: string;\n\n  @OneToOne(type => Address, address => address.id)\n  @JoinColumn({name: 'address_id'})\n  address: Address;\n\n  @Column()\n  name: string;\n}\n```\n\n```text\npublic async getAccountByAccountIdWithRelations(accountId: string): Promise<Account> {\n    return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n  }\n```\n\n========================================\n\nComments:\n- Can you add some more context around your answer?\n- I've added a complete example\n- That's right, cascade makes it delete and save recursive, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":241,"estimatedTokens":1321}}782{"id":"stack-47747930","source":"stackoverflow","questionId":47747930,"title":"How to resolve DI issue in nest.js?","tags":["node.js","typescript","dependency-injection","nestjs"],"text":"Title: How to resolve DI issue in nest.js?\nTags: node.js, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI wanna understand how to import 3rd party library in nestjs through DI. So, i have a class `AuthService`:\n\n```\nexport class AuthService {\n constructor(\n @Inject(constants.JWT) private jsonWebToken: any,\n ){}\n ....\n}\n```\n\nJWT provider:\n\n```\nimport * as jwt from 'jsonwebtoken';\nimport {Module} from '@nestjs/common';\nimport constants from '../../../constants';\n\nconst jwtProvider = {\n provide: constants.JWT,\n useValue: jwt,\n};\n\n@Module({\n components: [jwtProvider],\n})\nexport class JWTProvider {}\n```\n\nLibraries module:\n\n```\nimport { Module } from '@nestjs/common';\nimport {BcryptProvider} from './bcrypt/bcrypt.provider';\nimport {JWTProvider} from './jsonwebtoken/jwt.provider';\n\n@Module({\n components: [\n BcryptProvider,\n JWTProvider,\n ],\n controllers: [],\n exports: [\n BcryptProvider,\n JWTProvider,\n ],\n})\nexport class LibrariesModule{\n}\n```\n\nI'm getting this error:\n\n```\nError: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.\n at Injector. (D:\\Learning\\nest\\project\\node_modules\\@nestjs\\core\\injector\\injector.js:156:23)\n at Generator.next ()\n at fulfilled (D:\\Learning\\nest\\project\\node_modules\\@nestjs\\core\\injector\\injector.js:4:58)\n at \n at process._tickCallback (internal/process/next_tick.js:188:7)\n```\n\nBesides, I wanna hear some recommendations about not using type `any` in the `jsonWebToken` variable.\n\n========================================\n\nCode:\n```text\nexport class AuthService {\n   constructor(\n     @Inject(constants.JWT) private jsonWebToken: any,\n   ){}\n  ....\n}\n```\n\n```text\nimport * as jwt from 'jsonwebtoken';\nimport {Module} from '@nestjs/common';\nimport constants from '../../../constants';\n\nconst jwtProvider = {\n  provide: constants.JWT,\n  useValue: jwt,\n};\n\n@Module({\n  components: [jwtProvider],\n})\nexport class JWTProvider {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport {BcryptProvider} from './bcrypt/bcrypt.provider';\nimport {JWTProvider} from './jsonwebtoken/jwt.provider';\n\n@Module({\n  components: [\n    BcryptProvider,\n    JWTProvider,\n  ],\n  controllers: [],\n  exports: [\n    BcryptProvider,\n    JWTProvider,\n  ],\n})\nexport class LibrariesModule{\n}\n```\n\n```text\nError: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.\n    at Injector.<anonymous> (D:\\Learning\\nest\\project\\node_modules\\@nestjs\\core\\injector\\injector.js:156:23)\n    at Generator.next (<anonymous>)\n    at fulfilled (D:\\Learning\\nest\\project\\node_modules\\@nestjs\\core\\injector\\injector.js:4:58)\n    at <anonymous>\n    at process._tickCallback (internal/process/next_tick.js:188:7)\n```\n\n```text\nAuthService\n```\n\n```text\nany\n```\n\n```text\njsonWebToken\n```\n\n```text\n@Module({\n  modules: [LibrariesModule], // <= added this line\n  components: [AuthService, JwtStrategy],\n  controllers: [],\n})\nexport class AuthModule {\n\n}\n```\n\n========================================\n\nComments:\n- I digged a little bit deeper, and, according to comments in source code: \"The component can inject dependencies through constructor. Those dependencies should belongs to the same module.\". Question is the same, but how do i inject external component?\n- Do i need to make separate question or keep this?","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":154,"estimatedTokens":848}}783{"id":"stack-70709925","source":"stackoverflow","questionId":70709925,"title":"How to add description to @ApiTags for swagger in NestJS?","tags":["swagger","nestjs"],"text":"Title: How to add description to @ApiTags for swagger in NestJS?\nTags: swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to add desription for block of api.\n\nI have tried:\n\n```\n@ApiOperation({\n description: 'Operation description'\n})\n```\n\nIt doesn't work.\n\n========================================\n\nTop Answer:\nTo improve previous answer:\nYou can add tag description on initial step\n\n```\nnew DocumentBuilder()\n.setTitle('API with NestJS')\n...\n.addTag('SomeTag1', 'Tag description 1')\n.addTag('SomeTag2', 'Tag description 2')\n```\n\nAnd then use tag on class level (controller)\n\n```\n@ApiTags('SomeTag1')\n```\n\n========================================\n\nCode:\n```text\n@ApiOperation({\n  description: 'Operation description'\n})\n```\n\n```js\n@ApiOperation({ summary: 'Operation description' })\n```\n\n```js\n@ApiTags('MyTag')\n```\n\n```text\nnew DocumentBuilder()\n.setTitle('API with NestJS')\n...\n.addTag('SomeTag1', 'Tag description 1')\n.addTag('SomeTag2', 'Tag description 2')\n```\n\n```text\n@ApiTags('SomeTag1')\n```\n\n```js\n// users.controller.ts\n@ApiTag({\n  name: 'users',\n  description: 'Get all users',\n})\n@ApiBearerAuth()\n@Controller('users')\nexport class UsersController {}\n\n\n// ApiTag.decorator.ts\nimport { swaggerConfig } from '@/common/swagger';\nimport { TagObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface';\nimport { ApiTags } from '@nestjs/swagger';\nimport { applyDecorators } from '@nestjs/common';\n\nexport const ApiTag = (tagObject: TagObject) => {\n  swaggerConfig.tags.unshift(tagObject);\n  return applyDecorators(ApiTags(tagObject.name));\n};\n\n//  common/swagger.ts\nimport { DocumentBuilder } from '@nestjs/swagger';\n\nconst swaggerConfig = new DocumentBuilder()\n  .setTitle('title')\n  .setDescription('api docs')\n  .setVersion('1.0')\n  .addBearerAuth()\n  .build();\n\nexport { swaggerConfig };\n\n//main.ts\n  const options: SwaggerDocumentOptions = {\n    operationIdFactory: (controllerKey: string, methodKey: string) => methodKey,\n  };\n  const document = SwaggerModule.createDocument(app, swaggerConfig, options);\n  SwaggerModule.setup('docs', app, document);\n```\n\n========================================\n\nComments:\n- Unable to resolve signature of class decorator when ca lled as an expression. 8 @ApiOperation({ summary: 'Operation description' })\n- I have this error\n- `@ApiOperation` is meant to be used on methods and can't be used on classes. I think what you are looking for is `@ApiTags()`. Check here: docs.nestjs.com/openapi/decorators\n- No such functionality\n- I want to add description to @ApiTags('')\n- Adding a description to the tag doesnโ€˜t seem to be supported by NestJS at the moment.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":118,"estimatedTokens":726}}784{"id":"stack-60610383","source":"stackoverflow","questionId":60610383,"title":"Nestjs Event Sourcing - Event Persistence","tags":["typescript","domain-driven-design","nestjs","cqrs","event-sourcing"],"text":"Title: Nestjs Event Sourcing - Event Persistence\nTags: typescript, domain-driven-design, nestjs, cqrs, event-sourcing\nSource: Stack Overflow\n\nQuestion:\nHow is event persistence handled in Nestjs? It's not clear in the documentation (Read the CQRS Recipe), how we should persist events and how we reply them using snapshots. Its also not clear how to create the read side separated from the write side.\n\n========================================\n\nTop Answer:\nLate to the party here, but in case you're still looking for a solution for event-persistence: @ocoda/event-sourcing is a NestJS module that offers the basic functionality that @nestjs/cqrs provides, but also adds the necessary tools for storing and retrieving events (and snapshots). On the other hand, what it still lacks are Saga's and a built-in way of doing event-replays.\n\nFull disclosure: I'm the creator of the library.\n\n========================================\n\nCode:\n```text\nCommand\n```\n\n```text\nSaga\n```\n\n```text\nQuery\n```\n\n```text\nEvent\n```\n\n```text\nAggregateRoot\n```\n\n```text\nQuery\n```\n\n========================================\n\nComments:\n- Read side of events?\n- \"One last tip is to never make direct calls to your read-side logic from write-side code (a recipe for trouble as it destroys the command/query separation).\" Is this true only for a read and write side within the same aggregate? Is it okay to call a read side of one aggregate from the write side of another?\n- @G.Kashtanov I believe that is context/domain specific. If the saga does not mutate the data you are trying to read, it shouldn't matter.\n- I've read about event sourcing and I've found that we can roll back the system state to a specific place. e.g roll back a transaction and give money back using payment microservice when our wallet microservice get fails. Is it correct? or do we need to dispatch new events for that purpose?\n- If you refer here to 'time travel' it may be possible, but you will likely have to perform Compensating Transaction, because a monetary refund will be subject to a different event flow than the initial money transfer. But ideally the failure should be handled in your design's eventual consistency of a transaction where a PaymentReceived isn't available on such events. So the process flows can't continue and you might retry the failed actions / commands.","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":49,"estimatedTokens":584}}785{"id":"stack-63630805","source":"stackoverflow","questionId":63630805,"title":"How to set default time zone in Nestjs?","tags":["nestjs","nestjs-config"],"text":"Title: How to set default time zone in Nestjs?\nTags: nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI tried below script but it didn't work.\n\n```\n{\n \"scripts\": {\n \"start\": \"TZ='UTC' nest start\"\n }\n}\n```\n\n[System Information]\n\nOS Version : Linux 5.4\n\nNodeJS Version : v12.18.3\n\nNPM Version : 6.14.6 \n\n[Nest CLI]\n\nNest CLI Version : 7.4.1 \n\n[Nest Platform Information]\n\nplatform-express version : 7.0.0\n\npassport version : 7.0.0\n\ntypeorm version : 7.1.0\n\ncommon version : 7.0.0\n\nconfig version : 0.5.0\n\ncore version : 7.0.0\n\njwt version : 7.0.0\n\n========================================\n\nCode:\n```text\n{\n  \"scripts\": {\n    \"start\": \"TZ='UTC' nest start\"\n  }\n}\n```\n\n```sh\nTZ=UTC node\n> d = new Date()\n> d.toLocaleTimeString()\n```\n\n```text\n\"start\": \"TZ=UTC nest start\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":63,"estimatedTokens":195}}786{"id":"stack-61954312","source":"stackoverflow","questionId":61954312,"title":"NestJs - Class-validator not returning full validation error object","tags":["node.js","typescript","validation","nestjs","class-validator"],"text":"Title: NestJs - Class-validator not returning full validation error object\nTags: node.js, typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI am using class-validator in NestJS to create valdations like this:\n\n```\nexport class LoginDTO {\n@IsEmail()\n@MinLength(4)\nemail: string;\n\n@IsNotEmpty()\n@MinLength(4)\npassword: string;\n```\n\n}\n\nIt works, but not as expected. The returned object looks like this :\n\n```\n{\n\"statusCode\": 400,\n\"message\": [\n \"email must be longer than or equal to 4 characters\",\n \"email must be an email\"\n],\n\"error\": \"Bad Request\"\n```\n\n}\n\nWhile i want it to contain all the information like this :\n\n```\n{\n \"statusCode\": 400,\n [{\n target: /* post object */,\n property: \"title\",\n value: \"Hello\",\n constraints: {\n length: \"$property must be longer than or equal to 10 characters\"\n }]\n \"error\": \"Bad Request\"\n}\n```\n\nHow to do to return all the missing properties ?\n\n========================================\n\nCode:\n```text\nexport class LoginDTO {\n@IsEmail()\n@MinLength(4)\nemail: string;\n\n@IsNotEmpty()\n@MinLength(4)\npassword: string;\n```\n\n```text\n{\n\"statusCode\": 400,\n\"message\": [\n    \"email must be longer than or equal to 4 characters\",\n    \"email must be an email\"\n],\n\"error\": \"Bad Request\"\n```\n\n```text\n{\n    \"statusCode\": 400,\n    [{\n        target: /* post object */,\n        property: \"title\",\n        value: \"Hello\",\n        constraints: {\n        length: \"$property must be longer than or equal to 10 characters\"\n    }]\n    \"error\": \"Bad Request\"\n}\n```\n\n```js\nexceptionFactory: (errors) => new BadRequestException(errors),\n```\n\n```text\nNestv7\n```\n\n```text\nValidationPipe\n```\n\n```text\nexceptionFactory\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":415}}787{"id":"stack-71742545","source":"stackoverflow","questionId":71742545,"title":"NestJS HTTP Module needs to be imported in every feature module","tags":["nestjs"],"text":"Title: NestJS HTTP Module needs to be imported in every feature module\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nIn nestjs the http module needs to be imported into every feature module. Is there any way to import the http module only once throughout the full application?\n\nAlthough in all the feature modules the http configurations are the same, why do we need to import and configure in each one.\n\nThanks.\n\n========================================\n\nTop Answer:\nIf you don't want to create a wrapper module, you can also:\n\n```\n@Module({\n imports: [\n {\n ...HttpModule.register(httpModuleOptions),\n global: true\n }\n ],\n})\nexport class AppModule {}\n```\n\n========================================\n\nCode:\n```js\n@Global()\n@Module({\n  imports: [HttpModule.register(httpModuleOptions)],\n  exports: [HttpModule],\n})\nexport class GlobalHttpModule {}\n```\n\n```text\nAppModule\n```\n\n```text\nHttpService\n```\n\n```js\n@Module({\n  imports: [\n    {\n      ...HttpModule.register(httpModuleOptions),\n      global: true\n    }\n  ],\n})\nexport class AppModule {}\n```\n\n```js\n@Module({\n  imports: [\n    HttpModule.register({ global: true }),\n  ],\n  // ... controllers & providers\n})\n```\n\n```text\nHttpModule\n```\n\n```text\nregister\n```\n\n```text\n{ global: true }\n```\n\n```text\nConfigModule\n```\n\n```text\nforRoot\n```\n\n```text\nisGlobal\n```\n\n========================================\n\nComments:\n- Thanks mate. Can you also put a reference to where I can read more about this? Noob at nestjs here.\n- @RohitGupta module re-exporting and global modules","metadata":{"transformedAt":"2026-08-18T18:33:02.468Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":98,"estimatedTokens":379}}788{"id":"stack-68180035","source":"stackoverflow","questionId":68180035,"title":"Nest.js get request header in passport local strategy","tags":["node.js","mongodb","jwt","passport.js","nestjs"],"text":"Title: Nest.js get request header in passport local strategy\nTags: node.js, mongodb, jwt, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow can I get the request headers inside passport local strategy?\nI need a separate database for each entity, using mongodb so I need a way to get the subdomain before authentication in order to determine the database that I should connect to\n\n```\n@Injectable()\n export class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private authService: AuthService) {\n super({ usernameField: 'email' })\n }\n \n async validate(email: string, password: string, headers:Headers): Promise {\n //** this is what I want to have\n //** const subdomain = headers.host.split(\".\")[0]\n const user = await this.authService.validateUser({ email, password ,//** subdomain})\n if (!user) {\n throw new UnauthorizedException()\n }\n return user\n }\n }\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\n    export class LocalStrategy extends PassportStrategy(Strategy) {\n        constructor(private authService: AuthService) {\n            super({ usernameField: 'email' })\n        }\n    \n        async validate(email: string, password: string, headers:Headers): Promise<IUser> {\n            //** this is what I want to have\n            //** const subdomain = headers.host.split(\".\")[0]\n            const user = await this.authService.validateUser({ email, password ,//** subdomain})\n            if (!user) {\n                throw new UnauthorizedException()\n            }\n            return user\n        }\n    }\n```\n\n```js\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n  constructor(private authService: AuthService) {\n    super({ usernameField: 'email', passReqToCallback: true })\n  }\n\n  async validate(req: Request, email: string, password: string, headers:Headers): Promise<IUser> {\n    const subdomain = req.headers.host.split(\".\")[0];\n    const user = await this.authService.validateUser({ email, password ,//** subdomain})\n    if (!user) {\n      throw new UnauthorizedException()\n    }\n    return user\n  }\n}\n```\n\n```text\npassReqToCallback: true\n```\n\n```text\nsuper\n```\n\n```text\nreq\n```\n\n```text\nvalidate\n```\n\n========================================\n\nComments:\n- How can access to ``` user ``` from the controller?\n- Like you would with any passport strategy. `req.user`\n- Thanks bro I couldn't find the docs which this property is specified","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":89,"estimatedTokens":608}}789{"id":"stack-70802610","source":"stackoverflow","questionId":70802610,"title":"Module not found: Error: Can't resolve 'class-transformer/storage' - Angular Universal / NestJs","tags":["angular","nestjs","server-side-rendering","angular-universal"],"text":"Title: Module not found: Error: Can't resolve 'class-transformer/storage' - Angular Universal / NestJs\nTags: angular, nestjs, server-side-rendering, angular-universal\nSource: Stack Overflow\n\nQuestion:\nFolks, I've been trying to implement an application using angular with angular universal and NestJs.\nI believe that is possible to seize the nest server not only for SSR, but also to also provide API endpoints.\n\nI've made the setup recommended on https://github.com/nestjs/ng-universal using `ng add @nestjs/ng-universal`, pretty standard. After that I added my code to the angular src folder and installed the needed dependencies.\n\nThe problem is that when I try to import a module to nest app.module, I get the following error:\n`Error: Module not found: Error: Can't resolve 'class-transformer/storage'`\n\nI've tried to use webpack, but since my knowledge on webpack is petty, the results were failure after failure, as expected.\n\nFirst, is it possible to seize the server also to provide endpoints?\nSecond, what should I do to resolve this module?\n\n**Please find below the repository for reproducing the issue:**\n\nhttps://github.com/vitordhers/universal-nest\n\nThanks in advance\n\n========================================\n\nTop Answer:\nFor anyone using webpack with nestjs add the `class-transformer/storage` into the `lazyImport` on the `webpack.config.js` file.\n\n========================================\n\nCode:\n```text\nng add @nestjs/ng-universal\n```\n\n```text\nError: Module not found: Error: Can't resolve 'class-transformer/storage'\n```\n\n```text\nnpm install --save class-transformer@0.3.1\n```\n\n```text\nclass-transformer/storage\n```\n\n```text\nlazyImport\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nimport { defaultMetadataStorage } from 'class-transformer/cjs/storage';\n```\n\n```text\nnpm install --save class-transformer@0.3.1\n```\n\n```text\nyaml\ncustom:\n esbuild:\n   bundle: true\n   minify: true\n   sourcemap: true\n   exclude: ['aws-sdk']\n   target: 'node18'\n   platform: 'node'\n   concurrency: 10\n   external:\n     - 'class-transformer'\n     - '@nestjs/websockets'\n     - '@nestjs/websockets/socket-module'\n     - '@nestjs/microservices/microservices-module'\n```\n\n========================================\n\nComments:\n- Do you have a config you could ? I have added to mine and still isnt working\n- This is kind of old but the config I used back then was: ``` module.exports = (o, w) => { const lazyI = ['@nestjs/microservices/microservices-module','@nestjs/webso&zwnj;&#8203;ckets/socket-module'&zwnj;&#8203;,'class-transformer/&zwnj;&#8203;storage']; return { plugins: [ ...o.plugins, new w.IgnorePlugin({ checkResource(resource) { if (lazyI.includes(resource)) { try { require.resolve(resource); } catch (err) { return true; } } return false; }, }), ], } ```\n- I skip some parts of the config like the `output`, `external` and `optimization` keys","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":88,"estimatedTokens":712}}790{"id":"stack-67066064","source":"stackoverflow","questionId":67066064,"title":"Error: metatype is not a constructor when using instance of own HTTPS Server class","tags":["node.js","nestjs"],"text":"Title: Error: metatype is not a constructor when using instance of own HTTPS Server class\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nGood evening, I am playing around with nest and want to achieve an own HTTPS-Server that can be instantiated everywhere in other projects. Right at the beginning I get the following error-message:\n\n```\nTypeError: metatype is not a constructor\n```\n\nโ€ฆ when I init the following HTTPS-Server:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';\nimport * as fs from 'fs';\n\n@Injectable()\nexport class HttpsServer {\n\n constructor() {}\n\n async bootstrap() {\n const httpsOptions = {\n key: fs.readFileSync('./certs/server.key'),\n cert: fs.readFileSync('./certs/server.cert'),\n };\n const app = await NestFactory.create(\n new FastifyAdapter({ https: httpsOptions }),\n );\n\n await app.listen(443);\n }\n}\n```\n\nlike this:\n\n```\nimport { Logger } from '@nestjs/common';\nimport { HttpsServer } from 'server-lib';\n\nconst logger = new Logger();\nconst app = new HttpsServer();\n\napp.bootstrap().then(() => {\n logger.log('Bootstrap complete!');\n}).catch((error) => {\n logger.log('Bootstrap failed: ', error);\n process.exit(1);\n});\n```\n\nThx for help...\n\n========================================\n\nTop Answer:\nYou probably have used an incorrect guard.\nCheck @UseGuards() and use the correct guard for that function.\n\n========================================\n\nCode:\n```text\nTypeError: metatype is not a constructor\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';\nimport * as fs from 'fs';\n\n@Injectable()\nexport class HttpsServer {\n\n    constructor() {}\n\n    async bootstrap() {\n        const httpsOptions = {\n            key: fs.readFileSync('./certs/server.key'),\n            cert: fs.readFileSync('./certs/server.cert'),\n        };\n        const app = await NestFactory.create<NestFastifyApplication>(\n            new FastifyAdapter({ https: httpsOptions }),\n        );\n\n        await app.listen(443);\n    }\n}\n```\n\n```text\nimport { Logger } from '@nestjs/common';\nimport { HttpsServer } from 'server-lib';\n\nconst logger = new Logger();\nconst app = new HttpsServer();\n\napp.bootstrap().then(() => {\n  logger.log('Bootstrap complete!');\n}).catch((error) => {\n  logger.log('Bootstrap failed: ', error);\n  process.exit(1);\n});\n```\n\n```js\nexport class HttpsServer {\n\n    constructor(private readonly rootModule: Type<any>) {} // Type comes from @nestjs/common\n\n    async bootstrap() {\n        const httpsOptions = {\n            key: fs.readFileSync('./certs/server.key'),\n            cert: fs.readFileSync('./certs/server.cert'),\n        };\n        const app = await NestFactory.create<NestFastifyApplication>(\n            this.rootModule, \n            new FastifyAdapter({ https: httpsOptions }),\n        );\n\n        await app.listen(443);\n    }\n}\n```\n\n```text\nnest new\n```\n\n```text\nAppModule\n```\n\n```text\nHttpModule\n```\n\n```text\nconstructor\n```\n\n```text\nnew HttpServer()\n```\n\n```text\nNestFactory\n```\n\n```text\nFastifyAdapter\n```\n\n```text\nimport * as Entities from './entities\n```\n\n========================================\n\nComments:\n- Where's the `AppModule` for the `NestFactory.create`?\n- I have no one :-(. I&#180;m new on this stuff. Maybe you have a link for me...\n- My issue was related to this solution. I accidentally imported the incorrect AuthGuard class, causing the error seen above.","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":168,"estimatedTokens":894}}791{"id":"stack-71484150","source":"stackoverflow","questionId":71484150,"title":"Nest Js - How to generate a file and send it as a request response without saving the file locally?","tags":["javascript","file","nestjs"],"text":"Title: Nest Js - How to generate a file and send it as a request response without saving the file locally?\nTags: javascript, file, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a task where I need to export a json to csv via an endpoint. When accessing the endpoint, the route should return the .csv file with the data. Is there a way to do this without having to save the file locally?\n\n========================================\n\nComments:\n- But in this case, the interceptor will only work when I'm receiving the request in my API, right? In my case, I need to receive a request, generate the .csv file and return as a result, without saving the file locally.\n- If you have the file as a file object in memory, you should be able to return a streamable file docs.nestjs.com/techniques/streaming-files\n- I'll read about it, thanks for the help!","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":212}}792{"id":"stack-71723286","source":"stackoverflow","questionId":71723286,"title":"can not generate resource nestjs : typeScript","tags":["typescript","npm","nestjs","yarnpkg"],"text":"Title: can not generate resource nestjs : typeScript\nTags: typescript, npm, nestjs, yarnpkg\nSource: Stack Overflow\n\nQuestion:\nI am getting this error:\n\n```\nTypeError: Cannot read property 'properties' of undefined\n\nFailed to execute command: \nnode @nestjs/schematics:resource --name=post --no-dry-run --language=\"ts\" --sourceRoot=\"src\" --spec\n```\n\nWhat Iโ€™ve tried so far:\n\n```\nnpm i -g @nestjs/schematics\n```\n\nand\n\n```\nnpm install --save-dev webpack-cli@3.1.1\n```\n\nbut they also did not work.\n\nIssue when creating new resources with nest g resource\n\n**package.json**\n\n```\n{\n \"name\": \"nestjs\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"prebuild\": \"rimraf dist\",\n \"build\": \"nest build\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"nest start\",\n \"start:dev\": \"nest start --watch\",\n \"start:debug\": \"nest start --debug --watch\",\n \"start:prod\": \"node dist/main\",\n \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@hapi/joi\": \"^17.1.1\",\n \"@nestjs/common\": \"^8.0.0\",\n \"@nestjs/config\": \"^2.0.0\",\n \"@nestjs/core\": \"^8.0.0\",\n \"@nestjs/jwt\": \"^8.0.0\",\n \"@nestjs/mapped-types\": \"*\",\n \"@nestjs/passport\": \"^8.2.1\",\n \"@nestjs/platform-express\": \"^8.0.0\",\n \"@nestjs/typeorm\": \"^8.0.3\",\n \"@types/bcrypt\": \"^5.0.0\",\n \"@types/cookie-parser\": \"^1.4.2\",\n \"@types/hapi__joi\": \"^17.1.8\",\n \"@types/passport-jwt\": \"^3.0.6\",\n \"@types/passport-local\": \"^1.0.34\",\n \"bcrypt\": \"^5.0.1\",\n \"cookie-parser\": \"^1.4.6\",\n \"passport\": \"^0.5.2\",\n \"passport-jwt\": \"^4.0.0\",\n \"passport-local\": \"^1.0.0\",\n \"pg\": \"^8.7.3\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^3.0.2\",\n \"rxjs\": \"^7.2.0\",\n \"typeorm\": \"^0.2.45\"\n },\n \"devDependencies\": {\n \"@nestjs/cli\": \"^8.0.0\",\n \"@nestjs/schematics\": \"^8.0.0\",\n \"@nestjs/testing\": \"^8.0.0\",\n \"@types/express\": \"^4.17.13\",\n \"@types/jest\": \"27.4.1\",\n \"@types/node\": \"^16.0.0\",\n \"@types/supertest\": \"^2.0.11\",\n \"@typescript-eslint/eslint-plugin\": \"^5.0.0\",\n \"@typescript-eslint/parser\": \"^5.0.0\",\n \"eslint\": \"^8.0.1\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"jest\": \"^27.2.5\",\n \"prettier\": \"^2.3.2\",\n \"source-map-support\": \"^0.5.20\",\n \"supertest\": \"^6.1.3\",\n \"ts-jest\": \"^27.0.3\",\n \"ts-loader\": \"^9.2.3\",\n \"ts-node\": \"^10.0.0\",\n \"tsconfig-paths\": \"^3.10.1\",\n \"typescript\": \"^4.3.5\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"collectCoverageFrom\": [\n \"**/*.(t|j)s\"\n ],\n \"coverageDirectory\": \"../coverage\",\n \"testEnvironment\": \"node\"\n }\n}\n```\n\n**ts config**\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"skipLibCheck\": true,\n \"strictNullChecks\": true,\n \"noImplicitAny\": false,\n \"strictBindCallApply\": false,\n \"forceConsistentCasingInFileNames\": false,\n \"noFallthroughCasesInSwitch\": false\n }\n}\n```\n\n**Edit:** I have also tried the following that didnโ€™t work:\n\n```\nnpx nest g resource post\n```\n\n========================================\n\nTop Answer:\nI had similar issue. in my case my global and local nest cli version were out of sync. I ran\n\n```\nnpm i -g @nestjs/cli\n```\n\nEverything works fine now\n\n========================================\n\nCode:\n```none\nTypeError: Cannot read property 'properties' of undefined\n\nFailed to execute command: \nnode @nestjs/schematics:resource --name=post --no-dry-run --language=\"ts\" --sourceRoot=\"src\" --spec\n```\n\n```none\nnpm i -g @nestjs/schematics\n```\n\n```none\nnpm install --save-dev webpack-cli@3.1.1\n```\n\n```json\n{\n  \"name\": \"nestjs\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@hapi/joi\": \"^17.1.1\",\n    \"@nestjs/common\": \"^8.0.0\",\n    \"@nestjs/config\": \"^2.0.0\",\n    \"@nestjs/core\": \"^8.0.0\",\n    \"@nestjs/jwt\": \"^8.0.0\",\n    \"@nestjs/mapped-types\": \"*\",\n    \"@nestjs/passport\": \"^8.2.1\",\n    \"@nestjs/platform-express\": \"^8.0.0\",\n    \"@nestjs/typeorm\": \"^8.0.3\",\n    \"@types/bcrypt\": \"^5.0.0\",\n    \"@types/cookie-parser\": \"^1.4.2\",\n    \"@types/hapi__joi\": \"^17.1.8\",\n    \"@types/passport-jwt\": \"^3.0.6\",\n    \"@types/passport-local\": \"^1.0.34\",\n    \"bcrypt\": \"^5.0.1\",\n    \"cookie-parser\": \"^1.4.6\",\n    \"passport\": \"^0.5.2\",\n    \"passport-jwt\": \"^4.0.0\",\n    \"passport-local\": \"^1.0.0\",\n    \"pg\": \"^8.7.3\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^7.2.0\",\n    \"typeorm\": \"^0.2.45\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^8.0.0\",\n    \"@nestjs/schematics\": \"^8.0.0\",\n    \"@nestjs/testing\": \"^8.0.0\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"27.4.1\",\n    \"@types/node\": \"^16.0.0\",\n    \"@types/supertest\": \"^2.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.0.0\",\n    \"@typescript-eslint/parser\": \"^5.0.0\",\n    \"eslint\": \"^8.0.1\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-prettier\": \"^4.0.0\",\n    \"jest\": \"^27.2.5\",\n    \"prettier\": \"^2.3.2\",\n    \"source-map-support\": \"^0.5.20\",\n    \"supertest\": \"^6.1.3\",\n    \"ts-jest\": \"^27.0.3\",\n    \"ts-loader\": \"^9.2.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"tsconfig-paths\": \"^3.10.1\",\n    \"typescript\": \"^4.3.5\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"collectCoverageFrom\": [\n      \"**/*.(t|j)s\"\n    ],\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  }\n}\n```\n\n```json\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": true,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false\n  }\n}\n```\n\n```none\nnpx nest g resource post\n```\n\n```text\nnest update -f -t latest\n```\n\n```text\nyarn upgrade-interactive --latest\n```\n\n```text\nyarn global add @nestjs/schematics\n```\n\n```bash\nnpm  i -g @nestjs/cli\n```\n\n========================================\n\nComments:\n- Since v9.0.0 release, the command update was removed. To upgrade your dependencies, you can use dedicated tools like ncu (npmjs.com/package/npm-check-updates) ncu -u or use yarn upgrade-interactive\n- This fixed my issue - 2023 Apr with M1 Mac","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":326,"estimatedTokens":1919}}793{"id":"stack-71889130","source":"stackoverflow","questionId":71889130,"title":"Render.com: HttpOnly Cookie not being set in browser storage when doing res.cookie between Web Services","tags":["cookies","nestjs","cross-domain","samesite","httponly"],"text":"Title: Render.com: HttpOnly Cookie not being set in browser storage when doing res.cookie between Web Services\nTags: cookies, nestjs, cross-domain, samesite, httponly\nSource: Stack Overflow\n\nQuestion:\nI have a NestJs app that uses HttpOnly cookies for authentication. In development everything works perfectly. My NextJs client (http://localhost:4200) uses Graphql to send a login request to my NestJs server (http://localhost:3333), which sets httpOnly cookies in the response, and then the client successfully adds the cookies to the browser storage.\n\nHowever, when I deploy both apps to Render.com, everything works apart from the final step. The cookies are successfully received in the response, but are not added to the browser storage. Interestingly, if I use the GraphQL playground of the deployed production server to make the login request, everything works. So, clearly, the issue seems to be that the request is coming from a subdomain.\n\n**My production configuration:**\n\nClient: https://swingapple-web-staging.onrender.com\n\nServer: https://swingapple-api-staging.onrender.com\n\n**Cookies settings (Server):**\n\n```\nsameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',\nsecure: process.env.NODE_ENV === 'production',\ndomain: process.env.NODE_ENV === 'production' ? '.onrender.com' : undefined\n```\n\n**Nestjs's GraphQLModule settings (Server):**\n\n```\nplayground: true,\nintrospection: true,\nautoSchemaFile: true,\nsortSchema: true,\ncontext: ({ req, res }) => ({ req, res }),\ncors: {\n credentials: true,\n origin: [process.env.CLIENT_URL, 'http://localhost:4200']\n}\n```\n\n**Relevant Nest main.ts config (server):**\n\n```\napp.set('trust proxy', 1);\n```\n\n**graphql-request settings (client):**\n\n```\ncredentials: 'include'\n```\n\nI've spent days trying to figure this out so any help would be really appreciated!\n\n========================================\n\nTop Answer:\nYou can't do anything other than just adding a custom domain. I find this strange.\nRender should do something about it.\n\n========================================\n\nCode:\n```text\nsameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',\nsecure: process.env.NODE_ENV === 'production',\ndomain: process.env.NODE_ENV === 'production' ? '.onrender.com' : undefined\n```\n\n```text\nplayground: true,\nintrospection: true,\nautoSchemaFile: true,\nsortSchema: true,\ncontext: ({ req, res }) => ({ req, res }),\ncors: {\n    credentials: true,\n    origin: [process.env.CLIENT_URL, 'http://localhost:4200']\n}\n```\n\n```text\napp.set('trust proxy', 1);\n```\n\n```text\ncredentials: 'include'\n```\n\n```text\nonrender.com\n```\n\n========================================\n\nComments:\n- No worries Pear, happy to help!\n- hi, will this work for the free tier for render.com? I'm looking for free options.\n- Based on the render.com docs, your first 25 custom domains are indeed free: render.com/docs/custom-domains","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":96,"estimatedTokens":715}}794{"id":"stack-75249661","source":"stackoverflow","questionId":75249661,"title":"Using @Type discriminator with class-validator and class-transform not working in tandem","tags":["nestjs","class-validator","class-transformer"],"text":"Title: Using @Type discriminator with class-validator and class-transform not working in tandem\nTags: nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have a class with a property on it, which can be a number of classes based on a property. `@Type` obviously is perfect for this, but the issue is, the discriminator does not exist on the object, it exists on the parent.\n\nConsider the following:\n\n```\nclass Parent {\n type: 'a' | 'b'\n\n @Type(() => ?, {\n discriminator: {\n property: 'type',\n subTypes: [\n { value: TypeA, name: 'a' },\n { value: TypeB, name: 'b' },\n ] \n }\n }\n data: TypeA | TypeB\n\n}\n```\n\nNaturally I can't do this. I tried a custom decorator which does something like:\n\n```\nconst TypeOnParent: () => PropertyDecorator = () => {\n const __class__ = class {}\n const prop = '__type'\n\n return (target, key) => {\n Transform(({ value, obj }) => {\n value[prop] = obj.type\n return value\n })(target, key)\n\n Type(() => __class__, {\n keepDiscriminatorProperty: true,\n discriminator: {\n property: prop,\n subTypes: [\n { name: 'a', value: TypeA },\n { name: 'b', value: TypeB },\n ],\n },\n })(target, key)\n }\n}\n\nclass Parent {\n type: 'a' | 'b'\n\n @TypeOnParent('type')\n data: TypeA | TypeB\n\n}\n```\n\nThe goal here is to pass the parent prop onto the child, so that `Type` discriminator can do its job. However, the discriminator prop that I pass onto the child 'data' prop doesn't seem to work. It just defaults to using the **class** instance. I've tried changing the order of the decorators.\n\nThe result is an identical object no matter what, but if I pass the value in manually via payload, it works fine. If I use the transform, it never works.\n\nAm I missing something? Does class-transform ALWAYS run `type` before any other decorators? Or is there a better way to achieve this?\nI am using nestjs global validation pipe if that helps.\n\n========================================\n\nTop Answer:\nThe discriminator `property` attribute expect a value which is a property in each your subtypes. In your case `TypeA` and `TypeB` should both have the `type` property. We then get the following:\n\n```\nclass Type {\n type: 'a' | 'b'\n} \n\nclass TypeA extends Type {\n a: number;\n}\n\nclass TypeB extends Type {\n b: string\n}\n\n \nclass Parent {\n @Type(() => ?, {\n discriminator: {\n property: 'type',\n subTypes: [\n { value: TypeA, name: 'a' },\n { value: TypeB, name: 'b' },\n ] \n }\n }\n data: TypeA | TypeB\n}\n```\n\n========================================\n\nCode:\n```js\nclass Parent {\n  type: 'a' | 'b'\n\n  @Type(() => ?, {\n    discriminator: {\n      property: 'type',\n      subTypes: [\n        { value: TypeA, name: 'a' },\n        { value: TypeB, name: 'b' },\n      ]    \n    }\n  }\n  data: TypeA | TypeB\n\n}\n```\n\n```js\nconst TypeOnParent: () => PropertyDecorator = () => {\n  const __class__ = class {}\n  const prop = '__type'\n\n  return (target, key) => {\n    Transform(({ value, obj }) => {\n      value[prop] = obj.type\n      return value\n    })(target, key)\n\n    Type(() => __class__, {\n      keepDiscriminatorProperty: true,\n      discriminator: {\n        property: prop,\n        subTypes: [\n          { name: 'a', value: TypeA },\n          { name: 'b', value: TypeB },\n        ],\n      },\n    })(target, key)\n  }\n}\n\nclass Parent {\n  type: 'a' | 'b'\n\n  @TypeOnParent('type')\n  data: TypeA | TypeB\n\n}\n```\n\n```text\n@Type\n```\n\n```text\nType\n```\n\n```text\ntype\n```\n\n```js\n@Type((opts) => opts.object.type === 'a' ? TypeA : TypeB)\n  data: TypeA | TypeB\n```\n\n```text\nclass Type {\n  type: 'a' | 'b'\n} \n\nclass TypeA extends Type {\n  a: number;\n}\n\nclass TypeB extends Type {\n  b: string\n}\n\n \nclass Parent {\n  @Type(() => ?, {\n    discriminator: {\n      property: 'type',\n      subTypes: [\n        { value: TypeA, name: 'a' },\n        { value: TypeB, name: 'b' },\n      ]    \n    }\n  }\n  data: TypeA | TypeB\n}\n```\n\n```text\nproperty\n```\n\n```text\nTypeA\n```\n\n```text\nTypeB\n```\n\n```text\ntype\n```\n\n========================================\n\nComments:\n- sad that it works also for me, I replaced the discriminator with a switch and works: @Type((type) => { switch (type?.object.type) { case 'a': return A; case 'b': return B; case 'c': return C; case 'd': return D; default: return Parent; } })","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":221,"estimatedTokens":1045}}795{"id":"stack-58041234","source":"stackoverflow","questionId":58041234,"title":"NestJS pipe Joi.validate() (is not a function)","tags":["hapi.js","nestjs"],"text":"Title: NestJS pipe Joi.validate() (is not a function)\nTags: hapi.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI try to use Joi validator on **NestJS** with pipe.\n\nhttps://docs.nestjs.com/pipes#object-schema-validation\n\n```\nimport * as Joi from '@hapi/joi';\nimport { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';\n\n@Injectable()\nexport class JoiValidationPipe implements PipeTransform {\n constructor(\n private readonly schema: Joi.ObjectSchema,\n ) {}\n\n transform(value: any, metadata: ArgumentMetadata) {\n const { error } = Joi.validate(value, this.schema);\n\n if (error) {\n throw new BadRequestException('Validation failed');\n }\n\n return value;\n }\n}\n```\n\nIt doesn't work properly.\n\n TypeError: Joi.validate is not a function\n\n========================================\n\nTop Answer:\nI have made an PR to update the https://docs.nestjs.com and it looks like it is already deployed, so you can refer to it.\n\n`@hapijs/joi` deprecated `Joi.validate` with version 16 and you have to call `.validate` directly on schema.\n\n========================================\n\nCode:\n```js\nimport * as Joi from '@hapi/joi';\nimport { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';\n\n@Injectable()\nexport class JoiValidationPipe implements PipeTransform {\n  constructor(\n    private readonly schema: Joi.ObjectSchema,\n  ) {}\n\n  transform(value: any, metadata: ArgumentMetadata) {\n    const { error } = Joi.validate(value, this.schema);\n\n    if (error) {\n      throw new BadRequestException('Validation failed');\n    }\n\n    return value;\n  }\n}\n```\n\n```text\nconst schema = Joi.object({\n    name: Joi.string().min(3).required()\n});\nconst result = schema.validate(req.body);\n```\n\n```text\nschema.validate\n```\n\n```text\nJoi.validate\n```\n\n```text\n@hapijs/joi\n```\n\n```text\nJoi.validate\n```\n\n```text\n.validate\n```\n\n========================================\n\nComments:\n- Can you try with `Joi.object(this.schema).validate(value)` ?","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":98,"estimatedTokens":495}}796{"id":"stack-69083859","source":"stackoverflow","questionId":69083859,"title":"Can't mock Paginate function in jest unit tests","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: Can't mock Paginate function in jest unit tests\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock my service's findAll function. For this I either need to mock the repository function `findAndCount` myEntityRepository or the `paginate` function of of nestjs-typeorm-paginate node module. `findAll` function fetches list of records from table and is paginated using NodeModule nestjs-typeorm-paginate.\n\n**Try-1:** Mocking myEntityRepository\nBut it fails with error and traceback:\n\n```\nTypeError: queryBuilder.limit is not a function\n\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:119:28\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n at Object..__awaiter (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:4:12)\n at paginateQueryBuilder (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:115:12)\n at Object. (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:22:15)\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n```\n\nmy.service.ts\n\n```\nimport { IPaginationOptions, paginate, Pagination } from 'nestjs-typeorm-paginate'\n\nexport class MyService {\n constructor(@InjectRepository(MyEntity) private myEntityRepository: Repository) { }\n\n async findAll(options: IPaginationOptions): Promise> {\n try {\n return await paginate(this.myEntityRepository, options)\n } catch (error) {\n throw error\n }\n }\n}\n```\n\nmy.service.spec.ts\n\n```\ndescribe('MyService Basic GET findAll test cases', () => {\n let service: MyService\n let repositoryMock: MockType>\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [MyService,\n {\n provide: getRepositoryToken(MyEntity), useFactory: repositoryMockFactory\n }\n ],\n }).compile()\n\n service = module.get(MyService)\n repositoryMock = module.get(getRepositoryToken(MyEntity))\n\n const itemList = [{\n id: 1,\n my_field: 'a1',\n }, {\n id: 2,\n my_field: 'a2',\n }, ]\n\n it('should findAll() the MyEntity', async () => {\n expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n })\n})\n\nconst repositoryMockFactory: () => MockType> = jest.fn(() => ({\n find: jest.fn(entity => entity),\n findAndCount: jest.fn(entity => entity),\n}))\n```\n\n**Try-2:** Mocking paginate\nThen I tried mocking paginate method but still it returns error:\n\n`TypeError: Cannot redefine property: paginate at Function.defineProperty ()`\n\nmy.service.spec.ts with Pagination mock changes)\n\n```\nimport * as nestjsTypeormPaginate from 'nestjs-typeorm-paginate' // imported at top\n ....\n ....\n it('should findAll() the MyEntity', async () => {\n const queryDto: QueryMyEntityDto = { customerId: 1 }\n const options: IPaginationOptions = { page: 1, limit: 10 }\n let paginationMock = jest.spyOn(nestjsTypeormPaginate, 'paginate')\n paginationMock.mockImplementation((dto, options) => Promise.resolve({\n items: itemList.slice(0, 2),\n meta: {\n itemCount: 2,\n totalItems: 2,\n totalPages: 1,\n currentPage: 1,\n }\n }))\n repositoryMock.find.mockReturnValue(itemList)\n expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n })\n ...\n```\n\nBefore writing this question:\nI tried following posts:\n\n- Use `jest.spyOn` on an exported function from a Node module\n\n- How to mock imported named function in Jest when module is unmocked\n\n- https://github.com/nestjsx/nestjs-typeorm-paginate/issues/143\n\n========================================\n\nCode:\n```text\nTypeError: queryBuilder.limit is not a function\n\n      at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:119:28\n      at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n      at Object.<anonymous>.__awaiter (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:4:12)\n      at paginateQueryBuilder (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:115:12)\n      at Object.<anonymous> (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:22:15)\n      at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n```\n\n```text\nimport { IPaginationOptions, paginate, Pagination } from 'nestjs-typeorm-paginate'\n\nexport class MyService {\n  constructor(@InjectRepository(MyEntity) private myEntityRepository: Repository<MyEntity>) { }\n\n  async findAll(options: IPaginationOptions): Promise<Pagination<MyEntity>> {\n    try {\n      return await paginate<MyEntity>(this.myEntityRepository, options)\n    } catch (error) {\n      throw error\n    }\n  }\n}\n```\n\n```text\ndescribe('MyService Basic GET findAll test cases', () => {\n  let service: MyService\n  let repositoryMock: MockType<Repository<MyEntity>>\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [MyService,\n        {\n          provide: getRepositoryToken(MyEntity), useFactory: repositoryMockFactory\n        }\n      ],\n    }).compile()\n\n    service = module.get<MyService>(MyService)\n    repositoryMock = module.get(getRepositoryToken(MyEntity))\n\n    const itemList = [{\n        id: 1,\n        my_field: 'a1',\n    }, {\n        id: 2,\n        my_field: 'a2',\n    }, ]\n\n  it('should findAll() the MyEntity', async () => {\n    expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n  })\n})\n\nconst repositoryMockFactory: () => MockType<Repository<MyEntity>> = jest.fn(() => ({\n  find: jest.fn(entity => entity),\n  findAndCount: jest.fn(entity => entity),\n}))\n```\n\n```text\nimport * as nestjsTypeormPaginate from 'nestjs-typeorm-paginate' // imported at top\n  ....\n  ....\n  it('should findAll() the MyEntity', async () => {\n    const queryDto: QueryMyEntityDto = { customerId: 1 }\n    const options: IPaginationOptions = { page: 1, limit: 10 }\n    let paginationMock = jest.spyOn(nestjsTypeormPaginate, 'paginate')\n    paginationMock.mockImplementation((dto, options) => Promise.resolve({\n      items: itemList.slice(0, 2),\n      meta: {\n        itemCount: 2,\n        totalItems: 2,\n        totalPages: 1,\n        currentPage: 1,\n      }\n    }))\n    repositoryMock.find.mockReturnValue(itemList)\n    expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n  })\n  ...\n```\n\n```text\nfindAndCount\n```\n\n```text\npaginate\n```\n\n```text\nfindAll\n```\n\n```text\nTypeError: Cannot redefine property: paginate at Function.defineProperty (<anonymous>)\n```\n\n```js\n// At the top level of your unit test file, before the import of the service\n\n// Declare your itemList\nconst itemList = ['item1', 'item2', 'item3', 'item4'];\n\n// Mock the external module and the paginate function\njest.mock('nestjs-typeorm-paginate', () => ({\n  paginate: jest.fn().mockResolvedValue({\n      items: itemList.slice(0, 2),\n      meta: {\n        itemCount: 2,\n        totalItems: 2,\n        totalPages: 1,\n        currentPage: 1,\n      }\n    }),\n}));\n\n// ... unit tests\n```\n\n========================================\n\nComments:\n- can you show me how do you call this inside the test?it would be really help full","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":247,"estimatedTokens":1725}}797{"id":"stack-61860550","source":"stackoverflow","questionId":61860550,"title":"Nestjs - What is the correct way to create a DTO file to transform a nested json object?","tags":["javascript","node.js","nestjs","dto"],"text":"Title: Nestjs - What is the correct way to create a DTO file to transform a nested json object?\nTags: javascript, node.js, nestjs, dto\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a DTO file to transform the values and save a Document. \n\n```\nexport class CreateProductDto {\n readonly pricing: {\n readonly list: number;\n } \n}\n\nasync create(@Body() createProductDto: CreateProductDto) {\n console.log(createProductDto);\n console.log(createProductDto.pricing.list); \n}\n```\n\n```\nimport * as mongoose from 'mongoose';\n\nexport const ProductSchema = new mongoose.Schema({\n pricing: {\n list: {\n type: Number,\n },\n },\n});\n```\n\nBut the value of princing.list is **undefined**.\n\nWhat is the correct way to do this in NestJS?\n\n========================================\n\nCode:\n```js\nexport class CreateProductDto {\n  readonly pricing: {\n    readonly list: number;\n  } \n}\n\nasync create(@Body() createProductDto: CreateProductDto) {\n  console.log(createProductDto);\n  console.log(createProductDto.pricing.list); \n}\n```\n\n```js\nimport * as mongoose from 'mongoose';\n\nexport const ProductSchema = new mongoose.Schema({\n  pricing: {\n    list: {\n      type: Number,\n    },\n  },\n});\n```\n\n```text\nimport { IsNumber, IsObject } from 'class-validator';\nimport { Type } from 'class-transformer';\nexport class ListDto {\n  @IsNumber()\n  readonly list: number\n}\n\nexport class CreateProductDto {\n  @IsObject()\n  @ValidateNested() @Type(() => ListDto)\n  readonly pricing: ListDto\n}\n```\n\n```text\nimport { ValidationPipe } from '@nestjs/common';\napp.useGlobalPipes(new ValidationPipe());\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":83,"estimatedTokens":392}}798{"id":"stack-76193788","source":"stackoverflow","questionId":76193788,"title":"changing namespace of express in typescript","tags":["typescript","namespaces","nestjs"],"text":"Title: changing namespace of express in typescript\nTags: typescript, namespaces, nestjs\nSource: Stack Overflow\n\nQuestion:\nI wanna change the express namespace in my typescript file and add another option to it, but eslint get some errors,\n\n```\ndeclare global {\n namespace Express {\n interface Request {\n currentUser?: User;\n }\n }\n}\n```\n\nError is:\nES2015 module syntax is preferred over namespaces.\n\nhow can i fix this error except change ts rules\n\n========================================\n\nCode:\n```text\ndeclare global {\n  namespace Express {\n    interface Request {\n      currentUser?: User;\n    }\n  }\n}\n```\n\n```text\ndeclare module 'express' {\n  export interface Request {\n    currentUser?: User;\n  }\n}\n```\n\n========================================\n\nComments:\n- thanks a lot, but after add this eslint said Property 'session' does not exist on type 'Request>\n- Try extending from `express`'s native `Request` interface\n- can u write it, sry, I can't understand\n- `import { Request } from 'express'` declare module 'express' { export interface RequestExtended extends Request { currentUser?: User; } }\n- no, it's not working. 'extends' clause of exported interface 'RequestExtended' has or is using private name 'Request'.","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":51,"estimatedTokens":306}}799{"id":"stack-75530960","source":"stackoverflow","questionId":75530960,"title":"Socket Gateway provide and error in nodes modules","tags":["websocket","socket.io","nestjs"],"text":"Title: Socket Gateway provide and error in nodes modules\nTags: websocket, socket.io, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to make a simple gateway in my project using websocket. I have an issue with NestJs when I want to make it.\n\nenter image description here\n\n```\nimport { \n SubscribeMessage, \n WebSocketGateway, \n WebSocketServer, \n OnGatewayDisconnect,\n ConnectedSocket,\n} from '@nestjs/websockets';\nimport { Server } from 'socket.io';\n\n@WebSocketGateway()\nexport class ChatGateway { //implements OnGatewayDisconnect {\n\n constructor() {}\n\n @WebSocketServer() server : Server;\n\n}\n```\n\nenter image description here\n\n```\nimport { Module } from '@nestjs/common';\nimport { ChatService } from './chat.service';\nimport { ChatGateway } from './chat.gateway';\n\n@Module({\n providers: [\n ChatService,\n ChatGateway\n ]\n})\nexport class ChatModule {}\n```\n\nAnd I got this error :\n\nenter image description here\n\n```\n/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/gateway-metadata-explorer.js:13\n .getAllMethodNames(instancePrototype)\n ^\nTypeError: this.metadataScanner.getAllMethodNames is not a function\n at GatewayMetadataExplorer.explore (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/gateway-metadata-explorer.js:13:14)\n at WebSocketsController.subscribeToServerEvents (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/web-sockets-controller.js:33:61)\n at WebSocketsController.connectGatewayToServer (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/web-sockets-controller.js:30:14)\n at SocketModule.connectGatewayToServer (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:47:35)\n at /Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:36:38\n at IteratorWithOperators.forEach (/Users/mlecherb/transcendance-1/backend/node_modules/iterare/src/iterate.ts:202:13)\n at SocketModule.connectAllGateways (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:36:14)\n at /Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:31:61\n at ModulesContainer.forEach ()\n at SocketModule.register (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:31:17)\n```\n\nDoes anyone have an idea ?\n\nThanks\n\nI already tried to make it the shortest possible, I have download all the package necessary.\n\n========================================\n\nTop Answer:\n- delete node_modules\n\n- delete pack-lock.json\nthen install the packages using npm i --legacy-peer-deps\nthis resolved my issue same as yours\n\n========================================\n\nCode:\n```text\nimport { \n    SubscribeMessage, \n    WebSocketGateway, \n    WebSocketServer, \n    OnGatewayDisconnect,\n    ConnectedSocket,\n} from '@nestjs/websockets';\nimport { Server } from 'socket.io';\n\n@WebSocketGateway()\nexport class ChatGateway { //implements OnGatewayDisconnect {\n\n    constructor() {}\n\n    @WebSocketServer() server : Server;\n\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ChatService } from './chat.service';\nimport { ChatGateway } from './chat.gateway';\n\n@Module({\n  providers: [\n            ChatService,\n            ChatGateway\n        ]\n})\nexport class ChatModule {}\n```\n\n```text\n/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/gateway-metadata-explorer.js:13\n            .getAllMethodNames(instancePrototype)\n             ^\nTypeError: this.metadataScanner.getAllMethodNames is not a function\n    at GatewayMetadataExplorer.explore (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/gateway-metadata-explorer.js:13:14)\n    at WebSocketsController.subscribeToServerEvents (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/web-sockets-controller.js:33:61)\n    at WebSocketsController.connectGatewayToServer (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/web-sockets-controller.js:30:14)\n    at SocketModule.connectGatewayToServer (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:47:35)\n    at /Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:36:38\n    at IteratorWithOperators.forEach (/Users/mlecherb/transcendance-1/backend/node_modules/iterare/src/iterate.ts:202:13)\n    at SocketModule.connectAllGateways (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:36:14)\n    at /Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:31:61\n    at ModulesContainer.forEach (<anonymous>)\n    at SocketModule.register (/Users/mlecherb/transcendance-1/backend/node_modules/@nestjs/websockets/socket-module.js:31:17)\n```\n\n========================================\n\nComments:\n- I solved this issue by downgrade my version of @nestjs/platform-socket.io and @nestjs/websockets to 9.2.1. I just had to run : npm install @nestjs/platform-socket.io@9.2.1 @nestjs/websockets@9.2.1\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":140,"estimatedTokens":1333}}800{"id":"stack-75363096","source":"stackoverflow","questionId":75363096,"title":"Generics type response with swagger in nestjs","tags":["typescript","types","swagger","nestjs"],"text":"Title: Generics type response with swagger in nestjs\nTags: typescript, types, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nexport class PaginatedResult {\n\n @Expose()\n @ApiResponseProperty(type: T}) // Unfortunately, this is not working beacue its a type but used as a value\n @Transform(({ obj }) =>\n obj.data.map((data) => new obj.classConstructor(data)),\n )\n data: T[];\n}\n```\n\nAs you can see the data is of Type T which has the options Item or Tag and a few more, but swagger will always only display Item also on endpoints where I have defined the ResponseType as: `{type: PaginatedResult}`\n\nIs there any solution?\n\n========================================\n\nTop Answer:\nAnother solution is like this:\n\n```\nimport { Type } from '@nestjs/common';\nimport { ApiOkResponse, ApiProperty, ApiSchema } from '@nestjs/swagger';\n\nexport class MetaInfo {\n @ApiProperty()\n totalItems: number;\n}\n\nexport interface IMeta {\n items: T[];\n meta: MetaInfo;\n}\n\n/**\n * Creates a DTO class that implements {@linkcode IMeta | IMeta} and is decorated with {@linkcode ApiSchema | @ApiSchema}. Use it as a type in the \\@ApiResponse decorators (such as {@linkcode ApiOkResponse | @ApiOkResponse}).\n * @param openApiSchemaName The name of the schema in the OpenAPI specification\n * @returns The created DTO class, implements {@linkcode IMeta | IMeta}\n */\nexport function createMetaDto(itemType: Type, openApiSchemaName: string): Type> {\n @ApiSchema({ name: openApiSchemaName })\n class MetaDto implements IMeta {\n @ApiProperty({\n description: 'Array of items',\n type: itemType,\n isArray: true,\n required: true\n })\n items: T[];\n\n @ApiProperty({\n description: 'Metadata about the response',\n type: MetaInfo,\n required: true,\n })\n meta: MetaInfo;\n }\n\n return MetaDto;\n}\n\n// model.ts\nclass Hello {\n @ApiProperty()\n id: string;\n\n @ApiProperty()\n name: string;\n\n @ApiProperty()\n age: number;\n}\n\nclass World {\n @ApiProperty()\n prop1: string;\n\n @ApiProperty()\n prop2: number;\n}\n\n// controller.ts\n\n@Get('hello')\n@ApiOperation({ operationId: 'getHello' })\n@ApiOkResponse({ type: createMetaDto(Hello, 'HelloItems') })\ngetHello(): IMeta {\n const hello: Hello = { id: 'hello', name: 'Adam', age: 42 };\n return { items: [hello], meta: { totalItems: 1 } };\n}\n\n@Get('world')\n@ApiOperation({ operationId: 'getWorld' })\n@ApiOkResponse({ type: createMetaDto(World, 'WorldItems') })\ngetWorld(): IMeta {\n const world: World = { prop1: 'Milky Way', prop2: 1.15 * Math.pow(10, 12) };\n return { items: [world], meta: { totalItems: 1 } };\n}\n```\n\nThis allows you to generate from openApi document and have different names.\n\nAlso, inside the typescript you have interface constraint, so all is typesafe.\n\n========================================\n\nCode:\n```text\nexport class PaginatedResult<T> {\n\n @Expose()\n @ApiResponseProperty(type: T}) // Unfortunately, this is not working beacue its a type but used as a value\n @Transform(({ obj }) =>\n  obj.data.map((data) => new obj.classConstructor(data)),\n )\n data: T[];\n}\n```\n\n```text\n{type: PaginatedResult<Tag>}\n```\n\n```text\nexport const ApiOkResponseCustom = <GenericType extends Type<unknown>>(data: GenericType ) =>\n  applyDecorators(\n    ApiExtraModels(ModelWithGeneric, data),\n    ApiOkResponse({\n      description: `The paginated result of ${data.name}`,\n      schema: {\n        allOf: [\n          { $ref: getSchemaPath(ModelWithGeneric) },\n          {\n            properties: {\n              genericFieldName: {\n                type: 'array',\n                items: { $ref: getSchemaPath(data) },\n              },},},],},}))\n```\n\n```text\n@Controller('')\nexport class SomeController {\n\n  @Get('/')\n  ApiOkResponseCustom(GenericType)\n  async get(): Promise<ModelWithGeneric<GenericType>> {}\n}\n```\n\n```js\nimport { Type } from '@nestjs/common';\nimport { ApiOkResponse, ApiProperty, ApiSchema } from '@nestjs/swagger';\n\nexport class MetaInfo {\n  @ApiProperty()\n  totalItems: number;\n}\n\nexport interface IMeta<T> {\n  items: T[];\n  meta: MetaInfo;\n}\n\n/**\n * Creates a DTO class that implements {@linkcode IMeta | IMeta<T>} and is decorated with {@linkcode ApiSchema | @ApiSchema}. Use it as a type in the \\@ApiResponse decorators (such as {@linkcode ApiOkResponse | @ApiOkResponse}).\n * @param openApiSchemaName The name of the schema in the OpenAPI specification\n * @returns The created DTO class, implements {@linkcode IMeta | IMeta<T>}\n */\nexport function createMetaDto<T>(itemType: Type<T>, openApiSchemaName: string): Type<IMeta<T>> {\n  @ApiSchema({ name: openApiSchemaName })\n  class MetaDto implements IMeta<T> {\n    @ApiProperty({\n      description: 'Array of items',\n      type: itemType,\n      isArray: true,\n      required: true\n    })\n    items: T[];\n\n    @ApiProperty({\n      description: 'Metadata about the response',\n      type: MetaInfo,\n      required: true,\n    })\n    meta: MetaInfo;\n  }\n\n  return MetaDto;\n}\n\n// model.ts\nclass Hello {\n  @ApiProperty()\n  id: string;\n\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n}\n\nclass World {\n  @ApiProperty()\n  prop1: string;\n\n  @ApiProperty()\n  prop2: number;\n}\n\n// controller.ts\n\n@Get('hello')\n@ApiOperation({ operationId: 'getHello' })\n@ApiOkResponse({ type: createMetaDto(Hello, 'HelloItems') })\ngetHello(): IMeta<Hello> {\n  const hello: Hello = { id: 'hello', name: 'Adam', age: 42 };\n  return { items: [hello], meta: { totalItems: 1 } };\n}\n\n@Get('world')\n@ApiOperation({ operationId: 'getWorld' })\n@ApiOkResponse({ type: createMetaDto(World, 'WorldItems') })\ngetWorld(): IMeta<World> {\n  const world: World = { prop1: 'Milky Way', prop2: 1.15 * Math.pow(10, 12) };\n  return { items: [world], meta: { totalItems: 1 } };\n}\n```\n\n========================================\n\nComments:\n- This only works for pagination.\n- aalonso.dev/blog/&hellip; this answer is explained much specific in this link.","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":241,"estimatedTokens":1445}}801{"id":"stack-76455855","source":"stackoverflow","questionId":76455855,"title":"What is the default timezone for nestjs cron (@Cron) decorator","tags":["node.js","cron","nestjs","scheduled-tasks","cron-task"],"text":"Title: What is the default timezone for nestjs cron (@Cron) decorator\nTags: node.js, cron, nestjs, scheduled-tasks, cron-task\nSource: Stack Overflow\n\nQuestion:\nI am writing a cron to run at midnight every day in Indian Standard Time.\n\n```\n@Injectable()\nexport class CronService {\n\n @Cron(\"0 0 * * *\")\n async midnightCron() {\n // implementation\n }\n\n}\n```\n\nMy instance is deployed in `AWS Mumbai region`.\n\nI want to know if the @Cron decorator uses local time or UTC time for execution ?\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class CronService {\n\n  @Cron(\"0 0 * * *\")\n  async midnightCron() {\n    // implementation\n  }\n\n}\n```\n\n```text\nAWS Mumbai region\n```\n\n```text\ncron\n```\n\n```text\nTZ\n```\n\n```text\nUTC\n```\n\n```text\nDate\n```\n\n========================================\n\nComments:\n- It uses local timezone, this should have been mentioned in the documentation, took me long to figure out.","metadata":{"transformedAt":"2026-08-18T18:33:02.469Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":62,"estimatedTokens":231}}802{"id":"stack-72511998","source":"stackoverflow","questionId":72511998,"title":"How to manage multi-device simultaneous login with JWT tokens?","tags":["authentication","jwt","authorization","nestjs","passport-jwt"],"text":"Title: How to manage multi-device simultaneous login with JWT tokens?\nTags: authentication, jwt, authorization, nestjs, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nMy query is regarding supporting multi-device login for the same user at the same time using JWT tokens. I am using NestJS as my backend.\n\nUser table: userid, username, password(contains hashed password), name, refreshToken(contains hashed refresh token)\n\nWhen the user does a /api/login call, on having a valid username and password, the access token and refresh token are generated using jwt passport library. The refresh token is hashed and stored in the refresh column of the user table for that particular user and the access token and the refresh token are sent to the client through the response.\n\nDuring the /api/refresh call, the refresh token sent by the user is validated with the hashed refresh token that is present in the user table for that user and then, a new access token and a new refresh token are generated. The new refresh token is hashed and updated in the user table refreshToken column for that same user row.\n\nThis flow works perfectly for a user logged in with a single device. When the same user gets logged in using multiple devices at the same time, during login, the refresh token is updated in the refreshToken column of the user table for the same user row, which makes us lose an existing/valid refresh token for the same user.\n\nFlow:\n\n- user 1 logs in using device 1 --> refreshToken column for user 1 is updated with a new refresh token\n\n- user 1 logs in using device 2 --> refreshToken column for user 1 is overwritten with a new refresh token and we lose the refresh token that was created for device 1\n\nI would like to know what would be the best industrial practice to manage the JWT refresh flow for a user logged in with multiple devices at the same time?\n\n========================================\n\nComments:\n- Having only refresh token won't work, you will need one refresh token per browser/device. related As a bonus, if a second device (attacker that stole your token somehow) uses the same refresh token, you can detect that and delete all refresh tokens and force the user to re-enter credentials.\n- Thanks Michal, I think this will work. But, there is a minor issue that I see here. The reason behind hashing the token in the DB is to prevent people with access to the DB from being able to use the token to access someone else's account. Any way to prevent this?\n- @KunalKarmakar if someone already has access to the database then can't they already access any user's account data? Unless you are storing the refresh tokens in a completely seperate database.\n- @BigGerman makes sense. Still, just for a bit of security.\n- it's to prevent an internal employee from being being able to super easily impersonate a user. Of course, any employee who is viewing database info can see everything, but they still can't usually behave like a real user. They would have to edit the database in very particular ways and touch systems that may be spread out all over the place running live. With the hash, you remove that edgecase\n- if you hash the RT, you cant decrypt it to know if this RT is linked to the AccessToken. In case of multiple device, thus multiple entry in DB for the same user_id. Usually many example only compare the RT from client and the Hash RT from DB. I was thinking this way, when user signIn, first create RT and insert into db, get the row id, and insert the id into AT creation. wdyt?","metadata":{"transformedAt":"2026-08-18T18:33:02.470Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":32,"estimatedTokens":880}}803{"id":"stack-71569580","source":"stackoverflow","questionId":71569580,"title":"class-validator relational validation with custom error messages","tags":["typescript","nestjs","class-validator"],"text":"Title: class-validator relational validation with custom error messages\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nso I was building an API where by user gives us `type` and `value` in the request body, `type` could be `CNIC, EMAIL, MOBILE`\n\nNow based on the `type` I have to validate the value like if `EMAIL` is valid or if `MOBILE` is valid etc.\n\nSo as we can see that `value` field depends on the `type` field to validate it.\n\nI need a way to handle this using `class-validator` `validationPipe`.\n\n========================================\n\nCode:\n```text\ntype\n```\n\n```text\nvalue\n```\n\n```text\ntype\n```\n\n```text\nCNIC, EMAIL, MOBILE\n```\n\n```text\ntype\n```\n\n```text\nEMAIL\n```\n\n```text\nMOBILE\n```\n\n```text\nvalue\n```\n\n```text\ntype\n```\n\n```text\nclass-validator\n```\n\n```text\nvalidationPipe\n```\n\n```text\nimport {\n  registerDecorator,\n  ValidationOptions,\n  ValidationArguments,\n  isEmail,\n} from 'class-validator';\nimport { CA_DetailsTypes } from './models';\n\nexport function ValidateByAliasType(\n  property: string,\n  validationOptions?: ValidationOptions,\n) {\n  // eslint-disable-next-line @typescript-eslint/ban-types\n  return function (object: Object, propertyName: string) {\n    registerDecorator({\n      name: 'validateByAliasType',\n      target: object.constructor,\n      propertyName: propertyName,\n      constraints: [property],\n      options: validationOptions,\n      validator: {\n        validate(value: any, args: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          const relatedValue = (args.object as any)[relatedPropertyName];\n          if (relatedValue === CA_DetailsTypes.EMAIL) {\n            return isEmail(value) && value.length > 5 && value.length <= 99;\n          }\n          if (relatedValue === CA_DetailsTypes.CNIC) {\n            return value.length === 13;\n          }\n          if (relatedValue === CA_DetailsTypes.MOBILE) {\n            return value.length === 11;\n          }\n          if (relatedValue === CA_DetailsTypes.TXT) {\n            return value.length > 3 && value.length <= 99;\n          }\n          return false;\n        },\n      },\n    });\n  };\n}\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\nimport { IsEnum, IsNotEmpty } from 'class-validator';\n\nexport enum CA_DetailsTypes {\n  'CNIC' = 'CNIC',\n  'MOBILE' = 'MOBILE',\n  'EMAIL' = 'EMAIL',\n  'TXT' = 'TXT',\n}\n\nexport class CA_FetchDetails_DTO {\n  @ApiProperty({\n    example: 'MOBILE',\n    type: 'enum',\n    enum: CA_DetailsTypes,\n  })\n  @IsNotEmpty()\n  @IsEnum(CA_DetailsTypes)\n  type: CA_DetailsTypes;\n\n  @ApiProperty({ example: '03070000002' })\n  @ValidateByAliasType('type')\n  value: string;\n}\n```\n\n```text\nimport {\n  registerDecorator,\n  ValidationOptions,\n  ValidationArguments,\n  isEmail,\n} from 'class-validator';\nimport { CA_DetailsTypes } from './models';\n\nexport function ValidateByAliasType(\n  property: string,\n  validationOptions?: ValidationOptions,\n) {\n  // eslint-disable-next-line @typescript-eslint/ban-types\n  return function (object: Object, propertyName: string) {\n    registerDecorator({\n      name: 'validateByAliasType',\n      target: object.constructor,\n      propertyName: propertyName,\n      constraints: [property],\n      options: validationOptions,\n      validator: {\n        validate(value: any, args: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          const relatedValue = (args.object as any)[relatedPropertyName];\n          if (relatedValue === CA_DetailsTypes.EMAIL) {\n            return isEmail(value) && value.length > 5 && value.length <= 99;\n          }\n          if (relatedValue === CA_DetailsTypes.CNIC) {\n            return value.length === 13;\n          }\n          if (relatedValue === CA_DetailsTypes.MOBILE) {\n            return value.length === 11;\n          }\n          if (relatedValue === CA_DetailsTypes.TXT) {\n            return value.length > 3 && value.length <= 99;\n          }\n          return false;\n        },\n        defaultMessage(args?: ValidationArguments) {\n          const [relatedPropertyName] = args.constraints;\n          const relatedValue = (args.object as any)[relatedPropertyName];\n          switch (relatedValue) {\n            case CA_DetailsTypes.EMAIL:\n              return 'Please enter valid email!';\n\n            case CA_DetailsTypes.MOBILE:\n              return 'Please enter valid mobile!';\n\n            case CA_DetailsTypes.CNIC:\n              return 'Please enter valid CNIC!';\n\n            default:\n              return 'Invalid value!';\n          }\n        },\n      },\n    });\n  };\n}\n```\n\n```text\nvalidate-value-by-type.decorator.ts\n```\n\n```text\nclient.request.dto.ts\n```\n\n```text\nvalue\n```\n\n```text\ntype\n```\n\n```text\ntype\n```\n\n```text\nclass-validator\n```\n\n```text\ntype\n```\n\n```text\ntype\n```\n\n```text\ndefaultMessage()\n```\n\n```text\nvalidate-value-by-type.decorator.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.470Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":233,"estimatedTokens":1216}}804{"id":"stack-72753717","source":"stackoverflow","questionId":72753717,"title":"Select columns from sub-relation not working in typeorm","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: Select columns from sub-relation not working in typeorm\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an `Order` and `User` Entities\n\n### Order\n\n```\n@Entity('orders')\nexport class Order {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('enum', {enum: OrderStatus, default: OrderStatus.NEW})\n status: OrderStatus\n \n @Column('float')\n amount: number\n\n @Column('float')\n fees: number\n\n @ManyToOne(() => User, (user) => user.orders)\n user: User;\n \n @OneToMany(() => OrderToProduct, orderToProduct => orderToProduct.order, {\n cascade: true,\n })\n products: OrderToProduct[]\n\n @CreateDateColumn()\n createdAt: Date = new Date();\n\n @UpdateDateColumn()\n updatedAt: Date;\n}\n```\n\n### User\n\n```\n@Entity('users')\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({length: 255})\n name: string;\n \n @Column({length: 255, unique: true})\n email: string;\n\n @Column({length: 255})\n password: string; \n\n @CreateDateColumn()\n createdAt: Date = new Date();\n \n @OneToMany(() => Order, (order) => order.user)\n orders: Order[];\n\n @UpdateDateColumn()\n updatedAt: Date;\n\n @OneToMany(() => Product, (product) => product.user)\n products: Product[]\n\n}\n```\n\nAll I want is to retrieve the orders with their user `name` only what I try is like this\n\n```\nthis.orderRepository.find({\n relations: {\n user: {\n id: true,\n name: true\n }\n },\n where: {\n user: {\n id: user.id\n }\n }\n})\n```\n\nbut it returns with an error\n\nEntityPropertyNotFoundError: Property \"id\" was not found in \"User\". Make sure your query is correct.\n\nBut if i try to get all the object of user like this it works fine\n\n```\nrelations: {\n user: true\n},\n```\n\n========================================\n\nTop Answer:\nThe error is that our queries have fields with the same name as the \"id\" so you have to add to the select these fields:\n\n```\nthis.userRepository.findOne({ \n where: { id: res.locals.user },\n select: { \n firstName: true,\n lastName: true,\n email: true,\n phone: true,\n createdAt: true,\n updatedAt: true,\n role: { name: true },\n }, \n relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error: MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```\n[\n {\n \"message\": \"ER_BAD_FIELD_ERROR: Unknown column 'distinctAlias.User_id' in 'field list'\"\n }\n]\n```\n\nAnd the correct way to write it is:\n\n```\nthis.userRepository.findOne({ \n where: { id: res.locals.user },\n select: { \n id: true,\n firstName: true,\n lastName: true,\n email: true,\n phone: true,\n createdAt: true,\n updatedAt: true,\n role: { id: true, name: true },\n }, \n relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error:MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```\n{\n \"id\": 1,\n \"email\": \"andres_rod24@hotmail.com\",\n \"phone\": \"3016224924\",\n \"firstName\": \"Juan Andres\",\n \"lastName\": \"Rodriguez Arenas\",\n \"createdAt\": \"2023-01-04T03:49:57.092Z\",\n \"updatedAt\": \"2023-01-04T03:49:57.092Z\",\n \"role\": {\n \"id\": 1,\n \"name\": \"Administrator\"\n }\n}\n```\n\n========================================\n\nCode:\n```js\n@Entity('orders')\nexport class Order {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column('enum', {enum: OrderStatus, default: OrderStatus.NEW})\n    status: OrderStatus\n    \n    @Column('float')\n    amount: number\n\n    @Column('float')\n    fees: number\n\n    @ManyToOne(() => User, (user) => user.orders)\n    user: User;\n    \n    @OneToMany(() => OrderToProduct, orderToProduct => orderToProduct.order, {\n        cascade: true,\n    })\n    products: OrderToProduct[]\n\n    @CreateDateColumn()\n    createdAt: Date = new Date();\n\n    @UpdateDateColumn()\n    updatedAt: Date;\n}\n```\n\n```js\n@Entity('users')\nexport class User {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column({length: 255})\n    name: string;\n    \n    @Column({length: 255, unique: true})\n    email: string;\n\n    @Column({length: 255})\n    password: string;   \n\n    @CreateDateColumn()\n    createdAt: Date = new Date();\n    \n    @OneToMany(() => Order, (order) => order.user)\n    orders: Order[];\n\n    @UpdateDateColumn()\n    updatedAt: Date;\n\n    @OneToMany(() => Product, (product) => product.user)\n    products: Product[]\n\n}\n```\n\n```js\nthis.orderRepository.find({\n    relations: {\n        user: {\n            id: true,\n            name: true\n        }\n    },\n    where: {\n        user: {\n            id: user.id\n        }\n    }\n})\n```\n\n```text\nrelations: {\n   user: true\n},\n```\n\n```text\nOrder\n```\n\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nrelations: {\n    user:true\n},\nwhere: {\n    user: {\n        id: user.id\n    }\n},\nselect: {\n  user: {\n    id:true,\n    name: true\n  }\n// your other columns from order entity.\n}\n```\n\n```js\nthis.userRepository.findOne({ \n  where: {  id: res.locals.user  },\n  select: { \n    firstName: true,\n    lastName: true,\n    email: true,\n    phone: true,\n    createdAt: true,\n    updatedAt: true,\n    role: { name: true },\n  }, \n  relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error: MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```json\n[\n    {\n        \"message\": \"ER_BAD_FIELD_ERROR: Unknown column 'distinctAlias.User_id' in 'field list'\"\n    }\n]\n```\n\n```js\nthis.userRepository.findOne({ \n  where: { id: res.locals.user },\n  select: { \n    id: true,\n    firstName: true,\n    lastName: true,\n    email: true,\n    phone: true,\n    createdAt: true,\n    updatedAt: true,\n    role: { id: true, name: true },\n  }, \n  relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error:MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```json\n{\n    \"id\": 1,\n    \"email\": \"andres_rod24@hotmail.com\",\n    \"phone\": \"3016224924\",\n    \"firstName\": \"Juan Andres\",\n    \"lastName\": \"Rodriguez Arenas\",\n    \"createdAt\": \"2023-01-04T03:49:57.092Z\",\n    \"updatedAt\": \"2023-01-04T03:49:57.092Z\",\n    \"role\": {\n        \"id\": 1,\n        \"name\": \"Administrator\"\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.470Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":346,"estimatedTokens":1484}}805{"id":"stack-69291211","source":"stackoverflow","questionId":69291211,"title":"TypeORM error with MongoDB: .find() does not work, error: TypeError: Cannot read property 'prototype' of undefined","tags":["mongodb","nestjs","typeorm"],"text":"Title: TypeORM error with MongoDB: .find() does not work, error: TypeError: Cannot read property 'prototype' of undefined\nTags: mongodb, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI set up a Nest.Js / TypeORM / MongoDB stack as described here.\n\nIt works to create an object user in MongoDB using the `create()` function, the object is recorded into the right database into the `User` collection.\n\nHowever, when I attempt to get it using the `find({id})` or the `findAll()` function I get an error and I cannot get the item from the database even though it's there.\n\nHere is my `user.service.ts` file:\n\n```\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { validate } from 'class-validator';\nimport { CreateUserDto } from './user.dto';\nimport { User } from '../model/user.entity';\nimport { UserRO } from './user.interface';\n\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: MongoRepository,\n ) {}\n\n // abstracting access to the model via service\n public async getAll() {\n // getting data from database\n return await this.userRepository.find();\n }\n\n // abstracting access to the model via service\n public async get(id: string) {\n const user = await this.userRepository.findOne({ _id: id });\n if (!user) {\n const errors = { User: ' not found' };\n throw new HttpException({ errors }, 401);\n }\n\n return this.buildUserRO(user);\n }\n\n async create(dto: CreateUserDto): Promise {\n // check uniqueness of username/email\n const { username } = dto;\n const newUser = new User();\n newUser.username = username;\n // newUser.contexts = [];\n\n const errors = await validate(newUser);\n if (errors.length > 0) {\n const _errors = { username: 'Userinput is not valid.' };\n throw new HttpException(\n { message: 'Input data validation failed', _errors },\n HttpStatus.BAD_REQUEST,\n );\n } else {\n const savedUser = await this.userRepository.save(newUser);\n return this.buildUserRO(savedUser);\n }\n }\n\n}\n```\n\nand also the `user.interface.ts`:\n\n```\nexport interface UserData {\n username: string;\n _id: string;\n}\n\n// user response object\nexport interface UserRO {\n user: UserData;\n}\n```\n\nand a part of the `user.controller.ts`:\n\n```\n@Get(':id')\n findOne(@Param('id') id: string): Promise {\n console.log(`getting user with id: ${id}`);\n const user = this.serv.get(id);\n return user;\n }\n```\n\nand finally the `model/user.entity.ts`:\n\n```\n@Entity({ name: 'User' })\nexport class User {\n @ObjectIdColumn()\n _id: string;\n\n @Column({ type: 'varchar', length: 50 })\n username: string;\n\n @OneToMany((type) => Context, (context) => context.user)\n contexts: Context[];\n}\n```\n\nThe error I get when I try to find the saved context:\n\n```\n[Nest] 75671 - 09/22/2021, 9:22:18 PM ERROR [ExceptionsHandler] Cannot read property 'prototype' of undefined\nTypeError: Cannot read property 'prototype' of undefined\n at FindCursor.cursor.toArray (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:707:37)\n at MongoEntityManager. (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:190:46)\n at step (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:143:27)\n at Object.next (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:124:57)\n at fulfilled (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:114:62)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n```\n\nI tried with MongoDB 4. and 3. versions and it's the same problem.\n\nWhat am I doing wrong and how to get pass this error and be able to query the records well in MongoDB?\n\nThanks!\n\n========================================\n\nTop Answer:\nThis is a version issue.\nTo fix this try to use **version 3** by downgrading\n\nFirst remove existing mongodb package\n\n```\nnpm uninstall mongodb\n// Or\nyarn remove mongodb\n```\n\nThen install again with version 3.\n\n```\nnpm install mongodb@3\n// Or\nyarn add mongodb@3\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { validate } from 'class-validator';\nimport { CreateUserDto } from './user.dto';\nimport { User } from '../model/user.entity';\nimport { UserRO } from './user.interface';\n\n@Injectable()\nexport class UserService {\n  constructor(\n    @InjectRepository(User)\n    private readonly userRepository: MongoRepository<User>,\n  ) {}\n\n  // abstracting access to the model via service\n  public async getAll() {\n    // getting data from database\n    return await this.userRepository.find();\n  }\n\n  // abstracting access to the model via service\n  public async get(id: string) {\n    const user = await this.userRepository.findOne({ _id: id });\n    if (!user) {\n      const errors = { User: ' not found' };\n      throw new HttpException({ errors }, 401);\n    }\n\n    return this.buildUserRO(user);\n  }\n\n\n\n  async create(dto: CreateUserDto): Promise<UserRO> {\n    // check uniqueness of username/email\n    const { username } = dto;\n    const newUser = new User();\n    newUser.username = username;\n    // newUser.contexts = [];\n\n    const errors = await validate(newUser);\n    if (errors.length > 0) {\n      const _errors = { username: 'Userinput is not valid.' };\n      throw new HttpException(\n        { message: 'Input data validation failed', _errors },\n        HttpStatus.BAD_REQUEST,\n      );\n    } else {\n      const savedUser = await this.userRepository.save(newUser);\n      return this.buildUserRO(savedUser);\n    }\n  }\n\n\n}\n```\n\n```text\nexport interface UserData {\n  username: string;\n  _id: string;\n}\n\n// user response object\nexport interface UserRO {\n  user: UserData;\n}\n```\n\n```text\n@Get(':id')\n  findOne(@Param('id') id: string): Promise<UserRO> {\n    console.log(`getting user with id: ${id}`);\n    const user = this.serv.get(id);\n    return user;\n  }\n```\n\n```text\n@Entity({ name: 'User' })\nexport class User {\n  @ObjectIdColumn()\n  _id: string;\n\n  @Column({ type: 'varchar', length: 50 })\n  username: string;\n\n  @OneToMany((type) => Context, (context) => context.user)\n  contexts: Context[];\n}\n```\n\n```text\n[Nest] 75671  - 09/22/2021, 9:22:18 PM   ERROR [ExceptionsHandler] Cannot read property 'prototype' of undefined\nTypeError: Cannot read property 'prototype' of undefined\n    at FindCursor.cursor.toArray (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:707:37)\n    at MongoEntityManager.<anonymous> (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:190:46)\n    at step (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:143:27)\n    at Object.next (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:124:57)\n    at fulfilled (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:114:62)\n    at processTicksAndRejections (internal/process/task_queues.js:97:5)\n```\n\n```text\ncreate()\n```\n\n```text\nUser\n```\n\n```text\nfind({id})\n```\n\n```text\nfindAll()\n```\n\n```text\nuser.service.ts\n```\n\n```text\nuser.interface.ts\n```\n\n```text\nuser.controller.ts\n```\n\n```text\nmodel/user.entity.ts\n```\n\n```text\nnpm uninstall mongodb\n// Or\nyarn remove mongodb\n```\n\n```text\nnpm install mongodb@3\n// Or\nyarn add mongodb@3\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.470Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":302,"estimatedTokens":1909}}806{"id":"stack-70521273","source":"stackoverflow","questionId":70521273,"title":"How to unit test a custom repository of TypeORM in NestJS?","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: How to unit test a custom repository of TypeORM in NestJS?\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n### Class to test\n\nMy TypeORM repository `extends` AbstractRepository:\n\n```\n@EntityRepository(User)\nexport class UsersRepository extends AbstractRepository {\n\n async findByEmail(email: string): Promise {\n return await this.repository.findOne({ email })\n }\n}\n```\n\n### Unit test\n\n```\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [UsersRepository]\n }).compile()\n\n usersRepository = module.get(UsersRepository)\n })\n\n describe('findByEmail', () => {\n it(`should return the user when the user exists in database.`, async () => {\n const fetchedUser = await usersRepository.findByEmail('test1@test.com')\n })\n })\n})\n```\n\nHere, I get the error:\n\n```\nTypeError: Cannot read property 'getRepository' of undefined\n\n at UsersRepository.get (repository/AbstractRepository.ts:43:29)\n at UsersRepository.findByEmail (users/users.repository.ts:11:23)\n at Object. (users/users.repository.spec.ts:55:49)\n```\n\nSo, my question is, how do I mock the `repository` or `repository.findOne`?\n\nIn other words, how do I mock the fields that are inherited from the `AbstractRepository` which are `protected` and cannot be accessed from `UsersRepository` instance?\n\nThere is a similar question here but it is for extending from `Repository` instead of `AbstractRepository`. They are able to mock `findOne` because it's `public`.\n\n### What I tried\n\nI tried to mock it in a NestJS recommended way, but this is for non-custom repositories and doesn't work in my case:\n\n```\n{\n provide: getRepositoryToken(User),\n useValue: {\n findOne: jest.fn().mockResolvedValue(new User())\n }\n}\n```\n\n========================================\n\nTop Answer:\nAlthough your solution works, it causes repetition of db initialization code in all the repositories. I'd like to propose an alternate solution that works for me.\n\n**Step 1. Create a global configuration file `jest.config.ts` in your project root folder.**\n\n```\n// project-root/jest.config.ts\n\nimport type { Config } from '@jest/types';\n\nconst config: Config.InitialOptions = {\n moduleFileExtensions: ['js', 'json', 'ts'],\n rootDir: 'src',\n testRegex: '.*\\\\.spec\\\\.ts$',\n testEnvironment: 'node',\n preset: 'ts-jest',\n setupFilesAfterEnv: ['/jest.setup.ts'], // [!code focus]\n};\n\nexport default config;\n```\n\n**Step 2. create global setup file `src/jest.setup.ts` that contains global initialization code.**\n\n```\n// src/jest.setup.ts\n\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const testDbConfig: TypeOrmModuleOptions = {\n type: 'sqlite',\n database: ':memory:',\n dropSchema: true,\n synchronize: true,\n autoLoadEntities: true,\n};\n\n// assign the testDbConfig to a global variable\nglobal.testDbConfig = testDbConfig;\n```\n\n**Step 3: Create your repositories and inject the entity manager into the constructor.**\n\n```\nimport { EntityManager, Repository } from 'typeorm';\nimport { User } from './entities/user.entity';\n\nexport class UserRepository extends Repository {\n constructor(private readonly entityManager: EntityManager) {\n super(Movie, entityManager);\n }\n\n // my custom method that I need to unit test\n async findByEmail(title: string): Promise {\n return this.findOne({ where: { email } });\n }\n}\n```\n\n**Step 4. Unit test your repositories by making entries into the in-memory database via the `entityManager` and then try reading the entries with your custom repository methods.**\n\n```\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository;\n let entityManager: EntityManager;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [TypeOrmModule.forRoot(global.testDbConfig), TypeOrmModule.forFeature([User])],\n providers: [\n {\n provide: UsersRepository,\n useFactory: (entityManager: EntityManager) => new UsersRepository(entityManager),\n inject: [EntityManager],\n },\n ],\n }).compile();\n\n const repositoryToken = getRepositoryToken(UsersRepository);\n usersRepository = module.get(repositoryToken);\n entityManager = module.get(EntityManager);\n });\n\n // clear the user table to avoid clash with other test cases\n beforeEach(async () => {\n await entityManager.clear(User);\n });\n\n it('Should find the user by his email-id correctly', async () => {\n const testUser = new User();\n testUser.email = \"johndoe@example.com\"\n\n await entityManager.save(User, testUser);\n\n const fetchedUser = await usersRepository.findByEmail(testUser.email);\n expect(fetchedUser).toBeDefined();\n expect(fetchedUser.email).toEqual(testUser.email)\n });\n})\n```\n\nOnce complete, just run the test suite. That's all!\n\n========================================\n\nCode:\n```text\n@EntityRepository(User)\nexport class UsersRepository extends AbstractRepository<User> {\n\n  async findByEmail(email: string): Promise<User> {\n    return await this.repository.findOne({ email })\n  }\n}\n```\n\n```text\ndescribe('UsersRepository', () => {\n  let usersRepository: UsersRepository\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [UsersRepository]\n    }).compile()\n\n    usersRepository = module.get<UsersRepository>(UsersRepository)\n  })\n\n  describe('findByEmail', () => {\n    it(`should return the user when the user exists in database.`, async () => {\n      const fetchedUser = await usersRepository.findByEmail('test1@test.com')\n    })\n  })\n})\n```\n\n```text\nTypeError: Cannot read property 'getRepository' of undefined\n\n      at UsersRepository.get (repository/AbstractRepository.ts:43:29)\n      at UsersRepository.findByEmail (users/users.repository.ts:11:23)\n      at Object.<anonymous> (users/users.repository.spec.ts:55:49)\n```\n\n```text\n{\n  provide: getRepositoryToken(User),\n  useValue: {\n    findOne: jest.fn().mockResolvedValue(new User())\n  }\n}\n```\n\n```text\nextends\n```\n\n```text\nrepository\n```\n\n```text\nrepository.findOne\n```\n\n```text\nAbstractRepository\n```\n\n```text\nprotected\n```\n\n```text\nUsersRepository\n```\n\n```text\nRepository<Entity>\n```\n\n```text\nAbstractRepository<Entity>\n```\n\n```text\nfindOne\n```\n\n```text\npublic\n```\n\n```text\nconst testConnection = 'testConnection'\n\ndescribe('UsersRepository', () => {\n  let usersRepository: UsersRepository\n\n  beforeEach(async () => {\n    const connection = await createConnection({\n      type: 'sqlite',\n      database: ':memory:',\n      dropSchema: true,\n      entities: [User],\n      synchronize: true,\n      logging: false,\n      name: testConnection\n    })\n\n    usersRepository = connection.getCustomRepository(UsersRepository)\n  })\n\n  afterEach(async () => {\n    await getConnection(testConnection).close()\n  })\n\n  describe('findByEmail', () => {\n    it(`should return the user when the user exists in database.`, async () => {\n      await usersRepository.createAndSave(testUser)\n      const fetchedUser = await usersRepository.findByEmail(testUser.email)\n      expect(fetchedUser.email).toEqual(testUser.email)\n    })\n  })\n})\n```\n\n```js\n// project-root/jest.config.ts\n\nimport type { Config } from '@jest/types';\n\nconst config: Config.InitialOptions = {\n  moduleFileExtensions: ['js', 'json', 'ts'],\n  rootDir: 'src',\n  testRegex: '.*\\\\.spec\\\\.ts$',\n  testEnvironment: 'node',\n  preset: 'ts-jest',\n  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'], // [!code focus]\n};\n\nexport default config;\n```\n\n```js\n// src/jest.setup.ts\n\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const testDbConfig: TypeOrmModuleOptions = {\n  type: 'sqlite',\n  database: ':memory:',\n  dropSchema: true,\n  synchronize: true,\n  autoLoadEntities: true,\n};\n\n// assign the testDbConfig to a global variable\nglobal.testDbConfig = testDbConfig;\n```\n\n```js\nimport { EntityManager, Repository } from 'typeorm';\nimport { User } from './entities/user.entity';\n\nexport class UserRepository extends Repository<User> {\n  constructor(private readonly entityManager: EntityManager) {\n    super(Movie, entityManager);\n  }\n\n\n  // my custom method that I need to unit test\n  async findByEmail(title: string): Promise<User | undefined> {\n    return this.findOne({ where: { email } });\n  }\n}\n```\n\n```js\ndescribe('UsersRepository', () => {\n  let usersRepository: UsersRepository;\n  let entityManager: EntityManager;\n\n  beforeAll(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports: [TypeOrmModule.forRoot(global.testDbConfig), TypeOrmModule.forFeature([User])],\n      providers: [\n        {\n          provide: UsersRepository,\n          useFactory: (entityManager: EntityManager) => new UsersRepository(entityManager),\n          inject: [EntityManager],\n        },\n      ],\n    }).compile();\n\n    const repositoryToken = getRepositoryToken(UsersRepository);\n    usersRepository = module.get<UsersRepository>(repositoryToken);\n    entityManager = module.get<EntityManager>(EntityManager);\n  });\n\n  // clear the user table to avoid clash with other test cases\n  beforeEach(async () => {\n    await entityManager.clear(User);\n  });\n\n  it('Should find the user by his email-id correctly', async () => {\n    const testUser = new User();\n    testUser.email = \"johndoe@example.com\"\n\n    await entityManager.save(User, testUser);\n\n    const fetchedUser = await usersRepository.findByEmail(testUser.email);\n    expect(fetchedUser).toBeDefined();\n    expect(fetchedUser.email).toEqual(testUser.email)\n  });\n})\n```\n\n```text\njest.config.ts\n```\n\n```text\nsrc/jest.setup.ts\n```\n\n```text\nentityManager\n```\n\n========================================\n\nComments:\n- Does it fit to the column type you declare for the entity? i am asking since i am using also postgres and one of the column is json type, also i have enum's\n- @MatanTubul, if you are using the TypeORM over the postgres, it should work although I haven't tested it. TypeORM queries eventually get converted to postgres or SQLite queries behind the scenes, depending on the database.","metadata":{"transformedAt":"2026-08-18T18:33:02.470Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":407,"estimatedTokens":2497}}807{"id":"stack-54778197","source":"stackoverflow","questionId":54778197,"title":"How do I return an id string instead of a _bsontype with NestJS Serialization","tags":["node.js","typescript","nestjs","typeorm","class-transformer"],"text":"Title: How do I return an id string instead of a _bsontype with NestJS Serialization\nTags: node.js, typescript, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nWhen using\n\n```\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\nlike it is explained in the Documentation here\n\nI get the desired filtered result, however while using mongodb the id is formatted in `_bsontype` instead of a normal `string` like it used to be without the interceptor like this:\n\n```\n{\n \"id\": {\n \"_bsontype\": \"ObjectID\",\n \"id\": {\n \"0\": 92,\n \"1\": 108,\n \"2\": 182,\n \"3\": 85,\n \"4\": 185,\n \"5\": 20,\n \"6\": 221,\n \"7\": 12,\n \"8\": 56,\n \"9\": 66,\n \"10\": 131,\n \"11\": 172\n }\n },\n \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n \"firstName\": \"The First Name\",\n \"lastName\": \"The Last Name\",\n \"email\": \"giberish@gmail.com\"\n}\n```\n\nHow can I convert it back to a normal id string like this?\n\n```\n{\n \"id\": \"5c6cb655b914dd0c384283ac\",\n \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n \"firstName\": \"The First Name\",\n \"lastName\": \"The Last Name\",\n \"email\": \"giberish@gmail.com\"\n \"password\": \"okthen\"\n}\n```\n\n========================================\n\nCode:\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\n{\n    \"id\": {\n        \"_bsontype\": \"ObjectID\",\n        \"id\": {\n            \"0\": 92,\n            \"1\": 108,\n            \"2\": 182,\n            \"3\": 85,\n            \"4\": 185,\n            \"5\": 20,\n            \"6\": 221,\n            \"7\": 12,\n            \"8\": 56,\n            \"9\": 66,\n            \"10\": 131,\n            \"11\": 172\n        }\n    },\n    \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n    \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n    \"firstName\": \"The First Name\",\n    \"lastName\": \"The Last Name\",\n    \"email\": \"giberish@gmail.com\"\n}\n```\n\n```text\n{\n    \"id\": \"5c6cb655b914dd0c384283ac\",\n    \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n    \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n    \"firstName\": \"The First Name\",\n    \"lastName\": \"The Last Name\",\n    \"email\": \"giberish@gmail.com\"\n    \"password\": \"okthen\"\n}\n```\n\n```text\n_bsontype\n```\n\n```text\nstring\n```\n\n```text\nimport { Transform } from 'class-transformer';\n\n@Entity()\nexport class User {\n  @ObjectIdColumn()\n  @Transform(({ value }) => value.toString(), { toPlainOnly: true })\n  _id: ObjectID;\n```\n\n```text\n@Transform()\n```\n\n```text\ntoPlainOnly\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nclassToPlain()\n```\n\n========================================\n\nComments:\n- It might help to lift the relevant repro steps from the link into your question directly.\n- The answer returns [Object Object] for me. I have to use `@Transform(({value}) => value.toString(), { toPlainOnly: true })`\n- @webHasan Thanks for your comment, I have updated the answer. The signature has changed with version 0.3.2, see changelog: github.com/typestack/class-transformer/blob/v0.5.1/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":142,"estimatedTokens":723}}808{"id":"stack-69103543","source":"stackoverflow","questionId":69103543,"title":"How to get distinct values from typeorm find \"query\"","tags":["nestjs","typeorm"],"text":"Title: How to get distinct values from typeorm find \"query\"\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement the following query on typeorm but unable to filter out the distinct values.\n\n```\nSELECT DISTINCT name, description, style, spec2, div FROM clothes WHERE name = 'CMD' and div in ('B01', 'B06', 'B07', 'B09')\n```\n\nMy existing code is like following.\n\n```\nthis._itemRepository.find({\n where: {\n \"name\" : \"values\",\n \"div\" : In([\"v1\",\"v2\"])\n },\n })\n```\n\nfind() method's parameter is `FindManyOptions` type but it doesn't have any attribute related to distinct values. Please help me to find a way\n\n========================================\n\nCode:\n```text\nSELECT DISTINCT name, description, style, spec2, div FROM clothes WHERE name = 'CMD' and div  in ('B01', 'B06', 'B07', 'B09')\n```\n\n```text\nthis._itemRepository.find({\n      where: {\n        \"name\" : \"values\",\n        \"div\" : In([\"v1\",\"v2\"])\n      },\n   })\n```\n\n```text\nFindManyOptions\n```\n\n```text\nthis._itemRepository.createQueryBuilder('clothes')\n.select(['name', 'description', 'style', 'spec2', 'div'])\n.where('name = CMD AND div IN (B01, B06, B07, B09)')\n.distinct()\n```\n\n```text\nthis._itemRepository.createQueryBuilder('clothes')\n.select('DISTINCT(name)')\n.where('name = CMD AND div IN (B01, B06, B07, B09)')\n```\n\n```text\nfind\n```\n\n```text\nqueryBuilder\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":64,"estimatedTokens":338}}809{"id":"stack-64282183","source":"stackoverflow","questionId":64282183,"title":"NestJS. Can't inject a repository from a different module","tags":["nestjs","typeorm"],"text":"Title: NestJS. Can't inject a repository from a different module\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to use a *typeorm custom repository* defined in another module.\n\nFollowing the documentation:\n\nIf you want to use the repository outside of the module which imports TypeOrmModule.forFeature, you'll need to re-export the providers generated by it. You can do this by exporting the whole module, like this:\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([Role])],\n exports: [TypeOrmModule]\n})\nexport class RoleModule {}\n```\n\nNow if we import UsersModule in UserHttpModule, we can use @InjectRepository(User) in the providers of the latter module.\n\nIn my case i do:\n\n```\n@Module({\n imports: [RoleModule],\n providers: [UsersService],\n controllers: [UsersController]\n})\nexport class UserModule {}\n```\n\nNow when i inject the Role repository\n\n```\nexport class UserService {\n constructor(@InjectRepository(Role) private roleRepository: Repository) {}\n}\n```\n\ni've got an error:\n`Nest can't resolve dependencies of the UserService (?).`\n\nIs it me or is the documentation incorrect?\nCan someone suggest what is the error here or give a corrected example?\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([Role])],\n  exports: [TypeOrmModule]\n})\nexport class RoleModule {}\n```\n\n```text\n@Module({\n  imports: [RoleModule],\n  providers: [UsersService],\n  controllers: [UsersController]\n})\nexport class UserModule {}\n```\n\n```text\nexport class UserService {\n  constructor(@InjectRepository(Role) private roleRepository: Repository<Role>) {}\n}\n```\n\n```text\nNest can't resolve dependencies of the UserService (?).\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([Role]), RoleModule], // <-- here\n  providers: [UsersService],\n  controllers: [UsersController]\n})\nexport class UserModule {}\n```\n\n```text\nTypeOrmModule.forFeature([Role])\n```\n\n========================================\n\nComments:\n- I know you've already accepted an answer, but what was the full error you were getting?\n- `[ExceptionHandler] Nest can't resolve dependencies of the UserService (?). Please make sure that the argument RoleRepository at index [1] is available in the UserModule context. Potential solutions: - If RoleRepository is a provider, is it part of the current UserModule? - If RoleRepository is exported from a separate @Module, is that module imported within UserModule? @Module({ imports: [ &#47;* the Module containing RoleRepository *&#47; ] })`\n- do we need to import RoleModule as well? If i omit RoleModule in import and only import `TypeOrmModule.forFeature([Role])` it doesn't work?\n- Why do we have to import the entities again although we already import the whole module which contains the corresponding entity?","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":96,"estimatedTokens":698}}810{"id":"stack-53956655","source":"stackoverflow","questionId":53956655,"title":"How to return an image file correctly using nest.js?","tags":["javascript","rest","nestjs"],"text":"Title: How to return an image file correctly using nest.js?\nTags: javascript, rest, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to return the requested image file. My client is downloading the file, but I can't display it because it's an invalid `png` file. If I open the stored file `tmpFile.png`, I can see it correctly. So probably the problem is on how I'm sending it back to the client asking for it.\n\n```\n// This is my controller\nasync getFile(@Param('bucketname') bucketName: string,\n @Param('filename') fileName: string) {\nreturn await this.appService.getFile(bucketName, fileName);\n\n// This is the function called\ngetFile(bucketName: string, fileName: string) {\n return new Promise(resolve => {\n this.minioClient.getObject(bucketName, fileName, (e, dataStream) => {\n if (e) {\n console.log(e);\n }\n\n let size = 0;\n const binary = fs.createWriteStream('tmpFile.png');\n\n dataStream.on('data', chunk => {\n size += chunk.length;\n binary.write(chunk);\n });\n dataStream.on('end', () => {\n binary.end();\n resolve(binary);\n });\n });\n });\n }\n```\n\n========================================\n\nCode:\n```text\n// This is my controller\nasync getFile(@Param('bucketname') bucketName: string,\n            @Param('filename') fileName: string) {\nreturn await this.appService.getFile(bucketName, fileName);\n\n\n// This is the function called\ngetFile(bucketName: string, fileName: string) {\n    return new Promise(resolve => {\n      this.minioClient.getObject(bucketName, fileName, (e, dataStream) => {\n        if (e) {\n          console.log(e);\n        }\n\n        let size = 0;\n        const binary = fs.createWriteStream('tmpFile.png');\n\n        dataStream.on('data', chunk => {\n          size += chunk.length;\n          binary.write(chunk);\n        });\n        dataStream.on('end', () => {\n          binary.end();\n          resolve(binary);\n        });\n      });\n    });\n  }\n```\n\n```text\npng\n```\n\n```text\ntmpFile.png\n```\n\n```text\n// This is my controller\nasync getFile(@Param('bucketname') bucketName: string, @Param('filename') fileName: string, @Res() response) {\n  return (await this.appService.getFile(bucketName, fileName)).pipe(response);\n}\n```\n\n========================================\n\nComments:\n- refer to this answer - stackoverflow.com/questions/54607278/&hellip;\n- Title is misleading. It should have been specified as \"[AWS] return image file correctly using nestjs\"\n- Why it should be aws?","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":599}}811{"id":"stack-59787828","source":"stackoverflow","questionId":59787828,"title":"Nest JS add another secret key to refresh token with @nestjs/jwt","tags":["nestjs","jwt"],"text":"Title: Nest JS add another secret key to refresh token with @nestjs/jwt\nTags: nestjs, jwt\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make authentication with access and refresh tokens on NestJs. As i saw in nestjs documentation i should register my secret key in auth module. I did that.\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'RefreshToken', schema: RefreshTokenSchema }]),\n UsersModule,\n PassportModule,\n JwtModule.register({\n secret: jwtConstants.secret,\n }),\n ],\n providers: [AuthService, LocalStrategy, JwtStrategy],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\nThis secret key is used when im creating my tokens in auth service.\n\n```\nimport { JwtService } from '@nestjs/jwt';\nconst accessToken = this.jwtService.sign(payload, { expiresIn: '60s'});\nconst refreshToken = this.jwtService.sign(payload, { expiresIn: '24h' });\n```\n\nWhen im trying to set secret key in this.jwtService.sign function\nlike \n\n```\nconst accessToken = this.jwtService.sign(payload, 'secretkey' ,{ expiresIn: '60s'})\n```\n\nI've got error. It tells me that function can get only two arguments.\nSo how can create two secret keys and use each other for proper token?\n\n========================================\n\nTop Answer:\n@nestjs/jwt JwtService allows you to pass options to the sign() method.\n\nyou can just...\n\n```\nlet token = this.jwtService.sign(payload);\nlet refreshToken = this.jwtService.sign(payload, {\n secret: jwtConstants.jwt_refresh_secret,\n expiresIn: jwtConstants.jwt_refresh_expire\n});\n```\n\n`token` uses params you registered the service with and `refreshToken` will use alternate params\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: 'RefreshToken', schema: RefreshTokenSchema }]),\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n    }),\n  ],\n  providers: [AuthService, LocalStrategy, JwtStrategy],\n  controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { JwtService } from '@nestjs/jwt';\nconst accessToken = this.jwtService.sign(payload, { expiresIn: '60s'});\nconst refreshToken = this.jwtService.sign(payload, { expiresIn: '24h' });\n```\n\n```text\nconst accessToken = this.jwtService.sign(payload, 'secretkey' ,{ expiresIn: '60s'})\n```\n\n```js\nexport class JwtStrategy extends PassportStrategy(Strategy, 'accessToken') {}\n```\n\n```js\nexport class JwtStrategy2 extends PassportStrategy(Strategy, 'refreshToken') {}\n```\n\n```js\n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: 'RefreshToken', schema: RefreshTokenSchema }]),\n    UsersModule,\n    PassportModule.register({ defaultStrategy: 'accessToken' }),\n    JwtModule.register({\n      secret: jwtConstants.secret,\n    }),\n  ],\n  providers: [AuthService, LocalStrategy, JwtStrategy, JwtStrategy2],\n  controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n```text\nlet token = this.jwtService.sign(payload);\nlet refreshToken = this.jwtService.sign(payload, {\n  secret: jwtConstants.jwt_refresh_secret,\n  expiresIn: jwtConstants.jwt_refresh_expire\n});\n```\n\n```text\ntoken\n```\n\n```text\nrefreshToken\n```\n\n========================================\n\nComments:\n- I have a similar issue. But I need different timeouts for each strategy. Is it possible?\n- Couldn't you just change the token signing in the service?\n- How can I use the second `jwtService` in this case?","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":133,"estimatedTokens":854}}812{"id":"stack-70906216","source":"stackoverflow","questionId":70906216,"title":"Nest can't resolve dependencies of the AuthenticationService","tags":["javascript","angular","nestjs"],"text":"Title: Nest can't resolve dependencies of the AuthenticationService\nTags: javascript, angular, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am new to nest js and I am trying to implement authenticating with nest js using JWT Token. I flow This article to implement my authenticating code.\n\nWhen I run the code I get an error like this.\n\n**\n\n[Nest] 16236 - 01/29/2022, 7:16:06 PM ERROR [ExceptionHandler] Nest\ncan't resolve dependencies of the AuthenticationService (?,\nJwtService, ConfigService). Please make sure that the argument\nUsersService at index [0] is available in the AuthenticationModule\ncontext. Potential solutions:\n\n- If UsersService is a provider, is it part of the current AuthenticationModule?\nIf UsersService is exported from a separate @Module, is that module imported within AuthenticationModule? @Module({\nimports: [ /* the Module containing UsersService */ ] })\n\n**\n\nAnd I have no idea what is wrong with my code.\n\nThis is my UserModule :\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [UsersService],\n})\nexport class UsersModule {}\n```\n\nThis is my AuthenticationModule:\n\n```\n@Module({\n imports: [\n UsersModule,\n PassportModule,\n ConfigModule,\n JwtModule.registerAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n secret: configService.get('JWT_SECRET'),\n signOptions: {\n expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,\n },\n }),\n }),\n ],\n controllers: [AuthenticationController],\n providers: [AuthenticationService, LocalStrategy, JwtStrategy],\n})\nexport class AuthenticationModule {}\n```\n\nThis is my AppModule:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot(ORM_CONFIG),\n ConfigModule.forRoot({\n validationSchema: Joi.object({\n JWT_SECRET: 'ABC',\n JWT_EXPIRATION_TIME: '1d',\n }),\n }),\n ItemModule,\n CategoryModule,\n ItemHasCategoryModule,\n OrderModule,\n OrderHasItemModule,\n PaymentModule,\n CustomerModule,\n UsersModule,\n AuthenticationModule,\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nMy AuthenticationService File :\n\n```\n@Injectable()\nexport class AuthenticationService {\n constructor(\n private readonly usersService: UsersService,\n private readonly jwtService: JwtService,\n private readonly configService: ConfigService,\n ) {}\n```\n\nMy UsersService File :\n\n```\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User) private readonly userRepository: Repository,\n ) {}\n```\n\n**If anyone knows the answer to this...I really need your help..I am struggling with this error for hours...Thank you.**\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  controllers: [UsersController],\n  providers: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\n@Module({\n  imports: [\n    UsersModule,\n    PassportModule,\n    ConfigModule,\n    JwtModule.registerAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: async (configService: ConfigService) => ({\n        secret: configService.get('JWT_SECRET'),\n        signOptions: {\n          expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,\n        },\n      }),\n    }),\n  ],\n  controllers: [AuthenticationController],\n  providers: [AuthenticationService, LocalStrategy, JwtStrategy],\n})\nexport class AuthenticationModule {}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(ORM_CONFIG),\n    ConfigModule.forRoot({\n      validationSchema: Joi.object({\n        JWT_SECRET: 'ABC',\n        JWT_EXPIRATION_TIME: '1d',\n      }),\n    }),\n    ItemModule,\n    CategoryModule,\n    ItemHasCategoryModule,\n    OrderModule,\n    OrderHasItemModule,\n    PaymentModule,\n    CustomerModule,\n    UsersModule,\n    AuthenticationModule,\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\n@Injectable()\nexport class AuthenticationService {\n  constructor(\n    private readonly usersService: UsersService,\n    private readonly jwtService: JwtService,\n    private readonly configService: ConfigService,\n  ) {}\n```\n\n```text\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User) private readonly userRepository: Repository<User>,\n  ) {}\n```\n\n```text\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  controllers: [UsersController],\n  providers: [UsersService],\n  exports: [UsersService] \n}) \nexport class UsersModule {}\n```\n\n========================================\n\nComments:\n- @Eldar In the nestjs documentation, they are exporting the service. docs.nestjs.com/security/authentication\n- @Soheb my bad, I thought they angular modularization design, but it seems there are some differences.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":207,"estimatedTokens":1178}}813{"id":"stack-61742615","source":"stackoverflow","questionId":61742615,"title":"Nest.js handling errors for HttpService","tags":["rxjs","axios","nestjs"],"text":"Title: Nest.js handling errors for HttpService\nTags: rxjs, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to test NestJS's built in HttpService (which is based on Axios). I'm having trouble testing error/exception states though. In my test suite I have:\n\n```\nlet client: SomeClearingFirmClient;\n\n const mockConfigService = {\n get: jest.fn((type) => {\n switch(type) {\n case 'someApiBaseUrl': {\n return 'http://example.com'\n }\n case 'someAddAccountEndpoint': {\n return '/ClientAccounts/Add';\n }\n case 'someApiKey': {\n return 'some-api-key';\n }\n\n default:\n return 'test';\n }\n }),\n };\n\n const successfulAdd: AxiosResponse = {\n data: {\n batchNo: '39cba402-bfa9-424c-b265-1c98204df7ea',\n warning: '',\n },\n status: 200,\n statusText: 'OK',\n headers: {},\n config: {},\n };\n\n const failAddAuth: AxiosError = {\n code: '401',\n config: {},\n name: '',\n message: 'Not Authorized',\n }\n\n const mockHttpService = {\n post: jest.fn(),\n get: jest.fn(),\n }\n\n it('Handles a failure', async () => {\n expect.assertions(1);\n mockHttpService.post = jest.fn(() => of(failAddAuth));\n\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n {\n provide: ConfigService,\n useValue: mockConfigService,\n },\n {\n provide: HttpService,\n useValue: mockHttpService,\n },\n SomeClearingFirmClient,\n ],\n }).compile();\n\n client = module.get(SomeClearingFirmClient);\n\n const payload = new SomeClearingPayload();\n try {\n await client.addAccount(payload);\n } catch(e) {\n console.log('e', e);\n }\n });\n```\n\nAnd my implementation is:\n\n```\nasync addAccount(payload: any): Promise {\n const addAccountEndpoint = this.configService.get('api.someAddAccountEndpoint');\n const url = `${this.baseUrl}${addAccountEndpoint}?apiKey=${this.apiKey}`;\n const config = {\n headers: {\n 'Content-Type': 'application/json',\n }\n };\n\n const response = this.httpService.post(url, payload, config)\n .pipe(\n map(res => {\n return res.data;\n }),\n catchError(e => {\n throw new HttpException(e.response.data, e.response.status);\n }),\n ).toPromise().catch(e => {\n throw new HttpException(e.message, e.code);\n });\n\n return response;\n }\n```\n\nRegardless of whether I use Observables or Promises, I can't get anything to catch. 4xx level errors sail on through as a success. I feel like I remember Axios adding some sort of config option to reject/send an Observable error to subscribers on failures... but I could be imagining that. Am I doing something wrong in my test harness? The other StackOverflow posts I've seen seem to say that piping through `catchError` should do the trick, but my errors are going through the `map` operator.\n\n========================================\n\nCode:\n```text\nlet client: SomeClearingFirmClient;\n\n  const mockConfigService = {\n    get: jest.fn((type) => {\n      switch(type) {\n        case 'someApiBaseUrl': {\n          return 'http://example.com'\n        }\n        case 'someAddAccountEndpoint': {\n          return '/ClientAccounts/Add';\n        }\n        case 'someApiKey': {\n          return 'some-api-key';\n        }\n\n        default:\n          return 'test';\n      }\n    }),\n  };\n\n  const successfulAdd: AxiosResponse = {\n    data: {\n      batchNo: '39cba402-bfa9-424c-b265-1c98204df7ea',\n      warning: '',\n    },\n    status: 200,\n    statusText: 'OK',\n    headers: {},\n    config: {},\n  };\n\n  const failAddAuth: AxiosError = {\n    code: '401',\n    config: {},\n    name: '',\n    message: 'Not Authorized',\n  }\n\n  const mockHttpService = {\n    post: jest.fn(),\n    get: jest.fn(),\n  }\n\n  it('Handles a failure', async () => {\n    expect.assertions(1);\n    mockHttpService.post = jest.fn(() => of(failAddAuth));\n\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        {\n          provide: ConfigService,\n          useValue: mockConfigService,\n        },\n        {\n          provide: HttpService,\n          useValue: mockHttpService,\n        },\n        SomeClearingFirmClient,\n      ],\n    }).compile();\n\n    client = module.get<SomeClearingFirmClient>(SomeClearingFirmClient);\n\n    const payload = new SomeClearingPayload();\n    try {\n      await client.addAccount(payload);\n    } catch(e) {\n      console.log('e', e);\n    }\n  });\n```\n\n```text\nasync addAccount(payload: any): Promise<SomeAddResponse> {\n    const addAccountEndpoint = this.configService.get('api.someAddAccountEndpoint');\n    const url = `${this.baseUrl}${addAccountEndpoint}?apiKey=${this.apiKey}`;\n    const config = {\n      headers: {\n        'Content-Type': 'application/json',\n      }\n    };\n\n    const response = this.httpService.post(url, payload, config)\n      .pipe(\n        map(res => {\n          return res.data;\n        }),\n        catchError(e => {\n          throw new HttpException(e.response.data, e.response.status);\n        }),\n      ).toPromise().catch(e => {\n        throw new HttpException(e.message, e.code);\n      });\n\n    return response;\n  }\n```\n\n```text\ncatchError\n```\n\n```text\nmap\n```\n\n```js\nmockHttpService.post = jest.fn(() => of(failAddAuth));\n```\n\n```js\n// Something to comply with `HttpException`'s arguments\nconst err = { response: 'resp', status: '4xx' };\n\nmockHttpService.post = jest.fn(() => throwError(err));\n```\n\n```text\nmockHttpService\n```\n\n```text\nof(failAddAuth)\n```\n\n```text\nfailAddAuth\n```\n\n```text\ncatchError\n```\n\n```text\nthis.httpService.post(url, payload, config)\n```\n\n```text\ncatchError\n```\n\n```text\npost()\n```\n\n```text\nthrowError(err)\n```\n\n```text\nnew Observable(s => s.error(err))\n```\n\n========================================\n\nComments:\n- Ok, that makes sense. The issue was in the mock itself. Thanks!\n- How come `expect(mockHttpService.post).toHaveBeenCalled();` fails the test? Is there something special we must do to make it observe/know that it was called?","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":274,"estimatedTokens":1427}}814{"id":"stack-67453970","source":"stackoverflow","questionId":67453970,"title":"User is undefined on the context.switchToHttp().getRequest() nestjs","tags":["javascript","node.js","jwt","nestjs","roles"],"text":"Title: User is undefined on the context.switchToHttp().getRequest() nestjs\nTags: javascript, node.js, jwt, nestjs, roles\nSource: Stack Overflow\n\nQuestion:\nI'm new to nestJs and I needed to add role based access to the application so I followed the documentation but in the execution context user doesn't exist. I can't seems to find the problem here's the github repo if you need to seem more code: https://github.com/anjula-sack/slinc-backend\n\n**roles.guard.ts**\n\n```\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { ROLES_KEY } from 'src/decorators/roles.decorator';\nimport Role from 'src/util/enums/role.enum';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n if (!requiredRoles) {\n return true;\n }\n const { user } = context.switchToHttp().getRequest();\n console.log(context.switchToHttp().getRequest().req);\n\n return requiredRoles.some((role) => user.type === role);\n }\n}\n```\n\n**app.controller.ts**\n\n```\n@UseGuards(JwtAuthGuard, RolesGuard)\n @Get('me/business')\n @Roles(Role.ADMIN)\n getBusiness(@Request() req) {\n return this.usersService.getUserBusiness(req.user.id);\n }\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { ROLES_KEY } from 'src/decorators/roles.decorator';\nimport Role from 'src/util/enums/role.enum';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n    if (!requiredRoles) {\n      return true;\n    }\n    const { user } = context.switchToHttp().getRequest();\n    console.log(context.switchToHttp().getRequest().req);\n\n    return requiredRoles.some((role) => user.type === role);\n  }\n}\n```\n\n```text\n@UseGuards(JwtAuthGuard, RolesGuard)\n  @Get('me/business')\n  @Roles(Role.ADMIN)\n  getBusiness(@Request() req) {\n    return this.usersService.getUserBusiness(req.user.id);\n  }\n```\n\n```text\n// Remove the following code in app.module.ts\n{\n    provide: APP_GUARD,\n    useClass: RolesGuard,\n}\n```\n\n```text\napp.module.ts\n```\n\n```text\napp.useGlobalGuard()\n```\n\n========================================\n\nComments:\n- Do you have the `RolesGuard` bound globally by chance?\n- yeah it's in the app.module.ts\n- Could you the documentation you followed? Also, could you explain how you send the `user` in the request? Is it inside the header or the body? I tried the github URL you posted, but I guess it is a private repository so I can't see\n- can you check now? I made it public @ErangaHeshan\n- what if I want to use role guard as global? I don't wanna mention it in every controller.\n- I removed it from app.module.ts and placed in auth.module.ts. Now, It is working fine.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":109,"estimatedTokens":797}}815{"id":"stack-67212239","source":"stackoverflow","questionId":67212239,"title":"TypeORM: update entity column with relation (@joinColumn) via Repository","tags":["node.js","typescript","postgresql","nestjs","typeorm"],"text":"Title: TypeORM: update entity column with relation (@joinColumn) via Repository\nTags: node.js, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have the following entities:\n\n```\n@Entity({ name: 'user' })\nexport class UserEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n nullable: false,\n unique: true,\n })\n login: string;\n}\n```\n\n```\n@Entity({ name: 'wallet' })\nexport class WalletEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => UserEntity)\n @JoinColumn({ name: 'user_id' })\n user: UserEntity;\n\n @Column({\n name: 'address',\n type: 'text',\n })\n address: string;\n}\n```\n\nSo, the wallet table is looks like this:\n\n```\n-------------------------\n id | user_id | address\n-------------------------\n 1 | 1 | 0x12 \n-------------------------\n 2 | 43 | 0x10\n```\n\nAnd I like to update the `wallet` entity via Repository api. But the problem is, that I can't just:\n\n```\nWalletRepository.save({ address: '0x12', userId: 2 })\n```\n\nBecause Typescript give me an error, that `userId` should be `userEntity`, but not number. But I want to update a relation column. So is there any option to update it?\n\n========================================\n\nCode:\n```text\n@Entity({ name: 'user' })\nexport class UserEntity extends BasicEntity {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({\n    nullable: false,\n    unique: true,\n  })\n  login: string;\n}\n```\n\n```text\n@Entity({ name: 'wallet' })\nexport class WalletEntity extends BasicEntity {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @ManyToOne(() => UserEntity)\n  @JoinColumn({ name: 'user_id' })\n  user: UserEntity;\n\n  @Column({\n    name: 'address',\n    type: 'text',\n  })\n  address: string;\n}\n```\n\n```text\n-------------------------\n id | user_id | address\n-------------------------\n 1  |    1    |   0x12   \n-------------------------\n 2  |    43    |  0x10\n```\n\n```text\nWalletRepository.save({ address: '0x12', userId: 2 })\n```\n\n```text\nwallet\n```\n\n```text\nuserId\n```\n\n```text\nuserEntity\n```\n\n```text\n@Entity({ name: 'wallet' })\nexport class WalletEntity extends BasicEntity {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @ManyToOne(() => UserEntity, (entity: UserEntity) => entity.id)\n  @JoinColumn({ name: 'user_id' })\n  user: UserEntity;\n\n  @Column({ name: 'user_id', type: 'int' })\n  userId: number;\n\n  @Column({\n    name: 'address',\n    type: 'text',\n  })\n  address: string;\n}\n```\n\n```text\n{name: user_id}\n```\n\n```text\nuserID\n```\n\n```text\njoin\n```\n\n```text\nrelations[]\n```\n\n```text\nuser\n```\n\n========================================\n\nComments:\n- Thank you for posting your findings, could find very little docs on this\n- I think you also need make sure `userId` field can be set to null right? since there will be only one `user_id` field in db, from the many to one relation, a wallet can have user as null, but with the manually defined `userId` field in WalletEntity it insist that user should not be null","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":164,"estimatedTokens":737}}816{"id":"stack-76133634","source":"stackoverflow","questionId":76133634,"title":"How to import \"crypto\" system library in NodeJS because it is suddenly undefined?","tags":["node.js","nestjs","cryptojs"],"text":"Title: How to import \"crypto\" system library in NodeJS because it is suddenly undefined?\nTags: node.js, nestjs, cryptojs\nSource: Stack Overflow\n\nQuestion:\nI updated a NestJS based project from 2021 that contains an import like this:\n\n```\nimport crypto from 'crypto';\n```\n\nNowadays, with Node 18, `crypto` is undefined.\n\nWhat happened to this lib, and is there a replacement available? According to NodeJS documentation, this actually should not happen to be removed.\n\n========================================\n\nCode:\n```text\nimport crypto from 'crypto';\n```\n\n```text\ncrypto\n```\n\n```text\nnode:crypto\n```\n\n```text\nnode:\n```\n\n```text\nimport * as crypto from 'crypto'\n```\n\n```text\nsyntheticDefaultImports: true\n```\n\n```text\ntsconfig\n```\n\n```text\nesModuleInterop\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Thanks a lot! esModuleInterop: true was the best approach here for nestJS+TS.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":58,"estimatedTokens":228}}817{"id":"stack-51574878","source":"stackoverflow","questionId":51574878,"title":"Debugging Nest App using path mapping by TS","tags":["node.js","typescript","visual-studio-code","nestjs"],"text":"Title: Debugging Nest App using path mapping by TS\nTags: node.js, typescript, visual-studio-code, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to debug a typescript-node app (by nestjs) but as I included the path mapping by Typescript ->\n\n https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping\n\nit doesn't work anymore, it **throws this error**:\n\nhttps://i.sstatic.net/fyBV8.jpg\n\n**Debug config file** looks like this:\n\nhttps://i.sstatic.net/ZrVfv.jpg\n\nAnd **TSCONFIG file** looks like this:\n\nhttps://i.sstatic.net/ac7Ho.jpg\n\nJust to mention that the app works fine, the tests are passing fine and everything is working as expected, except when I press play to debug de app. \n\nA work-around is to replace those paths by the relative normal path to be imported, but that means getting rid of the path mapping feature brought by TS and that's my last shot.\n\n========================================\n\nTop Answer:\nAs for **debugging**, I wonder why you've introduced nodemon in case of using *typescript* and having *ts-node* already installed.\nYour solution can be simplified using only tsconfig-paths lib. After installing, launch.json in vscode may be updated as follows:\n\n```\n{\n \"configurations\": [{\n \"type\": \"node\",\n \"request\": \"launch\",\n \"name\": \"Debug Nest App\",\n \"args\": [\"src/main.ts\"],\n \"runtimeArgs\": [\"-r\", \"ts-node/register\", \"-r\", \"tsconfig-paths/register\"],\n \"autoAttachChildProcesses\": true\n }]\n}\n```\n\nHere is the link to that particular point in package documentation.\n\nPS: Nest framework provides script `start:debug` out of the box which also can be simply attached to launch.json configuration.\n\n========================================\n\nCode:\n```text\n\"jest\": {\n    \"moduleFileExtensions\": [ ... ],\n    \"moduleNameMapper\": {\n      \"@db/(.*)\": \"<rootDir>/core/database/$1\",\n      \"@exceptions/(.*)\": \"<rootDir>/core/exceptions/$1\",\n      \"@permissions/(.*)\": \"<rootDir>/permissions/$1\",\n      \"@roles/(.*)\": \"<rootDir>/roles/$1\",\n      \"@users/(.*)\": \"<rootDir>/users/$1\",\n      \"@videos/(.*)\": \"<rootDir>/videos/$1\"\n    },\n    \"rootDir\": \"src\",\n    ...\n```\n\n```text\n{\n            \"type\": \"node\",\n            \"request\": \"launch\",\n            \"name\": \"Nest Debug\",\n            \"runtimeExecutable\": \"npm\",\n            \"runtimeArgs\": [\n                \"run-script\",\n                \"debug\"\n            ],\n            \"port\": 9229\n        },\n```\n\n```text\n\"debug\": \"nodemon --config nodemon-debug.json\",\n```\n\n```text\n{\n  \"watch\": [\n    \"src\"\n  ],\n  \"ext\": \"ts\",\n  \"ignore\": [\n    \"src/**/*.spec.ts\"\n  ],\n  \"exec\": \"node --inspect-brk -r ts-node/register -r tsconfig-paths/register src/main.ts\"\n}\n```\n\n```text\n{\n  \"configurations\": [{\n    \"type\": \"node\",\n    \"request\": \"launch\",\n    \"name\": \"Debug Nest App\",\n    \"args\": [\"src/main.ts\"],\n    \"runtimeArgs\": [\"-r\", \"ts-node/register\", \"-r\", \"tsconfig-paths/register\"],\n    \"autoAttachChildProcesses\": true\n  }]\n}\n```\n\n```text\nstart:debug\n```\n\n========================================\n\nComments:\n- NodeJS does not support this resolution scheme. The purpose of the typescript path mapping is to *model* the behavior of loaders that do support it, not to *implement* that behavior. TypeScript is not a loader.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":118,"estimatedTokens":801}}818{"id":"stack-76793746","source":"stackoverflow","questionId":76793746,"title":"Manage optional and required fields using another field in Nestjs DTO","tags":["typescript","validation","nestjs","dto","class-validator"],"text":"Title: Manage optional and required fields using another field in Nestjs DTO\nTags: typescript, validation, nestjs, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI want to make fields required based on another field in the DTO itself.\n\nCurrently my DTO looks like:\n\n```\nimport { LOGIN_TYPE } from \"src/utils/constants\";\nimport { IsIn, IsNotEmpty, IsOptional } from \"class-validator\";\n\nexport class LoginDto {\n @IsOptional()\n phoneNumber: string\n\n @IsOptional()\n fcmToken: string\n\n @IsOptional()\n accessToken: string\n\n @IsOptional()\n @IsIn([LOGIN_TYPE.APPLE, LOGIN_TYPE.GOOGLE, LOGIN_TYPE.FACEBOOK, LOGIN_TYPE.PHONE_NUMBER_OTP])\n loginType: string = LOGIN_TYPE.PHONE_NUMBER_OTP;\n}\n```\n\nBut the problem is, I don'y want to make it optional blindly.\n\nIf \"loginType\" = PHONE_NUMBER_OTP, I want \"phoneNumber\" as the mandatory parameter\nIf \"loginType\" = GOOGLE || APPLE || FACEBOOK, I want \"accessToken\" as the mandatory parameter\n\nHow can I achieve that in DTO itself.\n\nI have used {transform: true} already. Any help or suggestion handle in another way is much appeciated! Thank you so much in advance\n\nTried: Making all optional but I don't wanna handle those stuffs inside my service\nExpectation: I want to handled this validations in DTO itself\n\n========================================\n\nCode:\n```text\nimport { LOGIN_TYPE } from \"src/utils/constants\";\nimport { IsIn, IsNotEmpty, IsOptional } from \"class-validator\";\n\nexport class LoginDto {\n    @IsOptional()\n    phoneNumber: string\n\n    @IsOptional()\n    fcmToken: string\n\n    @IsOptional()\n    accessToken: string\n\n    @IsOptional()\n    @IsIn([LOGIN_TYPE.APPLE, LOGIN_TYPE.GOOGLE, LOGIN_TYPE.FACEBOOK, LOGIN_TYPE.PHONE_NUMBER_OTP])\n    loginType: string = LOGIN_TYPE.PHONE_NUMBER_OTP;\n}\n```\n\n```js\nimport { LOGIN_TYPE } from \"src/utils/constants\";\nimport { IsIn, IsNotEmpty, IsOptional, ValidateIf } from \"class-validator\";\n\nexport class LoginDto {\n    @IsOptional()\n    phoneNumber: string\n\n    @IsOptional()\n    fcmToken: string\n\n    @ValidateIf((body) => [LOGIN_TYPE.APPLE, LOGIN_TYPE.GOOGLE, LOGIN_TYPE.FACEBOOK].includes(body.loginType))\n    @IsNotEmpty()\n    accessToken: string\n\n    @IsOptional()\n    @IsIn([LOGIN_TYPE.APPLE, LOGIN_TYPE.GOOGLE, LOGIN_TYPE.FACEBOOK, LOGIN_TYPE.PHONE_NUMBER_OTP])\n    loginType: string = LOGIN_TYPE.PHONE_NUMBER_OTP;\n}\n```\n\n```text\naccessToken\n```\n\n```text\n@ValidateIf()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":593}}819{"id":"stack-71259682","source":"stackoverflow","questionId":71259682,"title":"Prisma is opening too many connections with PostgrsQL when running Jest end to end testing","tags":["jestjs","nestjs","prisma"],"text":"Title: Prisma is opening too many connections with PostgrsQL when running Jest end to end testing\nTags: jestjs, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying here to do end to end testing with Jest on a NestJS/GraphQL app and Prisma as my ORM.\n\nWhat happens here is Prisma is opening too many connections with Postgres, I've tried to fix this problem by using prisma.$disconnect() after each test but it doesn't seem to work...\n\nThis is what I've tried so far.\n\n```\nimport { PrismaService } from '../src/prisma.service';\n\ndescribe('Users', () => {\n let app: INestApplication;\n const gql = '/graphql';\n let prisma;\n\n beforeEach(async () => {\n prisma = new PrismaService();\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterEach(async () => {\n await prisma.$disconnect();\n });\n\n it('Query - Users', async () => {\n //Using prisma to query database\n });\n});\n```\n\nMy Prisma service (I got it from NestJS documentation Text ):\n\n```\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n async onModuleInit() {\n await this.$connect();\n }\n\n async enableShutdownHooks(app: INestApplication) {\n this.$on('beforeExit', async () => {\n await app.close();\n });\n }\n}\n```\n\nThese are the errors I'm getting after running all the tests (serially):\n\nhttps://i.sstatic.net/nloMQ.png\n\nI've already looked through Prisma documentation but didn't find anything about how to setup properly a Jest environment with NestJS and Prisma.\n\nThanks for your help !\n\n========================================\n\nTop Answer:\nAfter trying the solution of limiting the number of connections, I start getting timeout in my tests. Searching more, the real problem may be related to a problem that happen only in development, caused to how module reloads are handled by Nest (https://github.com/prisma/prisma/issues/5007#issuecomment-618433162). What solved for me was this\n\n```\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n private prisma: PrismaClient;\n\n constructor() {\n super();\n if (process.env.NODE_ENV === 'production') {\n this.prisma = new PrismaClient();\n } else {\n if (!global.prisma) {\n global.prisma = new PrismaClient();\n }\n this.prisma = global.prisma as PrismaClient;\n }\n }\n\n async onModuleInit() {\n await this.prisma.$connect();\n }\n\n async onModuleDestroy() {\n await this.prisma.$disconnect();\n }\n}\n```\n\nNow your application in development has only one instance of client, what avoid the bug related to Nest\n\n========================================\n\nCode:\n```text\nimport { PrismaService } from '../src/prisma.service';\n\ndescribe('Users', () => {\n  let app: INestApplication;\n  const gql = '/graphql';\n  let prisma;\n\n  beforeEach(async () => {\n    prisma = new PrismaService();\n\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  afterEach(async () => {\n    await prisma.$disconnect();\n  });\n\n  it('Query - Users', async () => {\n    //Using prisma to query database\n  });\n});\n```\n\n```text\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });\n  }\n}\n```\n\n```text\npostgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public&connection_limit=1\n```\n\n```text\nconnection_limit=1\n```\n\n```text\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n  private prisma: PrismaClient;\n\n  constructor() {\n    super();\n    if (process.env.NODE_ENV === 'production') {\n      this.prisma = new PrismaClient();\n    } else {\n      if (!global.prisma) {\n        global.prisma = new PrismaClient();\n      }\n      this.prisma = global.prisma as PrismaClient;\n    }\n  }\n\n  async onModuleInit() {\n    await this.prisma.$connect();\n  }\n\n  async onModuleDestroy() {\n    await this.prisma.$disconnect();\n  }\n}\n```\n\n========================================\n\nComments:\n- Looks like it did the trick. Thanks for your help !\n- This limits the connection to the database, but connections are not closing after the request completes or times out.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":190,"estimatedTokens":1160}}820{"id":"stack-54507039","source":"stackoverflow","questionId":54507039,"title":"DRY principles in NestJS entities with typeorm and class-validator","tags":["nestjs","typeorm"],"text":"Title: DRY principles in NestJS entities with typeorm and class-validator\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs there a way to turn this code \n\n```\nexport class person {\n @IsString()\n @Column('text')\n name: string\n\n @IsOptional()\n @IsString()\n @Column('text')\n description?: string\n}\n```\n\nInto something that resembles this\n\n```\nexport class person {\n name: string\n description?: string\n}\n```\n\nI'm aware that decorators are needed, but SSOT seems lost when property type has to be declared three times or more per property.\n\nIs there an easier way around this? JOI? Schema generation?\n\n========================================\n\nCode:\n```text\nexport class person {\n  @IsString()\n  @Column('text')\n  name: string\n\n  @IsOptional()\n  @IsString()\n  @Column('text')\n  description?: string\n}\n```\n\n```text\nexport class person {\n  name: string\n  description?: string\n}\n```\n\n```js\nconst CombinedDecorator = (target, property, descriptor) => {\n   IsOptional(target, property, descriptor);\n   IsString(target, property, descriptor);\n   Column('text')(target, property, descriptor);\n}\n\nclass Person {\n   @CombinedDecorator()\n   name: string;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":68,"estimatedTokens":289}}821{"id":"stack-63778644","source":"stackoverflow","questionId":63778644,"title":"Annotating an annonymus middleware in Newrelic in a NestJS app","tags":["node.js","express","nestjs","newrelic"],"text":"Title: Annotating an annonymus middleware in Newrelic in a NestJS app\nTags: node.js, express, nestjs, newrelic\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS (with Express Server) for a project and trying to optimize the performance on some of the endpoints, using New Relic I noticed that a big chunk of the response time of all endpoints is spent in an anonymous middleware, reaching 89% at some points.\n\nhttps://i.sstatic.net/qAw36.png\n\nIs there a way to find out which middleware is this?\n\n========================================\n\nCode:\n```js\n@Controller('test')\nexport class TestController {\n  @Get()\n  testGet() {\n    return 'do the thing';\n  }\n}\n```\n\n```js\napp.get('test', (req, res, next) => {\n  res.send('do the thing');\n})\n```\n\n```js\n@Controller('test')\nexport class TestController {\n  @Get()\n  @UseFilter(SomeExceptionFilter)\n  testGet() {\n    return 'do the thing';\n  }\n}\n```\n\n```text\napp.get('test', (req, res, next) => {\n  let returnVal = '';\n  try {\n    returnVal = controller.testGet();\n  } catch (err) {\n    returnVal = someExceptionFilterInstnace.catch(err, customArgumentHostThatNestMaintains);\n  }\n  res.send(returnVal);\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":52,"estimatedTokens":288}}822{"id":"stack-62990134","source":"stackoverflow","questionId":62990134,"title":"Nestjs, How to get entity table name?","tags":["node.js","nestjs","typeorm"],"text":"Title: Nestjs, How to get entity table name?\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow to get entity table name ? (ex: member-pre-sale-detail)\nI want to set table comment\n\n```\n// Seeder: Clear & set Comment\nexport default class ClearAllSeed implements Seeder {\n public async run(factory: Factory, connection: Connection): Promise {\n\n const deleteEntities = [\n {table: OrderHead, comment: '่จ‚ๅ–ฎ/ไธป่กจ'},\n ]\n\n for(const entity of deleteEntities){\n await connection\n .createQueryBuilder()\n .delete()\n .from(entity.table)\n .execute();\n\n await connection\n // >>>> but table name is MemberPreSaleDetail not member-pre-sale-detail\n .query(`alter table ${entity.table.name} comment '${entity.comment}'`);\n }\n }\n}\n\n// Sampel Entity\n@Entity('member-pre-sale-detail')\nexport class MemberPreSaleDetail {\n @PrimaryGeneratedColumn({unsigned: true})\n id?: number;\n\n @Column({comment: 'ๅนพๆ‰น(ๆ•ดๆ‰น)', type: 'mediumint', default: 0})\n batchQty: number;\n}\n```\n\n### Expected behavior\n\nget the 'member-pre-sale-detail' string\n\n### Environment\n\nNest version: 7.0.7\n \nFor Tooling issues:\n- Node version: v14.5.0\n- Platform: Mac\n\n========================================\n\nTop Answer:\nyou got to easy way\n\n`getManager().getRepository(User).metadata.tableName`\n\nOR\n\nextends the User class with the BaseEntity from typeorm and do\n\n`user.getRepository().metadata.tableName`\n\n========================================\n\nCode:\n```text\n// Seeder: Clear & set Comment\nexport default class ClearAllSeed implements Seeder {\n    public async run(factory: Factory, connection: Connection): Promise<void> {\n\n\n        const deleteEntities = [\n            {table: OrderHead, comment: '่จ‚ๅ–ฎ/ไธป่กจ'},\n       ]\n\n       for(const entity of deleteEntities){\n            await connection\n                .createQueryBuilder()\n                .delete()\n                .from(entity.table)\n                .execute();\n\n            await connection\n                // >>>> but table name is MemberPreSaleDetail not member-pre-sale-detail\n                .query(`alter table ${entity.table.name} comment '${entity.comment}'`);\n        }\n   }\n}\n\n// Sampel Entity\n@Entity('member-pre-sale-detail')\nexport class MemberPreSaleDetail {\n  @PrimaryGeneratedColumn({unsigned: true})\n  id?: number;\n\n  @Column({comment: 'ๅนพๆ‰น(ๆ•ดๆ‰น)', type: 'mediumint', default: 0})\n  batchQty: number;\n}\n```\n\n```text\nconnection.getMetadata(MemberPreSaleDetail)\n```\n\n```text\nname\n```\n\n```text\ntableName\n```\n\n```text\ngivenTableName\n```\n\n```text\ngivenTableName\n```\n\n```text\ngetManager().getRepository(User).metadata.tableName\n```\n\n```text\nuser.getRepository().metadata.tableName\n```\n\n========================================\n\nComments:\n- hmm I am not sure how this `@Entity` decorator works but I think that you can try sth like this :`entity.constructor.name`","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":137,"estimatedTokens":698}}823{"id":"stack-66371967","source":"stackoverflow","questionId":66371967,"title":"NextJS process.env. variables undefined on button click fetch data","tags":["node.js","reactjs","environment-variables","next.js","nestjs"],"text":"Title: NextJS process.env. variables undefined on button click fetch data\nTags: node.js, reactjs, environment-variables, next.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm having issue with ENV variables.\nOn the first request with :\n\n```\nexport const getStaticProps = async () => {\n const posts = await getPosts(1);\n return { props: posts, revalidate: 5 };\n};\n```\n\neverything goes fine and it fetchs all the data, but on button click i want to fetch new data and i got 404 :\n\n```\nxhr.js:177 GET http://localhost:3000/fr/undefined/ghost/api/v3/content/posts?key=undefined&fields=id%2Ctitle%2Cfeature_image%2Cslug%2Cexcerpt%2Ccustom_excerpt%2Creading_time%2Ccreated_at&include=authors%2Ctags&page=2 404 (Not Found)\n```\n\nas you can see env variables result to undefined , i dont know why.\nhow i fetch the data :\n\n```\nconst fetchNewData =async (currentPage)=>{\n console.log(currentPage);\n const post = await getPosts(currentPage)\n console.log(post);\n }\n```\n\nHow i use env\n\n```\nexport const CONTENTKEY=process.env.contentKey\nexport const BLOG_API = process.env.blogApiLink;\n```\n\n```\nimport axios from \"axios\";\nimport {BLOG_API,CONTENTKEY} from \"../segret_keys\"\nexport const getPosts = async (page) => {\n const pageUrl =\n BLOG_API +\n \"/ghost/api/v3/content/posts/?key=\" +\n CONTENTKEY +\n \"&fields=id,title,feature_image,slug,excerpt,custom_excerpt,reading_time,created_at&include=authors,tags&page=\" +\n page;\n console.log(pageUrl);\n return axios({\n method: \"get\",\n url: pageUrl,\n }) //&filter=tag:blog,tag:Blog\n .then((res) => {\n return { status: res.status, data: res.data };\n })\n .catch((err) => {\n console.log(err.response.status, err.response.data);\n return { status: err.response.status, data: \"\" };\n });\n};\n```\n\n========================================\n\nCode:\n```text\nexport const getStaticProps = async () => {\n  const posts = await getPosts(1);\n  return { props: posts, revalidate: 5 };\n};\n```\n\n```text\nxhr.js:177 GET http://localhost:3000/fr/undefined/ghost/api/v3/content/posts?key=undefined&fields=id%2Ctitle%2Cfeature_image%2Cslug%2Cexcerpt%2Ccustom_excerpt%2Creading_time%2Ccreated_at&include=authors%2Ctags&page=2 404 (Not Found)\n```\n\n```text\nconst fetchNewData =async (currentPage)=>{\n    console.log(currentPage);\n      const post = await getPosts(currentPage)\n      console.log(post);\n  }\n```\n\n```text\nexport const CONTENTKEY=process.env.contentKey\nexport const BLOG_API = process.env.blogApiLink;\n```\n\n```text\nimport axios from \"axios\";\nimport {BLOG_API,CONTENTKEY} from \"../segret_keys\"\nexport const getPosts = async (page) => {\n  const pageUrl =\n    BLOG_API +\n    \"/ghost/api/v3/content/posts/?key=\" +\n    CONTENTKEY +\n    \"&fields=id,title,feature_image,slug,excerpt,custom_excerpt,reading_time,created_at&include=authors,tags&page=\" +\n    page;\n      console.log(pageUrl);\n      return axios({\n    method: \"get\",\n    url: pageUrl,\n  }) //&filter=tag:blog,tag:Blog\n    .then((res) => {\n      return { status: res.status, data: res.data };\n    })\n    .catch((err) => {\n      console.log(err.response.status, err.response.data);\n      return { status: err.response.status, data: \"\" };\n    });\n};\n```\n\n```text\nNEXT_PUBLIC_contentKey=somevalue\n```\n\n```text\nprocess.env.NEXT_PUBLIC_contentKey\n```\n\n```text\nmodule.exports = {\n  publicRuntimeConfig: {\n    contentKey: process.env.contentKey,\n    blogApiLink: process.env.blogApiLink,\n  }\n}\n```\n\n```text\nimport getConfig from \"next/config\";\nconst { publicRuntimeConfig } = getConfig();\n\nexport const CONTENTKEY= publicRuntimeConfig.contentKey\nexport const BLOG_API = publicRuntimeConfig.blogApiLink;\n```\n\n```text\nNEXT_PUBLIC_\n```\n\n```text\nEnvironment Variables\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":148,"estimatedTokens":906}}824{"id":"stack-63081532","source":"stackoverflow","questionId":63081532,"title":"Nestjs GraphQL subscriptions onConnect & onDisconnect callbacks","tags":["graphql","nestjs","apollo-server"],"text":"Title: Nestjs GraphQL subscriptions onConnect & onDisconnect callbacks\nTags: graphql, nestjs, apollo-server\nSource: Stack Overflow\n\nQuestion:\nIs there an approach to hook into the onConnect and onDisconnect lifecycle-events in Nestjs?\n\n========================================\n\nTop Answer:\nIt turns out you can provide them in the subscriptions portion of the graphql configuration\n\n```\nsubscriptions: {\n keepAlive: subscriptionsTimeout,\n onConnect: (connectionParams, websocket, context) => {\n console.log(`connectionParams: ${connectionParams}, websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n },\n onDisconnect: ( websocket, context) => {\n console.log(`websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n }\n },\n```\n\n========================================\n\nCode:\n```text\nsubscriptions: {\n        'graphql-ws': true\n}\n```\n\n```text\nsubscriptions: {\n        'graphql-ws': {\n          onConnect: (context: Context) => {\n            const { connectionParams, subscriptions } = context;\n            console.log(\n              `connectionParams: ${connectionParams}, subscriptions: ${JSON.stringify(\n                subscriptions,\n              )}}, context ${JSON.stringify(context)}`,\n            );\n          },\n          onDisconnect: (context: Context) => {\n            const { connectionParams, subscriptions } = context;\n            console.log(\n              `connectionParams: ${JSON.stringify(\n                connectionParams,\n              )}}, subscriptions: ${JSON.stringify(\n                subscriptions,\n              )}, context ${JSON.stringify(context)}`,\n            );\n          },\n```\n\n```text\ngraph-ws\n```\n\n```text\ngraphql-ws\n```\n\n```text\nsubscriptions: {\n    keepAlive: subscriptionsTimeout,\n    onConnect: (connectionParams, websocket, context) => {\n      console.log(`connectionParams: ${connectionParams}, websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n    },\n    onDisconnect: ( websocket, context) => {\n      console.log(`websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n    }\n  },\n```\n\n========================================\n\nComments:\n- This approach worked for me up until NestJS 8.\n- Thanks. This works perfectly for NestJS 8.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":571}}825{"id":"stack-58286024","source":"stackoverflow","questionId":58286024,"title":"How to Ignore a specific route logging using Fastify in NestJs?","tags":["node.js","logging","nestjs","fastify"],"text":"Title: How to Ignore a specific route logging using Fastify in NestJs?\nTags: node.js, logging, nestjs, fastify\nSource: Stack Overflow\n\nQuestion:\nI want to ignore or change the logLevel of a route in my NestJs application using Fastify. \n\nThis is how I do it normally in Fastify application. Here I am changing the `/health` route `logLevel` to `error` so that it will only log when there is an error in health. \n\n```\nserver.get('/health', { logLevel: 'error' }, async (request, reply) => {\n if (mongoose.connection.readyState === 1) {\n reply.code(200).send()\n } else {\n reply.code(500).send()\n }\n})\n```\n\nBut This is my health controller in NestJs\n\n```\n@Get('health')\ngetHealth(): string {\n return this.appService.getHealth()\n}\n```\n\nAnd main.ts file.\n\n```\nconst app = await NestFactory.create(\n AppModule,\n new FastifyAdapter({\n logger: true\n }),\n )\n```\n\nI don't want to log the health route only and not the routes. \n\nPlease help in this regards.\n\n========================================\n\nTop Answer:\nIf one is willing to use `nestjs-pino` can use something like this:\n\n```\nLoggerModule.forRoot({\n pinoHttp: {\n transport:\n process.env.NODE_ENV !== 'production'\n ? { target: 'pino-pretty', options: { singleLine: true } }\n : null,\n customProps: () => ({ context: 'HTTP' }),\n autoLogging: {\n ignore: (req) => {\n return ['/health/ping', '/swagger'].some((e) => req.originalUrl.includes(e))\n },\n },\n },\n}),\n```\n\n========================================\n\nCode:\n```text\nserver.get('/health', { logLevel: 'error' }, async (request, reply) => {\n    if (mongoose.connection.readyState === 1) {\n        reply.code(200).send()\n    } else {\n        reply.code(500).send()\n    }\n})\n```\n\n```text\n@Get('health')\ngetHealth(): string {\n  return this.appService.getHealth()\n}\n```\n\n```text\nconst app = await NestFactory.create<NestFastifyApplication>(\n        AppModule,\n        new FastifyAdapter({\n            logger: true\n        }),\n    )\n```\n\n```text\n/health\n```\n\n```text\nlogLevel\n```\n\n```text\nerror\n```\n\n```text\nimport fastify from 'fastify'\n\n\nconst fastifyInstance = fastify()\nfastifyInstance.addHook('onRoute', opts => {\n        if (opts.path === '/health') {\n            opts.logLevel = 'silent'\n        }\n    })\n```\n\n```text\nonRoute\n```\n\n```text\nLoggerModule.forRoot({\n    pinoHttp: {\n        transport:\n            process.env.NODE_ENV !== 'production'\n                ? { target: 'pino-pretty', options: { singleLine: true } }\n                : null,\n        customProps: () => ({ context: 'HTTP' }),\n        autoLogging: {\n            ignore: (req) => {\n                return ['/health/ping', '/swagger'].some((e) => req.originalUrl.includes(e))\n            },\n        },\n    },\n}),\n```\n\n```text\nnestjs-pino\n```\n\n========================================\n\nComments:\n- did you find a solve?\n- @BinaryShrub yup. I posted the solution which worked for us.\n- this doesn't work with fastifyLoggers enabled","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":149,"estimatedTokens":724}}826{"id":"stack-57431221","source":"stackoverflow","questionId":57431221,"title":"Schema hasn't been registered for model \"ResourceSchema\". - nest js","tags":["node.js","typescript","mongoose","schema","nestjs"],"text":"Title: Schema hasn't been registered for model \"ResourceSchema\". - nest js\nTags: node.js, typescript, mongoose, schema, nestjs\nSource: Stack Overflow\n\nQuestion:\nHello everyone i am trying to build api with Nest js and mongodb.\n\ni am trying to make relationship between schema and i get that Error when i am trying to populate resource from role\n\n```\n[Nest] 12308 - 2019-08-09 4:22 PM [ExceptionsHandler] Schema hasn't been registered for model \"ResourceSchema\".\nUse mongoose.model(name, schema) +6998ms\nMissingSchemaError: Schema hasn't been registered for model \"ResourceSchema\".\nUse mongoose.model(name, schema)\n```\n\nmy RoleSchema\n\n```\nimport * as mongoose from 'mongoose';\nimport {ResourceModel} from './resourceSchema';\n\nconst Schema = mongoose.Schema;\n\nexport const RoleSchema = new Schema({\n name: {\n type: String,\n unique: true,\n required: [true, 'Role name is required'],\n },\n resources: [{\n type: mongoose.Schema.Types.ObjectId,\n ref: 'ResourceModel',\n }],\n permissions: [{type: String}],\n});\n```\n\nmy ResourceSchema\n\n```\nimport * as mongoose from 'mongoose';\n\nconst Schema = mongoose.Schema;\n\nexport const ResourceSchema = new Schema({\n name: {\n type: String,\n unique: true,\n required: [true, 'Role type is required'],\n },\n routingInfo: {type: String},\n iconName: {type: String},\n iconType: {type: String},\n subResources: [{type: mongoose.Schema.Types.Mixed, ref: 'ResourceModel'}],\n});\n\nexport const ResourceModel = mongoose.model('Resource', ResourceSchema);\n```\n\nmy Role service.ts\npopulate resources array\n\n```\n...\n\n@Injectable()\nexport class RoleService {\n constructor(@InjectModel('roles') private readonly roleModel: Model) {\n }\n\n async findAll(): Promise {\n return await this.roleModel.find().populate({path: 'resources', Model: ResourceModel});\n }\n\n// also tried that\n async findAll(): Promise {\n return await this.roleModel.find().populate({path: 'resources', Model: ResourceSchema});\n }\n}\n```\n\nmy resorce mdule \n\n```\nimport {Module} from '@nestjs/common';\nimport {ResourcesController} from './resources.controller';\nimport {ResourcesService} from './resources.service';\nimport {MongooseModule} from '@nestjs/mongoose';\nimport {ResourceSchema} from '../schemas/resourceSchema';\nimport {ConfigService} from '../config/config.service';\nimport {AuthService} from '../auth/auth.service';\nimport {UsersService} from '../users/users.service';\nimport {UserSchema} from '../schemas/userSchema';\n\n@Module({\n imports: [MongooseModule.forFeature([{name: 'users', schema: UserSchema}]),\n MongooseModule.forFeature([{name: 'resources', schema: ResourceSchema}])],\n providers: [ResourcesService, UsersService, AuthService, ConfigService],\n controllers: [ResourcesController],\n exports: [ResourcesService],\n})\nexport class ResourcesModule {\n}\n```\n\nso when i do GET REQUEST on postman i get that error\nanyone can tell what i am doing wrong?????\n\nThanks in andvaced\n\n========================================\n\nTop Answer:\nI had a similar issue with a supporting schema that was never imported into any module. I resolved it by importing that target schema into a random module like so:\n\n```\nimports: [MongooseModule.forFeature([{ name: LoanOfficer.name, schema: LoanOfficerSchema }])]\n```\n\n========================================\n\nCode:\n```text\n[Nest] 12308   - 2019-08-09 4:22 PM   [ExceptionsHandler] Schema hasn't been registered for model \"ResourceSchema\".\nUse mongoose.model(name, schema) +6998ms\nMissingSchemaError: Schema hasn't been registered for model \"ResourceSchema\".\nUse mongoose.model(name, schema)\n```\n\n```text\nimport * as mongoose from 'mongoose';\nimport {ResourceModel} from './resourceSchema';\n\nconst Schema = mongoose.Schema;\n\nexport const RoleSchema = new Schema({\n  name: {\n    type: String,\n    unique: true,\n    required: [true, 'Role name is required'],\n  },\n  resources: [{\n    type: mongoose.Schema.Types.ObjectId,\n    ref: 'ResourceModel',\n  }],\n  permissions: [{type: String}],\n});\n```\n\n```text\nimport * as mongoose from 'mongoose';\n\nconst Schema = mongoose.Schema;\n\nexport const ResourceSchema = new Schema({\n  name: {\n    type: String,\n    unique: true,\n    required: [true, 'Role type is required'],\n  },\n  routingInfo: {type: String},\n  iconName: {type: String},\n  iconType: {type: String},\n  subResources: [{type: mongoose.Schema.Types.Mixed, ref: 'ResourceModel'}],\n});\n\nexport const ResourceModel = mongoose.model('Resource', ResourceSchema);\n```\n\n```text\n...\n\n@Injectable()\nexport class RoleService {\n  constructor(@InjectModel('roles') private readonly roleModel: Model<Role>) {\n  }\n\n  async findAll(): Promise<Role[]> {\n    return await this.roleModel.find().populate({path: 'resources', Model: ResourceModel});\n  }\n\n// also tried that\n async findAll(): Promise<Role[]> {\n    return await this.roleModel.find().populate({path: 'resources', Model: ResourceSchema});\n  }\n}\n```\n\n```text\nimport {Module} from '@nestjs/common';\nimport {ResourcesController} from './resources.controller';\nimport {ResourcesService} from './resources.service';\nimport {MongooseModule} from '@nestjs/mongoose';\nimport {ResourceSchema} from '../schemas/resourceSchema';\nimport {ConfigService} from '../config/config.service';\nimport {AuthService} from '../auth/auth.service';\nimport {UsersService} from '../users/users.service';\nimport {UserSchema} from '../schemas/userSchema';\n\n@Module({\n  imports: [MongooseModule.forFeature([{name: 'users', schema: UserSchema}]),\n    MongooseModule.forFeature([{name: 'resources', schema: ResourceSchema}])],\n  providers: [ResourcesService, UsersService, AuthService, ConfigService],\n  controllers: [ResourcesController],\n  exports: [ResourcesService],\n})\nexport class ResourcesModule {\n}\n```\n\n```text\nexport const Resource = mongoose.model('Resource', ResourceSchema);\n```\n\n```text\nsubResources: [{type: mongoose.Schema.Types.Mixed, ref: 'Resource'}],\n```\n\n```text\nreturn await this.roleModel.find().populate({path: 'resources', Model: Resource });\n```\n\n```text\nResourceSchema\n```\n\n```text\nimports: [MongooseModule.forFeature([{ name: LoanOfficer.name, schema: LoanOfficerSchema }])]\n```\n\n========================================\n\nComments:\n- and the ref? should still be the Schema? still gives me the error\n- Ah you should change the ref too. I forgot it\n- change the ref ro 'Resource'?\n- also should change the resources at RoleSchema. work as a magic\n- btw this is correct way to do nested Schema inside smae schema?\n- I don't have much experience with mongoose but in the docs it says `Note: ObjectId, Number, String, and Buffer are valid for use as refs. However, you should use ObjectId unless you are an advanced user and have a good reason for doing so`.\n- In my case it was model not being uppercase in Model.","metadata":{"transformedAt":"2026-08-18T18:33:02.471Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":241,"estimatedTokens":1668}}827{"id":"stack-60791014","source":"stackoverflow","questionId":60791014,"title":"Nestjs with Typeorm Transaction in custom repository","tags":["typescript","nestjs","typeorm"],"text":"Title: Nestjs with Typeorm Transaction in custom repository\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a custom repository class like this with NestJS/Typeorm:\n\n```\nimport { Repository, EntityRepository, getConnection } from 'typeorm';\nimport { RefreshToken } from './refresh-token.entity';\nimport { User } from './user.entity';\nimport { InternalServerErrorException } from '@nestjs/common';\n\n@EntityRepository(RefreshToken)\nexport class RefreshTokenRepository extends Repository {\n\n async refreshToken({ token, user }: RefreshToken): Promise {\n const connection = getConnection();\n const queryRunner = connection.createQueryRunner();\n\n // establish real database connection using our new query runner\n await queryRunner.connect();\n\n // lets now open a new transaction:\n await queryRunner.startTransaction();\n\n try {\n // execute some operations on this transaction:\n await queryRunner.manager.delete(RefreshToken, { token });\n\n const refreshToken = await queryRunner.manager.save(\n this.buildToken(user),\n );\n\n // commit transaction now:\n await queryRunner.commitTransaction();\n\n return refreshToken;\n } catch (err) {\n // since we have errors lets rollback changes we made\n await queryRunner.rollbackTransaction();\n } finally {\n // you need to release query runner which is manually created:\n await queryRunner.release();\n }\n }\n}\n```\n\nIs there a different way to make/build a transaction than the one I did in `refreshToken()` method please? Because getting a connection feels broken and not appropriate with the way NestJS works.\n\nThanks.\n\n========================================\n\nCode:\n```text\nimport { Repository, EntityRepository, getConnection } from 'typeorm';\nimport { RefreshToken } from './refresh-token.entity';\nimport { User } from './user.entity';\nimport { InternalServerErrorException } from '@nestjs/common';\n\n@EntityRepository(RefreshToken)\nexport class RefreshTokenRepository extends Repository<RefreshToken> {\n\n  async refreshToken({ token, user }: RefreshToken): Promise<RefreshToken> {\n    const connection = getConnection();\n    const queryRunner = connection.createQueryRunner();\n\n    // establish real database connection using our new query runner\n    await queryRunner.connect();\n\n    // lets now open a new transaction:\n    await queryRunner.startTransaction();\n\n    try {\n      // execute some operations on this transaction:\n      await queryRunner.manager.delete(RefreshToken, { token });\n\n      const refreshToken = await queryRunner.manager.save(\n        this.buildToken(user),\n      );\n\n      // commit transaction now:\n      await queryRunner.commitTransaction();\n\n      return refreshToken;\n    } catch (err) {\n      // since we have errors lets rollback changes we made\n      await queryRunner.rollbackTransaction();\n    } finally {\n      // you need to release query runner which is manually created:\n      await queryRunner.release();\n    }\n  }\n}\n```\n\n```text\nrefreshToken()\n```\n\n```js\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      entities: [],\n      synchronize: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```js\ntry {\n  const refreshToken = await this.manager.transaction(async entityManager => {\n    await entityManager.delete(RefreshToken, { token });\n    return entityManager.save(RefreshToken, this.buildToken(user));\n  });\n\n  // commit done: use refreshToken here\n} catch (error) {\n  // rollback done: handle error here\n}\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nTypeOrmModule\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nRepository\n```\n\n========================================\n\nComments:\n- Thanks a lot; I tried these before and the manager was returning `null`, I retried today and now it works :)","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":153,"estimatedTokens":958}}828{"id":"stack-66306793","source":"stackoverflow","questionId":66306793,"title":"How to use @admin-bro/nestjs with @admin-bro/typeorm and postgres in a right way?","tags":["node.js","postgresql","nestjs","typeorm","admin-bro"],"text":"Title: How to use @admin-bro/nestjs with @admin-bro/typeorm and postgres in a right way?\nTags: node.js, postgresql, nestjs, typeorm, admin-bro\nSource: Stack Overflow\n\nQuestion:\nThe admin-bro-nestjs repository contains a comprehensive example with example with mongoose. But I need use it with typeorm and postgres.\n\nI tried to adapt this example for typeorm:\n\n```\n// main.ts\nimport AdminBro from 'admin-bro';\nimport { Database, Resource } from '@admin-bro/typeorm';\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from './app.module';\n\nAdminBro.registerAdapter({ Database, Resource });\n\nconst bootstrap = async () => {\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n}\nbootstrap();\n```\n\nand\n\n```\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { AdminModule } from '@admin-bro/nestjs';\nimport { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserEntity } from './user/user.entity';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'password',\n database: 'database_test',\n entities: [UserEntity],\n synchronize: true,\n logging: false,\n }),\n AdminModule.createAdminAsync({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n ],\n inject: [\n getRepositoryToken(UserEntity),\n ],\n useFactory: (userRepository: Repository) => ({\n adminBroOptions: {\n rootPath: '/admin',\n resources: [\n { resource: userRepository },\n ],\n },\n auth: {\n authenticate: async (email, password) => Promise.resolve({ email: 'test' }),\n cookieName: 'test',\n cookiePassword: 'testPass',\n },\n }),\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\nBut on application start I get the following error:\n\n```\nNoResourceAdapterError: There are no adapters supporting one of the resource you provided\n```\n\nDoes anyone have any experience putting all these libraries together?\n\n========================================\n\nCode:\n```text\n// main.ts\nimport AdminBro from 'admin-bro';\nimport { Database, Resource } from '@admin-bro/typeorm';\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from './app.module';\n\nAdminBro.registerAdapter({ Database, Resource });\n\nconst bootstrap = async () => {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { AdminModule } from '@admin-bro/nestjs';\nimport { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserEntity } from './user/user.entity';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n        type: 'postgres',\n        host: 'localhost',\n        port: 5432,\n        username: 'postgres',\n        password: 'password',\n        database: 'database_test',\n        entities: [UserEntity],\n        synchronize: true,\n        logging: false,\n      }),\n    AdminModule.createAdminAsync({\n      imports: [\n        TypeOrmModule.forFeature([UserEntity]),\n      ],\n      inject: [\n        getRepositoryToken(UserEntity),\n      ],\n      useFactory: (userRepository: Repository<UserEntity>) => ({\n        adminBroOptions: {\n          rootPath: '/admin',\n          resources: [\n            { resource: userRepository },\n          ],\n        },\n        auth: {\n          authenticate: async (email, password) => Promise.resolve({ email: 'test' }),\n          cookieName: 'test',\n          cookiePassword: 'testPass',\n        },\n      }),\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nNoResourceAdapterError: There are no adapters supporting one of the resource you provided\n```\n\n```text\n// user.entity\nimport { Entity, BaseEntity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class UserEntity extends BaseEntity{\n  @PrimaryGeneratedColumn()\n  id: number;\n  @Column()\n  name: string;\n}\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AdminModule } from '@admin-bro/nestjs';\n \nimport { Database, Resource } from '@admin-bro/typeorm';\nimport AdminBro from 'admin-bro'\nAdminBro.registerAdapter({ Database, Resource });\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      // ...\n    }),\n    AdminModule.createAdmin({\n        adminBroOptions: {\n          resources: [UserEntity],\n          rootPath: '/admin',\n        },\n    })\n  ],\n  // ...\n})\n```\n\n```text\nNoResourceAdapterError: There are no adapters supporting one of the resource you provided\n```\n\n```text\nNoResourceAdapterError\n```\n\n```text\nUserEntity\n```\n\n```text\nBaseEntity\n```\n\n```text\nBaseEntity\n```\n\n========================================\n\nComments:\n- this answer worked for me, saved me hours of debugging and checking what's wrong\n- I didn't think this would do anything, but turns out it was the root cause for me also.\n- My entities extends to BaseEntity, still the problem continues","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":229,"estimatedTokens":1314}}829{"id":"stack-53646042","source":"stackoverflow","questionId":53646042,"title":"How to inject model if the model is in the root module only","tags":["javascript","node.js","typescript","mongoose","nestjs"],"text":"Title: How to inject model if the model is in the root module only\nTags: javascript, node.js, typescript, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to inject a mongo db model in NestJS Service. The model is present in the root module only.\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Model } from 'mongoose';\nimport { IFolderModel } from './interfaces/folder.interface';\n\n@Injectable()\nexport class FolderService {\n constructor(@InjectModel('IFolder') private folderModel: Model) {\n\n }\n\n async create(folderInstance: IFolderModel): Promise {\n const folderModelToBeSaved = new this.folderModel(folderInstance);\n return await folderModelToBeSaved.save();\n }\n\n async findAll(): Promise {\n return await this.folderModel.find().exec();\n }\n}\n```\n\nI am getting following error while starting application using `npm run start`\n\n`Error: Nest can't resolve dependencies of the FolderService (?). Please make sure that the argument at index [0] is available in the AppModule context.`\n\nContents of AppModule\n\n```\nlet mongodb = env.mongodb;\n let url = `mongodb://${mongodb.user}:${mongodb.pwd}@${mongodb.host}:${mongodb.port}/${mongodb.dbName}`;\n\n @Module({\n imports: [MongooseModule.forRoot(url)],\n controllers: [AppController, FolderController],\n providers: [AppService, FolderService],\n })\n export class AppModule { }\n```\n\n========================================\n\nTop Answer:\nThis should be in the imports array of your module\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'FolderName', schema: FolderSchema }]),\n ],\n})\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Model } from 'mongoose';\nimport { IFolderModel } from './interfaces/folder.interface';\n\n@Injectable()\nexport class FolderService {\n    constructor(@InjectModel('IFolder') private folderModel: Model<IFolderModel>) {\n\n    }\n\n    async create(folderInstance: IFolderModel): Promise<IFolderModel> {\n       const folderModelToBeSaved = new this.folderModel(folderInstance);\n       return await folderModelToBeSaved.save();\n    }\n\n    async findAll(): Promise<IFolderModel[]> {\n       return await this.folderModel.find().exec();\n    }\n}\n```\n\n```text\nlet mongodb = env.mongodb;\n let url = `mongodb://${mongodb.user}:${mongodb.pwd}@${mongodb.host}:${mongodb.port}/${mongodb.dbName}`;\n\n @Module({\n    imports: [MongooseModule.forRoot(url)],\n    controllers: [AppController, FolderController],\n    providers: [AppService, FolderService],\n })\n export class AppModule { }\n```\n\n```text\nnpm run start\n```\n\n```text\nError: Nest can't resolve dependencies of the FolderService (?). Please make sure that the argument at index [0] is available in the AppModule context.\n```\n\n```text\nMongooseModule.forFeature([{ name: 'Folder', schema: FolderSchema }])\n```\n\n```text\nMongooseModule.forFeature\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: 'FolderName', schema: FolderSchema }]),\n  ],\n})\n```\n\n========================================\n\nComments:\n- If a dedicated feature is not created, is there a way I can import schema?\n- Just do the `MongooseModule.forFeature` import in the same module as the `forRoot` import. :-)","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":128,"estimatedTokens":825}}830{"id":"stack-56629059","source":"stackoverflow","questionId":56629059,"title":"NestJS access response object in pipes","tags":["node.js","typescript","nestjs"],"text":"Title: NestJS access response object in pipes\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using pipes for request validation. If the request fails, I want to redirect to a page but don't want to throw error. The question is, how can I access the response object in validation?\n\nThis is my validation pipe.\n\n```\n@Injectable()\nexport class ValidationPipe implements PipeTransform {\n async transform(value: any, { metatype }: ArgumentMetadata) {\n if (!metatype || !this.toValidate(metatype)) {\n return value;\n }\n const object = plainToClass(metatype, value);\n const errors = await validate(object);\n if (errors.length > 0) {\n // in here i need to response with res.redirect('') function\n throw new BadRequestException('Validation failed');\n }\n return value;\n }\n private toValidate(metatype: Function): boolean {\n const types: Function[] = [String, Boolean, Number, Array, Object];\n return !types.includes(metatype);\n }\n}\n```\n\nInstead of throwing exception i need to access res.redirect() function\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class ValidationPipe implements PipeTransform<any> {\n  async transform(value: any, { metatype }: ArgumentMetadata) {\n    if (!metatype || !this.toValidate(metatype)) {\n      return value;\n    }\n    const object = plainToClass(metatype, value);\n    const errors = await validate(object);\n    if (errors.length > 0) {\n     // in here i need to response with res.redirect('') function\n      throw new BadRequestException('Validation failed');\n    }\n    return value;\n  }\n  private toValidate(metatype: Function): boolean {\n    const types: Function[] = [String, Boolean, Number, Array, Object];\n    return !types.includes(metatype);\n  }\n}\n```\n\n```text\nresponse\n```\n\n```text\npipe\n```\n\n```text\ninterceptor\n```\n\n```text\nfilter\n```\n\n```text\nPipes\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":461}}831{"id":"stack-74941279","source":"stackoverflow","questionId":74941279,"title":"Class Validator is not working with nestjs","tags":["nestjs","class-validator","class-transformer"],"text":"Title: Class Validator is not working with nestjs\nTags: nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have some projects with nestjs, I've always used the class validator, but recently it doesn't seem to be working. It simply doesn't call the DTO to validate.\n\ncontroller\n\n```\n@Post()\n async create(@Body() body: UserDTO) {\n return body;\n }\n```\n\nMy DTO\n\n```\nimport { IsNotEmpty, IsString } from 'class-validator';\n\nexport class UserDTO {\n @IsNotEmpty()\n @IsString()\n name: string;\n}\n```\n\nmain\n\n```\napp.useGlobalPipes(\n new ValidationPipe({\n whitelist: true,\n forbidNonWhitelisted: true,\n transform: true,\n }),\n );\n```\n\nversions class validator and class transformer\n\n```\n\"class-transformer\": \"^0.5.1\",\n\"class-validator\": \"^0.13.2\",\n```\n\n========================================\n\nTop Answer:\nIn some cases Class validator behaves broken when you are using form-data in postman instead of the json body. try using json data to pass the body, it worked in for me.\n\n========================================\n\nCode:\n```text\n@Post()\n  async create(@Body() body: UserDTO) {\n    return body;\n  }\n```\n\n```text\nimport { IsNotEmpty, IsString } from 'class-validator';\n\nexport class UserDTO {\n  @IsNotEmpty()\n  @IsString()\n  name: string;\n}\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      whitelist: true,\n      forbidNonWhitelisted: true,\n      transform: true,\n    }),\n  );\n```\n\n```text\n\"class-transformer\": \"^0.5.1\",\n\"class-validator\": \"^0.13.2\",\n```\n\n```text\n@Module({\n  imports: [ConfigModule.forRoot(), UserModule, AuthModule],\n  controllers: [],\n  providers: [\n    {\n      provide: APP_PIPE,\n      useValue: new ValidationPipe({\n        whitelist: true,\n        forbidNonWhitelisted: true,\n        transform: true,\n      }),\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n@Controller('users')\nexport class UsersController {\n  @Post('/signup')\n  create(\n    @Body()\n    createUserDTO: CreateUserDTO,\n  ) {\n    // firstName, lastName, email, password, createdAt\n    return createUserDTO;\n  }\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(3000);\n}\nbootstrap();\n\nimport { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';\n\nexport class CreateUserDTO {\n  // firstname could be empty\n  @IsOptional()\n  @IsString()\n  firstName: string;\n  //   lastName could be empty\n  @IsOptional()\n  @IsString()\n  lastName: string;\n  //   Email format\n  // should not be empty\n  @IsEmail()\n  @IsNotEmpty()\n  email: string;\n  //   password\n  @IsNotEmpty()\n  @IsString()\n  password: string;\n}\n\n  \"class-transformer\": \"^0.5.1\",\n   \"class-validator\": \"^0.14.1\",\n```\n\n========================================\n\nComments:\n- Can you show a sample request as well so we can verify what should be validating here?\n- This should be not necessary if you are declaring it as a GlobalPipe\n- Yes, but the way it is in the documentation didn't work, I've used it in other projects and it works correctly, I even created a new project, just adding the class-validator, and it doesn't work.\n- Can you the request you were making?. I have the exact code and works as expected\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":158,"estimatedTokens":861}}832{"id":"stack-54475802","source":"stackoverflow","questionId":54475802,"title":"Setup two different static folders with Nest","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: Setup two different static folders with Nest\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to use Nest to serve two static applications. Basically it means I have a public folder like\n\n```\n/public\n /admin\n /main\n```\n\nIn nest I do\n\n```\napp.useStaticAssets(join(__dirname, '..', 'public/main'));\n```\n\nNow if I go to `http://localhost:3000` it will serve `/public/main/index.html`. This is good, however, when I navigate to `http://localhost:3000/admin` I want `/public/admin/index.html`\n\nOne solution would be to copy everything inside `/main` directly into `public`, but that will complicate my build process, and I have the feeling that what I need is very easy, because in express you can do\n\n```\napp.use('/admin/*', app.useStaticAssets(join(__dirname, '..', 'public/admin')));\napp.use(app.useStaticAssets(join(__dirname, '..', 'public/')))\n```\n\nSomething like this (not tested, but it feels right :) )\n\n========================================\n\nCode:\n```text\n/public\n       /admin\n       /main\n```\n\n```text\napp.useStaticAssets(join(__dirname, '..', 'public/main'));\n```\n\n```text\napp.use('/admin/*', app.useStaticAssets(join(__dirname, '..', 'public/admin')));\napp.use(app.useStaticAssets(join(__dirname, '..', 'public/')))\n```\n\n```text\nhttp://localhost:3000\n```\n\n```text\n/public/main/index.html\n```\n\n```text\nhttp://localhost:3000/admin\n```\n\n```text\n/public/admin/index.html\n```\n\n```text\n/main\n```\n\n```text\npublic\n```\n\n```text\napp.useStaticAssets(join(__dirname, '..', 'public/admin'), {prefix: '/admin'});\n```\n\n```text\nprefix\n```\n\n========================================\n\nComments:\n- Thanks a lot, that did the trick. Do you also have an url to documentation about this subject?\n- Glad it's working for you. :-) I don't think this is in the docs, I just checked the `ServeStaticOptions` interface. The code docs are pretty good.\n- Ok, thnx I'll do that next time!","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":86,"estimatedTokens":483}}833{"id":"stack-60295124","source":"stackoverflow","questionId":60295124,"title":"Add Swagger base path field in Nest.js project","tags":["swagger","nestjs","nestjs-swagger"],"text":"Title: Add Swagger base path field in Nest.js project\nTags: swagger, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI am trying to use nestjs/swagger to create a swagger file from my back-end and I am facing a problem related to the base path. What I want to achieve is to show version as base path instead of showing it in all the methods available, which is ugly and confusing.\n\nMy API, right now, has the following structure (this is a set of what is present in `app.module.ts`):\n\n```\nconst routes: Routes = [\n {\n path: '/api',\n module: ApiModule,\n children: [\n {\n path: '/v1',\n module: V1Module,\n children: [\n {\n path: '/orders',\n module: OrdersModule\n },\n {\n path: '/users',\n module: UsersModule\n }\n ]\n }\n ]\n }\n];\n```\n\nThis way, once I generate and check the swagger, I see all my methods following the `/api/v1` prefix. This could be an example:\n\n**orders**\n\n```\nGET /api/v1/orders\nPOST /api/v1/orders\nGET /api/v1/orders/{order_id}\n...\n```\n\n**users**\n\n```\nGET /api/v1/users\nPOST /api/v1/users\nGET /api/v1/users/{user_id}\n...\n```\n\nWhat I want is to get rid of `/api/v1` appearing in any method. I know that SWAGGER has fields for `host` and `basePath`, but do not find any way to populate it in Nest.js. Researching, I have found that there were `.setBasePath()` and `.addServer()` methods, but they do not work for me (I am pretty sure they are deprecated).\n\nThank very much for your help.\n\n========================================\n\nTop Answer:\nThis worked for me `addServer(url)`\n\n========================================\n\nCode:\n```js\nconst routes: Routes = [\n  {\n    path: '/api',\n    module: ApiModule,\n    children: [\n      {\n        path: '/v1',\n        module: V1Module,\n        children: [\n          {\n            path: '/orders',\n            module: OrdersModule\n          },\n          {\n            path: '/users',\n            module: UsersModule\n          }\n        ]\n      }\n    ]\n  }\n];\n```\n\n```text\nGET   /api/v1/orders\nPOST  /api/v1/orders\nGET   /api/v1/orders/{order_id}\n...\n```\n\n```text\nGET   /api/v1/users\nPOST  /api/v1/users\nGET   /api/v1/users/{user_id}\n...\n```\n\n```text\napp.module.ts\n```\n\n```text\n/api/v1\n```\n\n```text\n/api/v1\n```\n\n```text\nhost\n```\n\n```text\nbasePath\n```\n\n```text\n.setBasePath()\n```\n\n```text\n.addServer()\n```\n\n```text\nsetGlobalPrefix('api/v1')\n```\n\n```text\naddServer(url)\n```\n\n========================================\n\nComments:\n- But they are your endpoints though, aren't they?\n- Yeah but I do not want it to work that way. I want Nest.js to serve over /api/v1/\n- then I'd suggest not using `nestjs-router` at all\n- And then how can I route?\n- You don't need nestjs-router to route.\n- I deleted my previous answers to update. This is really the way to go but I feel like it is poorly explained and confusing. What you have to do if you want to use `api&#47;v1` as a global prefix is starting the app with `setGlobalPrefix('api&#47;v1')`, delete the routes `api` and `v1` and set the children as main routes and add the configuration values `ingnoreGlobalPrefix` and `addServer('api&#47;v1')`. I recommend you to update your answer to explain it.\n- You can use the versioning for the v1 part: docs.nestjs.com/techniques/versioning","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":151,"estimatedTokens":796}}834{"id":"stack-59025595","source":"stackoverflow","questionId":59025595,"title":"Respond with a custom status code in validation process","tags":["javascript","typescript","nestjs","class-validator"],"text":"Title: Respond with a custom status code in validation process\nTags: javascript, typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'd like to change the status code during the validation stage.\n\n```\nimport { IsEmail, IsNotEmpty } from 'class-validator';\n\nexport class CreateUserDto {\n @IsEmail()\n email: string;\n\n @IsNotEmpty()\n password: string;\n}\n```\n\nWith these rules in place, if a request hits our endpoint with an invalid email property in the request body, the application will automatically respond with a 400 Bad Request code.\n\nMy question is, is it possible to change the status code from 400 to 422 (Unprocessable Entity)?\n\n========================================\n\nTop Answer:\nSince 7.0.6, Nest added the option of set globaly the default http status code for ValidationPipes.\n\nIssue: https://github.com/nestjs/nest/issues/4393\n\nExample:\n\n```\napp.useGlobalPipes(\n new ValidationPipe({\n errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,\n }),\n );\n```\n\n========================================\n\nCode:\n```js\nimport { IsEmail, IsNotEmpty } from 'class-validator';\n\nexport class CreateUserDto {\n  @IsEmail()\n  email: string;\n\n  @IsNotEmpty()\n  password: string;\n}\n```\n\n```text\nFilter\n```\n\n```text\nBadRequestExceptions\n```\n\n```text\nres\n```\n\n```text\napp.useGlobalPipes(\n        new ValidationPipe({\n          errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,\n        }),\n      );\n```\n\n========================================\n\nComments:\n- Jay, what you're saying is, after creating a custom filter to catch `BadRequestExceptions` and make the status code to be transformed anything I want, then use it from controllers where it requires?\n- Yep, you just add the `@UseFilters` decorator to the controller that should return a 422 instead of a 400\n- This is all I can think of now. Thanks for an idea :)","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":459}}835{"id":"stack-66476115","source":"stackoverflow","questionId":66476115,"title":"RabbitMQ in NestJS, error on both Producer and Consumer","tags":["rabbitmq","nestjs"],"text":"Title: RabbitMQ in NestJS, error on both Producer and Consumer\nTags: rabbitmq, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have the following app https://github.com/rengthp/nestjs-rabbitmq-microservice\n\nBut I get on Producer :\n\n[Nest] 6156 - 04/03/2021, 13:28:53 [ClientProxy] Disconnected from RMQ. Trying to reconnect. +25469ms\n[Nest] 6156 - 04/03/2021, 13:28:53 [ClientProxy] Object:\n\n```\n{\n \"err\": {\n \"code\": 406,\n \"classId\": 50,\n \"methodId\": 10\n }\n}\n +3ms\n```\n\nand on Consumer:\n\n```\n111ms\n[Nest] 1180 - 04/03/2021, 13:22:31 [Server] Disconnected from RMQ. Trying to reconnect. +1058ms\n[Nest] 1180 - 04/03/2021, 13:22:37 [Server] Disconnected from RMQ. Trying to reconnect. +6006ms\n[Nest] 1180 - 04/03/2021, 13:22:43 [Server] Disconnected from RMQ. Trying to reconnect. +6017ms\n[Nest] 1180 - 04/03/2021, 13:22:49 [Server] Disconnected from RMQ. Trying to reconnect. +6026ms\n```\n\nWhat could be wrong? the server is working...\n\n========================================\n\nTop Answer:\nThis error came up because you re-declare an existing queue with different parameters. The solution is simple. The option queue for both producers and consumers must be the same and all option parameters must be the same.\n\n========================================\n\nCode:\n```text\n{\n  \"err\": {\n    \"code\": 406,\n    \"classId\": 50,\n    \"methodId\": 10\n  }\n}\n +3ms\n```\n\n```text\n111ms\n[Nest] 1180   - 04/03/2021, 13:22:31   [Server] Disconnected from RMQ. Trying to reconnect. +1058ms\n[Nest] 1180   - 04/03/2021, 13:22:37   [Server] Disconnected from RMQ. Trying to reconnect. +6006ms\n[Nest] 1180   - 04/03/2021, 13:22:43   [Server] Disconnected from RMQ. Trying to reconnect. +6017ms\n[Nest] 1180   - 04/03/2021, 13:22:49   [Server] Disconnected from RMQ. Trying to reconnect. +6026ms\n```\n\n```text\nasync onApplicationBootstrap() { await this._clientProxyUser.connect();}\n```\n\n========================================\n\nComments:\n- Hi @CarlosMagalhaes I'm facing the same issue, how did you solve it...?. I'm getting on client side.","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":70,"estimatedTokens":502}}836{"id":"stack-76778166","source":"stackoverflow","questionId":76778166,"title":"Prisma findMany where relationship is not null","tags":["javascript","node.js","nestjs","prisma"],"text":"Title: Prisma findMany where relationship is not null\nTags: javascript, node.js, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI have these two low-end models and I want to list all their subcategories with their menus, provided that the menu is not empty.\n\n```\nmodel SubCategory {\n id Int @id @default(autoincrement())\n label String\n image String\n categories Category[] @relation(\"CategoryToSubCategory\")\n menu Menu[] @relation(\"MenuToSubCategory\")\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Menu {\n id Int @id @default(autoincrement())\n name String @db.VarChar(64)\n description String @db.Text\n favoriteMenus FavoriteMenus[]\n ingredients Ingredients[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([chefStoreId], map: \"Menu_chefStoreId_fkey\")\n @@fulltext([name, description])\n}\n```\n\nThe query I am writing is as follows:\n\n```\nconst topCategories = await this.prisma.subCategory.findMany({\n include: {\n menu: {\n where: {\n id: { not: null },\n },\n },\n },\n orderBy: {\n id: 'desc',\n },\n take: 50,\n});\n```\n\nBut it gives me the error `\"Argument`not`must not be null.\"`\n\n========================================\n\nCode:\n```text\nmodel SubCategory {\n  id         Int        @id @default(autoincrement())\n  label      String\n  image      String\n  categories Category[] @relation(\"CategoryToSubCategory\")\n  menu       Menu[]     @relation(\"MenuToSubCategory\")\n  createdAt  DateTime   @default(now())\n  updatedAt  DateTime   @updatedAt\n}\n\nmodel Menu {\n  id                     Int                     @id @default(autoincrement())\n  name                   String                  @db.VarChar(64)\n  description            String                  @db.Text\n  favoriteMenus          FavoriteMenus[]\n  ingredients            Ingredients[]\n  createdAt              DateTime                @default(now())\n  updatedAt              DateTime                @updatedAt\n\n  @@index([chefStoreId], map: \"Menu_chefStoreId_fkey\")\n  @@fulltext([name, description])\n}\n```\n\n```js\nconst topCategories = await this.prisma.subCategory.findMany({\n  include: {\n    menu: {\n      where: {\n        id: { not: null },\n      },\n    },\n  },\n  orderBy: {\n    id: 'desc',\n  },\n  take: 50,\n});\n```\n\n```text\n\"Argument\n```\n\n```text\nmust not be null.\"\n```\n\n```text\nconst topCategories = this.prisma.subCategory.findMany({\n    where: {\n      menu: {\n        some: {},\n      },\n    },\n    include: {\n      menu: true,\n    },\n    orderBy: {\n      id: 'desc',\n    },\n    take: 50,\n  });\n```\n\n```text\nmenu\n```\n\n```text\nMenu\n```\n\n```text\nsubCategory\n```\n\n```text\nsome\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":136,"estimatedTokens":647}}837{"id":"stack-68707237","source":"stackoverflow","questionId":68707237,"title":"NestJS - Access user from Guard","tags":["node.js","express","nestjs"],"text":"Title: NestJS - Access user from Guard\nTags: node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've been following the official NestJS documentation. I have successfully setup JWT passport authentication. I can access the user details from the @Req within controllers but I'm having issues accessing the user details from within the custom guard.\n\nThis works fine\n\n```\n@UseGuards(RolesGuard)\n@Get('me')\n getProfile(@Request() req) {\n return req.user;\n }\n```\n\nThis does not (curently logging for debug)\n\n```\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const roles = this.reflector.get('roles', context.getHandler());\n if (!roles) {\n console.log('No Roles');\n return true;\n }\n const request = context.switchToHttp().getRequest();\n \n // Returns Undefined \n console.log(request.user);\n return true;\n }\n}\n```\n\nThis is how I'm declaring each entry in the controller\n\n```\n@Get()\n @UseGuards(RolesGuard)\n @Roles('admin')\n findAll() {\n return this.usersService.findAll();\n }\n```\n\nThe pass through of roles metadata is working fine, just looks like the user isn't being appended to the context at the correct step.\n\nAny help would be great, thanks!\n\nEDIT: updated @UseGuards(RolesGuard), copied and pasted wrong version\n\n========================================\n\nTop Answer:\nThe issue is you are not using the rolesGuard :\n\n```\n@UseGuards(JwtAuthGuard) // the same for the second method.\n\n========================================\n\nCode:\n```text\n@UseGuards(RolesGuard)\n@Get('me')\n  getProfile(@Request() req) {\n    return req.user;\n  }\n```\n\n```text\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const roles = this.reflector.get<string[]>('roles', context.getHandler());\n    if (!roles) {\n      console.log('No Roles');\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    \n    // Returns Undefined \n    console.log(request.user);\n    return true;\n  }\n}\n```\n\n```text\n@Get()\n  @UseGuards(RolesGuard)\n  @Roles('admin')\n  findAll() {\n    return this.usersService.findAll();\n  }\n```\n\n```text\n@Get()\n  @Roles('admin')\n  @UseGuards(JwtAuthGuard, RolesGuard)\n  findAll() {\n    return this.usersService.findAll();\n  }\n```\n\n```text\n@UseGuards(JwtAuthGuard) // <= replace JwtAuthGuard with your guard: RolesGuard \n@Get('me')\ngetProfile(@Request() req) {\nreturn req.user;\n }\n```\n\n========================================\n\nComments:\n- Hey, Getting the same thing, undefined. I did try roles guard before but I copied and pasted the wrong version into here, troubleshooting tunnel vision\n- Looks like i've fixed it, need to chain the guards as per my own answer :)","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":126,"estimatedTokens":705}}838{"id":"stack-65214210","source":"stackoverflow","questionId":65214210,"title":"Nestjs on AWS Lambda (Serverless Framework) | How to access the event parameter?","tags":["node.js","amazon-web-services","nestjs","serverless-framework"],"text":"Title: Nestjs on AWS Lambda (Serverless Framework) | How to access the event parameter?\nTags: node.js, amazon-web-services, nestjs, serverless-framework\nSource: Stack Overflow\n\nQuestion:\nI'm hosting a Nestjs application on AWS Lambda (using the Serverless Framework).\nPlease note that the implementation is behind AWS API Gateway.\n\n**Question:** How can I access to `event` parameter in my Nest `controller`?\n\nThis is how I bootstrap the NestJS server:\n\n```\nimport { APIGatewayProxyHandler } from 'aws-lambda';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Server } from 'http';\nimport { ExpressAdapter } from '@nestjs/platform-express';\nimport * as awsServerlessExpress from 'aws-serverless-express';\nimport * as express from 'express';\n\nlet cachedServer: Server;\n\nconst bootstrapServer = async (): Promise => {\n const expressApp = express();\n const adapter = new ExpressAdapter(expressApp);\n const app = await NestFactory.create(AppModule, adapter);\n app.enableCors();\n await app.init();\n return awsServerlessExpress.createServer(expressApp);\n}\n\nexport const handler: APIGatewayProxyHandler = async (event, context) => {\n if (!cachedServer) {\n cachedServer = await bootstrapServer()\n }\n return awsServerlessExpress.proxy(cachedServer, event, context, 'PROMISE')\n .promise;\n};\n```\n\nHere is a function in one controller:\n\n```\n@Get()\ngetUsers(event) { // I'm struggling to understand how I can access the `event` paramenter, which is easily accessible in a \"normal\" node 12.x Lambda function:\n\n```\nmodule.exports.hello = async (event) => {\n return {\n statusCode: 200,\n body: 'In a normal Lambda, the event is easily accessible, but in NestJS its (apparently) not.'\n };\n};\n```\n\n========================================\n\nTop Answer:\nWith the latest version of the `@codegenie/serverless-express` package, you can easily access the API Gateway event context in your controllers without any additional middleware.\n\nNothing to do in handler function.\n\nSimply add to your controller :\n\n```\nconst { getCurrentInvoke } = require('@codegenie/serverless-express')\n...\nconst currentInvoke = getCurrentInvoke()\nconst context = currentInvoke.event.requestContext\n```\n\nSource\n\n========================================\n\nCode:\n```text\nimport { APIGatewayProxyHandler } from 'aws-lambda';\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Server } from 'http';\nimport { ExpressAdapter } from '@nestjs/platform-express';\nimport * as awsServerlessExpress from 'aws-serverless-express';\nimport * as express from 'express';\n\nlet cachedServer: Server;\n\nconst bootstrapServer = async (): Promise<Server> => {\n    const expressApp = express();\n    const adapter = new ExpressAdapter(expressApp);\n    const app = await NestFactory.create(AppModule, adapter);\n    app.enableCors();\n    await app.init();\n    return awsServerlessExpress.createServer(expressApp);\n}\n\nexport const handler: APIGatewayProxyHandler = async (event, context) => {\n    if (!cachedServer) {\n        cachedServer = await bootstrapServer()\n    }\n    return awsServerlessExpress.proxy(cachedServer, event, context, 'PROMISE')\n        .promise;\n};\n```\n\n```text\n@Get()\ngetUsers(event) { // <-- HOW TO ACCESS event HERE?? This event is undefined.\n    return {\n        statusCode: 200,\n        body: \"This function works and returns this JSON as expected.\"\n    }\n```\n\n```text\nmodule.exports.hello = async (event) => {\n    return {\n        statusCode: 200,\n        body: 'In a normal Lambda, the event is easily accessible, but in NestJS its (apparently) not.'\n    };\n};\n```\n\n```text\nevent\n```\n\n```text\ncontroller\n```\n\n```text\nevent\n```\n\n```text\nconst awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')\napp.use(awsServerlessExpressMiddleware.eventContext())\n```\n\n```text\nvar event = req.apiGateway.event;\nvar context = req.apiGateway.context;\n```\n\n```text\napp.use\n```\n\n```text\napp.init()\n```\n\n```text\nevent\n```\n\n```text\ncontext\n```\n\n```text\nconst { getCurrentInvoke } = require('@codegenie/serverless-express')\n...\nconst currentInvoke = getCurrentInvoke()\nconst context = currentInvoke.event.requestContext\n```\n\n```text\n@codegenie/serverless-express\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":172,"estimatedTokens":1054}}839{"id":"stack-63716756","source":"stackoverflow","questionId":63716756,"title":"TypeORM: How to partialy update given entity with query runner?","tags":["typescript","nestjs","typeorm"],"text":"Title: TypeORM: How to partialy update given entity with query runner?\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIf I want to partially update my user's name I can easily do this:\n\n```\nawait this.repository.save({ id: 1, name: 'john' });\n```\n\nBut when I do it with queryrunner, It requires all field to exist and throws `missing following properties from type 'User'`\n\n```\nawait queryRunner.manager.save({ id: 1, name: 'john' }); // Error: Missing property\n```\n\n========================================\n\nCode:\n```js\nawait this.repository.save({ id: 1, name: 'john' });\n```\n\n```js\nawait queryRunner.manager.save({ id: 1, name: 'john' }); // Error: Missing property\n```\n\n```text\nmissing following properties from type 'User'\n```\n\n```js\nawait queryRunner.manager.update(User, 1, { name: \"john\" });\n```\n\n```text\nsave\n```\n\n```text\ninsert\n```\n\n========================================\n\nComments:\n- @omidh referenced from github.com/typeorm/typeorm/issues/3772, I can not believe `missing following properties from type 'User'` is occured in `update` operation.Can u show sql transformed? And I think use `save` is a bad idea for `update`, because typeorm always check the correspond record whether exist and then do `update` or `insert`, that is costed.","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":48,"estimatedTokens":319}}840{"id":"stack-57257091","source":"stackoverflow","questionId":57257091,"title":"NestJS : return a string","tags":["angular","typescript","nestjs"],"text":"Title: NestJS : return a string\nTags: angular, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using @nrwl/Nx to create a project. \n\nI successfully add both Angular & Nest projects to it.\n\nI then try to test the connection between the two. \n\n**Angular code**\n\n```\ncontent;\n\ntestEndpoint() {\n this.http.get('api/test').subscribe(res => this.content = res);\n}\n```\n\n**Nest code**\n\n```\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get('test')\n testConnection(): string {\n return 'Some content';\n }\n}\n```\n\nAs seen, I am simply trying to return a string from the endpoint. In the documentation, \n\n Using this built-in method, when a request handler returns a JavaScript object or array, it will automatically be serialized to JSON. When it returns a string, however, Nest will send just a string without attempting to serialize it. This makes response handling simple: just return the value, and Nest takes care of the rest. \n\nSo naturally, I would expect this to work (their exemple is basically the same as this). \n\nBut I am met with the following error : \n\n error: SyntaxError: Unexpected token S in JSON at position 0 at [...]\n\nEven though the HTTP code is 200 and the content can be seen in the network tab. \n\nCould someone explain to me what's the issue ? \n\n(I have tried adding a content type header to the request, but to no success)\n\n**EDIT 1** : the request : \n\nhttps://i.sstatic.net/nRn6R.png\n\n========================================\n\nCode:\n```js\ncontent;\n\ntestEndpoint() {\n  this.http.get<any>('api/test').subscribe(res => this.content = res);\n}\n```\n\n```js\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get('test')\n  testConnection(): string {\n    return 'Some content';\n  }\n}\n```\n\n```text\nthis.http.get('api/test', {responseType: 'text'})\n```\n\n```text\nresponseType\n```\n\n```text\n'json'\n```\n\n```text\ntypeof T\n```\n\n========================================\n\nComments:\n- Could you check the headers of the response? If client considers it to be JSON (and it's apparently not; JSON-ed string starts from `\"` character), either client ignores the mime-type or server still sets it to 'application/json' (or something like that).\n- Try changing it to `http.get`, since that's what you're expecting.\n- @raina77ow I have uploaded the full request as an image to my question\n- @HereticMonkey not working\n- @raina77ow the content type header is misleading, but to let you know, after adding `@Header('Content-Type', 'text&#47;plain')` to Nest, it still doesn't work, the header gets removed.\n- This produces `apps&#47;client&#47;src&#47;app&#47;app.component.ts(16,38): error TS2322: Type '\"text\"' is not assignable to type '\"json\"'.`\n- From IntelliSense, the only allowed value would be `arraybuffer`\n- Overriding with `as any` did the trick though ! 2 minutes to mark it as resolved, thank you for your help !\n- Ah, yes. :( There's the issue describing the same problem, which is somehow still open. And yes, they mention the similar workaround.\n- @raina77ow can you answer my this question! stackoverflow.com/questions/57266622/&hellip;\n- If IntelliSense marks `text` as wrong, remove the `` from `http.get()`.","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":108,"estimatedTokens":809}}841{"id":"stack-61492354","source":"stackoverflow","questionId":61492354,"title":"Should I be using middleware or guards to authenticate with Auth0 and nestjs?","tags":["node.js","authentication","middleware","nestjs","auth0"],"text":"Title: Should I be using middleware or guards to authenticate with Auth0 and nestjs?\nTags: node.js, authentication, middleware, nestjs, auth0\nSource: Stack Overflow\n\nQuestion:\nI am in a conundrum.\n\nI started out building a good old fashioned REST API todo server using NestJS. Then I added Auth0 to it using this article which has you use `AuthGuard`:\n\nhttps://auth0.com/blog/developing-a-secure-api-with-nestjs-adding-authorization/\n\nHowever, I was never able to get things working correctly, always getting a `401 Unauthorized` error. It was frustrating.\n\nThen I found this article: \n\nhttps://auth0.com/blog/full-stack-typescript-apps-part-1-developing-backend-apis-with-nestjs/\n\nthat had me build middleware to authenticate with Auth0 and JWT. And lo and behold, it worked. \n\nBut it feels wrong -- I feel like I should be able to do the whole authorization thing with `@UseGuards` and `AuthGuard` and all that NestJS decorator goodness.\n\nSo I guess my question is two-fold: Am I wrong to be hesitant to use middleware over the NestJS decorator stuff? and Does anyone have a working, simple example of using the decorator stuff in NestJS?\n\n========================================\n\nTop Answer:\nfrom the Doc ....\n\n**Guards have access to the ExecutionContext instance**, **and thus know exactly what's going to be executed next**.\n\nmiddleware, It doesn't know which handler will be executed after calling the next() function.\n\n========================================\n\nCode:\n```text\nAuthGuard\n```\n\n```text\n401 Unauthorized\n```\n\n```text\n@UseGuards\n```\n\n```text\nAuthGuard\n```\n\n```text\n@Guard\n```\n\n========================================\n\nComments:\n- Thanks -- pretty much what I thought. The advice about how to use middleware is sound and correct. It just didn't feel right. I'll figure out the @Guard stuff.\n- Feel free to post an question in case of troubles and mention me in the comment, I will try to come and help\n- Just an addition to your answer: Guards will usually be applied at the controller or method level, so you can easily see which routes have guards applied to them. Using middleware will be bound to the module directly in the module file, so you may forget that you have middleware executing authentication logic when looking at your controller file.\n- I had the exact same question as the OP. But my experience has been to use middleware to verify the token (authentication) and parse the claims in the token, and then the controller/method level has the permission check (authorization). It also makes the user/token info available in the rest of the middleware for logging and such.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":63,"estimatedTokens":722}}842{"id":"stack-57336291","source":"stackoverflow","questionId":57336291,"title":"\"Cannot return null for non-nullable field\" when subscribing on NestJS with Graphql","tags":["angular","graphql","apollo-client","nestjs"],"text":"Title: \"Cannot return null for non-nullable field\" when subscribing on NestJS with Graphql\nTags: angular, graphql, apollo-client, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a nodejs backend done with `Nestjs` and I'm using `Graphql`. My frontend is Ionic/Angular using Apollo-angular for graphql stuff. \n**I'm having a problem subscribing data additions / changes.** Playground (provided by Nestjs) works just fine, which gives me a hint that the problem is in frontend.\n\nI have `game` and `scores` in my data model, each score belonging to a game. In frontend I'm trying to listen to the new scores added to a specific game.\n\n### Backend\n\nHere's a snippet from my `resolver`:\n\n```\n@Mutation(returns => Score)\nasync addScore(@Args('data') data: ScoreInput): Promise {\n return await this.scoresService.createScore(data);\n}\n\n@Subscription(returns => Score, {\n filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n})\nscoreAdded(@Args('gameId') gameId: string) {\n return this.pubSub.asyncIterator('scoreAdded');\n}\n```\n\nHere's the `service` method:\n\n```\nasync createScore(data: any): Promise {\n const score = await this.scoreModel.create(data);\n this.pubSub.publish('scoreAdded', { scoreAdded: score });\n}\n```\n\nThese are in my schema.gql:\n\n```\ntype Score {\n id: String\n game: String\n result: Int\n}\n\ntype Subscription {\n scoreAdded(gameId: String!): Score!\n}\n```\n\n### Frontend\n\nBased on `Apollo-angular`'s documentation, in my frontend I have this kind of service:\n\n```\nimport { Injectable } from '@angular/core';\nimport { Subscription } from 'apollo-angular';\nimport { SCORE_ADDED } from './graphql.queries';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ScoreListenerService extends Subscription {\n document = SCORE_ADDED;\n}\n```\n\nThis is in the frontend's graphql.queries:\n\n```\nexport const SCORE_ADDED = gql`\n subscription scoreAdded($gameId: String!) {\n scoreAdded(gameId: $gameId) {\n id\n game\n result\n }\n }\n`;\n```\n\nand I'm using this service like this in my component:\n\n```\nthis.scoreListener.subscribe({ gameId: this.gameId }).subscribe(({ data }) => {\n const score = data.scoreAdded;\n console.log(score);\n});\n```\n\n### The problem\n\nWith all this, my frontend gives me an error `ERROR Error: GraphQL error: Cannot return null for non-nullable field Subscription.scoreAdded.`\n\nDoing the subscription like this in Playground works, no problem at all.\n\n```\nsubscription {\n scoreAdded(gameId: \"5d24ad2c4cf6d3151ad31e3d\") {\n id\n game\n result\n }\n}\n```\n\n### Different problem\n\nI noticed that if I use `resolve` in my backend's resolver like this:\n\n```\n@Subscription(returns => Score, {\n resolve: value => value,\n filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n })\n scoreAdded(@Args('gameId') gameId: string) {\n return this.pubSub.asyncIterator('scoreAdded');\n }\n```\n\nthe error in frontend goes away, BUT it screws up the data in subscription, playground getting the added score with null in each attribute and the subscribe in frontend is NOT triggered at all.\n\n**Any help, what am I doing wrong here?**\nIt looks to me that my frontend is not correct but I'm not sure is it my bad or possibly a bug in Apollo-angular...\n\n========================================\n\nTop Answer:\nProvided answer above is correct, but for those who want to see the packages version used and imported files check this solution:\n\n**package.json** dependencies\n\n```\n{\n \"dependencies\": {\n \"@apollo/client\": \"^3.2.5\",\n \"@apollo/link-ws\": \"^2.0.0-beta.3\",\n \"apollo-angular\": \"^2.0.4\",\n \"subscriptions-transport-ws\": \"^0.9.18\",\n }\n}\n```\n\n**graphql.module.ts** code\n\n```\nimport { WebSocketLink } from '@apollo/link-ws';\nimport { NgModule } from '@angular/core';\nimport { APOLLO_OPTIONS } from 'apollo-angular';\nimport { InMemoryCache, split } from '@apollo/client/core';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { HttpLink } from 'apollo-angular/http';\n\nconst uri = 'http://localhost:3000/graphql';\nconst wsUrl = 'http://localhost:3000/graphql';\n\nexport function createApollo(hLink: HttpLink) {\n \n const ws = new WebSocketLink({\n uri: wsUrl,\n options: {\n reconnect: true\n }\n });\n\n const http = hLink.create({uri});\n\n const newLink = split(\n ({ query }) => {\n const def = getMainDefinition(query);\n return def.kind === 'OperationDefinition' && def.operation === 'subscription';\n },\n ws,\n http\n );\n \n return {\n link: newLink,\n cache: new InMemoryCache(),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all'\n }\n }\n };\n}\n\n@NgModule({\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n========================================\n\nCode:\n```text\n@Mutation(returns => Score)\nasync addScore(@Args('data') data: ScoreInput): Promise<IScore> {\n  return await this.scoresService.createScore(data);\n}\n\n@Subscription(returns => Score, {\n  filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n})\nscoreAdded(@Args('gameId') gameId: string) {\n  return this.pubSub.asyncIterator('scoreAdded');\n}\n```\n\n```text\nasync createScore(data: any): Promise<IScore> {\n  const score = await this.scoreModel.create(data);\n  this.pubSub.publish('scoreAdded', { scoreAdded: score });\n}\n```\n\n```text\ntype Score {\n  id: String\n  game: String\n  result: Int\n}\n\ntype Subscription {\n  scoreAdded(gameId: String!): Score!\n}\n```\n\n```text\nimport { Injectable } from '@angular/core';\nimport { Subscription } from 'apollo-angular';\nimport { SCORE_ADDED } from './graphql.queries';\n\n@Injectable({\n  providedIn: 'root',\n})\nexport class ScoreListenerService extends Subscription {\n  document = SCORE_ADDED;\n}\n```\n\n```text\nexport const SCORE_ADDED = gql`\n  subscription scoreAdded($gameId: String!) {\n    scoreAdded(gameId: $gameId) {\n      id\n      game\n      result\n    }\n  }\n`;\n```\n\n```text\nthis.scoreListener.subscribe({ gameId: this.gameId }).subscribe(({ data }) => {\n  const score = data.scoreAdded;\n  console.log(score);\n});\n```\n\n```text\nsubscription {\n  scoreAdded(gameId: \"5d24ad2c4cf6d3151ad31e3d\") {\n    id\n    game\n    result\n  }\n}\n```\n\n```text\n@Subscription(returns => Score, {\n    resolve: value => value,\n    filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n  })\n  scoreAdded(@Args('gameId') gameId: string) {\n    return this.pubSub.asyncIterator('scoreAdded');\n  }\n```\n\n```text\nNestjs\n```\n\n```text\nGraphql\n```\n\n```text\ngame\n```\n\n```text\nscores\n```\n\n```text\nresolver\n```\n\n```text\nservice\n```\n\n```text\nApollo-angular\n```\n\n```text\nERROR Error: GraphQL error: Cannot return null for non-nullable field Subscription.scoreAdded.\n```\n\n```text\nresolve\n```\n\n```text\nconst graphqlUri = 'http://localhost:3000/graphql';\n\nexport function createApollo(httpLink: HttpLink) {\n  return {\n    link: httpLink.create({ graphqlUri }),\n    cache: new InMemoryCache(),\n    defaultOptions: {\n      query: {\n        fetchPolicy: 'network-only',\n        errorPolicy: 'all',\n      },\n    },\n  };\n}\n```\n\n```text\nconst graphqlUri = 'http://localhost:3000/graphql';\nconst wsUrl = 'ws://localhost:3000/graphql';\n\nexport function createApollo(httpLink: HttpLink) {\n  const link = split(\n    // split based on operation type\n    ({ query }) => {\n      const { kind, operation } = getMainDefinition(query);\n      return kind === 'OperationDefinition' && operation === 'subscription';\n    },\n    new WebSocketLink({\n      uri: wsUrl,\n      options: {\n        reconnect: true,\n      },\n    }),\n    httpLink.create({\n      uri: graphqlUri,\n    })\n  );\n  return {\n    link,\n    cache: new InMemoryCache(),\n    defaultOptions: {\n      query: {\n        fetchPolicy: 'network-only',\n        errorPolicy: 'all',\n      },\n    },\n  };\n}\n```\n\n```text\n{\n   \"dependencies\": {\n      \"@apollo/client\": \"^3.2.5\",\n      \"@apollo/link-ws\": \"^2.0.0-beta.3\",\n      \"apollo-angular\": \"^2.0.4\",\n      \"subscriptions-transport-ws\": \"^0.9.18\",\n    }\n}\n```\n\n```text\nimport { WebSocketLink } from '@apollo/link-ws';\nimport { NgModule } from '@angular/core';\nimport { APOLLO_OPTIONS } from 'apollo-angular';\nimport { InMemoryCache, split } from '@apollo/client/core';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { HttpLink } from 'apollo-angular/http';\n\nconst uri = 'http://localhost:3000/graphql';\nconst wsUrl = 'http://localhost:3000/graphql';\n\nexport function createApollo(hLink: HttpLink) {\n    \n    const ws = new WebSocketLink({\n       uri: wsUrl,\n       options: {\n           reconnect: true\n       }\n    });\n\n    const http = hLink.create({uri});\n\n    const newLink = split(\n       ({ query }) => {\n          const def = getMainDefinition(query);\n          return def.kind === 'OperationDefinition' && def.operation === 'subscription';\n       },\n       ws,\n       http\n    );\n    \n    return {\n        link: newLink,\n        cache: new InMemoryCache(),\n        defaultOptions: {\n           watchQuery: {\n              fetchPolicy: 'network-only',\n              errorPolicy: 'all'\n           }\n        }\n    };\n}\n\n@NgModule({\n   providers: [\n     {\n        provide: APOLLO_OPTIONS,\n        useFactory: createApollo,\n        deps: [HttpLink],\n     },\n   ],\n})\nexport class GraphQLModule {}\n```\n\n========================================\n\nComments:\n- Is `score` defined inside the service method(i.e. does create actually return the created model)?\n- Yes, the service method returns the actual saved model correctly (in all of these cases). Without defining any `resolve` on backends Subscription part, everything works well on playground but the frontend Apollo client gets the `ERROR Error: GraphQL error: Cannot return null for non-nullable field Subscription.scoreAdded.`\n- and from where do you import getMainDefinition ?\n- Found your question & answer straight away. I suspect you saved, at the least, my day. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:02.472Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":449,"estimatedTokens":2458}}843{"id":"stack-73307606","source":"stackoverflow","questionId":73307606,"title":"Keycloak: Authorization between services and the public frontend","tags":["authentication","jwt","nestjs","keycloak","service-accounts"],"text":"Title: Keycloak: Authorization between services and the public frontend\nTags: authentication, jwt, nestjs, keycloak, service-accounts\nSource: Stack Overflow\n\nQuestion:\nI have an application which consists of a frontend and several backend services. The authentication is done via Keycloak.\nThe workflow looks like this:\nThe user logs into the frontend and gets a token from Keycloak. This token is sent to the backend with every request.\n\nThe following image explains the current architecture:\n\nhttps://i.sstatic.net/OFncw.png\n\nIn Keycloak I have the following clients:\n\n**1. Frontend**\n\n- Access Type: public\n\n- Client Protocol: openid-connect\n\n**2. Core Service**\n\n- Access Type: bearer-only\n\n- Client Protocol: openid-connect\n\n**3. User Service**\n\n- Access Type: bearer-only\n\n- Client Protocol: openid-connect\n\nHow can I validate calls between services now?\n\nI would imagine something like a service account and these have the possibility to call each other independently from the bearer-token from the frontend. The problem is that both services can be called from the frontend as well as between each other.\n\n**Edit:**\n\nMy API is written with NestJS.\n\nThe API of the user-service:\nhttps://i.sstatic.net/ys267.png\n\nAnd this is how I call the user-service in my core-service:\nhttps://i.sstatic.net/E54hZ.png\n\nand this is my keycloak configuration for the the user-service:\nhttps://i.sstatic.net/bmuFf.png\n\nAt the moment I don't add anything to the request and I don't have any extra configuration on the interface. So I added the `@Resource('user-service')`-Annotation to the Controller and the `@Scope()`-Annotation to the Endpoint.\n\nAfter that I don't get an error immediately and the endpoint is called.I can log that the logic is executed. But as response I still get a 401 Unauthorized Error.\n\nDo I need to specify a scope or what do I need to add in the `@Resource`-Annotation?\n\n**Edit 2:**\n\nI'll try to show you my current situation with many screenshots.\n\n### Initial situation\n\nhttps://i.sstatic.net/fXdOj.png\n\nHere is your drawing again. For me, points 1-5 work and point 8 works even if I do not call another service.\n\n### My Configuration\n\nThat this works, I have the following configuration:\n\n### Just Frontend and Core Service\n\nFrontend:\nhttps://i.sstatic.net/n6Jl8.png\n\nCore-Service:\nhttps://i.sstatic.net/KEvYN.png\n\nFor the core service (gutachten-backend), I do not need to make any further configurations for this. I also have 2 different roles and I can specify them within the API.\n\nUsing Postman I send a request to the API and get the token from http://KEYCLOAK-SERVER_URL/auth/realms/REALM_NAME/protocol/openid-connect/token.\n\nhttps://i.sstatic.net/EM0NC.png\n\nThese are my 2 testing methods. I call the first one and it works. The following is logged. Means the token is validated received and I get Access:\nhttps://i.sstatic.net/u4a6s.png\n\n### Calling the user service\n\nNow I call the second method. This method calls the user-service.\n\nThis is my request in the core-service:\nhttps://i.sstatic.net/6SywX.png\nI do not add anything else to my request. Like a bearer token in the header.\n\nThe endpoint in the user service is just a test method which logs a message.\n\nThis is my configuration for the user service:\nhttps://i.sstatic.net/kBvza.png\n\nI have now tried something with resources, policies and permissions.\n\n### Resource\n\nhttps://i.sstatic.net/BjKPu.png\n\n### Policies\n\nRole-Policy\nhttps://i.sstatic.net/EsXpZ.png\n\nClient-Policy:\nhttps://i.sstatic.net/HTyWV.png\n\n### Permission\n\nhttps://i.sstatic.net/5EReC.png\n\nAnd analogously the client permission\n\n### Questions and thoughts\n\n- All steps from the first drawing seem to work except 6 and 7\n\n- Do I need to add more information to my request from core service to user service?\n\n- How to deal with root url and resource urls?\nIn the code in the API, do I need to additionally configure the endpoints and specify the specific resources and policies? (NestJS offers the possibility to provide controllers with a `@Resource('')` and endpoints with `@Scopes([]))`\nAdditionally, through a tutorial on setting up keyacloak in NestJS, I turned on the following config:\n\nThis adds a global level resource guard, which is permissive.\nOnly controllers annotated with @Resource and\nmethods with @Scopes are handled by this guard.\n\n========================================\n\nTop Answer:\nKeycloak's **Token Verification API** can do it.\n\nThis is one of Architecture for Authorization of resource access permission.\n\nhttps://i.sstatic.net/Yhark.png\n\nBetween Core Service and User Service, Core Service needs to verify the access-token to Keycloak.\nIt means this token can access the User service API Yes(Allow) or No(Deny)\n\nThis is API format\n\n```\ncurl -X POST \\\n http://${host}:${port}/realms/${realm}/protocol/openid-connect/token \\\n -H \"Authorization: Bearer ${access_token}\" \\\n --data \"grant_type=urn:ietf:params:oauth:grant-type:uma-ticket\" \\\n --data \"audience={resource_server_client_id}\" \\\n --data \"permission=Resource A#Scope A\" \\\n --data \"permission=Resource B#Scope B\"\n```\n\nDemo Keycloak Token URL: **localhost:8180**\n\nAuthorization Enabled Realm: **test**\n\nAuthorization Enabled Client: **core-service**\n\nClient Resource: **resource:user-service**\n\n**User1** : can access it (**ALLOW**) password: 1234\n\n**User2** : can access it (**ALLOW**) password:1234\n\n### Steps\n\nGet User Access Token(instead of login) ->\n\nPreparations\nready to assign access-token(named user-token) variable in Postman\n\nhttps://i.sstatic.net/ksD1F.png\n\n```\nvar jsonData = JSON.parse(responseBody);\npostman.setEnvironmentVariable(\"user-token\", jsonData.access_token);\n```\n\nGet Token URL from Keycloak UI, click the *Endpoints*\nhttps://i.sstatic.net/Eosha.png\n\nhttps://i.sstatic.net/LIb0y.png\n\nGet User1's access token\nwith Bearer Token option with {{user-token}} in Authorization Tab\nhttps://i.sstatic.net/5jgIW.png\n\nhttps://i.sstatic.net/SX8P6.png\n\nVerify with user1 token from Core Service to Keycloak\nreturn 200 OK from Keycloak (ALLOW) - it is Circle 4 and 5 in my Architecture.\nSo Core Service forward API call to User Service for accessing service\n***Note*** - ***needs to finish Keycloak Permission setting***\n\nhttps://i.sstatic.net/AXbt1.png\n\nVerify with user2 token from Core Service to Keycloak\nreturn 200 OK from Keycloak (Allow) too.\nSo Core Service return an error to Front-end, like this user can't access a resource of User Service.\n\nMore detail information is in here\n\n### Keycloak Permission setting\n\nCreate Client\n\nCreate Client Resource\n\nAdd Client Role\n\nAdd Client Policy\n\nAdd Permission\n\nAll user mapping into Client role\n\nThis is Configuration in Keycloak\nCreate Client\nhttps://i.sstatic.net/6bZul.png\n\nCreate Client Resource\n\nhttps://i.sstatic.net/pV9y1.png\n\nAdd Client Role\nhttps://i.sstatic.net/sO2aa.png\n\nhttps://i.sstatic.net/QDIkA.png\n\nAdd Client Policy - role based\nhttps://i.sstatic.net/WPprJ.png\nhttps://i.sstatic.net/sgrKH.png\n\nAdd Permission\nhttps://i.sstatic.net/FVM67.png\n\nAll user mapping into Client role - any user if you want to add to access the resource.\nhttps://i.sstatic.net/hvi87.png\n\n========================================\n\nCode:\n```text\n@Resource('user-service')\n```\n\n```text\n@Scope()\n```\n\n```text\n@Resource\n```\n\n```text\n@Resource('<name>')\n```\n\n```text\n@Scopes([<list>]))\n```\n\n```text\ngetAccessToken(): Observable<string> {\n    const header = {\n      headers: {\n        'Content-Type': 'application/x-www-form-urlencoded',\n      },\n    };\n    return this.httpService.post(\n      '{{keycloakurl}}/auth/realms/{{realm}}/protocol/openid-connect/token',\n      `grant_type=client_credentials&client_id={{clientId}}&client_secret={{clientSecret}}`,\n      header).pipe(\n        map((response) => {\n          return response.data.access_token as string;\n        }\n        ));\n  }\n```\n\n```text\ncurl -X POST \\\n  http://${host}:${port}/realms/${realm}/protocol/openid-connect/token \\\n  -H \"Authorization: Bearer ${access_token}\" \\\n  --data \"grant_type=urn:ietf:params:oauth:grant-type:uma-ticket\" \\\n  --data \"audience={resource_server_client_id}\" \\\n  --data \"permission=Resource A#Scope A\" \\\n  --data \"permission=Resource B#Scope B\"\n```\n\n```text\nvar jsonData = JSON.parse(responseBody);\npostman.setEnvironmentVariable(\"user-token\", jsonData.access_token);\n```\n\n========================================\n\nComments:\n- thank you for the detailed answer. I have managed the configuration so far. I still have a question about the policy. you have created a policy that applies to certain users. I want every call from the service to be allowed, regardless of the user calling the api. Is it correct that I then create a \"client policy\" and specify the \"user-service\" in the core service?\n- But I still get an error with 401 unauthorized. I edited my question with more details. would be great if you knew an answer to this question\n- @ManuelWolf, Added more detail to avoid 401 Error. Hope to help it. if still 401 error, let me know which step's get 401 error. This change support all users. I have no experience nestJs + Keycloak. Which middle ware use for NestJS to access Keycloak? I will try but It will takes time, I will update again If I success it.\n- I have now added a hopefully understandable, detailed description under Edit 2. F&#252;r NestJS I use \"nest-keycloak-connect\" (npmjs.com/package/nest-keycloak-connect)\n- Thanks, I started to learn \"nest-keycloak-connect\" give me a couple of days more.\n- Hi. Unfortunately I still have the problem. Did you have time to look at the package and did you understand it. I would be very happy about an answer/help.\n- Hi @ManuelWolf, I am sorry, I try it but not success to figure out NextJS. you needs to figure out yourself.","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":311,"estimatedTokens":2416}}844{"id":"stack-63192245","source":"stackoverflow","questionId":63192245,"title":"Custom Route Decorators for NestJS","tags":["javascript","typescript","nestjs","typescript-decorator"],"text":"Title: Custom Route Decorators for NestJS\nTags: javascript, typescript, nestjs, typescript-decorator\nSource: Stack Overflow\n\nQuestion:\nI've created some custom parameter decorators for my routes, but I do not find any useful documentation on how to create a decorator for the route itself. There is some description how to bundle existing method decorators together which does not help me.\n\nWhat I'm trying to achieve is some simple scope validation. The scopes are already set up in the request context. What I currently have, only based on TypeScript decorators, but is actually going nowhere:\n\n**controller.ts**\n\n```\n@RequiredScope(AuthScope.OWNER)\n@Get('/some-route')\nasync get() {\n ...\n}\n```\n\n**required-scopes.ts**\n\n```\nexport function RequiredScope(...scopes: string[]) {\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n console.log(`Validation of scopes '${scopes.join(',')}' for input '${RequestContext.getScopes().join(',')}'`)\n if (!scopes.map(s => RequestContext.hasOneOfTheScopes(s)).find(valid => !valid)) {\n throw new HttpException(`Missing at least one scope of '${scopes.join(',')}'`, HttpStatus.FORBIDDEN)\n }\n }\n}\n```\n\nProblem here is that my request context is not even available because my middleware which does set up my context did not kick in yet. The request is failing immediately.\n\n**Can somebody point me into the right direction?**\n\n========================================\n\nCode:\n```text\n@RequiredScope(AuthScope.OWNER)\n@Get('/some-route')\nasync get() {\n    ...\n}\n```\n\n```text\nexport function RequiredScope(...scopes: string[]) {\n    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n        console.log(`Validation of scopes '${scopes.join(',')}' for input '${RequestContext.getScopes().join(',')}'`)\n        if (!scopes.map(s => RequestContext.hasOneOfTheScopes(s)).find(valid => !valid)) {\n            throw new HttpException(`Missing at least one scope of '${scopes.join(',')}'`, HttpStatus.FORBIDDEN)\n        }\n    }\n}\n```\n\n```text\nexport const Scopes = (...scopes: string[]) => SetMetadata('scopes', scopes)\n```\n\n```text\n@Injectable()\nexport class ScopesGuard implements CanActivate {\n\n    constructor(private reflector: Reflector) {}\n\n    canActivate(\n        context: ExecutionContext,\n    ): boolean | Promise<boolean> | Observable<boolean> {\n        const scopes = this.reflector.get<string[]>('scopes', context.getHandler())\n        if (!scopes || scopes.length === 0) return true\n        if (!scopes.map(s => RequestContext.hasOneOfTheScopes(s)).find(valid => !valid)) {\n            throw new HttpException(`Missing at least one scope of '${scopes.join(',')}'`, HttpStatus.FORBIDDEN)\n        }\n        return true\n    }\n}\n```\n\n```text\n@Module({\n    imports: [...],\n    controllers: [...],\n    providers: [\n        {\n            provide: APP_GUARD,\n            useClass: ScopesGuard,\n        }\n    ],\n})\n```\n\n```text\n@Scopes(AuthScope.OWNER)\n@Get('/some-route')\nasync get() {\n    ...\n}\n```\n\n```text\nscopes\n```\n\n========================================\n\nComments:\n- Have you tried to use a guard instead of making a decorator? docs.nestjs.com/guards\n- Thank you very much for this advice. It worked out quite nicely. Also, it fits a lot better for this use case.","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":111,"estimatedTokens":816}}845{"id":"stack-71176426","source":"stackoverflow","questionId":71176426,"title":"I need help on 'Cannot find namespace Kind' issue","tags":["node.js","nestjs","apollo"],"text":"Title: I need help on 'Cannot find namespace Kind' issue\nTags: node.js, nestjs, apollo\nSource: Stack Overflow\n\nQuestion:\nI just updated NestJs to latest (8.3.1) from 7.5, solved the issues that popped out, but I cannot get rid of one of them.\n\nThe full error:\n\n```\nnode_modules/@apollo/federation/dist/composition/utils.d.ts:43:316 - error TS2503: Cannot find namespace 'Kind'.\n```\n\nAlthough Kind is a constant imported from the GraphQl module, it seems it does not recognize it. Or maybe is a typescript issue?\n\nAny help would be greatly appreciated.\n\n========================================\n\nTop Answer:\nIt looks like `@apollo/gateway@0.48.1` has typing issues. `@apollo/gateway@0.47.0` is broken for GraphQL 15, so you have to downgrade to `@apollo/gateway@~0.46.0`:\n\n```\n$ yarn add @apollo/gateway@~0.46.0\n```\n\n========================================\n\nCode:\n```text\nnode_modules/@apollo/federation/dist/composition/utils.d.ts:43:316 - error TS2503: Cannot find namespace 'Kind'.\n```\n\n```text\n$ yarn add @apollo/gateway@~0.46.0\n```\n\n```text\n@apollo/gateway@0.48.1\n```\n\n```text\n@apollo/gateway@0.47.0\n```\n\n```text\n@apollo/gateway@~0.46.0\n```\n\n========================================\n\nComments:\n- Just ran into this too today. Might be something that needs a GitHub issue created.\n- Could anyone solve this issue? Thanks for your help!\n- What libraries were causing this issue? I'm having the same issue all of a sudden and cannot figure out what is causing this. Also downgrading @apollo/gateway does not seem to solve it. Thanks for a hint!\n- I just ran \"npm outdated\" on my project and updated all the libs that were mentioned there. Afterwards the error was gone.","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":56,"estimatedTokens":418}}846{"id":"stack-77267850","source":"stackoverflow","questionId":77267850,"title":"GCP Cloud Run Revision Request Count Metric Group By Route But Route is Empty","tags":["node.js","google-cloud-platform","nestjs","google-cloud-run","google-cloud-metrics"],"text":"Title: GCP Cloud Run Revision Request Count Metric Group By Route But Route is Empty\nTags: node.js, google-cloud-platform, nestjs, google-cloud-run, google-cloud-metrics\nSource: Stack Overflow\n\nQuestion:\nI am trying to set up alerting per route for my GCP Cloud Run service. Of the default metrics collected by default Request Count of the Cloud Run Revisions looks like a good candidate. My issue is that the 'route' label on these metrics is always empty. Is there something additional I need to configure to get this to populate?\n\nIt seems out that a label would exist on an out of the box metric that is never populated.\n\nI am running a nodejs app us the nestjs framework.\n\nI tried to group the Cloud Run Revision Request Count metric by Route but found that Route is always empty. I was expected the Route label to be populated with the api endpoint / url path for each request.\n\n========================================\n\nComments:\n- Where are you searching the route? The path is a better entry isn't it?\n- By default Cloud Run collects a number of metrics, the 'request count' metrics decribes itself as \"Number of requests reaching the revision. Excludes requests that are not reaching your container instances (for example, unauthorized requests or when maximum number of instances is reached). Captured at the end of the request lifecycle. Sampled every 60 seconds. After sampling, data is not visible for up to 180 seconds. response_code: Response code of a request. response_code_class: Response code class of a request. route: Route name that forwards a request.\" but the 'route' is always empty\n- You mentioned the empty \"route\" label is a known issue on Cloud Run's side. Do you have a link to the bug report/issue?\n- here is the issue link issuetracker.google.com/issues/322930749","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":20,"estimatedTokens":449}}847{"id":"stack-55899674","source":"stackoverflow","questionId":55899674,"title":"How can I set a session key from inside a GraphQL resolver in NestJS?","tags":["typescript","authentication","graphql","nestjs"],"text":"Title: How can I set a session key from inside a GraphQL resolver in NestJS?\nTags: typescript, authentication, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm discovering Nest.js and I want to setup a cookie based authentication system with GraphQL.\n\nI already installed express-session middleware, here is the configuration:\n\n**main.ts**\n\n```\napp.use(\n session({\n store: new redisStore({\n client: redis\n } as any),\n name: 'qid',\n secret: SESSION_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: {\n httpOnly: true,\n secure: !isDev,\n maxAge: 1000 * 60 * 60 * 24 * 7 * 365\n }\n })\n )\n```\n\nit works fine because when I do :\n\n```\napp.use((req: any, res: any, next: any) => {\n // Debug purpose\n req.session.userId = '42'\n next()\n })\n```\n\nThe cookie is added.\n\nRight now I have two mutations, **register** and **login**.\nIn the login mutation (or in the userService), after I found a user I want to do something like `req.session.userId = user.id` but I can't find a way to do this.\n\nI tried to add `@Context() ctx` to my mutation.\nIf I console log ctx, it contains everything I expect (req.session.id for example)\n\nBut if I do `ctx.req.session.userId = 'something'`, the cookie is not set!\n\nHere is my mutation:\n\n**user.resolver.ts**\n\n```\n@Mutation('login')\n async login(\n @Args('email') email: string,\n @Args('password') password: string,\n @Context() ctx: any\n ) {\n console.log(ctx.req.session.id) // Show the actual session id\n ctx.req.session.userId = 'something' // Do not set any cookie\n return await this.userService.login(email, password)\n }\n}\n```\n\nI am totally lost and I really need help, I'd love to understand what's happening. I know I'm probably doing this totally wrong but I'm new to both Nest and GraphQL..\n\nThank you guys...\n\n========================================\n\nTop Answer:\nfor this, it's better to do the configuration in the GraphQL config file instead of the client side\n\n**graphql.config.ts**\n\n```\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\nimport { join } from 'path';\n\nexport const GraphQLConfig: ApolloDriverConfig = {\n driver: ApolloDriver,\n debug: true,\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n playground: {\n settings: {\n 'editor.theme': 'light', // use value dark if you want a dark theme in the playground\n 'request.credentials': 'include',\n },\n },\n};\n```\n\nand assign the config file to the module directory\n\n**user.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphQLConfig } from 'src/config/graphql.config';\nimport { UserEntity } from 'src/entity/user.entity';\nimport { UserResolver } from './user.resolver';\nimport { UserService } from './user.service';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n GraphQLModule.forRoot(GraphQLConfig),\n ],\n providers: [UserService, UserResolver],\n})\nexport class UserModule {}\n```\n\nand it will automatically enable credentials value to be \"include\" from \"omit\"\n\n========================================\n\nCode:\n```text\napp.use(\n    session({\n      store: new redisStore({\n        client: redis\n      } as any),\n      name: 'qid',\n      secret: SESSION_SECRET,\n      resave: false,\n      saveUninitialized: false,\n      cookie: {\n        httpOnly: true,\n        secure: !isDev,\n        maxAge: 1000 * 60 * 60 * 24 * 7 * 365\n      }\n    })\n  )\n```\n\n```text\napp.use((req: any, res: any, next: any) => {\n      // Debug purpose\n      req.session.userId = '42'\n      next()\n    })\n```\n\n```text\n@Mutation('login')\n  async login(\n    @Args('email') email: string,\n    @Args('password') password: string,\n    @Context() ctx: any\n  ) {\n    console.log(ctx.req.session.id) // Show the actual session id\n    ctx.req.session.userId = 'something' // Do not set any cookie\n    return await this.userService.login(email, password)\n  }\n}\n```\n\n```text\nreq.session.userId = user.id\n```\n\n```text\n@Context() ctx\n```\n\n```text\nctx.req.session.userId = 'something'\n```\n\n```text\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\nimport { join } from 'path';\n\nexport const GraphQLConfig: ApolloDriverConfig = {\n  driver: ApolloDriver,\n  debug: true,\n  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n  playground: {\n    settings: {\n      'editor.theme': 'light', // use value dark if you want a dark theme in the playground\n      'request.credentials': 'include',\n    },\n  },\n};\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphQLConfig } from 'src/config/graphql.config';\nimport { UserEntity } from 'src/entity/user.entity';\nimport { UserResolver } from './user.resolver';\nimport { UserService } from './user.service';\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([UserEntity]),\n    GraphQLModule.forRoot(GraphQLConfig),\n  ],\n  providers: [UserService, UserResolver],\n})\nexport class UserModule {}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":212,"estimatedTokens":1248}}848{"id":"stack-68354969","source":"stackoverflow","questionId":68354969,"title":"Nestjs \"Reference Error: File is not defined\" only in test","tags":["typescript","jestjs","nestjs","nrwl-nx"],"text":"Title: Nestjs \"Reference Error: File is not defined\" only in test\nTags: typescript, jestjs, nestjs, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nMy test suite is failing to run because the \"File\" input type is undefined. This only happens when trying to run tests. The app works perfectly in development. Below is my console output.\n\n```\n$ nx run build-support-cases-api-core:test\n\n> nx run build-support-cases-api-core:test \n FAIL build-support-cases-api-core libs/build-support-cases/api/core/src/lib/__test__/buildSupportCase.service.spec.ts\n โ— Test suite failed to run\n\n ReferenceError: File is not defined\n\n 4 | export class CreateReceiptInput {\n 5 | @Field(() => String)\n > 6 | public receipt: File;\n | ^\n 7 |\n 8 | @Field(() => String)\n 9 | public vendorName: string;\n\n at Object. (../../../core/database/receipt/src/lib/dto/createReceipt.input.ts:6:19)\n at Object. (../../../core/database/receipt/src/lib/dto/createReceipt.dto.ts:1:1)\n```\n\nHere is the full source file for completeness\n\n```\nimport { Field, ID, InputType } from \"@nestjs/graphql\";\n\n@InputType()\nexport class CreateReceiptInput {\n @Field(() => String)\n public receipt: File;\n\n @Field(() => String)\n public vendorName: string;\n\n @Field(() => Date)\n public purchaseDate: Date;\n\n @Field(() => Number)\n public totalDollarAmount: number;\n\n @Field(() => String)\n public purchasedBy: string;\n\n @Field(() => String)\n public note: string;\n\n @Field(() => ID)\n public updateId?: number;\n}\n```\n\nIs there something in a config file somewhere that I am missing? How do I get past this issue so that my tests will run?\n\n========================================\n\nCode:\n```text\n$ nx run build-support-cases-api-core:test\n\n> nx run build-support-cases-api-core:test \n FAIL   build-support-cases-api-core  libs/build-support-cases/api/core/src/lib/__test__/buildSupportCase.service.spec.ts\n  โ— Test suite failed to run\n\n    ReferenceError: File is not defined\n\n      4 | export class CreateReceiptInput {\n      5 |   @Field(() => String)\n    > 6 |   public receipt: File;\n        |                   ^\n      7 |\n      8 |   @Field(() => String)\n      9 |   public vendorName: string;\n\n      at Object.<anonymous> (../../../core/database/receipt/src/lib/dto/createReceipt.input.ts:6:19)\n      at Object.<anonymous> (../../../core/database/receipt/src/lib/dto/createReceipt.dto.ts:1:1)\n```\n\n```text\nimport { Field, ID, InputType } from \"@nestjs/graphql\";\n\n@InputType()\nexport class CreateReceiptInput {\n  @Field(() => String)\n  public receipt: File;\n\n  @Field(() => String)\n  public vendorName: string;\n\n  @Field(() => Date)\n  public purchaseDate: Date;\n\n  @Field(() => Number)\n  public totalDollarAmount: number;\n\n  @Field(() => String)\n  public purchasedBy: string;\n\n  @Field(() => String)\n  public note: string;\n\n  @Field(() => ID)\n  public updateId?: number;\n}\n```\n\n```text\nexport interface File extends Blob {\n  readonly lastModified: number;\n  readonly name: string;\n}\n```\n\n```text\nimport { Field, ID, InputType } from \"@nestjs/graphql\";\nimport { File } from \"./interfaces\";\n@InputType()\nexport class CreateReceiptInput {\n  @Field(() => String)\n  public receipt: File;\n\n  @Field(() => String)\n  public vendorName: string;\n\n  @Field(() => Date)\n  public purchaseDate: Date;\n\n  @Field(() => Number)\n  public totalDollarAmount: number;\n\n  @Field(() => String)\n  public purchasedBy: string;\n\n  @Field(() => String)\n  public note: string;\n\n  @Field(() => ID)\n  public updateId?: number;\n}\n```\n\n========================================\n\nComments:\n- Where does `File` usually come from? What does it represent?\n- From the description, it is an interface that provides information about files and allows JavaScript in a web page to access their content. It comes from typescript. microsoft.github.io/PowerBI-JavaScript/interfaces/&hellip;\n- Okay, what does it represent though? It looks like that type comes from the `lib` types, which `ts-jest` is probably throwing out during type checking. You should probably have a dedicated type for that that doesn't come from `lib` (front end types)\n- It represents the input type of the CreateReceiptInput receipt method. I am posting an object of type CreateReceiptInput to my ReceiptService, where I upload the file to aws and save the url it uploaded to into my database. You are right that File is a front end type as it comes from FormData. Is there a different way I should be handling this?\n- You did not import `File`. It is an interface, which is defined somewhere else. So you have to import it.","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":155,"estimatedTokens":1124}}849{"id":"stack-65861573","source":"stackoverflow","questionId":65861573,"title":"NestJS-Mongoose: cannot access fullDocument on ChangeEvent","tags":["typescript","mongoose","model","nestjs","watch"],"text":"Title: NestJS-Mongoose: cannot access fullDocument on ChangeEvent\nTags: typescript, mongoose, model, nestjs, watch\nSource: Stack Overflow\n\nQuestion:\nI have the following basic snippet of code and my aim is to get the fullDocument property from the `obj: ChangeEvent` however I am not able to access this property (`Property 'fullDocument' does not exist on type 'ChangeEvent'`). The only properties I can access are _id, clusterTime and operationType. Is there something I am missing or should I just query the fullDocument non-directly (`obj['fullDocument']`)?\n\n```\nconst changeStream = this.model.watch([], { fullDocument: 'updateLookup' })\n .on('change', obj => {\n console.log(obj.fullDocument);\n });\n```\n\n========================================\n\nCode:\n```text\nconst changeStream = this.model.watch([], { fullDocument: 'updateLookup' })\n      .on('change', obj => {\n        console.log(obj.fullDocument);\n      });\n```\n\n```text\nobj: ChangeEvent\n```\n\n```text\nProperty 'fullDocument' does not exist on type 'ChangeEvent<any>'\n```\n\n```text\nobj['fullDocument']\n```\n\n```js\nconst changeStream = this.model\n  .watch([], { fullDocument: 'updateLookup' }) as ChangeStream<MySchema>; // <-- specialize using the cast\n      \nchangeStream.on('change', obj => {\n  console.log(obj.fullDocument);\n});\n```\n\n```text\nmongodb.ChangeStream\n```\n\n```text\nModel.watch\n```\n\n```text\n@types/mongoose\n```\n\n```text\nmongoose\n```\n\n```text\n@types/mongodb\n```\n\n```text\nwatch\n```\n\n```text\nwatch\n```\n\n```text\nchangeStream\n```\n\n```text\nMySchema\n```\n\n```text\n@Schema\n```\n\n========================================\n\nComments:\n- I do not use Mongoose. As far as I can tell this is an issue with the underlying mongodb nodejs driver. Even if you provide a type parameter to `watch`, the `change` event will still provide a `fullDocument` with the broad `Document` type.","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":89,"estimatedTokens":459}}850{"id":"stack-67442044","source":"stackoverflow","questionId":67442044,"title":"NestJS Mocking a Mixin that returns a Guard","tags":["unit-testing","dependency-injection","nestjs"],"text":"Title: NestJS Mocking a Mixin that returns a Guard\nTags: unit-testing, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm hoping to get some insight into an issue I'm having.\n\nI have a mixin that produces a guard. The resulting guard uses a service that is injected. Here's the code for the mixin:\n\n```\nimport {\n CanActivate,\n ExecutionContext,\n Injectable,\n mixin,\n} from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AccountService } from 'src/modules/account/account.service';\n\nexport const ForAccountGuard = (\n paramName: string,\n { required = false }: { required?: boolean } = {}\n) => {\n @Injectable()\n class _ForAccountGuard implements CanActivate {\n constructor(private readonly accountService: AccountService) {}\n\n async canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const accountId = ctx.getArgs()[paramName];\n const currentUser = ctx.getContext().user;\n\n if (required && !accountId) {\n return false;\n }\n\n if (accountId) {\n const account = await this.accountService.findUserAccount(\n accountId,\n currentUser.id\n );\n return !!account;\n }\n\n return true;\n }\n }\n\n return mixin(_ForAccountGuard);\n};\n```\n\nIn my tests for a resolver that uses this mixin as a guard I'm doing the following:\n\n```\n@Query(() => [PropertyEntity])\n @UseGuards(ForAccountGuard('accountId'))\n async allProperties(@Args() { accountId }: AllPropertiesArgs) {\n // \n }\n```\n\nSo, the issue I'm running into is that I get the following error when running tests:\n\n```\nCannot find module 'src/modules/account/account.service' from 'modules/common/guards/for-account.guard.ts'\n\n Require stack:\n modules/common/guards/for-account.guard.ts\n modules/property/property.resolver.spec.ts\n```\n\nIt looks like the injected AccountService isn't being resolved.\n\nI'm not exactly sure how to tell Nest's testing module to override a guard that is a mixin. I've been trying it like this, but it doesn't seem to be working:\n\n```\nbeforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n PropertyResolver,\n ...\n ],\n })\n .overrideGuard(ForAccountGuard)\n .useValue(createMock())\n .compile();\n );\n });\n```\n\nSo, how am I supposed to mock out a guard that is a mixin?\n\n========================================\n\nCode:\n```text\nimport {\n  CanActivate,\n  ExecutionContext,\n  Injectable,\n  mixin,\n} from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AccountService } from 'src/modules/account/account.service';\n\nexport const ForAccountGuard = (\n  paramName: string,\n  { required = false }: { required?: boolean } = {}\n) => {\n  @Injectable()\n  class _ForAccountGuard implements CanActivate {\n    constructor(private readonly accountService: AccountService) {}\n\n    async canActivate(context: ExecutionContext) {\n      const ctx = GqlExecutionContext.create(context);\n      const accountId = ctx.getArgs()[paramName];\n      const currentUser = ctx.getContext().user;\n\n      if (required && !accountId) {\n        return false;\n      }\n\n      if (accountId) {\n        const account = await this.accountService.findUserAccount(\n          accountId,\n          currentUser.id\n        );\n        return !!account;\n      }\n\n      return true;\n    }\n  }\n\n  return mixin(_ForAccountGuard);\n};\n```\n\n```text\n@Query(() => [PropertyEntity])\n  @UseGuards(ForAccountGuard('accountId'))\n  async allProperties(@Args() { accountId }: AllPropertiesArgs) {\n    // <implementation removed>\n  }\n```\n\n```text\nCannot find module 'src/modules/account/account.service' from 'modules/common/guards/for-account.guard.ts'\n\n    Require stack:\n      modules/common/guards/for-account.guard.ts\n      modules/property/property.resolver.spec.ts\n```\n\n```text\nbeforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        PropertyResolver,\n        ...\n      ],\n    })\n      .overrideGuard(ForAccountGuard)\n      .useValue(createMock<typeof ForAccountGuard>())\n      .compile();\n    );\n  });\n```\n\n```text\nimport { CanActivate, Injectable, mixin } from '@nestjs/common';\n\nexport const mockForAccountGuard = () => {\n  @Injectable()\n  class _ForAccountGuardMock implements CanActivate {\n    canActivate() {\n      return true;\n    }\n  }\n\n  return mixin(_ForAccountGuardMock);\n};\n```\n\n```text\n// in my test file\n\nimport { mockForAccountGuard } from '../common/guards/__mocks__/for-account.guard';\nimport { ForAccountGuard } from '../common/guards/for-account.guard';\n\njest.mock('../common/guards/for-account.guard', () => ({\n  ForAccountGuard: mockForAccountGuard,\n}));\n\n...\n\ndescribe('PropertyResolver', () => {\n  ...\n  beforeEach(() => {\n    ...\n    const module: TestingModule = await Test.createTestingModule({\n      ...\n    }).compile() // note, not using overrideGuards here\n  });\n})\n```\n\n```text\noverrideGuard\n```\n\n```text\njest.mock\n```\n\n```text\njest.mock\n```\n\n========================================\n\nComments:\n- Are you using absolute or relative imports? If you're using absolute (import starts with `src&#47;`) then you need to add the proper mapping into the `jest.config.js` file","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":224,"estimatedTokens":1283}}851{"id":"stack-73329395","source":"stackoverflow","questionId":73329395,"title":"Cannot set cookie with Nest.js","tags":["javascript","node.js","typescript","cookies","nestjs"],"text":"Title: Cannot set cookie with Nest.js\nTags: javascript, node.js, typescript, cookies, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have created `/sign-in` endpoint that basically returns object with 2 tokens - refresh token and access token.\n\n```\n@Post('/sign-in')\nsignIn(@Body() signInUserDto: SignInUserDto): Promise {\n return this.userService.signIn(signInUserDto);\n}\n```\n\nWhat I want to do, is to send access token normally as `JSON`, but send access token as cookie, so I changed a little bit this function and made it look like this.\n\n```\n@Post('/sign-in')\nasync signIn(\n @Request() req: ExpressRequest,\n @Response() res: ExpressResponse\n): Promise>> {\n const { _at, _rt } = await this.userService.signIn(req.body);\n res.cookie('_rt', _rt, {\n httpOnly: true,\n sameSite: 'strict',\n maxAge: 7 * 24 * 60 * 60 * 1000\n });\n return res.status(200).json({ _at });\n}\n```\n\nAs a result, I get access token in response, but I don't get refresh token in cookie. Right away I can tell, that on front-end I have `withCredentials: true` in axios. Also, when I send request to this endpoint with postman, I get cookie, but not on front-end. Why it happens and how I can make it set cookie?\n\n**PS.**\n\nIn server terminal, no matter how I send request, from front-end or postman, I get this warning:\n\n```\nError [ERR_INTERNAL_ASSERTION]: This is caused by either a bug in Node.js or incorrect usage of Node.js internals.\nPlease open an issue with this stack trace at https://github.com/nodejs/node/issues\n\n at assert (internal/assert.js:14:11)\n at ServerResponse.detachSocket (_http_server.js:223:3)\n at resOnFinish (_http_server.js:685:7)\n at ServerResponse.emit (events.js:314:20)\n at onFinish (_http_outgoing.js:735:10)\n at onCorkedFinish (_stream_writable.js:673:5)\n at afterWrite (_stream_writable.js:490:5)\n at afterWriteTick (_stream_writable.js:477:10)\n at processTicksAndRejections (internal/process/task_queues.js:83:21)\n```\n\n========================================\n\nCode:\n```text\n@Post('/sign-in')\nsignIn(@Body() signInUserDto: SignInUserDto): Promise<TokensDto> {\n  return this.userService.signIn(signInUserDto);\n}\n```\n\n```text\n@Post('/sign-in')\nasync signIn(\n  @Request() req: ExpressRequest,\n  @Response() res: ExpressResponse\n): Promise<ExpressResponse<any, Record<string, any>>> {\n  const { _at, _rt } = await this.userService.signIn(req.body);\n  res.cookie('_rt', _rt, {\n    httpOnly: true,\n    sameSite: 'strict',\n    maxAge: 7 * 24 * 60 * 60 * 1000\n  });\n  return res.status(200).json({ _at });\n}\n```\n\n```text\nError [ERR_INTERNAL_ASSERTION]: This is caused by either a bug in Node.js or incorrect usage of Node.js internals.\nPlease open an issue with this stack trace at https://github.com/nodejs/node/issues\n\n    at assert (internal/assert.js:14:11)\n    at ServerResponse.detachSocket (_http_server.js:223:3)\n    at resOnFinish (_http_server.js:685:7)\n    at ServerResponse.emit (events.js:314:20)\n    at onFinish (_http_outgoing.js:735:10)\n    at onCorkedFinish (_stream_writable.js:673:5)\n    at afterWrite (_stream_writable.js:490:5)\n    at afterWriteTick (_stream_writable.js:477:10)\n    at processTicksAndRejections (internal/process/task_queues.js:83:21)\n```\n\n```text\n/sign-in\n```\n\n```text\nJSON\n```\n\n```text\nwithCredentials: true\n```\n\n```text\nimport { NextApiRequest, NextApiResponse } from \"next\";\nimport { AxiosError } from \"axios\";\nimport { api } from \"../../../api\";\nimport { serialize } from 'cookie'\n\nexport default async (\n  req: NextApiRequest,\n  res: NextApiResponse\n) => {\n  try {\n    const { data } = await api.post('/user/sign-in', req.body)\n\n    res.setHeader('Set-Cookie', serialize('_rt', data.data._rt, {\n      httpOnly: true,\n      sameSite: 'strict',\n      maxAge: 7 * 24 * 60 * 60 * 1000\n    }))\n    return res.json(data)\n  } catch (error) {\n    return res\n      .status((error as AxiosError).response?.status as number)\n      .json((error as AxiosError).response?.data);\n  }\n}\n```\n\n```text\ncookie\n```\n\n```text\n@types/cookie\n```\n\n```text\nNext.js\n```\n\n```text\nSet-Cookie\n```\n\n```text\nApplication/Cookies\n```\n\n========================================\n\nComments:\n- How are you checking if you have the cookie on the front end? Have you checked the response headers for a `Set-Cookie` header?\n- I check it in Application/Cookies in devtools.\n- What about the response headers?\n- @JayMcDoniel Actually, nothing, but here you go. `Connection: keep-alive Content-Length: 282 Content-Type: application&#47;json; charset=utf-8 Date: Fri, 12 Aug 2022 06:24:20 GMT ETag: \"ho9ctu0n8u7u\" Keep-Alive: timeout=5 Vary: Accept-Encoding`\n- Hmm, okay, so cookie definitely isn't sent back. That error in your terminal looks interesting, is there anymore to it?\n- @JayMcDoniel By the way, I have an idea, why it happens, after click on button I send request 'twice'. First time is when service sends request to `Next.js` endpoint (folder structure describes routes, as you know), and the second one, when this endpoint sends this request to server. And at this second request is place, where I should put cookie, but as response type I have `NextApiResponse` and this type has no cookie field.\n- Okay, that sounds like an issue with Next not forwarding on the cookie, not that Nest (or rather express) isn't sending the cookie in the first place","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":163,"estimatedTokens":1314}}852{"id":"stack-53526497","source":"stackoverflow","questionId":53526497,"title":"Nest.js deployment to now.sh","tags":["javascript","node.js","typescript","nestjs","vercel"],"text":"Title: Nest.js deployment to now.sh\nTags: javascript, node.js, typescript, nestjs, vercel\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to deploy my demo application to zeit now.sh. In documentation I have found how I can deploy Node.js and Express.js application. But example that I am referring expects as parameter js file with server initialization, and by default Nest.js project has as entry point ts file. Whole application is written in typescript. If I try to use `main.ts` as entry point, I am getting this error:\n\n```\n11/28 08:05 PM (1m)\n\n{ Error: Cannot find module './app.module'\n at Function.Module._resolveFilename (module.js:547:15)\n at Function.Module._load (module.js:474:25)\n at Module.require (module.js:596:17)\n at require (internal/module.js:11:18)\n at Object. (/var/task/user/src/main.ts:26040:18)\n at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n at Module.module.exports.Object.defineProperty.value (/var/task/user/src/main.ts:26050:69)\n at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n at module.exports.Object.setPrototypeOf.__proto__ (/var/task/user/src/main.ts:85:18)\n at Object. (/var/task/user/src/main.ts:88:10) code: 'MODULE_NOT_FOUND' }\n\n11/28 08:05 PM (1m)\n\nError while initializing entrypoint: { Error: Cannot find module './app.module'\n at Function.Module._resolveFilename (module.js:547:15)\n at Function.Module._load (module.js:474:25)\n at Module.require (module.js:596:17)\n at require (internal/module.js:11:18)\n at Object. (/var/task/user/src/main.ts:26040:18)\n at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n at Module.module.exports.Object.defineProperty.value (/var/task/user/src/main.ts:26050:69)\n at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n at module.exports.Object.setPrototypeOf.__proto__ (/var/task/user/src/main.ts:85:18)\n at Object. (/var/task/user/src/main.ts:88:10) code: 'MODULE_NOT_FOUND' }\n```\n\nIs there anybody that have experience with deployment of Nest.js app to now.sh?\n\n========================================\n\nCode:\n```text\n11/28 08:05 PM (1m)\n\n{ Error: Cannot find module './app.module'\n    at Function.Module._resolveFilename (module.js:547:15)\n    at Function.Module._load (module.js:474:25)\n    at Module.require (module.js:596:17)\n    at require (internal/module.js:11:18)\n    at Object.<anonymous> (/var/task/user/src/main.ts:26040:18)\n    at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n    at Module.module.exports.Object.defineProperty.value (/var/task/user/src/main.ts:26050:69)\n    at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n    at module.exports.Object.setPrototypeOf.__proto__ (/var/task/user/src/main.ts:85:18)\n    at Object.<anonymous> (/var/task/user/src/main.ts:88:10) code: 'MODULE_NOT_FOUND' }\n\n11/28 08:05 PM (1m)\n\nError while initializing entrypoint: { Error: Cannot find module './app.module'\n    at Function.Module._resolveFilename (module.js:547:15)\n    at Function.Module._load (module.js:474:25)\n    at Module.require (module.js:596:17)\n    at require (internal/module.js:11:18)\n    at Object.<anonymous> (/var/task/user/src/main.ts:26040:18)\n    at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n    at Module.module.exports.Object.defineProperty.value (/var/task/user/src/main.ts:26050:69)\n    at __webpack_require__ (/var/task/user/src/main.ts:21:30)\n    at module.exports.Object.setPrototypeOf.__proto__ (/var/task/user/src/main.ts:85:18)\n    at Object.<anonymous> (/var/task/user/src/main.ts:88:10) code: 'MODULE_NOT_FOUND' }\n```\n\n```text\nmain.ts\n```\n\n```text\n{\n  \"version\": 2,\n  \"builds\": [\n    {\n      \"src\": \"dist/main.js\",\n      \"use\": \"@now/node-server\"\n    }\n  ],\n  \"routes\": [\n    {\n      \"src\": \"/(.*)\",\n      \"dest\": \"dist/main.js\"\n    }\n  ]\n}\n```\n\n```text\nnow.json\n```\n\n```text\nnpm run build\n```\n\n```text\nnow\n```\n\n========================================\n\nComments:\n- with this conf : NO_STATUS_CODE_FROM_LAMBDA\n- the same as for @MuhammedMoussa","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":111,"estimatedTokens":985}}853{"id":"stack-75057904","source":"stackoverflow","questionId":75057904,"title":"NestJS - Purpose of mixins and how are they different from inheritance?","tags":["typescript","inheritance","nestjs","mixins"],"text":"Title: NestJS - Purpose of mixins and how are they different from inheritance?\nTags: typescript, inheritance, nestjs, mixins\nSource: Stack Overflow\n\nQuestion:\nNestjs docs have no mention of `mixin`, so this is what I gathered from google and stackoverflow:\n\n- A mixin is a way to code between classes in nest.\n\n- It is a class that contains methods that can be used by other classes, and can be registered as a provider using the `@Injectable()` decorator.\n\n- Mixins are used to add additional functionality to a class without modifying the original class, and can be used with controllers, services, pipes, and guards.\n\n- Examples often include classes inheriting from mixins: `class SomeClass extends MixinClass {}`\n\nAt first I thought that this is for semantics sake, as inheritance implies a certain relationship between two classes, while a mixin is a way of sharing code. But the mechanics of using a mixin in nest are still relying on inheritance(`extends` keyword).\n\nWhat I am missing about mixins? How are they different from inheritance?\n\nIt seems that `class SomeClass extends SomeOtherClassThatIsntAMixin {}` achieves the same results.\n\n========================================\n\nCode:\n```text\nmixin\n```\n\n```text\n@Injectable()\n```\n\n```text\nclass SomeClass extends MixinClass {}\n```\n\n```text\nextends\n```\n\n```text\nclass SomeClass extends SomeOtherClassThatIsntAMixin {}\n```\n\n```text\nprotected name: string\n```\n\n```text\nMixinClass('someNewName')\n```\n\n```text\nname\n```\n\n```text\nAuthGuard\n```\n\n```text\nFileInterceptor\n```\n\n```text\nAuthGuard\n```\n\n```text\nPassportModule.register()\n```\n\n```text\nAuthGuard('strategy')\n```\n\n========================================\n\nComments:\n- The OP is correct with the observation, and the questions ask already show a better understanding of what a mixin should be and ever was meant to be in comparison to calling the pattern of... *\"a class-creating factory-function where the created class then gets extended\"* ...a mixin. And yes, every augmented/aggregated behavior of such a type is acquired by inheritance (introducing an *\"is a\"* relationship) and not by mixin based composition (which would result in a *\"has a\"* relationship). The OP has to live with this reality and not fight the wording but does not need to doubt her/himself\n- And yet the pattern of a factory-function which creates an ad-hoc implementation of an anonymous extended class is not a mixin. It is what it is - a class-creating factory-function. And since it always goes together with extending from such a created class, it is based from its creation to its usage on pure inheritance which might be better named *\"dynamic sub-classing\"* or *\"dynamic sub-typing\"*.\n- To an extent, I think it depends. Most Mixins in Nest have the express purpose of being used directly **or** extended (like the `AuthGuard`). For the factory-function (so long as you mean `useFactory`) you're usually not going to extend what the factory returns. Also, the factory returns an *instance* of the class while a mixin returns a *reference* to a class that still has to have `new` called on it.","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":82,"estimatedTokens":772}}854{"id":"stack-61846283","source":"stackoverflow","questionId":61846283,"title":"NestJs how to run a cron job 3 times a day at specific times","tags":["javascript","node.js","typescript","nestjs","cron-task"],"text":"Title: NestJs how to run a cron job 3 times a day at specific times\nTags: javascript, node.js, typescript, nestjs, cron-task\nSource: Stack Overflow\n\nQuestion:\nI'm building a notifications trigger method and wanted to be run 3 times per day at specific times. \n\nI have checked the documentation but didn't understand that regex code for and how to customize it as I need it!\n\nNow my method looks like this: ( it now runs evey min at second 45th for testing ) I need it for example runs at 6pm, 8pm, 11pm every day\n\n```\n@Cron('45 * * * * *')\nasync sendNotificaiotns() {\n console.log('sending notification');\n\n try {\n const randomArticle = await this.articleRepository\n .createQueryBuilder()\n // .select(\"id\")\n // .getMany();\n // .select(\"id\")\n .orderBy(\"RAND()\")\n .limit(1)\n .getOne();\n\n const input = new NotificationBySegmentBuilder()\n .setIncludedSegments(['Active Users', 'Inactive Users'])\n .notification() // .email()\n .setAttachments({\n data: {\n ...randomArticle,\n },\n big_picture: encodeURI(randomArticle.image)\n })\n .setHeadings({ 'en': randomArticle.title })\n .setContents({'en': randomArticle.excerpt })\n .build();\n\n console.log(randomArticle);\n await this.oneSignalService.createNotification(input);\n\n } catch (e) {\n console.log(e);\n }\n}\n```\n\n========================================\n\nTop Answer:\nPlease change your cron to the given below:\n\n```\n@Cron('0 0 18,20,23 * * *')\n```\n\nAbove given cron will run your function on every day at 6pm, 8pm and 11pm.\n\n========================================\n\nCode:\n```js\n@Cron('45 * * * * *')\nasync sendNotificaiotns() {\n    console.log('sending notification');\n\n    try {\n        const randomArticle = await this.articleRepository\n            .createQueryBuilder()\n            // .select(\"id\")\n            // .getMany();\n            // .select(\"id\")\n            .orderBy(\"RAND()\")\n            .limit(1)\n            .getOne();\n\n        const input = new NotificationBySegmentBuilder()\n            .setIncludedSegments(['Active Users', 'Inactive Users'])\n            .notification() // .email()\n            .setAttachments({\n                data: {\n                    ...randomArticle,\n                },\n                big_picture: encodeURI(randomArticle.image)\n            })\n            .setHeadings({ 'en': randomArticle.title })\n            .setContents({'en': randomArticle.excerpt })\n            .build();\n\n        console.log(randomArticle);\n        await this.oneSignalService.createNotification(input);\n\n    } catch (e) {\n        console.log(e);\n    }\n}\n```\n\n```text\nvar cron = require('node-cron');\n\ncron.schedule('0 18,20,23 * * *', () => {\n   console.log('Runing a job at 6pm,8pm and 11pm at America/Sao_Paulo timezone');\n }, {\n   scheduled: true,\n   timezone: \"America/Sao_Paulo\"\n });\n```\n\n```text\n0 18,20,23 * * *\n```\n\n```text\n@Cron('0 0 18,20,23 * * *')\n```\n\n========================================\n\nComments:\n- how do you specify timezone in annotation ?\n- @SmitThakkar like this `@Cron(CronExpression.EVERY_HOUR, { timeZone: 'Europe&#47;Paris' })`, check docs for `@Cron` options docs.nestjs.com/techniques/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":123,"estimatedTokens":771}}855{"id":"stack-71358644","source":"stackoverflow","questionId":71358644,"title":"NX NestJs - Unexpected error: Error: Unable to load hasher for task \"api:serve\"","tags":["nestjs","nomachine-nx"],"text":"Title: NX NestJs - Unexpected error: Error: Unable to load hasher for task \"api:serve\"\nTags: nestjs, nomachine-nx\nSource: Stack Overflow\n\nQuestion:\ni have been trying to these guide to learn NX, but i encounter this problem when i tried to serve the nestJs api\nyou can see the complete code on this repo\n\n```\nnx serve api\n```\n\ni get these error\n\n```\nError: Unable to resolve @nrwl/node:execute.\nCannot find executor 'execute' in /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/node/executors.json.\nat Workspaces.readExecutor (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/tao/src/shared/workspace.js:92:19)\nat getExecutorForTask (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/utils.js:135:22)\nat getCustomHasher (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/utils.js:140:25)\nat TasksSchedule. (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:114:62)\nat Generator.next ()\nat /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:117:75\nat new Promise ()\nat __awaiter (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:113:16)\nat TasksSchedule.hashTask (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:113:38)\nat TasksSchedule. (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:58:24)\n\nUnexpected error:\nError: Unable to load hasher for task \"api:serve\"\nat getCustomHasher (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/utils.js:145:15)\nat TasksSchedule. (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:114:62)\nat Generator.next ()\nat /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:117:75\nat new Promise ()\nat __awaiter (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:113:16)\nat TasksSchedule.hashTask (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:113:38)\nat TasksSchedule. (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:58:24)\nat Generator.next ()\nat /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:117:75\n```\n\ni the guide literally 1 to 1, same name and everything.\nso i suppose the problem is with my local machine (?) i running macOS 12.2.1 with M1 chip. or maybe these guide using some old version of nx (?) and something changed on the mean time?\n\nso if anyone can give me a clue on this, would be very appreciated. thanks\n\nedit :\n\ni've try to the official Nest with NX demo from their website.\nand still got the same error when i try to `nx serve api`\n\n========================================\n\nCode:\n```text\nnx serve api\n```\n\n```text\nError: Unable to resolve @nrwl/node:execute.\nCannot find executor 'execute' in /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/node/executors.json.\nat Workspaces.readExecutor (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/tao/src/shared/workspace.js:92:19)\nat getExecutorForTask (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/utils.js:135:22)\nat getCustomHasher (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/utils.js:140:25)\nat TasksSchedule.<anonymous> (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:114:62)\nat Generator.next (<anonymous>)\nat /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:117:75\nat new Promise (<anonymous>)\nat __awaiter (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:113:16)\nat TasksSchedule.hashTask (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:113:38)\nat TasksSchedule.<anonymous> (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:58:24)\n\nUnexpected error:\nError: Unable to load hasher for task \"api:serve\"\nat getCustomHasher (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/utils.js:145:15)\nat TasksSchedule.<anonymous> (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:114:62)\nat Generator.next (<anonymous>)\nat /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:117:75\nat new Promise (<anonymous>)\nat __awaiter (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:113:16)\nat TasksSchedule.hashTask (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:113:38)\nat TasksSchedule.<anonymous> (/Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/@nrwl/workspace/src/tasks-runner/tasks-schedule.js:58:24)\nat Generator.next (<anonymous>)\nat /Users/dariantvirgiesiswadie/Documents/pribadi/shirt-shop/node_modules/tslib/tslib.js:117:75\n```\n\n```text\nnx serve api\n```\n\n```text\n\"executor\": \"@nrwl/node:execute\" -> \"executor\": \"@nrwl/node:node\"\n\"executor\": \"@nrwl/node:build\" -> \"executor\": \"@nrwl/node:webpack\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.473Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":95,"estimatedTokens":1452}}856{"id":"stack-69591631","source":"stackoverflow","questionId":69591631,"title":"NestJS-Prisma, How to write a DTO that matches the prisma one to many type","tags":["typescript","nestjs","prisma"],"text":"Title: NestJS-Prisma, How to write a DTO that matches the prisma one to many type\nTags: typescript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS and Prisma. I'm trying to write an API for the corresponding prisma model.\n\nHere is my prisma model:\n\n```\nmodel orderable_test {\n id Int @id @unique @default(autoincrement())\n test_name String\n test_id Int\n price Int\n is_orderable Boolean\n is_active Boolean\n orderable_bundle orderable_bundle? @relation(fields: [orderable_bundleId], references: [id])\n orderable_bundleId Int?\n }\n \n model orderable_bundle {\n id Int @id @unique @default(autoincrement())\n bundle_name String\n bundle_id Int\n price Int\n is_orderable Boolean\n is_active Boolean\n orderable_tests orderable_test[]\n }\n```\n\nFor the orderable_test, my DTO works well, the DTO for orderable_test is:\n\n```\nclass OrderableTestDTO {\n\n @ApiProperty()\n test_name: string;\n @ApiProperty()\n test_id: number;\n @ApiProperty()\n price: number;\n @ApiProperty()\n is_orderable: boolean;\n @ApiProperty()\n is_active: boolean;\n @ApiPropertyOptional({default: null})\n orderable_bundleId:number|null;\n}\n```\n\nFor the orderable_bundle DTO, I have\n\n```\nclass OrderableBundleDTO {\n @ApiProperty()\n bundle_name: string;\n @ApiProperty()\n bundle_id: number;\n @ApiProperty()\n price: number;\n @ApiProperty()\n is_orderable: boolean;\n @ApiProperty()\n is_active: boolean;\n @ApiPropertyOptional({type: () => OrderableTestDTO})\n orderable_tests: OrderableTestDTO | null\n}\n```\n\nBased on the Prisma Official Document: I will need my DTO to be like\n\n```\nconst createBundle = await prisma.bundle.create({\n data: {\n bundle_name: 'Bob',\n bundle_id: 1\n ............\n orderable_tests: {\n create: [\n {\n id: 'String',\n test_name: 'String',\n test_id: 1,\n price: 0\n .....\n },\n ],\n },\n },\n})\n```\n\nBut currently, my DTO will be look like this: missing the `create:`\n\n```\nconst createBundle = await prisma.bundle.create({\n data: {\n bundle_name: 'Bob',\n bundle_id: 1\n ............\n orderable_tests: \n {\n id: 'String',\n test_name: 'String',\n test_id: 1,\n price: 0\n .....\n },\n\n },\n },\n})\n```\n\nAnd for the auto generated Prisma type: It looks like:\n\n```\nexport type orderable_bundleCreateInput = {\n bundle_name: string\n bundle_id: number\n price: number\n is_orderable: boolean\n is_active: boolean\n orderable_tests?: orderable_testCreateNestedManyWithoutOrderable_bundleInput\n }\n\n export type orderable_testCreateNestedManyWithoutOrderable_bundleInput = {\n create?: XOR, Enumerable>\n connectOrCreate?: Enumerable\n createMany?: orderable_testCreateManyOrderable_bundleInputEnvelope\n connect?: Enumerable\n }\n```\n\nI'm really new into type script and prisma, is it possible to have a DTO that looks exactly to the auto genenated prisma type, if not, how can I add the create: before my inner orderable_test under the orderable_bundle DTO. Thanks for viewing my question!\n\n========================================\n\nCode:\n```text\nmodel orderable_test {\n      id                 Int               @id @unique @default(autoincrement())\n      test_name          String\n      test_id            Int\n      price              Int\n      is_orderable       Boolean\n      is_active          Boolean\n      orderable_bundle   orderable_bundle? @relation(fields: [orderable_bundleId], references: [id])\n      orderable_bundleId Int?\n    }\n    \n    model orderable_bundle {\n      id              Int              @id @unique @default(autoincrement())\n      bundle_name     String\n      bundle_id       Int\n      price           Int\n      is_orderable    Boolean\n      is_active       Boolean\n      orderable_tests orderable_test[]\n    }\n```\n\n```text\nclass OrderableTestDTO {\n\n    @ApiProperty()\n    test_name: string;\n    @ApiProperty()\n    test_id: number;\n    @ApiProperty()\n    price: number;\n    @ApiProperty()\n    is_orderable: boolean;\n    @ApiProperty()\n    is_active: boolean;\n    @ApiPropertyOptional({default: null})\n    orderable_bundleId:number|null;\n}\n```\n\n```text\nclass OrderableBundleDTO {\n    @ApiProperty()\n    bundle_name: string;\n    @ApiProperty()\n    bundle_id: number;\n    @ApiProperty()\n    price: number;\n    @ApiProperty()\n    is_orderable: boolean;\n    @ApiProperty()\n    is_active: boolean;\n    @ApiPropertyOptional({type: () => OrderableTestDTO})\n    orderable_tests: OrderableTestDTO | null\n}\n```\n\n```text\nconst createBundle = await prisma.bundle.create({\n  data: {\n    bundle_name: 'Bob',\n    bundle_id: 1\n    ............\n    orderable_tests: {\n      create: [\n        {\n          id: 'String',\n          test_name: 'String',\n          test_id: 1,\n      price: 0\n          .....\n        },\n      ],\n    },\n  },\n})\n```\n\n```text\nconst createBundle = await prisma.bundle.create({\n  data: {\n    bundle_name: 'Bob',\n    bundle_id: 1\n    ............\n    orderable_tests: \n        {\n          id: 'String',\n          test_name: 'String',\n          test_id: 1,\n      price: 0\n          .....\n        },\n\n    },\n  },\n})\n```\n\n```text\nexport type orderable_bundleCreateInput = {\n    bundle_name: string\n    bundle_id: number\n    price: number\n    is_orderable: boolean\n    is_active: boolean\n    orderable_tests?: orderable_testCreateNestedManyWithoutOrderable_bundleInput\n  }\n\n  export type orderable_testCreateNestedManyWithoutOrderable_bundleInput = {\n    create?: XOR<Enumerable<orderable_testCreateWithoutOrderable_bundleInput>, Enumerable<orderable_testUncheckedCreateWithoutOrderable_bundleInput>>\n    connectOrCreate?: Enumerable<orderable_testCreateOrConnectWithoutOrderable_bundleInput>\n    createMany?: orderable_testCreateManyOrderable_bundleInputEnvelope\n    connect?: Enumerable<orderable_testWhereUniqueInput>\n  }\n```\n\n```text\ncreate:\n```\n\n```text\nexport type orderable_bundleUncheckedCreateInput = {\n    id?: number\n    bundle_name: string\n    bundle_id: number\n    price: number\n    is_orderable: boolean\n    is_active: boolean\n    order_infoId?: number | null\n    orderable_tests?: orderable_testUncheckedCreateNestedManyWithoutOrderable_bundleInput\n  }\n\n  export type orderable_testUncheckedCreateNestedManyWithoutOrderable_bundleInput = {\n    create?: XOR<Enumerable<orderable_testCreateWithoutOrderable_bundleInput>, Enumerable<orderable_testUncheckedCreateWithoutOrderable_bundleInput>>\n    connectOrCreate?: Enumerable<orderable_testCreateOrConnectWithoutOrderable_bundleInput>\n    createMany?: orderable_testCreateManyOrderable_bundleInputEnvelope\n    connect?: Enumerable<orderable_testWhereUniqueInput>\n  }\n\n  export type orderable_testCreateWithoutOrderable_bundleInput = {\n    test_name: string\n    test_id: number\n    price: number\n    is_orderable: boolean\n    is_active: boolean\n  }\n  .........\n```\n\n```text\nimport {ApiExtraModels,ApiProperty} from '@nestjs/swagger'\nimport {CreateOrderInfoDto} from './create-orderInfo.dto'\nimport {ConnectOrderInfoDto} from './connect-orderInfo.dto'\n\nexport class CreateOrderableBundleOrderInfoRelationInputDto {\ncreate?: CreateOrderInfoDto;\nconnect?: ConnectOrderInfoDto;\n}\n\n@ApiExtraModels(CreateOrderInfoDto,ConnectOrderInfoDto,CreateOrderableBundleOrderInfoRelationInputDto)\nexport class CreateOrderableBundleDto {\n@ApiProperty()\nbundle_name: string;\n@ApiProperty()\nbundle_id: number;\n@ApiProperty()\nprice: number;\n@ApiProperty()\nis_orderable: boolean;\n@ApiProperty()\nis_active: boolean;\n@ApiProperty()\norder_info: CreateOrderableBundleOrderInfoRelationInputDto;\n}\n\nexport class CreateOrderInfoDto {\nsample_id: number;\nsample_barcode: number;\n}\n\n  export class ConnectOrderInfoDto {\nid?: number;\nsample_id?: number;\nsample_barcode?: number;\n  }\n```\n\n========================================\n\nComments:\n- I think you copy-pasted the wrong information in some of the code snippets. Could you take a look (You posted both your schema and the create query twice). Your problem isn't super clear to me, could you try and clarify a bit better? Why can't you just use the auto-generated prisma types?\n- Thanks for the comment, I just post my DTO (previously, I mistakenly post the model as the dto). My question is whether it's possible to create a DTO class just like those auto generated types which can automatically turn to create,connect,connectORCreate depends on the logic. I would like to use DTO other than those automatically generated types because in DTO, I can apply pipe, validator or guards to it which is more flexible.\n- Hey sorry for the late reply, I was a bit busy yesterday. I took a look at your solution. Here's a library that might also work: github.com/tpdewolf/prisma-nestjs-dto-generator if you don't want to generate the DTOs by hand. (I can't comment on how well maintained this will be moving forward though :/ )\n- @TasinIshmam Thanks for sharing this package. It seems very helpful. I was confused at the start because NestJS official website does not tell how to write a DTO that can fit the relational model well and I cant not find any article or documents about this part. Most of NestJS- Prisma tutorial articles are just simple relation or no relation models.\n- Happy to help ๐Ÿ˜ƒ","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":337,"estimatedTokens":2238}}857{"id":"stack-74529773","source":"stackoverflow","questionId":74529773,"title":"How to create a shared package in a Turborepo (monorepo), for prisma generated models and types?","tags":["nestjs","prisma","monorepo","yarn-workspaces","turborepo"],"text":"Title: How to create a shared package in a Turborepo (monorepo), for prisma generated models and types?\nTags: nestjs, prisma, monorepo, yarn-workspaces, turborepo\nSource: Stack Overflow\n\nQuestion:\nI am creating a monorepo using Turborepo consisting of multiple Nestjs microservices, and an API gateway to act as the request distributer. In each microservice, Postgres is used as a database and Prisma as the ORM. Each microservice has its own schema + Prisma client, so it's not a shared schema/client.\n\nWe are looking to create a shared package for things like DTOs, as well as prisma generated types and entities. The package would be shared among all microservices so if I would export the prisma generated from the microservices to the package, a cyclic dependency occurs.\n\nI am new to monorepos so this is a complex topic for me to begin with, but I am hoping someone here on Stackoverflow may have some input on the matter. Appreciate it!\n\n========================================\n\nTop Answer:\nSolution i have found is to change the default dev script from nest to ts-node.\n\nWhat i have done for constant monitoring and restarting is to use devscript as nodemon to constant tracking of file changes.\n\nthen in nodemon.json (nodemon config file) using ts-node command to run the script.\n\n```\n//package.json file\n\"dev\": \"nodemon\"\n\n//nodemon.json file\n\n{\n \"watch\": [\"src\"],\n \"ext\": \"js,ts,json\",\n \"exec\": \"ts-node src/main.ts\"\n }\n```\n\n========================================\n\nCode:\n```js\n// turbo.json\n{\n  \"$schema\": \"https://turborepo.org/schema.json\",\n  \"pipeline\": {\n    \"build\": {\n      \"dependsOn\": [\n        \"^build\",\n        \"extraBuildScriptFromPackages\",\n        \"//#extraGlobalBuildScript\"\n      ],\n// ...\n    }\n  }\n}\n```\n\n```text\n//#\n```\n\n```text\n//package.json file\n\"dev\": \"nodemon\"\n\n//nodemon.json file\n\n\n{\n   \"watch\": [\"src\"],\n   \"ext\": \"js,ts,json\",\n   \"exec\": \"ts-node src/main.ts\"\n }\n```\n\n========================================\n\nComments:\n- I wasn't able to find an exact resource which demonstrates using Turborepo with prisma in a monorepo. Have you seen this example of using Prisma with Turborepo? github.com/vercel/turbo/tree/main/examples/with-prisma\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":76,"estimatedTokens":615}}858{"id":"stack-58268584","source":"stackoverflow","questionId":58268584,"title":"Serving public and private ports using Nestjs","tags":["express","nestjs"],"text":"Title: Serving public and private ports using Nestjs\nTags: express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm building a that aims to serve a mobile application. Besides serving the client, it will have several back-office functionalities.\n\nWe are using swagger and we do want to be able to access the swagger docs of our back-office endpoints. However, we do not want to expose all of our endpoints publicly. \n\nAssuming that having all endpoints public is a bad option one solutions we are thinking of is letting our server serve two ports, and then only exposing one port to the public. We have created a small sample repo that that serves a client module and a back-office module on two different ports.\n\nThe `main.ts` looks like the following:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { ClientModule } from './modules/client/client.module';\nimport * as express from 'express';\nimport * as http from 'http';\nimport {ExpressAdapter} from '@nestjs/platform-express';\nimport { BackOfficeModule } from './modules/backoffice/backoffice.module';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\n\nasync function bootstrap() {\n\n const clientServer = express();\n const clientApp = await NestFactory.create(\n ClientModule,\n new ExpressAdapter(clientServer),\n );\n const clientOptions = new DocumentBuilder()\n .setTitle('ClientServer')\n .setDescription('The client server API description')\n .setVersion('1.0')\n .addTag('client')\n .build();\n const clientDocument = SwaggerModule.createDocument(clientApp, clientOptions);\n SwaggerModule.setup('api', clientApp, clientDocument);\n await clientApp.init();\n\n const backOfficeServer = express();\n const backOfficeApp = await NestFactory.create(\n BackOfficeModule,\n new ExpressAdapter(backOfficeServer),\n );\n\n const backOfficeOptions = new DocumentBuilder()\n .setTitle('BackOffice')\n .setDescription('The back office API description')\n .setVersion('1.0')\n .addTag('backOffice')\n .build();\n const backOfficeDocument = SwaggerModule.createDocument(backOfficeApp, backOfficeOptions);\n SwaggerModule.setup('api', backOfficeApp, backOfficeDocument);\n await backOfficeApp.init();\n\n http.createServer(clientServer).listen(3000); // The public port (Load balancer will route traffic to this port)\n http.createServer(backOfficeServer).listen(4000); // The private port (Will be accessed through a bastian host or similar)\n}\nbootstrap();\n```\n\nAnother option would be to create a bigger separation of the codebase and infrastructure, however as this is a very early stage we feel that is unnecessary.\n\nOur question to the Nest community is thus, has anyone done this? If so, what is are your experience? What are the drawbacks to separating our backend code like this?\n\n========================================\n\nTop Answer:\nDisclaimer: this solution is for express+REST combination.\n\n### Routing\n\nEven thought nestjs can't separate controller's based on port, it can separate them based on host. Using that, you can add a reverse proxy in front of your application, that modifies the host header based on the port. Or, you can do that in an express middleware, to make things even more simpe. This is what I did:\n\n```\nasync function bootstrap() {\n const publicPort = 3000\n const privatePort = 4000\n\n const server = express()\n server.use((req, res, next) => {\n // act as a proper reverse proxy and set X-Forwarded-Host header if it hasn't been set\n req.headers['x-forwarded-host'] ??= req.headers.host\n switch (req.socket.localPort) {\n case publicPort:\n req.headers.host = 'public'\n break\n case privatePort:\n req.headers.host = 'private'\n break\n default:\n // this shouldn't be possible\n res.sendStatus(500)\n return\n }\n\n next()\n })\n\n const app = await NestFactory.create(AppModule, new ExpressAdapter(server))\n\n http.createServer(server).listen(publicPort)\n http.createServer(server).listen(privatePort)\n}\n```\n\nControllers:\n\n```\n@Controller({ path: 'cats', host: 'public' })\nexport class CatsController {...}\n\n@Controller({ path: 'internal' host: 'private' })\nexport class InternalController {...}\n```\n\nAlternatively, you can simplify by creating your own PublicController and PrivateController decorators:\n\n```\n// decorator for public controllers, also sets guard\nexport const PublicController = (path?: string): ClassDecorator => {\n return applyDecorators(Controller({ path, host: 'public' }), UseGuards(JwtAuthGuard))\n}\n\n// decorator for private controllers\nexport const PrivateController = (path?: string): ClassDecorator => {\n return applyDecorators(Controller({ path, host: 'private' }))\n}\n\n@PublicController('cats')\nexport class CatsController {...}\n\n@PrivateController('internal')\nexport class InternalController {...}\n```\n\n### Swagger\n\nFor swagger, SwaggerModule.createDocument has an option \"include\", which accepts a list of modules to include in the swagger docs. With a bit of effort we can also turn the swagger serving part into an express Router, so both the private and public swagger can be served on the same path, for the different ports:\n\n```\nasync function bootstrap() {\n const publicPort = 3000\n const privatePort = 4000\n\n const server = express()\n server.use((req, res, next) => {\n // act as a proper reverse proxy and set X-Forwarded-Host header if it hasn't been set\n req.headers['x-forwarded-host'] ??= req.headers.host\n switch (req.socket.localPort) {\n case publicPort:\n req.headers.host = 'public'\n break\n case privatePort:\n req.headers.host = 'private'\n break\n default:\n // this shouldn't be possible\n res.sendStatus(500)\n return\n }\n\n next()\n })\n\n const app = await NestFactory.create(AppModule, new ExpressAdapter(server))\n\n // setup swagger\n let publicSwaggerRouter = await createSwaggerRouter(app, [CatsModule])\n let privateSwaggerRouter: await createSwaggerRouter(app, [InternalModule])\n server.use('/api', (req: Request, res: Response, next: NextFunction) => {\n switch (req.headers.host) {\n case 'public':\n publicSwaggerRouter(req, res, next)\n return\n case 'private':\n privateSwaggerRouter(req, res, next)\n return\n default:\n // this shouldn't be possible\n res.sendStatus(500)\n return\n }\n })\n\n http.createServer(server).listen(publicPort)\n http.createServer(server).listen(privatePort)\n}\n\nasync function createSwaggerRouter(app: INestApplication, modules: Function[]): Promise {\n const swaggerConfig = new DocumentBuilder().setTitle('MyApp').setVersion('1.0').build()\n\n const document = SwaggerModule.createDocument(app, swaggerConfig, { include: modules })\n\n const swaggerUi = loadPackage('swagger-ui-express', 'SwaggerModule', () => require('swagger-ui-express'))\n\n const swaggerHtml = swaggerUi.generateHTML(document)\n const router = Router()\n .use(swaggerUi.serveFiles(document))\n .get('/', (req: Request, res: Response, next: NextFunction) => {\n res.send(swaggerHtml)\n })\n\n return router\n}\n```\n\n========================================\n\nCode:\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { ClientModule } from './modules/client/client.module';\nimport * as express from 'express';\nimport * as http from 'http';\nimport {ExpressAdapter} from '@nestjs/platform-express';\nimport { BackOfficeModule } from './modules/backoffice/backoffice.module';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\n\nasync function bootstrap() {\n\n  const clientServer = express();\n  const clientApp = await NestFactory.create(\n    ClientModule,\n    new ExpressAdapter(clientServer),\n  );\n  const clientOptions = new DocumentBuilder()\n    .setTitle('ClientServer')\n    .setDescription('The client server API description')\n    .setVersion('1.0')\n    .addTag('client')\n    .build();\n  const clientDocument = SwaggerModule.createDocument(clientApp, clientOptions);\n  SwaggerModule.setup('api', clientApp, clientDocument);\n  await clientApp.init();\n\n  const backOfficeServer = express();\n  const backOfficeApp = await NestFactory.create(\n    BackOfficeModule,\n    new ExpressAdapter(backOfficeServer),\n  );\n\n  const backOfficeOptions = new DocumentBuilder()\n    .setTitle('BackOffice')\n    .setDescription('The back office API description')\n    .setVersion('1.0')\n    .addTag('backOffice')\n    .build();\n  const backOfficeDocument = SwaggerModule.createDocument(backOfficeApp, backOfficeOptions);\n  SwaggerModule.setup('api', backOfficeApp, backOfficeDocument);\n  await backOfficeApp.init();\n\n  http.createServer(clientServer).listen(3000); // The public port (Load balancer will route traffic to this port)\n  http.createServer(backOfficeServer).listen(4000); // The private port (Will be accessed through a bastian host or similar)\n}\nbootstrap();\n```\n\n```text\nmain.ts\n```\n\n```text\nmain-client.ts\n```\n\n```text\nmain-back-office.ts\n```\n\n```text\nDocker\n```\n\n```text\nDocker\n```\n\n```text\nDockerfile\n```\n\n```text\nCMD\n```\n\n```text\nENTRYPOINT\n```\n\n```text\nconst httpsOptions = {\n    key: fs.readFileSync('./secrets/private-key.pem'),\n    cert: fs.readFileSync('./secrets/public-certificate.pem'),\n};\n\nconst server = express();\nconst app = await NestFactory.create(\n    ApplicationModule,\n    new ExpressAdapter(server),\n);\nawait app.init();\n\nhttp.createServer(server).listen(3000);\nhttps.createServer(httpsOptions, server).listen(443);\n```\n\n```text\nasync function bootstrap() {\n  const publicPort = 3000\n  const privatePort = 4000\n\n  const server = express()\n  server.use((req, res, next) => {\n    // act as a proper reverse proxy and set X-Forwarded-Host header if it hasn't been set\n    req.headers['x-forwarded-host'] ??= req.headers.host\n    switch (req.socket.localPort) {\n      case publicPort:\n        req.headers.host = 'public'\n        break\n      case privatePort:\n        req.headers.host = 'private'\n        break\n      default:\n        // this shouldn't be possible\n        res.sendStatus(500)\n        return\n    }\n\n    next()\n  })\n\n  const app = await NestFactory.create(AppModule, new ExpressAdapter(server))\n\n  http.createServer(server).listen(publicPort)\n  http.createServer(server).listen(privatePort)\n}\n```\n\n```text\n@Controller({ path: 'cats', host: 'public' })\nexport class CatsController {...}\n\n\n@Controller({ path: 'internal' host: 'private' })\nexport class InternalController {...}\n```\n\n```text\n// decorator for public controllers, also sets guard\nexport const PublicController = (path?: string): ClassDecorator => {\n  return applyDecorators(Controller({ path, host: 'public' }), UseGuards(JwtAuthGuard))\n}\n\n// decorator for private controllers\nexport const PrivateController = (path?: string): ClassDecorator => {\n  return applyDecorators(Controller({ path, host: 'private' }))\n}\n\n\n@PublicController('cats')\nexport class CatsController {...}\n\n\n@PrivateController('internal')\nexport class InternalController {...}\n```\n\n```text\nasync function bootstrap() {\n  const publicPort = 3000\n  const privatePort = 4000\n\n  const server = express()\n  server.use((req, res, next) => {\n    // act as a proper reverse proxy and set X-Forwarded-Host header if it hasn't been set\n    req.headers['x-forwarded-host'] ??= req.headers.host\n    switch (req.socket.localPort) {\n      case publicPort:\n        req.headers.host = 'public'\n        break\n      case privatePort:\n        req.headers.host = 'private'\n        break\n      default:\n        // this shouldn't be possible\n        res.sendStatus(500)\n        return\n    }\n\n    next()\n  })\n\n  const app = await NestFactory.create(AppModule, new ExpressAdapter(server))\n\n  // setup swagger\n  let publicSwaggerRouter = await createSwaggerRouter(app, [CatsModule])\n  let privateSwaggerRouter: await createSwaggerRouter(app, [InternalModule])\n  server.use('/api', (req: Request, res: Response, next: NextFunction) => {\n    switch (req.headers.host) {\n      case 'public':\n        publicSwaggerRouter(req, res, next)\n        return\n      case 'private':\n        privateSwaggerRouter(req, res, next)\n        return\n      default:\n        // this shouldn't be possible\n        res.sendStatus(500)\n        return\n    }\n  })\n\n  http.createServer(server).listen(publicPort)\n  http.createServer(server).listen(privatePort)\n}\n\nasync function createSwaggerRouter(app: INestApplication, modules: Function[]): Promise<Router> {\n  const swaggerConfig = new DocumentBuilder().setTitle('MyApp').setVersion('1.0').build()\n\n  const document = SwaggerModule.createDocument(app, swaggerConfig, { include: modules })\n\n  const swaggerUi = loadPackage('swagger-ui-express', 'SwaggerModule', () => require('swagger-ui-express'))\n\n  const swaggerHtml = swaggerUi.generateHTML(document)\n  const router = Router()\n    .use(swaggerUi.serveFiles(document))\n    .get('/', (req: Request, res: Response, next: NextFunction) => {\n      res.send(swaggerHtml)\n    })\n\n  return router\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":434,"estimatedTokens":3149}}859{"id":"stack-65420130","source":"stackoverflow","questionId":65420130,"title":"How to extend more than one dto class in Nestjs","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: How to extend more than one dto class in Nestjs\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am new to `nest.js` and have a question about it.\n\nI want to extend more than one `Dto` to my main `dto` class, but I know it is not possible to extend more than 2 `dto` classes. Do you have any idea how to do it ?\n\nHere is my main `dto` class:\n\n```\nexport class CarDto extends PickupLocationDto {\n @ApiProperty({ example: 'Aventador', description: 'The car name' })\n readonly modelName: string;\n}\n```\n\nRecently I am only able to extend it from `PickupLocationDto` class, but I want to extend one more `dto` class to this `CarDto` class.\n\nAny help is appreciated.\n\n========================================\n\nTop Answer:\nYou can use `mapped-types` to do that, first you will need to install the package (`yarn add @nestjs/mapped-types`) then use `IntersectionType` just like this:\n\n```\nimport { IntersectionType } from '@nestjs/mapped-types';\n\nexport class Dto3 extends IntersectionType(\n Dto1,\n Dto2,\n) {}\n```\n\n========================================\n\nCode:\n```js\nexport class CarDto extends PickupLocationDto {\n  @ApiProperty({ example: 'Aventador', description: 'The car name' })\n  readonly modelName: string;\n}\n```\n\n```text\nnest.js\n```\n\n```text\nDto\n```\n\n```text\ndto\n```\n\n```text\ndto\n```\n\n```text\ndto\n```\n\n```text\nPickupLocationDto\n```\n\n```text\ndto\n```\n\n```text\nCarDto\n```\n\n```text\nimport { ApiProperty, IntersectionType } from '@nestjs/swagger';\n\nexport class Dto3 extends IntersectionType(\n  Dto1,\n  Dto2,\n) {}\n```\n\n```text\n@nestjs/mapped-types\n```\n\n```js\nimport { IntersectionType } from '@nestjs/mapped-types';\n\nexport class Dto3 extends IntersectionType(\n  Dto1,\n  Dto2,\n) {}\n```\n\n```text\nmapped-types\n```\n\n```text\nyarn add @nestjs/mapped-types\n```\n\n```text\nIntersectionType\n```\n\n```text\nexport class Dto3 extends Dto1 {\n      public readonly dtoField: Dto2;\n    }\n```\n\n========================================\n\nComments:\n- do remember `ValidationPipe` will not work with the entended classes properties.","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":122,"estimatedTokens":512}}860{"id":"stack-51418222","source":"stackoverflow","questionId":51418222,"title":"Nest can't resolve dependencies of the AuthGuard (Guard decorator)","tags":["node.js","typescript","nestjs"],"text":"Title: Nest can't resolve dependencies of the AuthGuard (Guard decorator)\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've a AuthGuard who check the JWT token in controllers. I want use this Guard in controllers to check authentication. I've this error:\n\n Nest can't resolve dependencies of the AuthGuard (?, +). Please make sure that the argument at index [0] is available in the current context.\n\n### TestController.ts\n\n```\nimport {\n Controller,\n Post,\n Body,\n HttpCode,\n HttpStatus,\n UseInterceptors,\n UseGuards,\n} from \"@nestjs/common\";\nimport { TestService } from \"Services/TestService\";\nimport { CreateTestDto } from \"Dtos/CreateTestDto\";\nimport { ApiConsumes, ApiProduces } from \"@nestjs/swagger\";\nimport { AuthGuard } from \"Guards/AuthGuard\";\n\n@Controller(\"/tests\")\n@UseGuards(AuthGuard)\nexport class TestController {\n constructor(\n private readonly testService: TestService,\n ) {}\n\n @Post(\"/create\")\n @HttpCode(HttpStatus.OK)\n @ApiConsumes(\"application/json\")\n @ApiProduces(\"application/json\")\n async create(@Body() createTestDto: CreateTestDto): Promise {\n // this.testService.blabla();\n }\n}\n```\n\n### AuthGuard.ts\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from \"@nestjs/common\";\nimport { AuthService } from \"Services/AuthService\";\nimport { UserService } from \"Services/UserService\";\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n constructor(\n private readonly authService: AuthService,\n private readonly userService: UserService,\n ) {}\n\n async canActivate(dataOrRequest, context: ExecutionContext): Promise {\n try {\n // code is here\n return true;\n } catch (e) {\n return false;\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport {\n  Controller,\n  Post,\n  Body,\n  HttpCode,\n  HttpStatus,\n  UseInterceptors,\n  UseGuards,\n} from \"@nestjs/common\";\nimport { TestService } from \"Services/TestService\";\nimport { CreateTestDto } from \"Dtos/CreateTestDto\";\nimport { ApiConsumes, ApiProduces } from \"@nestjs/swagger\";\nimport { AuthGuard } from \"Guards/AuthGuard\";\n\n@Controller(\"/tests\")\n@UseGuards(AuthGuard)\nexport class TestController {\n  constructor(\n    private readonly testService: TestService,\n  ) {}\n\n  @Post(\"/create\")\n  @HttpCode(HttpStatus.OK)\n  @ApiConsumes(\"application/json\")\n  @ApiProduces(\"application/json\")\n  async create(@Body() createTestDto: CreateTestDto): Promise<void> {\n    // this.testService.blabla();\n  }\n}\n```\n\n```text\nimport { CanActivate, ExecutionContext, Injectable } from \"@nestjs/common\";\nimport { AuthService } from \"Services/AuthService\";\nimport { UserService } from \"Services/UserService\";\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n    constructor(\n        private readonly authService: AuthService,\n        private readonly userService: UserService,\n    ) {}\n\n    async canActivate(dataOrRequest, context: ExecutionContext): Promise<boolean> {\n        try {\n            // code is here\n            return true;\n        } catch (e) {\n            return false;\n        }\n    }\n}\n```\n\n```text\n@Module({\n  controllers: [TestController],\n  providers: [AuthService, TestService, UserService],\n})\nexport class YourModule {}\n```\n\n```text\n@Module({\n  providers: [AuthService],\n  exports: [AuthService],\n})\nexport class AuthModule {}\n\n@Module({\n  imports: [AuthModule],\n  controllers: [TestController],\n  providers: [TestService, UserService],\n})\nexport class YourModule {}\n```\n\n```text\nAuthService\n```\n\n```text\nAuthService\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n========================================\n\nComments:\n- Can you include your module?\n- Importing the service directly causes a whole new instance to be created every single time, so you can end up with multiple instances throughout your app. Importing the module ensures that doesn't happen: stackoverflow.com/questions/71383271/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":170,"estimatedTokens":960}}861{"id":"stack-63047146","source":"stackoverflow","questionId":63047146,"title":"Type 'typeof Questions' is not assignable to type 'typeof Model'","tags":["nestjs","sequelize-typescript"],"text":"Title: Type 'typeof Questions' is not assignable to type 'typeof Model'\nTags: nestjs, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI am getting the error `Type 'typeof Questions' is not assignable to type 'typeof Model'.` while added the relationship in the model.\n\nquestion.model.ts\n\n```\nimport { Column, Table, PrimaryKey, Default, DataType, Model } from \"sequelize-typescript\";\n\n@Table({timestamps: true})\nexport class Questions extends Model {\n\n @PrimaryKey\n @Default(DataType.UUIDV1)\n @Column(DataType.UUID)\n id: string;\n\n @Column\n question: string;\n\n @Column({ defaultValue: true })\n isActive: boolean;\n}\n```\n\noptions.model.ts\n\n```\nimport { Column, Table, PrimaryKey, Default, DataType, ForeignKey, HasOne, Model } from \"sequelize-typescript\";\nimport { Questions } from \"./models/questions.model\";\n\n@Table({timestamps: true})\nexport class Options extends Model {\n\n @PrimaryKey\n @Default(DataType.UUIDV1)\n @Column(DataType.UUID)\n id: string;\n\n @ForeignKey(() => Questions)\n @Column\n questionsId: number;\n\n @HasOne(() => Questions)\n question: Questions;\n\n @Column({ defaultValue: false })\n isCorrectAns: boolean;\n}\n```\n\nmy user module\n\n```\nimport { SequelizeModule } from '@nestjs/sequelize';\nimport { Questions } from './models/questions.model';\nimport { Options } from './options.model';\n\n@Module({\n imports: [\n SequelizeModule.forFeature([Questions, Options])\n ],\n controllers: [UserController],\n providers: [UserService]\n})\nexport class UserModule {}\n```\n\n========================================\n\nTop Answer:\nI've had this same issue. Could resolve this by removing the type constructor (``, ``).\n\nIn my case I had a QuestionsAttributes interface and had to change:\n\n```\nclass TalentData extends Model\n```\n\nto:\n\n```\nclass TalentData extends Model implements TalentDataAttributes\n```\n\nBut this appears to be a sequelize-typescript error.\n\n========================================\n\nCode:\n```text\nimport { Column, Table, PrimaryKey, Default, DataType, Model } from \"sequelize-typescript\";\n\n@Table({timestamps: true})\nexport class Questions extends Model<Questions> {\n\n    @PrimaryKey\n    @Default(DataType.UUIDV1)\n    @Column(DataType.UUID)\n    id: string;\n\n    @Column\n    question: string;\n\n    @Column({ defaultValue: true })\n    isActive: boolean;\n}\n```\n\n```text\nimport { Column, Table, PrimaryKey, Default, DataType, ForeignKey, HasOne, Model } from \"sequelize-typescript\";\nimport { Questions } from \"./models/questions.model\";\n\n@Table({timestamps: true})\nexport class Options extends Model<Options> {\n\n    @PrimaryKey\n    @Default(DataType.UUIDV1)\n    @Column(DataType.UUID)\n    id: string;\n\n    @ForeignKey(() => Questions)\n    @Column\n    questionsId: number;\n\n    @HasOne(() => Questions)\n    question: Questions;\n\n    @Column({ defaultValue: false })\n    isCorrectAns: boolean;\n}\n```\n\n```text\nimport { SequelizeModule } from '@nestjs/sequelize';\nimport { Questions } from './models/questions.model';\nimport { Options } from './options.model';\n\n@Module({\n  imports: [\n    SequelizeModule.forFeature([Questions, Options])\n  ],\n  controllers: [UserController],\n  providers: [UserService]\n})\nexport class UserModule {}\n```\n\n```text\nType 'typeof Questions' is not assignable to type 'typeof Model'.\n```\n\n```text\nModel\n```\n\n```text\nsequelize-typescript\n```\n\n```text\nsequelize/types\n```\n\n```text\nclass TalentData extends Model<TalentData, TalentDataAttributes>\n```\n\n```text\nclass TalentData extends Model implements TalentDataAttributes\n```\n\n```text\n<Questions>\n```\n\n```text\n<Options>\n```\n\n```text\n@ForeignKey(() => Quotes)\n@Column\nquote_id: number;  \n\n@BelongsTo(() => Quotes, {onDelete: \"cascade\", foreignKey: \"quote_id\"})\nquote: Quotes;\n```\n\n========================================\n\nComments:\n- Updated the import from `sequelize-typescript`, but the issue still remains","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":196,"estimatedTokens":949}}862{"id":"stack-73960298","source":"stackoverflow","questionId":73960298,"title":"Nestjs Swagger css not loading when deployed to vercel","tags":["node.js","swagger","nestjs","swagger-ui"],"text":"Title: Nestjs Swagger css not loading when deployed to vercel\nTags: node.js, swagger, nestjs, swagger-ui\nSource: Stack Overflow\n\nQuestion:\nNestjs swagger ui not loading styles when deployed to vercel but works well locally\n\nhttps://i.sstatic.net/MxxOD.png\n\nconsole and network requests\nhttps://i.sstatic.net/3pefL.png\n\nhttps://i.sstatic.net/ohaDJ.png\n\nI added vercel.json with the following configuration and deployed to vercel.\n\n```\n{\n \"version\": 2,\n \"builds\": [\n {\n \"src\": \"src/main.ts\",\n \"use\": \"@vercel/node\"\n }\n ],\n \"routes\": [\n {\n \"src\": \"/(.*)\",\n \"dest\": \"src/main.ts\",\n \"methods\": [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]\n }\n ]\n}\n```\n\nmain.ts\n\n```\nconst swaggerConfig = new DocumentBuilder()\n .setTitle('Tansfun')\n .setDescription('API for Tansfun')\n .setVersion('1.0')\n\n .addBearerAuth(\n {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'APIKey',\n name: 'APIKey',\n description: 'Enter API Key',\n in: 'header',\n },\n 'APIKey-auth', \n )\n .build();\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const document = SwaggerModule.createDocument(app, swaggerConfig);\n app.useGlobalPipes(new ValidationPipe());\n\n SwaggerModule.setup('api', app, document);\n\n await app.listen(port);\n}\nbootstrap();\n```\n\nI used @nestjs/swagger v6\n\n========================================\n\nTop Answer:\ntry with this, set the custom js and css\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n // swagger setup\n const config = new DocumentBuilder()\n .setTitle('Backend Generator')\n .setDescription('Documentation API Test')\n .setVersion('1.0')\n .setBasePath('api/v1')\n .addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' })\n .build();\n\n const document = SwaggerModule.createDocument(app, config);\n SwaggerModule.setup('swagger', app, document, {\n customSiteTitle: 'Backend Generator',\n customfavIcon: 'https://avatars.githubusercontent.com/u/6936373?s=200&v=4',\n customJs: [\n 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-bundle.min.js',\n 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.js',\n ],\n customCssUrl: [\n 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.min.css',\n 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.css',\n 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.css',\n ],\n });\n const cors = { ...CorsConfig };\n app.enableCors(cors);\n app.useGlobalPipes(new ValidationPipe({ whitelist: true }));\n app.setGlobalPrefix('api/v1');\n useContainer(app.select(AppModule), { fallbackOnErrors: true });\n\n await app.listen(5000);\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```js\n{\n  \"version\": 2,\n  \"builds\": [\n    {\n      \"src\": \"src/main.ts\",\n      \"use\": \"@vercel/node\"\n    }\n  ],\n  \"routes\": [\n    {\n      \"src\": \"/(.*)\",\n      \"dest\": \"src/main.ts\",\n      \"methods\": [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]\n    }\n  ]\n}\n```\n\n```js\nconst swaggerConfig = new DocumentBuilder()\n  .setTitle('Tansfun')\n  .setDescription('API for Tansfun')\n  .setVersion('1.0')\n\n  .addBearerAuth(\n    {\n      type: 'http',\n      scheme: 'bearer',\n      bearerFormat: 'APIKey',\n      name: 'APIKey',\n      description: 'Enter API Key',\n      in: 'header',\n    },\n    'APIKey-auth', \n  )\n  .build();\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const document = SwaggerModule.createDocument(app, swaggerConfig);\n  app.useGlobalPipes(new ValidationPipe());\n\n  SwaggerModule.setup('api', app, document);\n\n  await app.listen(port);\n}\nbootstrap();\n```\n\n```text\nNODE_ENV=\"development\"\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ServeStaticModule } from '@nestjs/serve-static';\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    ServeStaticModule.forRoot({\n      rootPath: join(__dirname, '..', 'swagger-static'),\n      serveRoot: process.env.NODE_ENV === 'development' ? '/' : '/swagger',\n    }),\n   ],\n   controllers: [AppController],\n   providers: [AppService],\n })\n\nexport class AppModule {}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\nimport { AppModule } from './app.module';\nimport { resolve } from 'path';\nimport { writeFileSync } from 'fs';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const options = new DocumentBuilder()\n    .setTitle('Cats example')\n    .setDescription('The cats API description')\n    .setVersion('1.0')\n    .addTag('cats')\n    .build();\n  const document = SwaggerModule.createDocument(app, options);\n  SwaggerModule.setup('/swagger', app, document);\n\n  await app.listen(process.env.PORT || 3000);\n\n  // get the swagger json file (if app is running in development mode)\n  if (process.env.NODE_ENV === 'development') {\n    const pathToSwaggerStaticFolder = resolve(process.cwd(), 'swagger-static');\n\n    // write swagger json file\n    const pathToSwaggerJson = resolve(\n      pathToSwaggerStaticFolder,\n      'swagger.json',\n    );\n    const swaggerJson = JSON.stringify(document, null, 2);\n    writeFileSync(pathToSwaggerJson, swaggerJson);\n    console.log(`Swagger JSON file written to: '/swagger-static/swagger.json'`);\n  }\n}\n\nbootstrap();\n```\n\n```text\nNODE_ENV=\"development\"\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ServeStaticModule } from '@nestjs/serve-static';\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    ServeStaticModule.forRoot({\n      rootPath: join(__dirname, '..', 'swagger-static'),\n      serveRoot: process.env.NODE_ENV === 'development' ? '/' : '/swagger',\n    }),\n   ],\n   controllers: [AppController],\n   providers: [AppService],\n })\n\nexport class AppModule {}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\n import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\n import { AppModule } from './app.module';\n // core\n import { resolve } from 'path';\n import { writeFileSync, createWriteStream } from 'fs';\n import { get } from 'http';\n\n async function bootstrap() {\n   const app = await NestFactory.create(AppModule);\n\n   const options = new DocumentBuilder()\n     .setTitle('Cats example')\n     .setDescription('The cats API description')\n     .setVersion('1.0')\n     .addTag('cats')\n     .build();\n   const document = SwaggerModule.createDocument(app, options);\n   SwaggerModule.setup('/swagger', app, document);\n\n   await app.listen(process.env.PORT || 3000);\n\n   // get the swagger json file (if app is running in development mode)\n   if (process.env.NODE_ENV === 'development') {\n\n     // write swagger ui files\n     get(\n       `${serverUrl}/swagger/swagger-ui-bundle.js`, function \n       (response) {\n         response.pipe(createWriteStream('swagger-static/swagger-ui-bundle.js'));\n         console.log(\n     `Swagger UI bundle file written to: '/swagger-static/swagger-ui-bundle.js'`,\n   );\n     });\n\n     get(`${serverUrl}/swagger/swagger-ui-init.js`, function (response) {\n       response.pipe(createWriteStream('swagger-static/swagger-ui-init.js'));\n       console.log(\n     `Swagger UI init file written to: '/swagger-static/swagger-ui-init.js'`,\n   );\n     });\n\n     get(\n   `${serverUrl}/swagger/swagger-ui-standalone-preset.js`,\n   function (response) {\n       response.pipe(\n       createWriteStream('swagger-static/swagger-ui-standalone-preset.js'),\n     );\n       console.log(\n       `Swagger UI standalone preset file written to: '/swagger-static/swagger-ui-standalone-preset.js'`,\n     );\n     });\n\n     get(`${serverUrl}/swagger/swagger-ui.css`, function (response) {\n       response.pipe(createWriteStream('swagger-static/swagger-ui.css'));\n       console.log(\n     `Swagger UI css file written to: '/swagger-static/swagger-ui.css'`,\n   );\n     });\n\n   }\n }\n\n bootstrap();\n```\n\n```text\nNODE_ENV\n```\n\n```text\napp.module.ts\n```\n\n```text\nswagger.json\n```\n\n```text\nswagger.json\n```\n\n```text\nmain.ts\n```\n\n```text\nhttps://yourprojectname.vercel.app/swagger/swagger.json\n```\n\n```text\nswagger.json\n```\n\n```text\nNODE_ENV\n```\n\n```text\napp.module.ts\n```\n\n```text\nswagger-ui-bundle.js\n```\n\n```text\nswagger-ui-init.js\n```\n\n```text\nswagger-ui-standalone-preset.js\n```\n\n```text\nswagger-ui.css\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  // swagger setup\n  const config = new DocumentBuilder()\n    .setTitle('Backend Generator')\n    .setDescription('Documentation API Test')\n    .setVersion('1.0')\n    .setBasePath('api/v1')\n    .addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' })\n    .build();\n\n  const document = SwaggerModule.createDocument(app, config);\n  SwaggerModule.setup('swagger', app, document, {\n    customSiteTitle: 'Backend Generator',\n    customfavIcon: 'https://avatars.githubusercontent.com/u/6936373?s=200&v=4',\n    customJs: [\n      'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-bundle.min.js',\n      'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.js',\n    ],\n    customCssUrl: [\n      'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.min.css',\n      'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.min.css',\n      'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.css',\n    ],\n  });\n  const cors = { ...CorsConfig };\n  app.enableCors(cors);\n  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));\n  app.setGlobalPrefix('api/v1');\n  useContainer(app.select(AppModule), { fallbackOnErrors: true });\n\n  await app.listen(5000);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- Can you add screenshots of the Network and Console tabs from your browser dev tools? So we can see what the exact errors are.\n- @Helen I have added the screenshots for the console and Network\n- @Rickhomes Hi..? Did u find a solution for this issue..? I am facing the same issue as u.\n- I have to include a get request to `index.html` to get it working on vercel.","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":419,"estimatedTokens":2553}}863{"id":"stack-61269160","source":"stackoverflow","questionId":61269160,"title":"How to use bcrypt module to save encrypted password in MongoDB using NestJS","tags":["typescript","authentication","postman","nestjs","bcrypt"],"text":"Title: How to use bcrypt module to save encrypted password in MongoDB using NestJS\nTags: typescript, authentication, postman, nestjs, bcrypt\nSource: Stack Overflow\n\nQuestion:\nHow can I save an encrypted password to MongoDB?\n\nP.S. I'm a beginner developer and still learning how to use NestJS\n\n========================================\n\nCode:\n```text\n@Entity(\"YourTable\", { schema: \"yourdb\" })\nexport class YourTable {\n   ...\n   @BeforeInsert()\n   async hashPassword() {\n      this.password = await bcrypt.hash(this.password, Number(process.env.HASH_SALT));\n   }\n   ...\n}\n```\n\n========================================\n\nComments:\n- bcrypt is not an encryption algorithm, it is a hashing algorithm. You cannot use bcrypt to encrypt a password.\n- okay my first doubt is cleared.Now how can i save encrypted password into mongo db database,Which module is build for this and how do i use that module in my nest app\n- For encryption, use an encryption algorithm. But you should never store encrypted passwords.\n- And what if I am using mongoose? Any idea? THanks :)","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":31,"estimatedTokens":265}}864{"id":"stack-68197106","source":"stackoverflow","questionId":68197106,"title":"How to use regexp for validate in nestjs?","tags":["nestjs"],"text":"Title: How to use regexp for validate in nestjs?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use regexp in validation in nestjs.\n\nFor example:\n\nRegExp\n\n```\npagePattern = '[a-z0-9\\-]+';\n```\n\nMethod\n\n```\n@Get('/:article')\n getIndex(\n @Param('article')\n ) {\n\n }\n```\n\nWhat can I use?\nValidationPipe?\n\n========================================\n\nTop Answer:\n```\n@Matches(new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)(?=.*).+$'), {\n message: 'qwe',\n })\n```\n\n========================================\n\nCode:\n```text\npagePattern    = '[a-z0-9\\-]+';\n```\n\n```text\n@Get('/:article')\n  getIndex(\n   @Param('article')\n  ) {\n\n  }\n```\n\n```js\nclass ArticleParamDTO {\n  @Matches('[a-z0-9\\-]+') // comes from class-validator\n  article: string;\n}\n```\n\n```js\n@Get(':article')\ngetIndex(@Param() { article }: ArticleParamDto) {\n\n}\n```\n\n```text\nValidationPipe\n```\n\n```text\n@Matches(new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)(?=.*).+$'), {\n    message: 'qwe',\n  })\n```\n\n========================================\n\nComments:\n- are there any ways to customize error messages for this case?\n- I believe the API for `@Matches()` is `@Matches(regex, message)`. Might be `@Matches(regex, options)` where `options.message` is the path you can use. Double check with class-validator's documentation\n- Please give context, what does it do?\n- I am not have \"You must have 50 reputation to comment\". I answered the question \"are there any ways to customize error messages for this case?\"","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":85,"estimatedTokens":366}}865{"id":"stack-54280856","source":"stackoverflow","questionId":54280856,"title":"TypeOrm: Create a ManyToOne relationship using uuid data type for the keys instead of integer","tags":["node.js","postgresql","typescript","nestjs","typeorm"],"text":"Title: TypeOrm: Create a ManyToOne relationship using uuid data type for the keys instead of integer\nTags: node.js, postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a Typescript Nestjs project using TypeORM and a PostgreSQL database, and I have trouble defining many-to-one relationships, because TypeORM tries to create an ID field of type integer, whereas I'm using UUID fields. Is there a way to tell TypeORM to use a different data-type than integer?\n\nHere's an example of an entity that's not working:\n\n```\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn()\n @Generated('uuid')\n id: string;\n}\n\n@Entity({name: 'users'})\nexport class User extends AgentKitsEntity implements UserModel {\n @Column()\n username: string;\n\n @ManyToOne(type => View)\n @JoinColumn({name: 'view_id', referencedColumnName: 'id'})\n view: View;\n}\n```\n\nThis leads to the following error:\n\n```\nquery failed: ALTER TABLE \"users\" ADD CONSTRAINT \"FK_2ed8b186dce83a446f94ac9aae4\" FOREIGN KEY (\"view_id\") REFERENCES \"views\"(\"id\")\nerror: { error: foreign key constraint \"FK_2ed8b186dce83a446f94ac9aae4\" cannot be implemented\n at Connection.parseE (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:554:11)\n at Connection.parseMessage (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:379:19)\n at Socket. (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:119:22)\n at emitOne (events.js:116:13)\n at Socket.emit (events.js:211:7)\n at addChunk (_stream_readable.js:263:12)\n at readableAddChunk (_stream_readable.js:250:11)\n at Socket.Readable.push (_stream_readable.js:208:10)\n at TCP.onread (net.js:601:20)\n name: 'error',\n length: 228,\n severity: 'ERROR',\n code: '42804',\n detail: 'Key columns \"view_id\" and \"id\" are of incompatible types: integer and uuid.',\n hint: undefined,\n position: undefined,\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'tablecmds.c',\n line: '6503',\n routine: 'ATAddForeignKeyConstraint' }\n```\n\nEDIT: Just to be clear, the issue isn't creating the UUID field for the primary key, that's working. The issue is that the table I'm referencing (in this example, \"views\"), uses a UUID primary key, so I need to use a UUID for the field referencing it as well (\"views\", in this example). TypeORM automatically creates the \"view_id\" field with an integer type, presumably because it assumes that primary key values will (should?) always be integers (which strikes me as a pretty crazy assumption). \n\nIt must be configurable somehow, no?\n\n========================================\n\nTop Answer:\nYou define `@PrimaryGeneratedColumn()` in schemas, which defaults to an integer sequence in postgres. The @Generated('uuid') doesn't change the column type. This decorator just tell to generate uuid instead of integer incrementation.\n\nCorrect way:\n\n```\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn('uuid')\n @Generated('uuid')\n id: string;\n}\n```\n\nWhen you create a primary key in TypeORM, you can use `@PrimaryGeneratedColumn('uuid')` to make the ID a UUID instead of a number. This ensures that in all related tables, TypeORM will automatically use UUIDs for the relationships.\n\n**But be careful:** UUIDs in PostgreSQL often need the `uuid-ossp` extension, and some cloud database providers donโ€™t include it by default. So this will throw an error.\n\n========================================\n\nCode:\n```text\nexport class AgentKitsEntity implements Model {\n  @PrimaryGeneratedColumn()\n  @Generated('uuid')\n  id: string;\n}\n\n@Entity({name: 'users'})\nexport class User extends AgentKitsEntity implements UserModel {\n  @Column()\n  username: string;\n\n  @ManyToOne(type => View)\n  @JoinColumn({name: 'view_id', referencedColumnName: 'id'})\n  view: View;\n}\n```\n\n```text\nquery failed: ALTER TABLE \"users\" ADD CONSTRAINT \"FK_2ed8b186dce83a446f94ac9aae4\" FOREIGN KEY (\"view_id\") REFERENCES \"views\"(\"id\")\nerror: { error: foreign key constraint \"FK_2ed8b186dce83a446f94ac9aae4\" cannot be implemented\n    at Connection.parseE (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:554:11)\n    at Connection.parseMessage (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:379:19)\n    at Socket.<anonymous> (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:119:22)\n    at emitOne (events.js:116:13)\n    at Socket.emit (events.js:211:7)\n    at addChunk (_stream_readable.js:263:12)\n    at readableAddChunk (_stream_readable.js:250:11)\n    at Socket.Readable.push (_stream_readable.js:208:10)\n    at TCP.onread (net.js:601:20)\n  name: 'error',\n  length: 228,\n  severity: 'ERROR',\n  code: '42804',\n  detail: 'Key columns \"view_id\" and \"id\" are of incompatible types: integer and uuid.',\n  hint: undefined,\n  position: undefined,\n  internalPosition: undefined,\n  internalQuery: undefined,\n  where: undefined,\n  schema: undefined,\n  table: undefined,\n  column: undefined,\n  dataType: undefined,\n  constraint: undefined,\n  file: 'tablecmds.c',\n  line: '6503',\n  routine: 'ATAddForeignKeyConstraint' }\n```\n\n```js\nexport class AgentKitsEntity implements Model {\n  @PrimaryGeneratedColumn('uuid')\n  @Generated('uuid')\n  id: string;\n}\n\n@Entity({name: 'users'})\nexport class User extends AgentKitsEntity implements UserModel {\n\n  @Column()\n  username: string;\n\n  @ManyToOne(type => View, { nullable: true })\n  @JoinColumn({name: 'view_id'})\n  view: View;\n}\n```\n\n```js\nexport class AgentKitsEntity implements Model {\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n}\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\n@Generated('uuid')\n```\n\n```text\nexport class AgentKitsEntity implements Model {\n  @PrimaryGeneratedColumn('uuid')\n  @Generated('uuid')\n  id: string;\n}\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\n@PrimaryGeneratedColumn('uuid')\n```\n\n```text\nuuid-ossp\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":190,"estimatedTokens":1505}}866{"id":"stack-66943353","source":"stackoverflow","questionId":66943353,"title":"Limit and skip related column in typeorm","tags":["typescript","nestjs","typeorm"],"text":"Title: Limit and skip related column in typeorm\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to limit the related data while finding with query builder, but I miss the concept.\n\nHere is my code to get the employee orders:\n\n```\nimport { getRepository, Repository } from \"typeorm\";\n\n public async findEmployeeQuery(id : number) {\n try {\n let query = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id})\n .leftJoinAndSelect('employee.customers' , 'customers')\n .getOne()\n const user = query\n return user\n } catch (error) {\n throw error\n }\n\n }\n```\n\nNow I want to limit the number of customers for each request - how can I do that?\n\nI tried the limit and skip options but this only works with the employee, not with the joined data.\n\n========================================\n\nTop Answer:\nYou have to make another query to limit customers:\n\n```\nimport { getRepository, Repository } from \"typeorm\";\n\npublic async findEmployeeQuery(id : number) {\n try {\n let user = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id});\n .getOne()\n\n user.customers = await getRepository(Customers)\n .createQueryBuilder('customer')\n .where('customer.employee= :id' , {user.id});\n .limit(10) // here you set limitation you want \n .getMany()\n\n return user;\n } catch (error) {\n throw error\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { getRepository, Repository } from \"typeorm\";\n\n    public async findEmployeeQuery(id : number) {\n        try {\n            let query = await getRepository(Employees)\n            .createQueryBuilder('employee')\n            .where('employee.id = :id' , {id})\n            .leftJoinAndSelect('employee.customers' , 'customers')\n            .getOne()\n            const user = query\n            return user\n        } catch (error) {\n            throw error\n        }\n\n    }\n```\n\n```js\nimport { getRepository, Repository } from \"typeorm\";\n\npublic async findEmployeeQuery(id : number) {\n    try {\n        let user = await getRepository(Employees)\n        .createQueryBuilder('employee')\n        .where('employee.id = :id' , {id})\n        .leftJoinAndSelect('employee.customers' , 'customers')\n        .take(4) // limits it to 4\n        .skip(5) // offset 5 entities\n        .getOne()\n\n        return user\n    } catch (error) {\n        throw error\n    }\n}\n```\n\n```js\nimport { getRepository, Repository } from \"typeorm\";\n\npublic async findEmployeeQuery(id : number) {\n    try {\n        let user = await getRepository(Employees)\n        .createQueryBuilder('employee')\n        .where('employee.id = :id' , {id});\n        .getOne()\n\n        user.customers = await getRepository(Customers)\n        .createQueryBuilder('customer')\n        .where('customer.employee= :id' , {user.id});\n        .limit(10) // here you set limitation you want \n        .getMany()\n\n        return user;\n    } catch (error) {\n        throw error\n    }\n}\n```\n\n```text\nlet category: any = await Category.findOne({\n      where: {\n        id: id,\n      },\n    });\n    // finding products linked to that category\n    let products = await orm\n      .createQueryBuilder(\"products\", \"p\")\n      .innerJoinAndSelect(\"p.categories\", \"c\", \"c.id = :categoryId\", {\n        categoryId: id,\n      })\n      // implementing pagination\n      .skip(offset)\n      .take(limit)\n      .getMany();\n    // Attaching the array to the Category Object\n    category.products = products;\n```\n\n========================================\n\nComments:\n- Try to do that in SQL first, to limit the numbers of relations you need to use a subquery. but it is really necessary this function ? Because this can have a considerable impact on your performance at a large scale.\n- You'd better make the query from the customers table not from the Employees table.\n- i did it for customers and it works fine Thank you\n- thank you i did it from the customers side and it works fine\n- keep this method in your mind in case you have multiple `leftjoins`, it'll help you ^^\n- Okay I will use it too\n- @Youba thanks for your help, but if user is an array, so i have to loop and it make so many query to database, do you have any idea?\n- sorry but it will not work coz it's limit the employees and I want to limit the customers who created by this employee,, anyway thanks for your help","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":156,"estimatedTokens":1090}}867{"id":"stack-72503661","source":"stackoverflow","questionId":72503661,"title":"refresh token API error \"secretOrPrivateKey must have a value\"","tags":["node.js","typescript","jwt","nestjs","refresh-token"],"text":"Title: refresh token API error \"secretOrPrivateKey must have a value\"\nTags: node.js, typescript, jwt, nestjs, refresh-token\nSource: Stack Overflow\n\nQuestion:\nWhen a user logs into the API generates a token so that he has access to other endpoints, but the token expires in 60sec, I made a function to generate a new valid token using the old token (which was stored in the database), but when I'm going to generate a new valid token I'm getting the secretOrPrivateKey must have a value error\n\nThe function refreshToken use function login to generate a new token\n\n### Nest error:\n\n```\nsecretOrPrivateKey must have a value\nError: secretOrPrivateKey must have a value\n at Object.module.exports [as sign] (C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\jsonwebtoken\\sign.js:107:20)\n at JwtService.sign (C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\@nestjs\\jwt\\dist\\jwt.service.js:28:20)\n at AuthService.login (C:\\Users\\talis\\nova api\\myflakes_api\\src\\auth\\auth.service.ts:18:39)\n at TokenService.refreshToken (C:\\Users\\talis\\nova api\\myflakes_api\\src\\token\\token.service.ts:39:37)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at TokenController.refreshToken (C:\\Users\\talis\\nova api\\myflakes_api\\src\\token\\token.controller.ts:12:16)\n at C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n### My code:\n\nFunction refreshToken in the file token.service.ts\n\n```\nasync refreshToken(oldToken: string) {\n let objToken = await this.tokenRepository.findOne({hash: oldToken})\n if (objToken) {\n let user = await this.userService.findOneOrFail({email:objToken.email})\n return this.authService.login(user)\n } else {\n return new UnauthorizedException(MessagesHelper.TOKEN_INVALID)\n }\n}\n```\n\nFunction login in the file auth.service.ts\n\n```\nasync login(user: UsersEntity) {\n const payload = { email: user.email, sub: user.idUser }\n const token = this.jwtService.sign(payload) // here!!!\n this.tokenService.save(token, user.email)\n return {\n token: token\n };\n}\n```\n\nError is on `const token = this.jwtService.sign(payload)`\n\nHere is the file jwt.strategy.ts\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { ExtractJwt, Strategy } from \"passport-jwt\";\nimport { jwtConstants } from \"../constants\";\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: jwtConstants.secret,\n });\n }\n\n async validate(payload: { sub: any; email: any; }) {\n return { id: payload.sub, email: payload.email}\n }\n}\n```\n\nAnd here local.strategy.ts\n\n```\nimport { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy } from \"passport-local\";\nimport { MessagesHelper } from \"src/helpers/messages.helper\";\nimport { AuthService } from \"../auth.service\";\n\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private authService: AuthService) {\n super({ usernameField: 'email' });\n }\n\n async validate(email: string, password: string): Promise {\n const user = await this.authService.validateUser(email, password);\n if(!user) \n throw new UnauthorizedException(MessagesHelper.PASSWORD_OR_EMAIL_INVALID)\n \n return user;\n }\n}\n```\n\nthis is the AuthModule where is JwtModule.register\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot(),\n UsersModule,\n PassportModule,\n TokenModule,\n JwtModule.register({\n secret: jwtConstants.secret,\n signOptions: { expiresIn: '60s' },\n }),\n ],\n controllers: [AuthController],\n providers: [AuthService, LocalStrategy, JwtStrategy],\n exports: [JwtModule, AuthService]\n})\nexport class AuthModule {}\n```\n\nGuys i tried to use images, but i'm new user and i still don't have a reputation, sorry.\n\n========================================\n\nCode:\n```text\nsecretOrPrivateKey must have a value\nError: secretOrPrivateKey must have a value\n   at Object.module.exports [as sign] (C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\jsonwebtoken\\sign.js:107:20)\n   at JwtService.sign (C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\@nestjs\\jwt\\dist\\jwt.service.js:28:20)\n   at AuthService.login (C:\\Users\\talis\\nova api\\myflakes_api\\src\\auth\\auth.service.ts:18:39)\n   at TokenService.refreshToken (C:\\Users\\talis\\nova api\\myflakes_api\\src\\token\\token.service.ts:39:37)\n   at processTicksAndRejections (node:internal/process/task_queues:96:5)\n   at TokenController.refreshToken (C:\\Users\\talis\\nova api\\myflakes_api\\src\\token\\token.controller.ts:12:16)\n   at C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n   at C:\\Users\\talis\\nova api\\myflakes_api\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\nasync refreshToken(oldToken: string) {\n    let objToken = await this.tokenRepository.findOne({hash: oldToken})\n    if (objToken) {\n        let user = await this.userService.findOneOrFail({email:objToken.email})\n        return this.authService.login(user)\n    } else {\n        return new UnauthorizedException(MessagesHelper.TOKEN_INVALID)\n    }\n}\n```\n\n```text\nasync login(user: UsersEntity) {\n    const payload = { email: user.email, sub: user.idUser }\n    const token = this.jwtService.sign(payload) // here!!!\n    this.tokenService.save(token, user.email)\n    return {\n        token: token\n    };\n}\n```\n\n```text\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { ExtractJwt, Strategy } from \"passport-jwt\";\nimport { jwtConstants } from \"../constants\";\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor() {\n        super({\n            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n            ignoreExpiration: false,\n            secretOrKey: jwtConstants.secret,\n        });\n    }\n\n    async validate(payload: { sub: any; email: any; }) {\n        return { id: payload.sub, email: payload.email}\n    }\n}\n```\n\n```text\nimport { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy } from \"passport-local\";\nimport { MessagesHelper } from \"src/helpers/messages.helper\";\nimport { AuthService } from \"../auth.service\";\n\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n    constructor(private authService: AuthService) {\n        super({ usernameField: 'email' });\n    }\n\n    async validate(email: string, password: string): Promise<any> {\n        const user = await this.authService.validateUser(email, password);\n        if(!user) \n            throw new UnauthorizedException(MessagesHelper.PASSWORD_OR_EMAIL_INVALID)\n        \n        return user;\n    }\n}\n```\n\n```text\n@Module({\n    imports: [\n    ConfigModule.forRoot(),\n    UsersModule,\n    PassportModule,\n    TokenModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n      controllers: [AuthController],\n      providers: [AuthService, LocalStrategy, JwtStrategy],\n      exports: [JwtModule, AuthService]\n})\nexport class AuthModule {}\n```\n\n```text\nconst token = this.jwtService.sign(payload)\n```\n\n```text\nconst token = this.jwtService.sign(payload, jwtConstants.secret)\n```\n\n```text\nreturn {\n      access_token: this.jwtService.sign(payload, { secret: process.env.JWT_SEC }),\n};\n```\n\n========================================\n\nComments:\n- what if you supply `secret` to `.sign` method as well? like so `this.jwtService.sign(payload, { secret: jwtConstants.secret })`\n- actually, can you show us how you've loaded the `JwtModule`?\n- i do not know why but i still get this error","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":248,"estimatedTokens":1964}}868{"id":"stack-69393098","source":"stackoverflow","questionId":69393098,"title":"How to test NestJs response interceptor","tags":["typescript","http","jestjs","nestjs","interceptor"],"text":"Title: How to test NestJs response interceptor\nTags: typescript, http, jestjs, nestjs, interceptor\nSource: Stack Overflow\n\nQuestion:\nI tried to this thread but it I keep getting an error.\n\n**transform-response.interceptor.ts:**\n\n```\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { ApiResponseInterface } from '@walletxp/shared-interfaces';\n\n@Injectable()\nexport class TransformResponseInterceptor\n implements NestInterceptor>>\n{\n intercept(context: ExecutionContext, next: CallHandler): Observable>> {\n return next.handle().pipe(map((data) => ({ success: true, data })));\n }\n}\n```\n\nand for it's test, **transform-response.interceptor.spec.ts:**\n\n```\nimport { TransformResponseInterceptor } from './transform-response.interceptor';\nconst interceptor = new TransformResponseInterceptor();\n\nconst executionContext: any = {\n switchToHttp: jest.fn().mockReturnThis(),\n getRequest: jest.fn().mockReturnThis(),\n};\n\nconst callHandler = {\n handle: jest.fn(),\n};\n\ndescribe('ResponseInterceptor', () => {\n it('should be defined', () => {\n expect(interceptor).toBeDefined();\n });\n describe('#intercept', () => {\n it('t1', async () => {\n (executionContext.switchToHttp().getRequest as jest.Mock).mockReturnValueOnce({\n body: { data: 'mocked data' },\n });\n callHandler.handle.mockResolvedValueOnce('next handle');\n const actualValue = await interceptor.intercept(executionContext, callHandler);\n expect(actualValue).toBe('next handle');\n expect(executionContext.switchToHttp().getRequest().body).toEqual({\n data: 'mocked data',\n addedAttribute: 'example',\n });\n expect(callHandler.handle).toBeCalledTimes(1);\n });\n });\n});\n```\n\nMy goal would be to mock the data returned from the controller and check if after it goes through the interceptor it equals the formatted data that I want.\n\n========================================\n\nTop Answer:\nI'll show a simple and cleaner real world example from my project. The example is similar to the one shown in the question which is about using an interceptor to transform an object. I use this interceptor to exclude sensitive properties like `hashedPassword` from the `user` object sent as a `response`:\n\n```\ndescribe('SerializerInterceptor', () => {\n let interceptor: SerializerInterceptor\n\n beforeEach(() => {\n interceptor = new SerializerInterceptor(UserDto)\n })\n\n it('should return user object without the sensitive properties', async () => {\n\n const context = createMock()\n const handler = createMock({\n handle: () => of(testUser)\n })\n\n const userObservable = interceptor.intercept(context, handler)\n const user = await lastValueFrom(userObservable)\n\n expect(user.id).toEqual(testUser.id)\n expect(user.username).toEqual(testUser.username)\n\n expect(user).not.toHaveProperty('hashedPassword')\n })\n})\n```\n\nFor mocking the `ExecutionContext` and `CallHandler`, we use `createMock()` function from the @golevelup/ts-jest package.\n\nNestJS `Interceptor` under the hood uses RxJS. So, when its `intercept()` method is called by the framework, it returns an `Observable` of our object. To cleanly extract our value from this `Observable`, we use the convenience function `lastValueFrom()` from RxJS.\n\nThe `testUser` here, is your object under test. You need to create it and provide it to the mock handler as shown above.\n\n========================================\n\nCode:\n```text\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { ApiResponseInterface } from '@walletxp/shared-interfaces';\n\n@Injectable()\nexport class TransformResponseInterceptor<T>\n  implements NestInterceptor<T, ApiResponseInterface<Record<string, unknown>>>\n{\n  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponseInterface<Record<string, unknown>>> {\n    return next.handle().pipe(map((data) => ({ success: true, data })));\n  }\n}\n```\n\n```text\nimport { TransformResponseInterceptor } from './transform-response.interceptor';\nconst interceptor = new TransformResponseInterceptor();\n\nconst executionContext: any = {\n  switchToHttp: jest.fn().mockReturnThis(),\n  getRequest: jest.fn().mockReturnThis(),\n};\n\nconst callHandler = {\n  handle: jest.fn(),\n};\n\ndescribe('ResponseInterceptor', () => {\n  it('should be defined', () => {\n    expect(interceptor).toBeDefined();\n  });\n  describe('#intercept', () => {\n    it('t1', async () => {\n      (executionContext.switchToHttp().getRequest as jest.Mock<any, any>).mockReturnValueOnce({\n        body: { data: 'mocked data' },\n      });\n      callHandler.handle.mockResolvedValueOnce('next handle');\n      const actualValue = await interceptor.intercept(executionContext, callHandler);\n      expect(actualValue).toBe('next handle');\n      expect(executionContext.switchToHttp().getRequest().body).toEqual({\n        data: 'mocked data',\n        addedAttribute: 'example',\n      });\n      expect(callHandler.handle).toBeCalledTimes(1);\n    });\n  });\n});\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { INestApplication, HttpStatus } from '@nestjs/common';\n\nimport { EmulatorHeadersInterceptor } from '@LIBRARY/interceptors/emulator-headers.interceptor';\n\nimport { AppModule } from '@APP/app.module';\n\ndescribe('Header Intercepter', () => {\n    let app: INestApplication;\n\n    afterAll(async () => {\n        await app.close();\n    });\n\n    beforeAll(async () => {\n        const moduleFixture: TestingModule = await Test.createTestingModule({\n            imports: [AppModule],\n        }).compile();\n\n        app = moduleFixture.createNestApplication();\n        app.useGlobalInterceptors(new EmulatorHeadersInterceptor());\n        await app.init();\n    });\n\n    it('./test (PUT) should have the interceptor data', async () => {\n        const ResponseData$ = await request(app.getHttpServer())\n            .put('/test')\n            .send();\n\n        expect(ResponseData$.status).toBe(HttpStatus.OK);\n        expect(ResponseData$.headers['myheader']).toBe('interceptor');\n    });\n});\n```\n\n```js\ndescribe('ResponseInterceptor', () => {\n  let interceptor: ResponseInterceptor;\n\n  beforeEach(() => {\n    interceptor = new ResponseInterceptor();\n  });\n\n  it('should map the data', (done) => {\n    // this sets up a mock execution context (which you don't use so it's blank)\n    // and a mock CallHandler that returns a known piece of data 'test data'\n    const obs$ = interceptor.intercept({} as any, { handle: () => of('test data') });\n    // this tests the observable, and calls done when it is complete\n    obs$.subscribe({\n      next: (val) => {\n        expect(val).toEqual({ success: true, data: 'test data' })\n      }),\n      complete: () => done()\n    })\n  });\n\n});\n```\n\n```text\ndescribe('SerializerInterceptor', () => {\n  let interceptor: SerializerInterceptor\n\n  beforeEach(() => {\n    interceptor = new SerializerInterceptor(UserDto)\n  })\n\n  it('should return user object without the sensitive properties', async () => {\n\n    const context = createMock<ExecutionContext>()\n    const handler = createMock<CallHandler>({\n      handle: () => of(testUser)\n    })\n\n    const userObservable = interceptor.intercept(context, handler)\n    const user = await lastValueFrom(userObservable)\n\n    expect(user.id).toEqual(testUser.id)\n    expect(user.username).toEqual(testUser.username)\n\n    expect(user).not.toHaveProperty('hashedPassword')\n  })\n})\n```\n\n```text\nhashedPassword\n```\n\n```text\nuser\n```\n\n```text\nresponse\n```\n\n```text\nExecutionContext\n```\n\n```text\nCallHandler\n```\n\n```text\ncreateMock()\n```\n\n```text\nInterceptor\n```\n\n```text\nintercept()\n```\n\n```text\nObservable\n```\n\n```text\nObservable\n```\n\n```text\nlastValueFrom()\n```\n\n```text\ntestUser\n```\n\n========================================\n\nComments:\n- Hi, thanks, this works as expected. Just one question, is this a good practice for testing? I feel like we are testing the '/test' route controller and not the interceptor directly. It definitely works, but I'd like to know if this way of testing interceptors is used on enterprise projects.\n- Good questions. I am only using NestJS on smaller projects, and other articles I have read, says leave these tests to integration (e2e), which is basically what this is. I expect you could test it directly with more knowledge of the NestJS inner workings, but this seems to work for my projects.\n- \"@LIBRARY\" \"@APP\" ? what do these mean ?\n- @Lucke these are paths in the `tsconfig.json` file so you can use them as short cuts. \"paths\": { \"@LIBRARY/*\": [ \"./src/library/*\" ], \"@APP/*\": [ \"./src/*\" ] }\n- Thank you, will definitely look into RxJS more.","metadata":{"transformedAt":"2026-08-18T18:33:02.474Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":298,"estimatedTokens":2179}}869{"id":"stack-78171563","source":"stackoverflow","questionId":78171563,"title":"Nest.js with Drizzle ORM","tags":["postgresql","nestjs","drizzle-orm"],"text":"Title: Nest.js with Drizzle ORM\nTags: postgresql, nestjs, drizzle-orm\nSource: Stack Overflow\n\nQuestion:\nAre there any more elegant ways to use Drizzle ORM in Nest.js besides the providers? For example like in Prisma with PrismaService, all I found is only with providers like:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\n\nimport { drizzle } from 'drizzle-orm/postgres-js';\nimport postgres from 'postgres';\nimport * as schema from './schema';\n\nexport const PG_CONNECTION = \"PG_CONNECTION\"; // ignore that it is not separate file\n\n@Module({\n providers: [\n {\n provide: PG_CONNECTION,\n inject: [ConfigService],\n useFactory: async (config: ConfigService) => {\n const connection = postgres(config.get(\"DATABASE_URL\"));\n return drizzle(connection, { schema });\n },\n },\n ],\n exports: [PG_CONNECTION],\n})\nexport class DrizzleModule {}\n```\n\nand then:\n\n```\nimport { Inject, Injectable } from '@nestjs/common';\nimport { PG_CONNECTION } from '../drizzle/drizzle.module';\nimport { dbType } from 'drizzle-orm/postgres-js'; // ignore, it doesn't matter yet\nimport * as schema from '../drizzle/schema';\n\n@Injectable()\nexport class UsersService {\n constructor(@Inject(PG_CONNECTION) private drizzle: dbType) {} // what I'm talking about\n\n async findAll() {\n return await this.drizzle.query.users.findMany();\n }\n}\n```\n\nwhat I'm talking about, we should inject (provider?) every time, import the constant and type from the db client, instead of this:\n\n```\nimport { Inject, Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service'\n\n@Injectable()\nexport class UsersService {\n constructor(private prisma: PrismaService) {}\n\n async findAll() {\n return await this.prisma.users.findMany();\n }\n}\n```\n\nI tried to find a solution but it seems this topic is really not popular.. I was expecting such a big Nest.js and Drizzle ORM community to have a good solution to use Drizzle with Nest\n\n========================================\n\nTop Answer:\nI had a slightly easier approach that didn't involve much. Here is an example of how i did it.\n\n**`'database.service.ts'`**:\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\n\nimport { neon } from '@neondatabase/serverless';\nimport { drizzle } from 'drizzle-orm/neon-http';\nimport { db, DatabaseType } from 'drizzle/db';\n\nimport {\n difficultyEnum,\n topicTagEnum,\n badgeEnum,\n} from 'drizzle/schema/enums/enums';\nimport * as schema from '../drizzle/schema';\n\n@Injectable()\nexport class DatabaseService implements OnModuleInit {\n private db: DatabaseType;\n\n constructor() {\n this.db = db;\n }\n\n async onModuleInit() {\n try {\n const sql = neon(process.env.DB_URL as string);\n this.db = drizzle(sql, {\n schema,\n logger: true,\n });\n\n console.log('Database connected successfully');\n } catch (error) {\n console.error('Failed to connect to the database', error);\n throw error;\n }\n }\n\n getDb() {\n return this.db;\n }\n}\n```\n\n**'`database.module.ts`'**:\n\n```\nimport { Module } from '@nestjs/common';\nimport { DatabaseService } from './database.service';\n\n@Module({\n providers: [DatabaseService],\n exports: [DatabaseService], // As we want to an instance of the 'DatabaseService' between several other modules, we need to export the 'DatabaseService' provider.\n})\nexport class DatabaseModule {}\n```\n\n**'`app.module.ts`':**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { QuestionsModule } from './questions/questions.module';\nimport { DatabaseModule } from './database/database.module';\n\n@Module({\n imports: [\n QuestionsModule,\n DatabaseModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n**'`questions.module.ts`':**\n\n```\nimport { Module } from '@nestjs/common';\nimport { QuestionsService } from './questions.service';\nimport { QuestionsController } from './questions.controller';\nimport { DatabaseModule } from 'src/database/database.module';\n\n// This is a feature module\n@Module({\n imports: [DatabaseModule], // This means 'QuestionsModule' can use any providers (service) that 'DatabaseModule' exports.\n controllers: [QuestionsController], // This is the controller that handles incoming HTTP requests related to questions (like fetching, adding, or deleting questions).\n providers: [QuestionsService], // This is included as a provider which is responsible for the business logic, such as interacting with the database to manage questions.\n})\nexport class QuestionsModule {}\n```\n\n**'`questions.service.ts`':**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { CreateQuestionDto } from './dto/create-question.dto';\nimport { UpdateQuestionDto } from './dto/update-question.dto';\n\nimport { eq } from 'drizzle-orm';\nimport { DatabaseService } from 'src/database/database.service';\n\nimport {\n questionTable,\n QuestionTableType,\n NewQuestionTableType,\n} from '../../drizzle/schema/models/question.model';\nimport { TopicTagType } from 'drizzle/schema/enums/enums';\n\n@Injectable()\nexport class QuestionsService {\n // This is a default constructor\n constructor(private readonly databaseService: DatabaseService) {}\n\n async create(createQuestionDto: CreateQuestionDto) {\n return 'This action adds a new question';\n }\n\n // GET all questions\n async findAllQuestions(): Promise {\n console.log('question.services.ts findAllQuestions() called'); // debug\n\n try {\n const fetchedQuestions = await this.databaseService\n .getDb()\n .query.questionTable.findMany();\n\n console.log(\n `Database Fetch: Retrieved ${fetchedQuestions.length} questions.`,\n fetchedQuestions,\n ); // debug\n\n return fetchedQuestions as QuestionTableType[];\n } catch (error) {\n console.error('Error fetching questions from database:', error);\n throw new Error('Error fetching questions from database');\n }\n }\n\n async findQuestionById(\n questionId: number,\n ): Promise {\n console.log('question.services.ts findQuestionById() called'); // debug\n\n try {\n const fetchedQuestion: QuestionTableType | undefined =\n await this.databaseService.getDb().query.questionTable.findFirst({\n where: eq(questionTable.id, questionId),\n });\n\n // Guard clause\n if (!fetchedQuestion) {\n console.error('Question not found in database');\n return null;\n }\n\n console.log('Database Fetch: Retrieved question:', fetchedQuestion); // debug\n\n return fetchedQuestion;\n } catch (error) {\n console.error('Error fetching question from database:', error);\n throw new Error('Error fetching question from database');\n }\n }\n\n async findQuestionsByTopic(\n topic: TopicTagType,\n ): Promise {\n console.log('question.services.ts findQuestionsByTopic() called'); // debug\n\n try {\n const fetchedQuestions: QuestionTableType[] = await this.databaseService\n .getDb()\n .query.questionTable.findMany({\n where: eq(questionTable.topicTag, topic),\n });\n\n // Guard clause\n if (!fetchedQuestions) {\n console.error('Questions not found in database');\n return null;\n }\n\n console.log(\n `Database Fetch: Retrieved ${fetchedQuestions.length} questions by topic ${topic}`,\n fetchedQuestions,\n ); // debug\n\n return fetchedQuestions;\n } catch (error) {\n console.error('Error fetching questions from database:', error);\n throw new Error('Error fetching questions from database');\n }\n }\n\n async update(id: number, updateQuestionDto: UpdateQuestionDto) {\n return `This action updates a #${id} question`;\n }\n\n async remove(id: number) {\n return `This action removes a #${id} question`;\n }\n}\n```\n\n**'`questions.controller.ts`':**\n\n```\nimport {\n Controller,\n Get,\n Post,\n Patch,\n Delete,\n Body,\n Param,\n NotFoundException,\n ValidationPipe,\n ParseIntPipe,\n ParseFloatPipe,\n ParseBoolPipe,\n ParseArrayPipe,\n ParseUUIDPipe,\n ParseEnumPipe,\n DefaultValuePipe,\n ParseFilePipe,\n} from '@nestjs/common';\nimport { QuestionsService } from './questions.service';\nimport { CreateQuestionDto } from './dto/create-question.dto';\nimport { UpdateQuestionDto } from './dto/update-question.dto';\nimport { topicTagEnum, TopicTagType } from '../../drizzle/schema/enums/enums';\n\nimport {\n QuestionTableType,\n NewQuestionTableType,\n} from 'drizzle/schema/models/question.model';\n\n@Controller('questions')\nexport class QuestionsController {\n constructor(private readonly questionsService: QuestionsService) {}\n\n // This is an example method decorator that defines a route handler for POST requests to the specified route.\n @Post()\n create(@Body() createQuestionDto: CreateQuestionDto) {\n return this.questionsService.create(createQuestionDto);\n }\n\n @Get()\n findAll(): Promise {\n return this.questionsService.findAllQuestions();\n }\n\n @Get(':id')\n async findQuestionById(\n @Param('id', ParseIntPipe) id: number,\n ): Promise {\n const question = await this.questionsService.findQuestionById(id);\n\n // Guard clause\n if (!question) {\n throw new NotFoundException(`Question with ID ${id} not found.`);\n }\n \n return question;\n }\n\n // @Get('topic/:topic')\n // findQuestionsByTopic(\n // @Param('topic', new ParseEnumPipe(topicTagEnum)) topic: TopicTagType,\n // ): Promise {\n // const questions = this.questionsService.findQuestionsByTopic(topic);\n\n // // Guard clause\n // if (!questions) {\n // throw new NotFoundException(`Questions with topic ${topic} not found.`);\n // }\n\n // return questions;\n // }\n\n @Get('topic/:topic')\n findQuestionsByTopic(\n @Param('topic') topic: TopicTagType,\n ): Promise {\n const questions = this.questionsService.findQuestionsByTopic(topic);\n\n // Guard clause\n if (!questions) {\n throw new NotFoundException(`Questions with topic ${topic} not found.`);\n }\n\n return questions;\n }\n\n @Patch(':id')\n update(\n @Param('id') id: string,\n @Body() updateQuestionDto: UpdateQuestionDto,\n ) {\n return this.questionsService.update(+id, updateQuestionDto);\n }\n\n @Delete(':id')\n remove(@Param('id') id: string) {\n return this.questionsService.remove(+id);\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { Module } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\n\nimport { drizzle } from 'drizzle-orm/postgres-js';\nimport postgres from 'postgres';\nimport * as schema from './schema';\n\nexport const PG_CONNECTION = \"PG_CONNECTION\"; // ignore that it is not separate file\n\n@Module({\n  providers: [\n    {\n      provide: PG_CONNECTION,\n      inject: [ConfigService],\n      useFactory: async (config: ConfigService) => {\n        const connection = postgres(config.get(\"DATABASE_URL\"));\n        return drizzle(connection, { schema });\n      },\n    },\n  ],\n  exports: [PG_CONNECTION],\n})\nexport class DrizzleModule {}\n```\n\n```js\nimport { Inject, Injectable } from '@nestjs/common';\nimport { PG_CONNECTION } from '../drizzle/drizzle.module';\nimport { dbType } from 'drizzle-orm/postgres-js'; // ignore, it doesn't matter yet\nimport * as schema from '../drizzle/schema';\n\n@Injectable()\nexport class UsersService {\n  constructor(@Inject(PG_CONNECTION) private drizzle: dbType<typeof schema>) {} // what I'm talking about\n\n  async findAll() {\n    return await this.drizzle.query.users.findMany();\n  }\n}\n```\n\n```js\nimport { Inject, Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service'\n\n@Injectable()\nexport class UsersService {\n  constructor(private prisma: PrismaService) {}\n\n  async findAll() {\n    return await this.prisma.users.findMany();\n  }\n}\n```\n\n```js\n@Injectable()\nexport class DrizzleService {\n  constructor(@Inject(PG_CONNECTION) readonly db: dbType<typeof schema>) {}\n}\n```\n\n```text\nPG_CONNECTION\n```\n\n```text\nPG_CONNECTION\n```\n\n```text\nDrizzleModule\n```\n\n```text\nDrizzleService\n```\n\n```text\nprivate readonly drizzle: DrizzleService\n```\n\n```text\nprisma\n```\n\n```text\nthis.drizzle.db\n```\n\n```text\nimport { drizzle } from 'drizzle-orm/postgres-js';\nimport { migrate } from 'drizzle-orm/postgres-js/migrator';\nimport * as postgres from 'postgres';\nimport { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport * as schema from './schema';\n\ntype DrizzleFn = typeof drizzle<typeof schema>;\nconst Drizzle = drizzle as unknown as {\n  new (...args: Parameters<DrizzleFn>): ReturnType<DrizzleFn>;\n};\n\n@Injectable()\nexport class DrizzleService\n  extends Drizzle\n  implements OnModuleInit, OnModuleDestroy\n{\n  private client: ReturnType<typeof postgres>;\n  private migrationClient: ReturnType<typeof postgres>;\n\n  constructor(private configService: ConfigService) {\n    const dbUrl = configService.get('DATABASE_URL');\n    const client = postgres(dbUrl);\n    const migrationClient = postgres(dbUrl, {\n      max: 1,\n    });\n    super(client, { schema, logger: true });\n    this.client = client;\n    this.migrationClient = migrationClient;\n    Object.setPrototypeOf(Object.getPrototypeOf(this), DbService.prototype);\n  }\n\n  async onModuleInit() {\n    await migrate(drizzle(this.migrationClient, { schema, logger: true }), {\n      migrationsFolder: './drizzle',\n      migrationsSchema: 'public',\n    });\n    this.migrationClient.end();\n  }\n\n  async onModuleDestroy() {\n    await Promise.all([this.migrationClient.end(), this.client.end()]);\n  }\n}\n```\n\n```text\ndrizzle\n```\n\n```text\nonMoudleInit\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\n\nimport { neon } from '@neondatabase/serverless';\nimport { drizzle } from 'drizzle-orm/neon-http';\nimport { db, DatabaseType } from 'drizzle/db';\n\nimport {\n  difficultyEnum,\n  topicTagEnum,\n  badgeEnum,\n} from 'drizzle/schema/enums/enums';\nimport * as schema from '../drizzle/schema';\n\n@Injectable()\nexport class DatabaseService implements OnModuleInit {\n  private db: DatabaseType;\n\n  constructor() {\n    this.db = db;\n  }\n\n  async onModuleInit() {\n    try {\n      const sql = neon(process.env.DB_URL as string);\n      this.db = drizzle(sql, {\n        schema,\n        logger: true,\n      });\n\n      console.log('Database connected successfully');\n    } catch (error) {\n      console.error('Failed to connect to the database', error);\n      throw error;\n    }\n  }\n\n  getDb() {\n    return this.db;\n  }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { DatabaseService } from './database.service';\n\n@Module({\n  providers: [DatabaseService],\n  exports: [DatabaseService], // As we want to share an instance of the 'DatabaseService' between several other modules, we need to export the 'DatabaseService' provider.\n})\nexport class DatabaseModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { QuestionsModule } from './questions/questions.module';\nimport { DatabaseModule } from './database/database.module';\n\n@Module({\n  imports: [\n    QuestionsModule,\n    DatabaseModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { QuestionsService } from './questions.service';\nimport { QuestionsController } from './questions.controller';\nimport { DatabaseModule } from 'src/database/database.module';\n\n// This is a feature module\n@Module({\n  imports: [DatabaseModule], // This means 'QuestionsModule' can use any providers (service) that 'DatabaseModule' exports.\n  controllers: [QuestionsController], // This is the controller that handles incoming HTTP requests related to questions (like fetching, adding, or deleting questions).\n  providers: [QuestionsService], // This is included as a provider which is responsible for the business logic, such as interacting with the database to manage questions.\n})\nexport class QuestionsModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { CreateQuestionDto } from './dto/create-question.dto';\nimport { UpdateQuestionDto } from './dto/update-question.dto';\n\nimport { eq } from 'drizzle-orm';\nimport { DatabaseService } from 'src/database/database.service';\n\nimport {\n  questionTable,\n  QuestionTableType,\n  NewQuestionTableType,\n} from '../../drizzle/schema/models/question.model';\nimport { TopicTagType } from 'drizzle/schema/enums/enums';\n\n@Injectable()\nexport class QuestionsService {\n  // This is a default constructor\n  constructor(private readonly databaseService: DatabaseService) {}\n\n  async create(createQuestionDto: CreateQuestionDto) {\n    return 'This action adds a new question';\n  }\n\n  // GET all questions\n  async findAllQuestions(): Promise<QuestionTableType[]> {\n    console.log('question.services.ts findAllQuestions() called'); // debug\n\n    try {\n      const fetchedQuestions = await this.databaseService\n        .getDb()\n        .query.questionTable.findMany();\n\n      console.log(\n        `Database Fetch: Retrieved ${fetchedQuestions.length} questions.`,\n        fetchedQuestions,\n      ); // debug\n\n      return fetchedQuestions as QuestionTableType[];\n    } catch (error) {\n      console.error('Error fetching questions from database:', error);\n      throw new Error('Error fetching questions from database');\n    }\n  }\n\n  async findQuestionById(\n    questionId: number,\n  ): Promise<QuestionTableType | null> {\n    console.log('question.services.ts findQuestionById() called'); // debug\n\n    try {\n      const fetchedQuestion: QuestionTableType | undefined =\n        await this.databaseService.getDb().query.questionTable.findFirst({\n          where: eq(questionTable.id, questionId),\n        });\n\n      // Guard clause\n      if (!fetchedQuestion) {\n        console.error('Question not found in database');\n        return null;\n      }\n\n      console.log('Database Fetch: Retrieved question:', fetchedQuestion); // debug\n\n      return fetchedQuestion;\n    } catch (error) {\n      console.error('Error fetching question from database:', error);\n      throw new Error('Error fetching question from database');\n    }\n  }\n\n  async findQuestionsByTopic(\n    topic: TopicTagType,\n  ): Promise<QuestionTableType[]> {\n    console.log('question.services.ts findQuestionsByTopic() called'); // debug\n\n    try {\n      const fetchedQuestions: QuestionTableType[] = await this.databaseService\n        .getDb()\n        .query.questionTable.findMany({\n          where: eq(questionTable.topicTag, topic),\n        });\n\n      // Guard clause\n      if (!fetchedQuestions) {\n        console.error('Questions not found in database');\n        return null;\n      }\n\n      console.log(\n        `Database Fetch: Retrieved ${fetchedQuestions.length} questions by topic ${topic}`,\n        fetchedQuestions,\n      ); // debug\n\n      return fetchedQuestions;\n    } catch (error) {\n      console.error('Error fetching questions from database:', error);\n      throw new Error('Error fetching questions from database');\n    }\n  }\n\n  async update(id: number, updateQuestionDto: UpdateQuestionDto) {\n    return `This action updates a #${id} question`;\n  }\n\n  async remove(id: number) {\n    return `This action removes a #${id} question`;\n  }\n}\n```\n\n```text\nimport {\n  Controller,\n  Get,\n  Post,\n  Patch,\n  Delete,\n  Body,\n  Param,\n  NotFoundException,\n  ValidationPipe,\n  ParseIntPipe,\n  ParseFloatPipe,\n  ParseBoolPipe,\n  ParseArrayPipe,\n  ParseUUIDPipe,\n  ParseEnumPipe,\n  DefaultValuePipe,\n  ParseFilePipe,\n} from '@nestjs/common';\nimport { QuestionsService } from './questions.service';\nimport { CreateQuestionDto } from './dto/create-question.dto';\nimport { UpdateQuestionDto } from './dto/update-question.dto';\nimport { topicTagEnum, TopicTagType } from '../../drizzle/schema/enums/enums';\n\nimport {\n  QuestionTableType,\n  NewQuestionTableType,\n} from 'drizzle/schema/models/question.model';\n\n@Controller('questions')\nexport class QuestionsController {\n  constructor(private readonly questionsService: QuestionsService) {}\n\n  // This is an example method decorator that defines a route handler for POST requests to the specified route.\n  @Post()\n  create(@Body() createQuestionDto: CreateQuestionDto) {\n    return this.questionsService.create(createQuestionDto);\n  }\n\n  @Get()\n  findAll(): Promise<QuestionTableType[]> {\n    return this.questionsService.findAllQuestions();\n  }\n\n  @Get(':id')\n  async findQuestionById(\n    @Param('id', ParseIntPipe) id: number,\n  ): Promise<QuestionTableType> {\n    const question = await this.questionsService.findQuestionById(id);\n\n    // Guard clause\n    if (!question) {\n      throw new NotFoundException(`Question with ID ${id} not found.`);\n    }\n    \n    return question;\n  }\n\n  // @Get('topic/:topic')\n  // findQuestionsByTopic(\n  //   @Param('topic', new ParseEnumPipe(topicTagEnum)) topic: TopicTagType,\n  // ): Promise<QuestionTableType[]> {\n  //   const questions = this.questionsService.findQuestionsByTopic(topic);\n\n  //   // Guard clause\n  //   if (!questions) {\n  //     throw new NotFoundException(`Questions with topic ${topic} not found.`);\n  //   }\n\n  //   return questions;\n  // }\n\n  @Get('topic/:topic')\n  findQuestionsByTopic(\n    @Param('topic') topic: TopicTagType,\n  ): Promise<QuestionTableType[]> {\n    const questions = this.questionsService.findQuestionsByTopic(topic);\n\n    // Guard clause\n    if (!questions) {\n      throw new NotFoundException(`Questions with topic ${topic} not found.`);\n    }\n\n    return questions;\n  }\n\n  @Patch(':id')\n  update(\n    @Param('id') id: string,\n    @Body() updateQuestionDto: UpdateQuestionDto,\n  ) {\n    return this.questionsService.update(+id, updateQuestionDto);\n  }\n\n  @Delete(':id')\n  remove(@Param('id') id: string) {\n    return this.questionsService.remove(+id);\n  }\n}\n```\n\n```text\n'database.service.ts'\n```\n\n```text\ndatabase.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nquestions.module.ts\n```\n\n```text\nquestions.service.ts\n```\n\n```text\nquestions.controller.ts\n```\n\n========================================\n\nComments:\n- Why do people inject the database connection token rather than injecting the database variable itself?\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":864,"estimatedTokens":5478}}870{"id":"stack-76741461","source":"stackoverflow","questionId":76741461,"title":"Nest.js + TypeORM. TypeORM didn't see .env file","tags":["typescript","environment-variables","nestjs","typeorm","cross-env"],"text":"Title: Nest.js + TypeORM. TypeORM didn't see .env file\nTags: typescript, environment-variables, nestjs, typeorm, cross-env\nSource: Stack Overflow\n\nQuestion:\nI have some issue about typeorm migrations. I have typeorm config (see below).\n\n`data-source.ts`:\n\n```\nimport { DataSource, DataSourceOptions } from 'typeorm';\n\nexport const dataSourceOptions: DataSourceOptions = {\n type: 'postgres',\n host: process.env.POSTGRES_HOST,\n port: +process.env.POSTGRES_PORT,\n username: process.env.POSTGRES_USERNAME,\n password: process.env.POSTGRES_PASSWORD,\n database: process.env.POSTGRES_DATABASE,\n entities: ['dist/**/*.entity.js'],\n migrations: ['dist/db/migrations/*.js'],\n synchronize: true,\n};\n\nconst dataSource = new DataSource(dataSourceOptions);\nexport default dataSource;\n```\n\nAnd when I'm trying to start migrations, typeorm throws an error (but if I replace process.env with normal string, it works).\n\nI attached scripts from package.json\n\n```\n\"build\": \"nest build\",\n\"start\": \"cross-env NODE_ENV=production nest start\",\n\"start:dev\": \"cross-env NODE_ENV=development nest start --watch\",\n\"typeorm\": \"npm run build && npx typeorm -d dist/db/data-source.js\",\n\"migration:generate\": \"npm run typeorm -- migration:generate\",\n\"migration:run\": \"npm run typeorm -- migration:run\",\n\"migration:down\": \"npm run typeorm -- migration:revert\"\n```\n\nI need the config to see data from env during migrations.\n\nMaybe this is caused by the fact that I use cross env. And I read it like this\n\n`App.module.ts`:\n\n```\n@Module({\n imports: [\n...\n ConfigModule.forRoot({\n envFilePath: `.${process.env.NODE_ENV}.env`,\n }),\n ],\n...\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nAnyway,I hope for your help\n\n========================================\n\nTop Answer:\nTo deal with commandline migrations, you can use an additional `typeorm.config.ts` file on the root directory.\n\n```\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nimport { resolve } from 'path';\n\nconfig({ path: resolve(__dirname, '.env') });\n\nconst DataSourceConfig = new DataSource({\n type: 'mysql',\n host: process.env.TYPEORM_HOST,\n port: Number(process.env.TYPEORM_PORT),\n username: process.env.TYPEORM_USERNAME,\n password: process.env.TYPEORM_PASSWORD,\n database: process.env.TYPEORM_DATABASE,\n migrations: ['./database/migrations/*'],\n synchronize: false,\n extra: {\n charset: 'utf8mb4',\n },\n migrationsTableName: 'migrations',\n});\n\nexport default DataSourceConfig;\n```\n\nAnd to use typeorm inside NestJS app, create a `typeorm.service.js` file.\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';\n\n@Injectable()\nexport class TypeOrmConfigService implements TypeOrmOptionsFactory {\n constructor(private configService: ConfigService) {}\n\n public createTypeOrmOptions(): TypeOrmModuleOptions {\n return {\n type: 'mysql',\n host: this.configService.get('TYPEORM_HOST'),\n port: this.configService.get('TYPEORM_PORT'),\n username: this.configService.get('TYPEORM_USERNAME'),\n password: this.configService.get('TYPEORM_PASSWORD'),\n database: this.configService.get('TYPEORM_DATABASE'),\n autoLoadEntities: true,\n };\n }\n}\n```\n\nAnd load this service in `app.module.ts` file\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),\n ]\n});\nexport class AppModule {}\n```\n\nAnd then inside `package.json` file, define the commands. Note that I'm using the `typeorm-ts-node-commonjs` package because my `typeorm.config.js` file is in Typescript.\n\n```\n\"migration:run\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:run\",\n\"migration:create\": \"cd database/migrations && typeorm-ts-node-commonjs migration:create\",\n\"migration:revert\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:revert\"\n```\n\n========================================\n\nCode:\n```text\nimport { DataSource, DataSourceOptions } from 'typeorm';\n\nexport const dataSourceOptions: DataSourceOptions = {\n  type: 'postgres',\n  host: process.env.POSTGRES_HOST,\n  port: +process.env.POSTGRES_PORT,\n  username: process.env.POSTGRES_USERNAME,\n  password: process.env.POSTGRES_PASSWORD,\n  database: process.env.POSTGRES_DATABASE,\n  entities: ['dist/**/*.entity.js'],\n  migrations: ['dist/db/migrations/*.js'],\n  synchronize: true,\n};\n\nconst dataSource = new DataSource(dataSourceOptions);\nexport default dataSource;\n```\n\n```text\n\"build\": \"nest build\",\n\"start\": \"cross-env NODE_ENV=production nest start\",\n\"start:dev\": \"cross-env NODE_ENV=development nest start --watch\",\n\"typeorm\": \"npm run build && npx typeorm -d dist/db/data-source.js\",\n\"migration:generate\": \"npm run typeorm -- migration:generate\",\n\"migration:run\": \"npm run typeorm -- migration:run\",\n\"migration:down\": \"npm run typeorm -- migration:revert\"\n```\n\n```text\n@Module({\n  imports: [\n...\n    ConfigModule.forRoot({\n      envFilePath: `.${process.env.NODE_ENV}.env`,\n    }),\n  ],\n...\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\ndata-source.ts\n```\n\n```text\nApp.module.ts\n```\n\n```text\nnpx typeorm ...\n```\n\n```text\nConfigModule.forRoot\n```\n\n```text\ndotenv\n```\n\n```text\n@nestjs/config\n```\n\n```text\nprocess.env\n```\n\n```js\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nimport { resolve } from 'path';\n\nconfig({ path: resolve(__dirname, '.env') });\n\nconst DataSourceConfig = new DataSource({\n  type: 'mysql',\n  host: process.env.TYPEORM_HOST,\n  port: Number(process.env.TYPEORM_PORT),\n  username: process.env.TYPEORM_USERNAME,\n  password: process.env.TYPEORM_PASSWORD,\n  database: process.env.TYPEORM_DATABASE,\n  migrations: ['./database/migrations/*'],\n  synchronize: false,\n  extra: {\n    charset: 'utf8mb4',\n  },\n  migrationsTableName: 'migrations',\n});\n\nexport default DataSourceConfig;\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';\n\n@Injectable()\nexport class TypeOrmConfigService implements TypeOrmOptionsFactory {\n  constructor(private configService: ConfigService) {}\n\n  public createTypeOrmOptions(): TypeOrmModuleOptions {\n    return {\n      type: 'mysql',\n      host: this.configService.get<string>('TYPEORM_HOST'),\n      port: this.configService.get<number>('TYPEORM_PORT'),\n      username: this.configService.get<string>('TYPEORM_USERNAME'),\n      password: this.configService.get<string>('TYPEORM_PASSWORD'),\n      database: this.configService.get<string>('TYPEORM_DATABASE'),\n      autoLoadEntities: true,\n    };\n  }\n}\n```\n\n```js\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),\n  ]\n});\nexport class AppModule {}\n```\n\n```text\n\"migration:run\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:run\",\n\"migration:create\": \"cd database/migrations && typeorm-ts-node-commonjs migration:create\",\n\"migration:revert\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:revert\"\n```\n\n```text\ntypeorm.config.ts\n```\n\n```text\ntypeorm.service.js\n```\n\n```text\napp.module.ts\n```\n\n```text\npackage.json\n```\n\n```text\ntypeorm-ts-node-commonjs\n```\n\n```text\ntypeorm.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":302,"estimatedTokens":1825}}871{"id":"stack-67997029","source":"stackoverflow","questionId":67997029,"title":"Mongoose - can't access createdAt","tags":["typescript","mongodb","express","mongoose","nestjs"],"text":"Title: Mongoose - can't access createdAt\nTags: typescript, mongodb, express, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm creating a NestJs application using Mongoose, I'm currently having a problem trying to access createdAt even though I have set timestamps to true, my code is below.\n\nproduct.schema.ts\n\n```\n@Schema({timestamps: true})\nexport class Product extends Document {\n @Prop({ required: true })\n name!: string;\n}\n```\n\nproduct.service.ts\n\n```\npublic async getProduct(name: string): Promise {\n const existingProduct = await this.productModel.findOne({ name });\n\n if (!existingProduct) {\n throw new NotFoundException();\n }\n\n existingProduct.createdAt //Property 'createdAt' does not exist on type 'Product'\n }\n```\n\n========================================\n\nCode:\n```text\n@Schema({timestamps: true})\nexport class Product extends Document {\n  @Prop({ required: true })\n  name!: string;\n}\n```\n\n```text\npublic async getProduct(name: string): Promise<void> {\n    const existingProduct = await this.productModel.findOne({ name });\n\n    if (!existingProduct) {\n      throw new NotFoundException();\n    }\n\n    existingProduct.createdAt //Property 'createdAt' does not exist on type 'Product'\n  }\n```\n\n```text\ntimestamps: true\n```\n\n```text\n@Prop()\n```\n\n========================================\n\nComments:\n- So do you mean I should use a constructor in the class?\n- I mean you just need to add the two properties to your `Product` class without the `@Prop()` decorator\n- @JayMcDoniel one question, can add an explanation to your answer for why then we have devs who are using `@Prop` decorator: stackoverflow.com/q/67799847/8784518","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":410}}872{"id":"stack-76077468","source":"stackoverflow","questionId":76077468,"title":"NestJS - ConfigService GET method is undefined when called within onModuleInit()","tags":["javascript","typescript","class","nestjs","lifecycle"],"text":"Title: NestJS - ConfigService GET method is undefined when called within onModuleInit()\nTags: javascript, typescript, class, nestjs, lifecycle\nSource: Stack Overflow\n\nQuestion:\nI'm trying to setup a transporter in the NestJS lifecylce method `onModuleInit()` with the npm library \"Nodemailer\". So that I can easily send emails from other services in my backend, but I'm getting an error that says the `get` method is undefined on `configService`. Bear in mind I can successfully retrieve my environment variables from other methods within my `MailService` class, it's just the `onModuleInit()` that's cause for grief. Is there some OOP principle that I'm not privy to which is my cause for issue? Any help appreciated, thanks in advance!\n\n**CODE**\n\n```\nimport { OnModuleInit } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport * as nodemailer from 'nodemailer';\nimport SMTPTransport from 'nodemailer/lib/smtp-transport';\n\ninterface EnvironmentVariables {\n MAIL_USER: string;\n MAIL_PASS: string;\n}\n\nexport class MailService implements OnModuleInit {\n transporter: nodemailer.Transporter;\n constructor(private configService: ConfigService) {}\n\n onModuleInit() {\n this.transporter = nodemailer.createTransport(\n {\n host: 'smtp.office365.com',\n secure: false,\n tls: {\n ciphers: 'SSLv3',\n },\n auth: {\n user: this.configService.get('MAIL_USER', { infer: true }),\n pass: this.configService.get('MAIL_PASS', { infer: true }),\n },\n logger: true,\n allowInternalNetworkInterfaces: false,\n })\n }\n```\n\n**ERROR**\n\n```\nuser: this.configService.get('MAIL_USER', { infer: true }),\n ^\nTypeError: Cannot read properties of undefined (reading 'get')\n```\n\nI was able to successfully retrieve environment variables with the `get` method in other methods that I had defined within the `MailService` class that I had created.\n\n========================================\n\nCode:\n```text\nimport { OnModuleInit } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport * as nodemailer from 'nodemailer';\nimport SMTPTransport from 'nodemailer/lib/smtp-transport';\n\ninterface EnvironmentVariables {\n  MAIL_USER: string;\n  MAIL_PASS: string;\n}\n\nexport class MailService implements OnModuleInit {\n  transporter: nodemailer.Transporter<SMTPTransport.SentMessageInfo>;\n  constructor(private configService: ConfigService<EnvironmentVariables>) {}\n\n  onModuleInit() {\n    this.transporter = nodemailer.createTransport(\n      {\n        host: 'smtp.office365.com',\n        secure: false,\n        tls: {\n          ciphers: 'SSLv3',\n        },\n        auth: {\n          user: this.configService.get('MAIL_USER', { infer: true }),\n          pass: this.configService.get('MAIL_PASS', { infer: true }),\n        },\n        logger: true,\n        allowInternalNetworkInterfaces: false,\n      })\n   }\n```\n\n```text\nuser: this.configService.get('MAIL_USER', { infer: true }),\n                                   ^\nTypeError: Cannot read properties of undefined (reading 'get')\n```\n\n```text\nonModuleInit()\n```\n\n```text\nget\n```\n\n```text\nconfigService\n```\n\n```text\nMailService\n```\n\n```text\nonModuleInit()\n```\n\n```text\nget\n```\n\n```text\nMailService\n```\n\n```text\n@Injectable()\n```\n\n========================================\n\nComments:\n- That was it thanks! Can't believe it was such a simple issue. ๐Ÿ˜…","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":130,"estimatedTokens":823}}873{"id":"stack-75474899","source":"stackoverflow","questionId":75474899,"title":"ERROR [ExceptionHandler] Cannot read property '__guards__' of undefined in NestJs","tags":["typescript","authentication","nestjs","passport.js"],"text":"Title: ERROR [ExceptionHandler] Cannot read property '__guards__' of undefined in NestJs\nTags: typescript, authentication, nestjs, passport.js\nSource: Stack Overflow\n\nQuestion:\nI'm working on implementing a simple authentication in a Nest project.\n\nWhen I add\n\n```\n@UseGuards(AuthGuard('local'))\n```\n\nto my controller I have the following Error :\n\n```\nERROR [ExceptionHandler] Cannot read property '__guards__' of undefined\n at /home/cedric/Bureau/programmation/project_bank/project/node_modules/@nestjs/core/scanner.js:147:152\n```\n\nI followed all the Nest official documentation to do this.\n\nMy controller is\n\n```\n@UseGuards(AuthGuard('local'))\n @Post('login')\n async login(@Request() req) {\n console.log(req.body.username);\n return req.body.username;\n }\n```\n\nand my auth.guard.ts\n\n```\n@Injectable()\nexport class LocalAuthGuard extends AuthGuard('local') {}\n```\n\n========================================\n\nTop Answer:\nIt really was a dependency version mismatch.\n\nI followed this procedure to update my project :\n\n- Install ncu from the npm-check-updates library:\n\n```\nsudo npm install -g npm-check-updates\n```\n\n- Run ncu in the project folder :\n\n```\nncu\n```\n\n- Update your dependencies:\n\n```\nncu -u\n```\n\n- Finally, install the updates\n\n```\nnpm install\n```\n\n========================================\n\nCode:\n```text\n@UseGuards(AuthGuard('local'))\n```\n\n```text\nERROR [ExceptionHandler] Cannot read property '__guards__' of undefined\n at /home/cedric/Bureau/programmation/project_bank/project/node_modules/@nestjs/core/scanner.js:147:152\n```\n\n```text\n@UseGuards(AuthGuard('local'))\n  @Post('login')\n  async login(@Request() req) {\n    console.log(req.body.username);\n    return req.body.username;\n  }\n```\n\n```text\n@Injectable()\nexport class LocalAuthGuard extends AuthGuard('local') {}\n```\n\n```text\n@nestjs/platform-express\n```\n\n```text\n@nestjs/core\n```\n\n```text\n@nestjs/common\n```\n\n```text\nsudo npm install -g npm-check-updates\n```\n\n```text\nncu\n```\n\n```text\nncu -u\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- can you the output of `npx nest info`\n- Of course ! [System Information] OS Version : Linux 5.15 NodeJS Version : v16.0.0 NPM Version : 7.10.0 [Nest CLI] Nest CLI Version : 9.1.9 [Nest Platform Information] platform-express version : 9.2.1 schematics version : 9.0.4 passport version : 9.0.3 swagger version : 6.1.4 testing version : 9.3.7 common version : 9.2.1 core version : 9.3.7 cli version : 9.1.9\n- Perfect!! I instanciated a new project in which I copied my code. This project is workind. The only differences between the two project was the platform-express version : 9.2.1 to 9.3.8! I just needed to update.","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":131,"estimatedTokens":666}}874{"id":"stack-74570823","source":"stackoverflow","questionId":74570823,"title":"How to Validate Array of Urls using Class-Validator?","tags":["typescript","nestjs","dto","class-validator"],"text":"Title: How to Validate Array of Urls using Class-Validator?\nTags: typescript, nestjs, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI am using Class-Validator to validate Properties of DTOs for Nest.js Application. In there I have a Property \"images\", which is an Array of Strings and those Strings are Urls. So, I want to validate each and every Url in that Array.\n\n```\nclass SomeDto {\n// ...\n \n// Array of Urls\n@IsArray()\n@IsUrl({each:true})\nimages: string[];\n\n// ...\n}\n```\n\nBut this doesn't seem to work. Does anyone know how to validate this Array of Urls.\n\n========================================\n\nCode:\n```js\nclass SomeDto {\n// ...\n       \n// Array of Urls\n@IsArray()\n@IsUrl({each:true})\nimages: string[];\n\n// ...\n}\n```\n\n```text\nexport declare function IsUrl(options?: ValidatorJS.IsURLOptions, validationOptions?: ValidationOptions): PropertyDecorator;\n```\n\n```text\nclass SomeDto {\n// ...\n       \n// Array of Urls\n@IsArray()\n@IsUrl({}, { each: true })\nimages: string[];\n\n// ...\n}\n```\n\n```text\nIsUrl\n```\n\n```text\nValidationOptions\n```\n\n```text\n{ each: true }\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":66,"estimatedTokens":270}}875{"id":"stack-73339762","source":"stackoverflow","questionId":73339762,"title":"What is the difference between @nestjs/websockets and @nestjs/platform-socket.io packages in NestJS","tags":["websocket","socket.io","nestjs"],"text":"Title: What is the difference between @nestjs/websockets and @nestjs/platform-socket.io packages in NestJS\nTags: websocket, socket.io, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have researched this topic online and have found nearly-similar questions to this - But, I need to know why in NestJS we have to use two packages to implement WebSocket communication.\n\nThe two packages are,\n\n- @nestjs/websockets\n\n- @nestjs/platform-socket.io\n\nI understand that WebSocket is the protocol and Socket.IO is a library which has both server and client versions of it.\n\nIn the gateway file of NestJS when implementing a WebSocket connection, one has to write code similar to below.\n\n```\nimport {\n ConnectedSocket,\n MessageBody,\n OnGatewayConnection,\n OnGatewayDisconnect,\n SubscribeMessage,\n WebSocketGateway,\n WebSocketServer,\n} from '@nestjs/websockets';\n\nimport { Server } from 'socket.io';\n```\n\nMy questions,\n\nWhat is the difference between `WebSocketServer` and `Server` here?\n\nWhy do we import `Server` from `socket.io` and not `@nestjs/platform-socket.io`?\n\nHow do you describe the purpose of using each of these packages in a single sentence?\n\n========================================\n\nCode:\n```js\nimport {\n  ConnectedSocket,\n  MessageBody,\n  OnGatewayConnection,\n  OnGatewayDisconnect,\n  SubscribeMessage,\n  WebSocketGateway,\n  WebSocketServer,\n} from '@nestjs/websockets';\n\nimport { Server } from 'socket.io';\n```\n\n```text\nWebSocketServer\n```\n\n```text\nServer\n```\n\n```text\nServer\n```\n\n```text\nsocket.io\n```\n\n```text\n@nestjs/platform-socket.io\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\n@nestjs/platform-socket.io\n```\n\n```text\nsocket.io\n```\n\n```text\n@nestjs/platform-ws\n```\n\n```text\nws\n```\n\n```text\nWebsocketServer\n```\n\n```text\nServer\n```\n\n```text\nSocket\n```\n\n```text\nsocket.io\n```\n\n```text\n@nestjs/platform-socket.io\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\n@nestjs/platform-socket.io\n```\n\n```text\nsocket.io\n```\n\n========================================\n\nComments:\n- I'm super thankful for this answer. Probably the fastest and one of the best answers I have received. This cleared a lot for me. Thanks @Jay!","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":132,"estimatedTokens":528}}876{"id":"stack-60237786","source":"stackoverflow","questionId":60237786,"title":"Class Validator @ValidateIf() not working properly","tags":["node.js","nestjs","class-validator"],"text":"Title: Class Validator @ValidateIf() not working properly\nTags: node.js, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI have the following class in nest js with this class validator:\n\n```\n@ValidateIf(val => val !== '*')\n @IsObject()\n @IsNotEmptyObject()\n queryParams: DbQuery | '*';\n```\n\nIf I send '*' it returns\n\n```\n[ 'queryParams must be a non-empty object' ]\n```\n\n========================================\n\nCode:\n```text\n@ValidateIf(val => val !== '*')\n @IsObject()\n @IsNotEmptyObject()\n queryParams: DbQuery | '*';\n```\n\n```text\n[ 'queryParams must be a non-empty object' ]\n```\n\n```text\n@ValidateIf(val => val.queryParams !== '*')\n@IsNotEmptyObject()\nqueryParams: DbQuery | '*';\n```\n\n========================================\n\nComments:\n- Does not work, either. I used @IsInt(ALWAYS) @ValidateIf(o => o.angle !== 127) @Min(-27, ALWAYS) @Max(90, ALWAYS) @IsOptional(ALWAYS) // eslint-disable-next-line max-len @ApiPropertyOptional({ type: Number, example: 3, }) public angle: number;\n- Sry, my mistake was: I forgot to add ALWAYS to validateIf @ValidateIf(o => o.angle !== 127, ALWAYS)","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":45,"estimatedTokens":275}}877{"id":"stack-67307883","source":"stackoverflow","questionId":67307883,"title":"NestJs using middleware on all routes","tags":["routes","nestjs","middleware"],"text":"Title: NestJs using middleware on all routes\nTags: routes, nestjs, middleware\nSource: Stack Overflow\n\nQuestion:\nI'm new to nestjs, and I'm using a middleware to authenticate my users. I would like to apply that for all routes. I'm currently adding controller one by one and it's becoming redundant.\n\n```\nexport class AppModule implements NestModule {\n public configure(consumer: MiddlewareConsumer): void {\n consumer.apply(GetUserMiddleware).forRoutes(\n UserController,\n //***\n );\n }\n}\n```\n\nI've surfed the documentation and could not find it (NestJs - Middleware).\n\nHow can I change this to get my middleware to work on all routes?\n\n========================================\n\nTop Answer:\n**1st Method:**\n\nIf you want to use your middleware on every route you can use global middleware.\n\n```\nconst app = await NestFactory.create(AppModule);\napp.use(yourMiddlewareMethod);\nawait app.listen(3000);\n```\n\nNOTE: Though this would work for every route so the user won't be able to login. In this case, you can override the usage of middleware on your user module by excluding it in `app.module.ts` like this\n\n```\nconsumer\n .apply(yourMiddlewareMethod)\n .exclude(\n { path: 'yourPath', method: RequestMethod.GET },\n { path: 'yourPath', method: RequestMethod.POST },\n 'yourPath/(.*)',\n )\n .forRoutes(yourController);\n```\n\n**2nd Method:**\n\nIn `app.module.ts` :\n\n```\n...\n export class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(yourMiddlewareMethod)\n .forRoutes(yourController);\n }\n }\n```\n\nHope this answers your question.\n\n========================================\n\nCode:\n```js\nexport class AppModule implements NestModule {\n  public configure(consumer: MiddlewareConsumer): void {\n    consumer.apply(GetUserMiddleware).forRoutes(\n      UserController,\n      //***\n    );\n  }\n}\n```\n\n```js\nexport class AppModule implements NestModule {\n  public configure(consumer: MiddlewareConsumer): void {\n    consumer.apply(GetUserMiddleware).forRoutes('*');\n  }\n}\n```\n\n```js\nexport class AppModule implements NestModule {\n  public configure(consumer: MiddlewareConsumer): void {\n    consumer.apply(GetUserMiddleware).forRoutes('{*splat}');\n  }\n}\n```\n\n```text\n'*'\n```\n\n```text\nforRoutes()\n```\n\n```text\n'{*splat}'\n```\n\n```text\nforRoutes()\n```\n\n```js\nimport { RequestMethod } from '@nestjs/common';\n// ...\n      .forRoutes({\n        path: '*',\n        method: RequestMethod.ALL,\n      });\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\napp.use(yourMiddlewareMethod);\nawait app.listen(3000);\n```\n\n```text\nconsumer\n  .apply(yourMiddlewareMethod)\n  .exclude(\n    { path: 'yourPath', method: RequestMethod.GET },\n    { path: 'yourPath', method: RequestMethod.POST },\n    'yourPath/(.*)',\n  )\n  .forRoutes(yourController);\n```\n\n```text\n...\n    export class AppModule implements NestModule {\n      configure(consumer: MiddlewareConsumer) {\n        consumer\n          .apply(yourMiddlewareMethod)\n          .forRoutes(yourController);\n      }\n    }\n```\n\n```text\napp.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nimport { createProxyMiddleware } from 'http-proxy-middleware';\nimport { StProxyService } from './st-proxy.service';\nimport { StProxyController } from './st-proxy.controller';\n\nexport class StProxyModule implements NestModule {\n  constructor(private readonly stProxyyService: StProxyService) {}\n\n  configure(consumer: MiddlewareConsumer) {\n    const stProxyMiddleware =\n      createProxyMiddleware(this.stProxyyService.getDefaultOptions());\n    consumer\n      .apply(stProxyMiddleware)\n      .forRoutes(StProxyController);\n  }\n}\n```\n\n```text\n@Controller('st-proxy')\nexport class StProxyController {\n  @All('*')\n  noopAction(): string {\n    return 'This action is no operation';\n  }\n}\n```\n\n========================================\n\nComments:\n- This worked for me\n- I've tried a similar approach, but the request keeps hanging. Can you the code?","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":189,"estimatedTokens":973}}878{"id":"stack-73824060","source":"stackoverflow","questionId":73824060,"title":"How can I validate a file type using Nestjs Pipes and FileTypeValidator","tags":["typescript","nestjs"],"text":"Title: How can I validate a file type using Nestjs Pipes and FileTypeValidator\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have implemented a simple Nestjs route inside of an controller with a file upload. The file is handled with Multer. Since its porpuse is to edit a profile picture of a user I need to validate the file to be an image. However for some reason I can't get it running with the `FileTypeValidator`. The uploaded file is being denied each time.\n\n```\n@UseInterceptors(\n FileInterceptor('file', {\n storage: MulterService.getStorage((req, file, cb) => {\n const filename = `${uuidv4()}`;\n const extension = path.parse(file.originalname).ext;\n\n cb(null, `${filename}${extension}`);\n }, MulterService.destinations.profilePictures),\n })\n)\n@Post('profile-picture')\neditProfilePicture(\n @UploadedFile(\n new ParseFilePipe({\n validators: [new FileTypeValidator({ fileType: 'png' })],\n // png files always denied\n // /\\^(jpeg|jpg|png|gif)$/ regex isn't working either\n })\n )\n file: Express.Multer.File\n): Promise {\n // ...\n}\n```\n\n========================================\n\nTop Answer:\nIf this`/\\.(jpg|jpeg|png)$/` will not work use this`'.(png|jpeg|jpg)'`\n\n```\n@UploadedFile(\n new ParseFilePipe({\n validators: [\n new MaxFileSizeValidator({ maxSize: max size of file in bytes }),\n new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' }),\n ],\n }),\n )\n file: Express.Multer.File\n```\n\n========================================\n\nCode:\n```text\n@UseInterceptors(\n  FileInterceptor('file', {\n    storage: MulterService.getStorage((req, file, cb) => {\n      const filename = `${uuidv4()}`;\n      const extension = path.parse(file.originalname).ext;\n\n      cb(null, `${filename}${extension}`);\n    }, MulterService.destinations.profilePictures),\n  })\n)\n@Post('profile-picture')\neditProfilePicture(\n  @UploadedFile(\n    new ParseFilePipe({\n      validators: [new FileTypeValidator({ fileType: 'png' })],\n      // png files always denied\n      // /\\^(jpeg|jpg|png|gif)$/ regex isn't working either\n    })\n  )\n  file: Express.Multer.File\n): Promise<User> {\n  // ...\n}\n```\n\n```text\nFileTypeValidator\n```\n\n```text\n@UploadedFile(\n    new ParseFilePipe({\n      validators: [\n        new MaxFileSizeValidator({ maxSize: max size of file in bytes }),\n        new FileTypeValidator({ fileType: /^image/ }),\n      ],\n    }),\n  )\n  file: Express.Multer.File\n```\n\n```text\nimage/\n```\n\n```text\n^\n```\n\n```text\nimage\n```\n\n```text\nimage\n```\n\n```text\n\\.\n```\n\n```text\n(jpeg|jpg|png|gif)$\n```\n\n```text\n@UploadedFile(\n    new ParseFilePipe({\n      validators: [\n        new MaxFileSizeValidator({ maxSize: max size of file in bytes }),\n        new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' }),\n      ],\n    }),\n  )\n  file: Express.Multer.File\n```\n\n```text\n/\\.(jpg|jpeg|png)$/\n```\n\n```text\n'.(png|jpeg|jpg)'\n```\n\n========================================\n\nComments:\n- I tried using the above pattern and I'm getting error: Validation failed (expected type is /\\\\.(jpg|jpeg|png)$/)\",\n- Code-only answers should be updated to explain how the code resolves the question, further guidance can be found in the Help Center\n- Wow, I remember that this was actually my problem back in the day. For some reason I never came back to this question. Thanks for posting this!","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":145,"estimatedTokens":814}}879{"id":"stack-70517803","source":"stackoverflow","questionId":70517803,"title":"NestJs: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string","tags":["node.js","postgresql","nestjs"],"text":"Title: NestJs: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\nTags: node.js, postgresql, nestjs\nSource: Stack Overflow\n\nQuestion:\ni have a problem with connecting to database in nest.js with typeorm and postgres.\n\nI created a **.env file** in the root project directory with the following content\n\n```\nPOSTGRES_HOST=127.0.0.1\nPOSTGRES_PORT=5432\nPOSTGRES_USER=postgres\nPOSTGRES_PASSWORD=password\nPOSTGRES_DATABASE=db-name\n```\n\nIn the **app.module.ts** I writed the code below:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { FeedModule } from './feed/feed.module';\n\n @Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: process.env.POSTGRES_HOST,\n port: parseInt(process.env.POSTGRES_PORT),\n username: process.env.POSTGRES_USER,\n password: process.env.POSTGRES_PASSWORD,\n database: process.env.POSTGRES_DATABASE,\n autoLoadEntities: true,\n synchronize: true,\n }),\n FeedModule,\n ],\n \n})\nexport class AppModule {}\n```\n\nBut when im running the app by npm start it throws this error: `new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')`\n\nWhat am I missing or doing wrong?\n\n========================================\n\nTop Answer:\nI was able to fix the problem by using the config module.\n\nJust do `npm i @nestjs/config`. Then in the imports array just above the TypeOrmModule put `ConfigModule.forRoot({ isGlobal: true }),`. This allows your module to get the environment variables from the `.env` file\n\n========================================\n\nCode:\n```text\nPOSTGRES_HOST=127.0.0.1\nPOSTGRES_PORT=5432\nPOSTGRES_USER=postgres\nPOSTGRES_PASSWORD=password\nPOSTGRES_DATABASE=db-name\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { FeedModule } from './feed/feed.module';\n\n  @Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    TypeOrmModule.forRoot({\n      type: 'postgres',\n      host: process.env.POSTGRES_HOST,\n      port: parseInt(<string>process.env.POSTGRES_PORT),\n      username: process.env.POSTGRES_USER,\n      password: process.env.POSTGRES_PASSWORD,\n      database: process.env.POSTGRES_DATABASE,\n      autoLoadEntities: true,\n      synchronize: true,\n    }),\n    FeedModule,\n  ],\n  \n})\nexport class AppModule {}\n```\n\n```text\nnew Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')\n```\n\n```text\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot(\n      envFilePath: `.${process.env.NODE_ENV}.env`\n    ),\n    TypeOrmModule.forRootAsync({\n      imports: [ConfigModule],\n      injects: [ConfigService],\n      useFactory: (configService: ConfigService) => ({\n        type: 'postgres',\n        host: configService.get(\"POSTGRES_HOST\"),\n        port: configService.get(\"POSTGRES_PORT\"),\n        username: configService.get(\"POSTGRES_USER\"),\n        password: configService.get(\"POSTGRES_PASSWORD\"),\n        database: configService.get(\"POSTGRES_DB\"),\n        entities: [],\n        synchronize: true,\n      }),\n    }),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\nTypeOrmModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: (configService: ConfigService) => ({\n    type: 'postgres',\n    host: configService.get('POSTGRES_HOST'),\n    port: +configService.get<number>('POSTGRES_PORT'),\n    username: configService.get('POSTGRES_USER'),\n    password: configService.get('POSTGRES_PASSWORD'),\n    database: configService.get('POSTGRES_DATABASE'),\n    synchronize: true,\n    autoLoadEntities: true,\n  }),\n  inject: [ConfigService],\n});\n```\n\n```text\nnpm i @nestjs/config\n```\n\n```text\nConfigModule.forRoot({ isGlobal: true }),\n```\n\n```text\n.env\n```\n\n```text\nnpm run build\n```\n\n========================================\n\nComments:\n- as trivial as it gets...this was the cause of my problem! Thanks for sharing!","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":165,"estimatedTokens":1039}}880{"id":"stack-73495506","source":"stackoverflow","questionId":73495506,"title":"How to get client ip in nestjs","tags":["ip","nestjs"],"text":"Title: How to get client ip in nestjs\nTags: ip, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to get an ip to record user logins.\n\nI tried `nestjs-real-ip` and `@Ip()`.\n\nAnd I tried to log in through my mobile phone and pc browser,\n\nbut all of them show `:::1`. How do I get the client's real IP?\n\n========================================\n\nTop Answer:\nBased on the Nestjs docs, You can use a decorator named `Ip` as \n\n```\nimport { Get, Ip } from \"@nestjs/common\"\n\n@Get('my-ip')\nasync getMyIp(@Ip() ip){\n return ip;\n}\n```\n\n========================================\n\nCode:\n```text\nnestjs-real-ip\n```\n\n```text\n@Ip()\n```\n\n```text\n:::1\n```\n\n```text\ncurl localhost:3000/ip\n::ffff:127.0.0.1\n```\n\n```text\ncurl 174.38.167.56:3000/ip\n::ffff:174.38.167.56\n```\n\n```js\nimport { Controller, Get, Req } from '@nestjs/common';\nimport { Request } from 'express';\n\n@Controller('ip')\nexport class IpController {\n    @Get()\n    getIpAddressFromRequest(@Req() request: Request): string {\n        return request.ip;\n    }\n}\n```\n\n```text\n:::1\n```\n\n```text\n127.0.0.1\n```\n\n```text\ncurl\n```\n\n```text\nffff\n```\n\n```text\nrequest.ip\n```\n\n```text\nimport { Get, Ip } from \"@nestjs/common\"\n\n@Get('my-ip')\nasync getMyIp(@Ip() ip){\n  return ip;\n}\n```\n\n```text\nIp\n```\n\n========================================\n\nComments:\n- Also, this will not work with GraphQL resolvers. github.com/nestjs/nest/issues/4453","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":102,"estimatedTokens":343}}881{"id":"stack-61187020","source":"stackoverflow","questionId":61187020,"title":"numeric parameter validation fails although requirements should pass","tags":["typescript","nestjs","class-validator"],"text":"Title: numeric parameter validation fails although requirements should pass\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI want to fetch a location by coordinates. I started with a simple DTO\n\n```\nexport class GetLocationByCoordinatesDTO {\n @IsNumber()\n @Min(-90)\n @Max(90)\n public latitude: number;\n\n @IsNumber()\n @Min(-180)\n @Max(180)\n public longitude: number;\n}\n```\n\nand this API endpoint\n\n```\n@Get(':latitude/:longitude')\npublic getLocationByCoordinates(@Param() { latitude, longitude }: GetLocationByCoordinatesDTO): Promise {\n // ...\n}\n```\n\nTo test this endpoint I'm calling this url\n\n localhost:3000/locations/0/0\n\nand unfortunately I get the following response\n\n```\n{\n \"statusCode\": 400,\n \"message\": [\n \"latitude must not be greater than 90\",\n \"latitude must not be less than -90\",\n \"latitude must be a number conforming to the specified constraints\",\n \"longitude must not be greater than 180\",\n \"longitude must not be less than -180\",\n \"longitude must be a number conforming to the specified constraints\"\n ],\n \"error\": \"Bad Request\"\n}\n```\n\nDoes someone know how to fix this? I would expect it to pass.\n\nIt seems that the url params are considered strings but how can I parse them to numbers then?\n\n========================================\n\nCode:\n```text\nexport class GetLocationByCoordinatesDTO {\n    @IsNumber()\n    @Min(-90)\n    @Max(90)\n    public latitude: number;\n\n    @IsNumber()\n    @Min(-180)\n    @Max(180)\n    public longitude: number;\n}\n```\n\n```text\n@Get(':latitude/:longitude')\npublic getLocationByCoordinates(@Param() { latitude, longitude }: GetLocationByCoordinatesDTO): Promise<Location> {\n  // ...\n}\n```\n\n```text\n{\n    \"statusCode\": 400,\n    \"message\": [\n        \"latitude must not be greater than 90\",\n        \"latitude must not be less than -90\",\n        \"latitude must be a number conforming to the specified constraints\",\n        \"longitude must not be greater than 180\",\n        \"longitude must not be less than -180\",\n        \"longitude must be a number conforming to the specified constraints\"\n    ],\n    \"error\": \"Bad Request\"\n}\n```\n\n```text\nimport { Min, Max, IsNumber } from 'class-validator';\nimport { Type } from 'class-transformer';\n\nexport class GetLocationByCoordinatesDTO {\n  @IsNumber()\n  @Type(() => Number)\n  @Min(-90)\n  @Max(90)\n  public latitude: number;\n\n  @IsNumber()\n  @Type(() => Number)\n  @Min(-180)\n  @Max(180)\n  public longitude: number;\n}\n```\n\n```text\nNumber\n```\n\n```text\nclass-transformer\n```\n\n```text\nnpm i class-transformer -S\n```\n\n========================================\n\nComments:\n- It's worth noting that this solution is also dependent on using the @Param() without specifying parameter tokens to the decorator (e.g. @Param(:id)). Trying to apply type validation on individual parameter tokens will not work. At least as of version 7.6.15.","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":129,"estimatedTokens":709}}882{"id":"stack-64769673","source":"stackoverflow","questionId":64769673,"title":"NestJS external event bus implementation with Redis","tags":["nestjs","cqrs"],"text":"Title: NestJS external event bus implementation with Redis\nTags: nestjs, cqrs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to integrate my nestjs application's cqrs setup with a external message service such as Redis. I've found a pull request and a comment on the nestJS github stating that I should be able to integrate my query/event/command bus with external services since version 7.0 of cqrs.\n\nI've been trying to implement this, but I can't find much information from nestjs on the subject. The only thing I could find was an outdated configuration example and an open topic on github for creating tutorials on how to implement this. I managed to replace the default publisher and subscriper by going off the limited help I could find on github about this topic, but I don't really understand how I can use that to connect to the external service or if this is the best approach for this problem.\n\n**EventBus**\n\n```\nimport { RedisEventSubscriber } from '../busses/redisEventSubscriber';\nimport { RedisEventPublisher } from '../busses/redisEventPublisher';\nimport { OnModuleInit } from '@nestjs/common';\nimport { ModuleRef } from \"@nestjs/core\";\nimport { CommandBus, EventBus as NestJsEventBus } from \"@nestjs/cqrs\";\n\nexport class EventBus extends NestJsEventBus implements OnModuleInit {\n\nconstructor( commandBus: CommandBus, moduleRef: ModuleRef) {\n super(commandBus, moduleRef);\n}\n\nonModuleInit() {\n\n const subscriber = new RedisEventSubscriber();\n subscriber.bridgeEventsTo(this._subject$);\n this.publisher = new RedisEventPublisher();\n\n }\n}\n```\n\n**Publisher**\n\n```\nexport class RedisEventPublisher implements IEventPublisher {\n\npublish(event: T) {\n console.log(\"Event published to Redis\")\n }\n}\n```\n\n**Subscriber**\n\n```\nexport class RedisEventSubscriber implements IMessageSource {\n\n bridgeEventsTo(subject: Subject) {\n console.log('bridged event to thingy')\n }\n}\n```\n\nIf anyone who has setup nestjs with an external message system before could their thoughts or a resource on how to do this properly, that would be appreciated.\n\n========================================\n\nCode:\n```text\nimport { RedisEventSubscriber } from '../busses/redisEventSubscriber';\nimport { RedisEventPublisher } from '../busses/redisEventPublisher';\nimport { OnModuleInit } from '@nestjs/common';\nimport { ModuleRef } from \"@nestjs/core\";\nimport { CommandBus, EventBus as NestJsEventBus } from \"@nestjs/cqrs\";\n\nexport class EventBus extends NestJsEventBus implements OnModuleInit {\n\nconstructor( commandBus: CommandBus, moduleRef: ModuleRef) {\n  super(commandBus, moduleRef);\n}\n\nonModuleInit() {\n\n  const subscriber = new RedisEventSubscriber();\n  subscriber.bridgeEventsTo(this._subject$);\n  this.publisher = new RedisEventPublisher();\n\n  }\n}\n```\n\n```text\nexport class RedisEventPublisher implements IEventPublisher {\n\npublish<T extends IEvent = IEvent>(event: T) {\n  console.log(\"Event published to Redis\")\n  }\n}\n```\n\n```text\nexport class RedisEventSubscriber implements IMessageSource {\n\n  bridgeEventsTo<T extends IEvent>(subject: Subject<T>) {\n    console.log('bridged event to thingy')\n  }\n}\n```\n\n```text\nexport class EventBusService implements IEventBusService {\n  \n  constructor(\n    private local: EventBus, // Injected from NestJS CQRS Module\n    @Inject('eventPublisher') private publisher: IEventPublisher,\n    @Inject('eventSubscriber') subscriber: IMessageSource) {\n      subscriber.bridgeEventsTo(this.local.subject$);\n   }\n  \n  publish(event: IEvent): void {\n    this.publisher.publish(event);\n  };\n}\n```\n\n```text\nexport class RedisEventSubscriber implements IMessageSource {\n\n  constructor(@Inject('redisClient') private client: RedisClient) {}\n\n  bridgeEventsTo<T extends IEvent>(subject: Subject<T>) {\n    this.client.subscribe('Foo');\n    this.client.on(\"message\", (channel: string, message: string) => {\n\n      const { payload, header } = JSON.parse(message);\n      const event = Events[header.name];\n\n      subject.next(new event(data.event.payload));\n    });\n  }\n};\n```\n\n```text\nexport class RedisEventPublisher implements IEventPublisher {\n\n  constructor(@Inject('redisClient') private client: RedisClient) {}\n\n  publish<T extends IEvent = IEvent>(event: T) {\n    const name = event.constructor.name;\n    const request = {\n      header: {\n        name\n      },\n      payload: {\n        event\n      }\n    }\n    this.client.publish('Foo', JSON.stringify(request));\n  }\n}\n```\n\n```text\nexport class EventBusService implements IEventBusService {\n  \n  constructor(\n    private eventBus: EventBus,\n    @Inject('eventPublisher') private eventPublisher: IEventPublisher,) {\n   }\n  \n  public publish<T extends IEvent>(event: T): void {\n\n    const data = {\n      payload: event,\n      eventName: event.constructor.name\n    }\n    \n    this.eventPublisher.publish(data);\n  };\n\n  async handle(string: string) : Promise<void> {\n\n    const data = JSON.parse(string);\n    const event = Events[data.event.eventName];\n\n    if (!event) {\n      console.log(`Could not find corresponding event for \n      ${data.event.eventName}`);\n    };\n\n    await this.eventBus.publish(new event(data.event.payload));\n  }\n}\n```\n\n```text\n@Controller()\nexport default class EventController {\n\n  constructor(@Inject('eventBusService') private eventBusService: \n  IEventBusService) {}\n\n  @EventPattern(inviteServiceTopic)\n  handleInviteServiceEvents(data: string) {\n    this.eventBusService.handle(data)\n  }\n}\n```\n\n```text\n.publish()\n```\n\n```text\n.bridgeEventsTo()\n```\n\n```text\nsubject.next()\n```\n\n```text\n@EventPattern()\n```\n\n```text\n@EventPattern()\n```\n\n========================================\n\nComments:\n- I was wondering if you have any link to a public github/gitlab repository with the complete code?\n- Nope I don't have this in a public repo. All the code you need specifically for this is in the answer. All that is missing is the general NestJS things such as the controllers and injection bits, but that can be found in the docs\n- The docs are not covering this in any significant way. Did you consider to create a PR for adding it?","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":229,"estimatedTokens":1504}}883{"id":"stack-70904341","source":"stackoverflow","questionId":70904341,"title":"How can I have class-transform converting properly the _id of a MongoDB class?","tags":["mongodb","mongoose","nestjs","class-transformer"],"text":"Title: How can I have class-transform converting properly the _id of a MongoDB class?\nTags: mongodb, mongoose, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI've the following MongoDB class:\n\n```\n@Schema()\nexport class Poker {\n @Transform(({ value }) => value.toString())\n _id: ObjectId;\n\n @Prop()\n title: string;\n\n @Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })\n @Type(() => User)\n author: User;\n}\n```\n\nwhich I return, transformed by `class-transform` in a NestJS server.\n\nIt get transformed by an interceptor:\n\n```\n@Get()\n @UseGuards(JwtAuthenticationGuard)\n @UseInterceptors(MongooseClassSerializerInterceptor(Poker))\n async findAll(@Req() req: RequestWithUser) {\n return this.pokersService.findAll(req.user);\n }\n```\n\nI'm not the author of the interceptor, but here is how it is implemented:\n\n```\nfunction MongooseClassSerializerInterceptor(\n classToIntercept: Type,\n): typeof ClassSerializerInterceptor {\n return class Interceptor extends ClassSerializerInterceptor {\n private changePlainObjectToClass(document: PlainLiteralObject) {\n if (!(document instanceof Document)) {\n return document;\n }\n\n return plainToClass(classToIntercept, document.toJSON());\n }\n\n private prepareResponse(\n response: PlainLiteralObject | PlainLiteralObject[],\n ) {\n if (Array.isArray(response)) {\n return response.map(this.changePlainObjectToClass);\n }\n\n return this.changePlainObjectToClass(response);\n }\n\n serialize(\n response: PlainLiteralObject | PlainLiteralObject[],\n options: ClassTransformOptions,\n ) {\n return super.serialize(this.prepareResponse(response), options);\n }\n };\n}\n\nexport default MongooseClassSerializerInterceptor;\n```\n\nThe problem I'm having, is that when I do a *console.log* of the return of my controller, I get this:\n\n```\n[\n {\n _id: new ObjectId(\"61f030a9527e209d8cad179b\"),\n author: {\n _id: new ObjectId(\"61f03085527e209d8cad1793\"),\n password: '--------------------------',\n name: '----------',\n email: '-------------',\n __v: 0\n },\n title: 'Wonderful first poker2',\n __v: 0\n }\n]\n```\n\nBut I get this returned:\n\n```\n[\n {\n \"_id\": \"61f5149643092051ba048c6e\",\n \"author\": {\n \"_id\": \"61f5149643092051ba048c6f\",\n \"name\": \"----------\",\n \"email\": \"-------------\",\n \"__v\": 0\n },\n \"title\": \"Wonderful first poker2\",\n \"__v\": 0\n }\n]\n```\n\nIf you check the id, it's not at all the same. Then the client will ask some data for this ID and receive nothing.\n\nAny idea what am I missing?\n\nAlso, every time I make a GET request, I receive a different value back.\n\n========================================\n\nTop Answer:\nEventually it is solved by\n\n```\n@Transform((value) => value.obj._id.toString())\n```\n\nthanks to J4N\n\n========================================\n\nCode:\n```text\n@Schema()\nexport class Poker {\n  @Transform(({ value }) => value.toString())\n  _id: ObjectId;\n\n  @Prop()\n  title: string;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })\n  @Type(() => User)\n  author: User;\n}\n```\n\n```text\n@Get()\n  @UseGuards(JwtAuthenticationGuard)\n  @UseInterceptors(MongooseClassSerializerInterceptor(Poker))\n  async findAll(@Req() req: RequestWithUser) {\n    return this.pokersService.findAll(req.user);\n  }\n```\n\n```text\nfunction MongooseClassSerializerInterceptor(\n  classToIntercept: Type,\n): typeof ClassSerializerInterceptor {\n  return class Interceptor extends ClassSerializerInterceptor {\n    private changePlainObjectToClass(document: PlainLiteralObject) {\n      if (!(document instanceof Document)) {\n        return document;\n      }\n\n      return plainToClass(classToIntercept, document.toJSON());\n    }\n\n    private prepareResponse(\n      response: PlainLiteralObject | PlainLiteralObject[],\n    ) {\n      if (Array.isArray(response)) {\n        return response.map(this.changePlainObjectToClass);\n      }\n\n      return this.changePlainObjectToClass(response);\n    }\n\n    serialize(\n      response: PlainLiteralObject | PlainLiteralObject[],\n      options: ClassTransformOptions,\n    ) {\n      return super.serialize(this.prepareResponse(response), options);\n    }\n  };\n}\n\nexport default MongooseClassSerializerInterceptor;\n```\n\n```text\n[\n  {\n    _id: new ObjectId(\"61f030a9527e209d8cad179b\"),\n    author: {\n      _id: new ObjectId(\"61f03085527e209d8cad1793\"),\n      password: '--------------------------',\n      name: '----------',\n      email: '-------------',\n      __v: 0\n    },\n    title: 'Wonderful first poker2',\n    __v: 0\n  }\n]\n```\n\n```text\n[\n    {\n        \"_id\": \"61f5149643092051ba048c6e\",\n        \"author\": {\n            \"_id\": \"61f5149643092051ba048c6f\",\n            \"name\": \"----------\",\n            \"email\": \"-------------\",\n            \"__v\": 0\n        },\n        \"title\": \"Wonderful first poker2\",\n        \"__v\": 0\n    }\n]\n```\n\n```text\nclass-transform\n```\n\n```text\n@Transform(params => params.obj._id)\n```\n\n```text\n@Transform(({ key, obj }) => obj[key])\n```\n\n```text\nconst mongoose = require('mongoose')\n\nconst mySchema = new mongoose.Schema({\n    field: String\n}, {\n    toJSON: {\n        transform(doc, ret) {\n            ret.id = ret._id;\n            delete ret._id;\n            delete ret.__v;\n        }\n    }\n})\n\nmodule.exports = mongoose.model(\"MySchema\", mySchema)\n```\n\n```text\nimport { Document } from 'mongoose';\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\nexport type MyDocument = MyClass & Document;\n\n@Schema({\n  toJSON: {\n    transform(doc, ret) {\n      ret.id = ret._id;\n      delete ret._id;\n      delete ret.__v;\n    },\n  },\n})\nexport class MyClass {\n  @Prop()\n  field: string;\n}\n\nexport const MySchema = SchemaFactory.createForClass(MyClass);\n```\n\n```text\n@nestjs/mongoose\n```\n\n```text\nnew mongoose.Schema\n```\n\n```text\n@Schema\n```\n\n```text\n@Transform((value) => value.obj._id.toString())\n```\n\n```ts\n...\nexport class Order {\n  // For root _id\n  @Type(() => String)\n  _id: mongoose.Types.ObjectId\n\n  // For subdoc _id\n  @Prop({ required: true, type: mongoose.Schema.Types.ObjectId, ref: User.name })\n  @Type(({ newObject, object, property }) => {\n    // if `createdAt` exists ok it's `populate`\n    if (object[property].createdAt) {\n      return User\n    } else {\n      return String\n    }\n  })\n  user: User\n  ...\n\n}\n```\n\n```ts\nexport class User {\n  @Type(() => String)\n  _id: mongoose.Types.ObjectId\n}\n```\n\n```ts\nexport class OrderController {\n  ...\n  @Get('item/:id')\n  @SerializeOptions({ type: Order })\n  @UseInterceptors(ClassSerializerInterceptor)\n  async item(@Param('id') id: string) {\n    const item = await this.orderService.getItem(id)\n    return item.toJSON()\n  }\n\n  @Get('list')\n  @SerializeOptions({ type: Order })\n  @UseInterceptors(ClassSerializerInterceptor)\n  async list() {\n    const item = await this.orderService.getList()\n    return item.map((v) => v.toJSON())\n  }\n  ...\n}\n```\n\n```ts\nexport class OrderService {\n  ...\n\n  async getItem(id: string) {\n    const query = this.orderModel.findOne()\n    // query.populate({\n    //   path: 'user'\n    // })\n    query.where({\n      _id: id\n    })\n    return query.exec()\n  }\n\n  async getList() {\n    const query = this.orderModel.find()\n    // query.populate({\n    //   path: 'user'\n    // })\n    return query.exec()\n  }\n  ...\n}\n```\n\n```text\nObjectId\n```\n\n```text\nString\n```\n\n```text\nclass-transform\n```\n\n```text\n@Type(() => String)\n```\n\n```text\n@Transform\n```\n\n```text\nplain2class\n```\n\n```text\nclass2plain\n```\n\n```text\nUser\n```\n\n```text\nString\n```\n\n```text\nimport { ObjectId } from 'mongodb';\n\nexport default function TransformMongoId() {\n    return function (_target: any, _propertyName: string, descriptor: PropertyDescriptor) {\n        const originalMethod = descriptor.value;\n\n        descriptor.value = async function (...args: unknown[]) {\n            try {\n                const result = await originalMethod.apply(this, args);\n\n                const transform = (obj: any) => {\n                    if (obj?._id instanceof ObjectId) {\n                        obj.id = obj._id.toString();\n                        delete obj._id;\n                    }\n                    return obj;\n                };\n\n                if (Array.isArray(result)) {\n                    return result.map(transform);\n                } else {\n                    return transform(result);\n                }\n            } catch (error) {\n                throw error;\n            }\n        };\n\n        return descriptor;\n    };\n}\n```\n\n```text\n@Expose()\n  @Transform(({ value }: {value: string}) => value.toString(), { \n  toPlainOnly: true })\n  id: string;\n```\n\n```text\nfindAll() {\n    return this.categoryModel.find().sort({ sort: 1 }).lean().exec();\n  }\n```\n\n```text\n@Get()\n  async getAll() {\n    const categories = await this.categoryService.findAll();\n    return categories.map((cat) => new CategoryDto(cat));\n  }\n```\n\n```text\nasync signIn(username: string, password: string): Promise<any> {\n    const user = await this.usersService.findOne({ username });\n    if (!user) throw new BadRequestException('invalid_payload');\n\n    const compare = await this.usersService.verifyPassword(user, password);\n    if (!compare) throw new BadRequestException('invalid_payload');\n\n    const [accessToken, refreshToken] = await Promise.all([\n      this.genAccessToken(user.id),\n      this.genRefreshToken(user.id),\n    ]);\n\n    return {\n      user: user.toObject(),\n      accessToken,\n      refreshToken,\n    };\n  }\n```\n\n```text\n@Post('login')\n  async signIn(@Body() signInDto: SignInDto) {\n    const { username, password } = signInDto;\n    const { user, accessToken, refreshToken } = await this.authService.signIn(\n      username,\n      password,\n    );\n    return {\n      user: new UserResponseDto(user),\n      accessToken,\n      refreshToken,\n    };\n  }\n```\n\n```text\nclass-transformer\n```\n\n```text\nlean\n```\n\n```text\n.toObject()\n```\n\n========================================\n\nComments:\n- Hi, thank you for the answer, I actually ended by doing the same as you: `@Transform((value) => value.obj._id.toString())`\n- @FazleRabbiAdor Glad I could pay the favor once ;)\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":514,"estimatedTokens":2535}}884{"id":"stack-70025283","source":"stackoverflow","questionId":70025283,"title":"TypeORM - Update only values that are provided and leave the rest as they are","tags":["nestjs","typeorm"],"text":"Title: TypeORM - Update only values that are provided and leave the rest as they are\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow would I approach this using TypeORM?\n\nI have an Entity lets call it EntityA.\n\nI have 1 EntityA in my database with name = Joe, age = 17\n\nNow my front end sends a post request to my API with an Object like { name: Joe, age: 16 }\n\nHow can I tell type orm to update the EntityA in the database with the name of \"Joe\" and only update the provided values that differ from what is currently stored in the database (age in this case) ?\n\n========================================\n\nCode:\n```js\nasync function update(id: string, user: User): Promise<User> {\n    // Update\n    await userRepository.update(id, {\n      ...(user.name && { name: user.name }),\n      ...(user.surname && { surname: user.surname }),\n      ...(user.age && { age: user.age }),\n    });\n\n    // Return\n    return this.repository.findOneOrFail(id);\n  }\n```\n\n```text\nundefined\n```\n\n```text\nnullable\n```\n\n```text\nuser\n```\n\n```text\nuser.name\n```\n\n========================================\n\nComments:\n- Great idea, but it still doesn't solve the original problem - if the user sends a user.name which is the same as in the DB, typeorm still updates it. You need to read the record from the DB, and add a comparison. Like: user.name && user.name !== currUser.name && ...\n- @Yehezkel No, too costly. If the values are the same, a single update is fine, since the records fields that are different are still updated.\n- I totally agree regarding the cost, just tried to answer the question exactly.","metadata":{"transformedAt":"2026-08-18T18:33:02.475Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":54,"estimatedTokens":399}}885{"id":"stack-56761837","source":"stackoverflow","questionId":56761837,"title":"Should I put command bus between controller and domain service?","tags":["node.js","design-patterns","crud","cqrs","nestjs"],"text":"Title: Should I put command bus between controller and domain service?\nTags: node.js, design-patterns, crud, cqrs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am working on a backend and try to implement CQRS patterns. \nI'm pretty clear about events, but sometimes struggle with commands.\n\nI've seen that commands are requested by users, or example `ChangePasswordCommand`. However in implementation level user is just calling an endpoint, handled by some controller.\n\nI can inject an `UserService` to my controller, which will handle domain logic and this is how basic tutorials do (I use Nest.js). However I feel that maybe this is where I should use command - so should I execute command `ChangePasswordCommand` in my controller and then domain module will handle it? \n\nImportant thing is that I need return value from the command, which is not a problem from implementation perspective, but it doesn't look good in terms of CQRS - I should ADD and GET at the same time.\n\nOr maybe the last option is to execute the command in controller and then emit an event (`PasswordChangedEvent`) in command handler. Next, wait till event comes back and return the value in controller.\n\nThis last option seems quite good to me, but I have problems with clear implementation inside request lifecycle.\n\nI base on \nhttps://docs.nestjs.com/recipes/cqrs\n\n========================================\n\nTop Answer:\nWhile the answer by @cperson is technically correct, I would like to add a few nuances to it.\n\nFirst something that may not be clear from the answer description where it advises to *\"emit an event (PasswordChangedEvent) in command handler\"*. This is what I would prefer as well, but watch out:\n\n- The `Command` is part of the infrastructure layer, and the `Event` is part of the domain.\n\n- So from the command you should trigger code on the `AggregateRoot` that emits the event.\n\n- This can be done with `mergeObjectContext` or `eventBus.publish` (see the NestJS docs).\n\n- Events can be applied from other domain objects, but the aggregate usually is the emitter (upon commit).\n\nThe other point I wanted to address is that an event-sourced architecture is assumed, i.e. applying CQRS/ES. While CQRS is often used in combination with Event Sourcing there is nothing that prescribes doing so. Event Sourcing can give additional advantages, but also comes with significant added complexity. You should carefully weigh the pros and cons of having ES.\n\nIn many cases you do not need Event Sourcing. Having just CQRS already gives you a lot of benefits, such as having your domain / bounded contexts well-contained. Separation between reads and writes, single-responsibility commands + queries (more SOLID in general), cleaner architecture, etc. On a higher level it is easier to shift focus from *'how do I implement this (CRUD-wise)?'*, to *'how do these user requirements fit in the domain model?'*.\n\nWithout ES you can have a single relational database and e.g. persist using TypeORM. You can persist events, but it is not needed. In many scenario's you can avoid the eventual consistency where clients need to subscribe to events (maybe you just use them to drive saga's and update read-side views/projections).\n\nYou can always start with just CQRS and add Event Sourcing later, when the need arises.\n\n========================================\n\nCode:\n```text\nChangePasswordCommand\n```\n\n```text\nUserService\n```\n\n```text\nChangePasswordCommand\n```\n\n```text\nPasswordChangedEvent\n```\n\n```text\nCommand\n```\n\n```text\nEvent\n```\n\n```text\nAggregateRoot\n```\n\n```text\nmergeObjectContext\n```\n\n```text\neventBus.publish\n```\n\n========================================\n\nComments:\n- Thanks for answer. So you basically confirmed my thoughts. The problem I have with this approach is that I *have* to adjust implementation and also how I do my client-server communication just to fit this pattern. I hoped to create my backend/API using CQRS to be open for rapid business logic changes. But to achieve this nice decoupling, I now have to surrender standard REST interface and implement websockets - they are cool tech but may be overkill for me. I wish I could somehow encapsulate command/event patterns between request and response cycle. Any ideas?\n- @ลukaszOstrowski There are many factors to consider when taking CQRS. I don't know that rapid business logic changes is one of the benefits of using this pattern. You can apply DDD in a standard n-tier architecture and forego the overhead of CQRS. In terms of REST, you would typically return a 201 Accepted when submitting a command. Your client would then wait until the command is complete before continuing. That can be websockets, or client-side polling. Or you could just as well process the command from your controller and return the result to the client. Each approach has its tradeoffs.\n- Ok thanks, I will think about it. The idea is that I am building startup and I have to quickly prototype, but on the other hand - things might change often. By implementing CQRS I see benefits of decoupling my domains\n- Having run a software business for several years (using CQRS+ES), and having recently completed my first \"startup\" idea (using standard N-tier and no fanciness), I can say with certainty that you should decide whether you are focused on the startup or focused on your own technological growth. Either one is a great motivator for going down the path you are headed, but these are two competing priorities, in reality. Pick the one that matters and be happy. Don't pick both.\n- I agree. What I try to achieve is extra overhead on architecture, so I can give up more implementations. Event driven architecture is something new to me (I don't usually do backend anyway) but I can already see the benefits. No fancy stuff, I don't go with event sourcing, just wanted more declarative approach which I use in frontend apps with Redux Saga. I'm far from over engineering, just want to build some stable foundation.\n- Thanks for the answer. Im totally into event driven architecture (designing app starting with actions, communication via events) and I implement it with cqrs, but Im not into ES itself. I agree it is a great concept (I use it on frontend with redux) but complexity on the backend is to high for me needs.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":92,"estimatedTokens":1565}}886{"id":"stack-72263849","source":"stackoverflow","questionId":72263849,"title":"@Transform() Boolean Cast Doesn't Work on DTO","tags":["typescript","nestjs","class-validator","class-transformer"],"text":"Title: @Transform() Boolean Cast Doesn't Work on DTO\nTags: typescript, nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'm using nestJS and class-transformer inside a DTO.\n\nHere's a simple example of what I did and my issue:\n\n```\nexport class SomeDTO{\n @Transform(({ value }) => value === \"true\" || value === true || value === 1)\n @IsBoolean()\n doDelete : boolean;\n }\n```\n\nI tried even `@Transform(({ value }) => { return value === \"true\" || value === true || value === 1})`\n\nNow, in my controller:\n\n```\n@Post(\"something\")\nsomeOperation(@Body() data : SomeDTO){\n console.log(data); \n}\n```\n\nLogging the data, the intended boolean `doDelete` is still a string and wasn't transformed to its native boolean type.\n\nDid tried proviiding any data like this:\n`@Transform(({ value }) => { return false})`\n\nBut in the controller, the data is still the same if we set the original DTO doDelete to true. It's not converting to false as we implied via `@Transform()`.\n\nDid I do something wrong? Appreciated the help and shedding some light.\n\nI've tried these related references but nothing seems to work.\n\n- Boolean in swagger sent as string instead of boolean in NestJS\n\n- https://github.com/nestjs/nest/issues/766#issuecomment-470261677\n\n========================================\n\nTop Answer:\nInteresting observation. I have added `ValidationPipe` with necessary parameters, but it didn't work.\nSpent a lot of time googling for what i did wrong, but no success.\n\nEventually everything worked after a restarted my application. For some reason watcher didn't loaded configuration of the pipe.\n\n========================================\n\nCode:\n```text\nexport class SomeDTO{\n        @Transform(({ value }) => value === \"true\" || value === true || value === 1)\n        @IsBoolean()\n        doDelete : boolean;\n    }\n```\n\n```text\n@Post(\"something\")\nsomeOperation(@Body()  data : SomeDTO){\n    console.log(data); \n}\n```\n\n```text\n@Transform(({ value }) => { return  value === \"true\" || value === true || value === 1})\n```\n\n```text\ndoDelete\n```\n\n```text\n@Transform(({ value }) => { return false})\n```\n\n```text\n@Transform()\n```\n\n```text\ntransform: true\n```\n\n```text\nValidationPipe\n```\n\n```text\n@Transform()\n```\n\n```text\nclass-validator\n```\n\n```text\ntransform: true\n```\n\n```text\nplainToInstance\n```\n\n```text\nValidationPipe\n```\n\n========================================\n\nComments:\n- Do you have the `transform: true` option set in your `ValidationPipe`?\n- @JayMcDoniel Correct. I didn't put `transform : true` on the validation pipe. Would you mind posting this in the answer section so that I could select this as the solution? Thanks for your help.\n- As Jay said the option needed to actually transform the data is \"transform: true\", and the option \"transformOptions: { enableImplicitConversion: true}\" makes it not working as expected!\n- This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":121,"estimatedTokens":858}}887{"id":"stack-72152136","source":"stackoverflow","questionId":72152136,"title":"NestJS microservices \"Cannot find module\"","tags":["node.js","module","nestjs","typeorm","node.js-typeorm"],"text":"Title: NestJS microservices \"Cannot find module\"\nTags: node.js, module, nestjs, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nSo, I'm trying to create my first microservice using NestJS, but the moment I try to run it, the service stops with this error:\n\n```\n[13:39:21] Found 0 errors. Watching for file changes.\n\nError: Cannot find module 'C:\\Users\\voryi\\IdeaProjects\\YWA\\des_server\\services\\learning-service\\dist\\main'\n at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)\n at Function.Module._load (node:internal/modules/cjs/loader:778:27)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)\n at node:internal/main/run_main_module:17:47\n```\n\n========================================\n\nTop Answer:\ntry `npm run build` and then restart your service\n\n========================================\n\nCode:\n```text\n[13:39:21] Found 0 errors. Watching for file changes.\n\nError: Cannot find module 'C:\\Users\\voryi\\IdeaProjects\\YWA\\des_server\\services\\learning-service\\dist\\main'\n    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)\n    at Function.Module._load (node:internal/modules/cjs/loader:778:27)\n    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)\n    at node:internal/main/run_main_module:17:47\n```\n\n```text\nmain.js\n```\n\n```text\ndist\n```\n\n```text\nnest-cli.json\n```\n\n```text\n\"entryFile\": \"learning-service/src/main\"\n```\n\n```text\nmain\n```\n\n```text\nnpm run build\n```\n\n```text\n\"start:prod\": \"node dist/src/main\"\n```\n\n```text\nnpm i @nestjs/microservices\n```\n\n========================================\n\nComments:\n- looks like you're trying to run `node dist&#47;main.js` while there's no `main.js`. Check out your `dist` directory\n- It actually does generate the main, but I guess that for some reason it can't see/read it... prnt.sc/AZ4-4f7XCI6p\n- there's no `main.js` in the first level of `dist` directory, tho. You can define the entry file by adding this to your `nest-cli.json`: `\"entryFile\": \"learning-service&#47;src&#47;main\"`\n- Thanks a lot! Could you tell me please where can I read how it works so when I face +/- the same problem I'll be able o solve it myself?\n- I guess you just need to know how typescript define the destination of your transpiled code. Learn about the following compiler options: `baseUrl`, `rootDir` and `outDir` at typescriptlang.org/docs/handbook/compiler-options.html\n- Thanks once again! How can I mark the question as solved? Or it's some mod's function that only they can do? If so, shouldn't you post it as an answer rather than comment so it can be marked as an appropriate one? Sorry, just some questions from the newbie xd\n- you can mark my answer as the right one :)\n- Didn't work. Gives the same error. But thanks for trying!\n- For my case, this is the actual answer\n- Adding an `entryFile` field solved the issue for my monolith.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":80,"estimatedTokens":727}}888{"id":"stack-58191518","source":"stackoverflow","questionId":58191518,"title":"Typescript decorator mess","tags":["javascript","node.js","typescript","decorator","nestjs"],"text":"Title: Typescript decorator mess\nTags: javascript, node.js, typescript, decorator, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there a way to solve massive decorator use inside classes?\n\nHere's an example of a **single** property of a class in my NestJS app, with an **incomplete swagger documentation** decorator:\n\n```\n@ApiModelProperty({\n description: 'description',\n })\n @Expose()\n @MaxLength(100, { message: 'message' })\n @IsString({ message: 'message' })\n @ValidateIf(address=> address.id !== null)\n @NotEquals(undefined, { message: 'message' })\n address: string;\n```\n\nThis gets huge and ugly in no time. Any way to make the code look cleaner, defining the decorators in another file, maybe?\n\n========================================\n\nTop Answer:\nDecorators are regular typescript functions. You can try to compose multiple decorators into a single one. For exemple, you could mix the validation ones into a single decorator, like this:\n\n```\nfunction apiStringField(maxLength: number, message: string, description?: string) {\n return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { \n ApiModelProperty()(target, propertyKey, descriptor)\n Expose()(target, propertyKey, descriptor)\n MaxLength(maxLength, { message })(target, propertyKey, descriptor) \n IsString({ message })(target, propertyKey, descriptor)\n NotEquals(undefined, { message })(target, propertyKey, descriptor) \n }\n}\n```\n\nAnd, use it like this (after importing it):\n\n```\n@apiStringField(100, 'message', 'description')\naddress: string;\n```\n\n========================================\n\nCode:\n```js\n@ApiModelProperty({\n    description: 'description',\n  })\n  @Expose()\n  @MaxLength(100, { message: 'message' })\n  @IsString({ message: 'message' })\n  @ValidateIf(address=> address.id !== null)\n  @NotEquals(undefined, { message: 'message' })\n  address: string;\n```\n\n```text\nfunction apiStringField(maxLength: number, message: string, description?: string) {\n  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { \n      ApiModelProperty()(target, propertyKey, descriptor)\n      Expose()(target, propertyKey, descriptor)\n      MaxLength(maxLength, { message })(target, propertyKey, descriptor) \n      IsString({ message })(target, propertyKey, descriptor)\n      NotEquals(undefined, { message })(target, propertyKey, descriptor) \n  }\n}\n```\n\n```text\n@apiStringField(100, 'message', 'description')\naddress: string;\n```\n\n```text\nimport { applyDecorators } from '@nestjs/common';\n\nexpose function ComposedDecorator(options: any) {\n  return applyDecorators(\n    Decorator1(),\n    Decorator2(),\n    AnotherDecoratorYouWant(),\n  )\n}\n```\n\n```text\n@ComposedDecorator(options)\n// methodOrClassOrProperty\n```\n\n========================================\n\nComments:\n- Could you define what you mean by `solve`?\n- If a library decides to use decorators it uses decorators ... not really much can be done about it .. maybe define some compound decorators..\n- @Olian04 By solve i mean not having so much lines of decorations in one single file, they make code hard to read and you have different types of them mixed (i.e. validation and documentation). Example, using express-validator you sometimes got a huge chained validation, but thanks to how the router uses middleware, you could remove that from your file into another one, then importing it as an array of validation middlewares. That makes code super clean.But I have little experience using decorators and i wanted to know if there is a way to have similar results.\n- A couple of things to take a look into, see if you can cut down on the number of decorators you are using. You have a `@ValidateIf(address => address.id !== null)` but your `address` type is `string` which doesn't have an id field. `@Expose()` is only needed if you want to expose the field of the class, but have no real validations to run against it, so there's an extraneous decorator. I'm pretty sure you can get rid of the `@NotEquals()` possibly by options in the `@IsString()` decorator or by using the `@Length()` decorator to combine your max and min length (1,100).","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":103,"estimatedTokens":1026}}889{"id":"stack-63675108","source":"stackoverflow","questionId":63675108,"title":"How to make a dynamic roles guard, to work in both controllers and handlers","tags":["nestjs","nestjs-passport"],"text":"Title: How to make a dynamic roles guard, to work in both controllers and handlers\nTags: nestjs, nestjs-passport\nSource: Stack Overflow\n\nQuestion:\nI'm defining a roles guard like this:\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(\n private reflector: Reflector,\n ) { }\n\n async matchRoles(roles: string[], userRole: User[\"roles\"]) {\n let match = false;\n\n if (roles.indexOf(userRole) > -1) {\n match = true;\n }\n\n return match\n }\n\n canActivate(\n context: ExecutionContext,\n ): boolean | Promise | Observable {\n const roles = this.reflector.get('roles', context.getClass());\n if (!roles) {\n return true;\n }\n const request = context.switchToHttp().getRequest();\n const user: User = request.user;\n\n return this.matchRoles(roles, user.roles)\n }\n}\n```\n\nin this roles example it works only in a controller level like this:\n\n```\n@Controller('games')\n@hasRoles('user')\n@UseGuards(AuthGuard(), JwtGuard, RolesGuard)\nexport class GamesController {\n...\n```\n\nBut i want it to work dynamically with both, at controller level, and handler level.\nso i can appy a `@hasRoles('user')` for every route in the controller, and `@hasRoles('admin')` for some routes in that controller.\n\nSo to do this i need to change the reflector method from `getClass` to `getHandler` dynamically.\n\n========================================\n\nCode:\n```js\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(\n    private reflector: Reflector,\n  ) { }\n\n  async matchRoles(roles: string[], userRole: User[\"roles\"]) {\n    let match = false;\n\n    if (roles.indexOf(userRole) > -1) {\n      match = true;\n    }\n\n    return match\n  }\n\n  canActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    const roles = this.reflector.get<string[]>('roles', context.getClass());\n    if (!roles) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const user: User = request.user;\n\n    return this.matchRoles(roles, user.roles)\n  }\n}\n```\n\n```js\n@Controller('games')\n@hasRoles('user')\n@UseGuards(AuthGuard(), JwtGuard, RolesGuard)\nexport class GamesController {\n...\n```\n\n```text\n@hasRoles('user')\n```\n\n```text\n@hasRoles('admin')\n```\n\n```text\ngetClass\n```\n\n```text\ngetHandler\n```\n\n```js\nconst roles = this.reflector.getAllAndMerge(\n  'roles',\n  [\n    context.getHandler(),\n    context.getClass()\n  ]\n);\n```\n\n```js\nconst roles = this.reflector.getAllAndOverride(\n  'roles',\n  [\n    context.getHandler(),\n    context.getClass()\n  ]\n);\n```\n\n```text\nReflector\n```\n\n```text\ngetAllAndMerge\n```\n\n```text\ngetAllAndOverride\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":154,"estimatedTokens":746}}890{"id":"stack-67298396","source":"stackoverflow","questionId":67298396,"title":"Nest.js GraphQL Schema generation during build","tags":["graphql","nestjs"],"text":"Title: Nest.js GraphQL Schema generation during build\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using the code-first approach to GraphQL with NestJS and have a monorepo setup using Nx.\n\nThe `schema.gql` is only produced when I run the server, which I can't do during CI. It's impractical for me to copy the whole repository into the docker image and start the server. The `schema.gql` isn't generated when you build the nest application.\n\nI've also looked at Generating the SDL manually doc on the NestJS website, but not really sure how to integrate that script.\n\nJust wondering if someone has managed to generate the schema without starting the server?\n\n========================================\n\nTop Answer:\nThe following worked out well for me. I spotted this in the docs here:\n\nhttps://docs.nestjs.com/graphql/quick-start#accessing-generated-schema\n\nI added a check to see if the ENV was production, as the location I wanted the file generating does already exist when in development mode.\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { GraphQLSchemaHost } from '@nestjs/graphql';\nimport { writeFileSync } from 'fs';\nimport { printSchema } from 'graphql';\nimport { join } from 'path';\nimport { ServerModule } from './server.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(ServerModule);\n await app.listen(process.env.PORT || 3001);\n\n if (process.env.NODE_ENV === 'production') {\n const { schema } = app.get(GraphQLSchemaHost);\n writeFileSync(join(process.cwd(), `/src/schema.gql`), printSchema(schema));\n }\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nschema.gql\n```\n\n```text\nschema.gql\n```\n\n```js\nconst resolvers = [MyResolver]\n\n/**\n * Generate GraphQL schema manually. NestJS does not generate the GraphQL schema\n * automatically during the build process and it doesn't generate the GraphQL\n * schema when starting the built app. This schema needs to be generated or\n * the GraphQL api would have nothing to use.\n *\n * @param {MyServices} serviceName - Name of the gavel service to generate a unique\n * schema.\n * @param {Function[]} resolvers - List of GraphQL resolvers being used in that app.\n * @returns {Promise<void>} Nothing gets returned. It will just write the schema and\n * throw an error if it fails.\n */\nexport async function generateGraphQLSchema(\n  serviceName: MyServices,\n  resolvers: Function[],\n): Promise<void> {\n  const app = await NestFactory.create(GraphQLSchemaBuilderModule)\n  await app.init()\n\n  const gqlSchemaFactory = app.get(GraphQLSchemaFactory)\n  const schema = await gqlSchemaFactory.create(resolvers)\n\n  writeFileSync(join(process.cwd(), `/${serviceName}-schema.gql`), printSchema(schema))\n}\n\n/**\n * Setup nest application.\n *\n * @param {string} port - Port the application should listen to.\n * @param {unknown} appModule - Main app module from a nest application.\n * @param {MyServices} serviceName - Name of the gavel service to generate a unique\n * schema.\n * @returns {Promise<void>}\n */\nasync function bootstrap(port: string, appModule: any, serviceName: MyServices): Promise<void> {\n  const app = await NestFactory.create(appModule)\n\n  // Endpoint prefix\n  const globalPrefix = `${config.get(`env`)}/v1/${serviceName}`\n  app.setGlobalPrefix(globalPrefix)\n\n  // Start Server\n  await app.listen(port, () => {\n    Logger.log(`Listening at http://localhost:${port}/${globalPrefix}/graphql`)\n  })\n}\n\n/**\n * Helper to crate standard Nest JS Server.\n *\n * @param {MyServices} serviceName - Name of service.\n * @param {unknown} appModule - Main app module from a nest application.\n */\nexport function initializeServer(serviceName: GavelService, appModule: any): void {\n  const environment = config.get(`env`)\n  const port = config.get(`port`)\n  initializeElasticApm(`service-${serviceName}`, {\n    framework: `nest`,\n    environment,\n    version: `${packageJson.version}`,\n  })\n  bootstrap(port, appModule, serviceName).catch((error) => {\n    const logger = getElasticSearchLogger(serviceName)\n    logger.error(\n      { error, environment: config.get(`env`), applicationName: serviceName },\n      error.message,\n    )\n  })\n}\n\ngenerateGraphQLSchema(MyServices.SERVICE_A, resolvers)\n  .then(() => initializeServer(MyServices.SERVICE_A, AppModule))\n  .catch((e) => console.error(e))\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { GraphQLSchemaHost } from '@nestjs/graphql';\nimport { writeFileSync } from 'fs';\nimport { printSchema } from 'graphql';\nimport { join } from 'path';\nimport { ServerModule } from './server.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(ServerModule);\n  await app.listen(process.env.PORT || 3001);\n\n  if (process.env.NODE_ENV === 'production') {\n    const { schema } = app.get(GraphQLSchemaHost);\n    writeFileSync(join(process.cwd(), `/src/schema.gql`), printSchema(schema));\n  }\n}\nbootstrap();\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { GraphQLSchemaBuilderModule, GraphQLSchemaFactory } from '@nestjs/graphql';\nimport { writeFileSync } from 'fs';\nimport { printSchema } from 'graphql';\nimport { join } from 'path';\n\nconst resolvers = [\n  // Your resolvers here\n];\n\nconst scalars = [\n  // Your scalars here\n];\n\nconst main = async () => {\n  const app = await NestFactory.create(GraphQLSchemaBuilderModule);\n  await app.init();\n\n  const gqlSchemaFactory = app.get(GraphQLSchemaFactory);\n  const schema = await gqlSchemaFactory.create(resolvers, scalars);\n\n  writeFileSync(join(process.cwd(), '/schema.graphql'), printSchema(schema));\n};\nmain();\n```\n\n```text\nnest start --entryFile generate-schema\n```\n\n```text\nsrc/generate-schema.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":185,"estimatedTokens":1414}}891{"id":"stack-70108473","source":"stackoverflow","questionId":70108473,"title":"Pagination in TypeORM/NestJS","tags":["javascript","orm","nestjs","backend","typeorm"],"text":"Title: Pagination in TypeORM/NestJS\nTags: javascript, orm, nestjs, backend, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have to introduce pagination in `findAll()` method. I really dont know how to do it. I tried but it is giving so many errors. I used `findAndCount()` method given by `typeorm` for that, But I am not sure how it will work.\n\nAs of now below method returning all the record. I need to return at a time 10 records. Please suggest what modification I need to do.\n\n```\nasync findAll(queryCertificateDto: QueryCertificateDto,page=1): Promise {\n \n let { country, sponser } = queryCertificateDto;\n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n if (sponser) {\n sponser = sponser.toUpperCase();\n query.andWhere('Upper(certificate.sponser)=:sponser', { sponser });\n }\n\n if (country) {\n country = country.toUpperCase();\n query.andWhere('Upper(certificate.country)=:country', { country });\n } \n const certificates = query.getMany(); \n return certificates;\n}\n```\n\nthis is `PaginatedResult` file.\n\n```\nexport class PaginatedResult {\n data: any[];\n meta: {\n total: number;\n page: number;\n last_page: number;\n };\n }\n```\n\nI tried changing code of `findAll()` but `where` clause is giving error. I am not sure how to handle `query.getMany()` in `pagination`.\n\n```\nconst take = query.take || 10\n const skip = query.skip || 0\n \n \n const [result, total] = await this.certificateRepository.findAndCount(\n {\n where: query.getMany(), //this is giving error\n take:take,\n skip:skip\n }\n );\n return result;\n```\n\nI need to introduce pagination in this method. Any help will be really helpful.\n\n========================================\n\nTop Answer:\nTypeorm has a really nice method specific to your usecase `findAndCount`\n\n```\nasync findAll(queryCertificateDto: QueryCertificateDto): Promise {\n\n const take = queryCertificateDto.take || 10\n const skip = queryCertificateDto.skip || 0\n const country = queryCertificateDto.keyword || ''\n const sponser = queryCertificateDto.sponser || ''\n \n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n const [result, total] = await this.certificateRepository.findAndCount(\n {\n where: { country: Like('%' + country + '%') AND sponser: Like('%' + sponser + '%') }, order: { name: \"DESC\" },\n take: take,\n skip: skip\n }\n );\n \n return {\n data: result,\n count: total\n };\n}\n```\n\nMore documentation about Repository class can be found here\n\n========================================\n\nCode:\n```text\nasync findAll(queryCertificateDto: QueryCertificateDto,page=1):  Promise<PaginatedResult> {\n    \n    let { country, sponser } = queryCertificateDto;\n\n    const query = this.certificateRepository.createQueryBuilder('certificate');\n\n    if (sponser) {\n        sponser = sponser.toUpperCase();\n        query.andWhere('Upper(certificate.sponser)=:sponser', { sponser });\n    }\n\n    if (country) {\n        country = country.toUpperCase();\n        query.andWhere('Upper(certificate.country)=:country', { country });\n    }      \n    const  certificates = query.getMany();     \n    return certificates;\n}\n```\n\n```text\nexport class PaginatedResult {\n        data: any[];\n        meta: {\n          total: number;\n          page: number;\n          last_page: number;\n        };\n      }\n```\n\n```text\nconst take = query.take || 10\n        const skip = query.skip || 0\n       \n      \n        const [result, total] = await this.certificateRepository.findAndCount(\n            {\n                where: query.getMany(),   //this is giving error\n                take:take,\n                skip:skip\n            }\n        );\n        return result;\n```\n\n```text\nfindAll()\n```\n\n```text\nfindAndCount()\n```\n\n```text\ntypeorm\n```\n\n```text\nPaginatedResult\n```\n\n```text\nfindAll()\n```\n\n```text\nwhere\n```\n\n```text\nquery.getMany()\n```\n\n```text\npagination\n```\n\n```text\nasync findAll(queryCertificateDto: QueryCertificateDto,page=1): Promise<PaginatedResult> {\n    // let's say limit and offset are passed here too\n    let { country, sponser, limit, offset } = queryCertificateDto;\n\n    const query = this.certificateRepository.createQueryBuilder('certificate');\n\n    if (sponser) {\n        sponser = sponser.toUpperCase();\n        query.andWhere('certificate.sponser = :sponser', { sponser });\n    }\n\n    if (country) {\n        country = country.toUpperCase();\n        query.andWhere('certificate.country = :country', { country });\n    }\n\n    // limit and take mean the same thing, while skip and offset mean the same thing\n    const certificates = await query\n        .orderBy(\"certificate.id\", \"ASC\")\n        .limit(limit || 10)\n        .offset(offset || 0)\n        .getMany();\n\n    // if you want to count just replace the `.getMany()` with `.getManyandCount()`;\n\n    return certificates;\n}```\n```\n\n```text\n.getMany()\n```\n\n```text\nwhere\n```\n\n```js\nasync findAll(queryCertificateDto: QueryCertificateDto):  Promise<PaginatedResult> {\n\n    const take = queryCertificateDto.take || 10\n    const skip = queryCertificateDto.skip || 0\n    const country = queryCertificateDto.keyword || ''\n    const sponser = queryCertificateDto.sponser || ''\n    \n\n    const query = this.certificateRepository.createQueryBuilder('certificate');\n\n    const [result, total] = await this.certificateRepository.findAndCount(\n        {\n            where: { country: Like('%' + country + '%') AND sponser: Like('%' + sponser + '%') }, order: { name: \"DESC\" },\n            take: take,\n            skip: skip\n        }\n    );\n     \n    return {\n        data: result,\n        count: total\n    };\n}\n```\n\n```text\nfindAndCount\n```\n\n========================================\n\nComments:\n- `where` clause is generally for providing a conditon. In your case `query.getMany()` does not not provides a condition.\n- I am struggling there only Tushar. Can you guide me how can I use the same method in my code? I have put the code which I tried to use but dint work. I have edited my question.\n- why do you need the query var? I don't see that you are using it afterwards\n- thanks. it is returning every time only first 10 records.\n- you're are welcome, if you want more records, just pass the limit as a query with the number of records you need and it will override the default limit which is 10, 10 is the default value, so if you don't pass any specific limit it will return 10 records. so for example, if you want 40 records, and you want it to start from an id of 11 the offset will be 10 and the limit will be 40. In a nutshell, having a limit is just saying I don't want more than this number of values, while offset is saying skip this number of records and start from here.\n- and because databases id's start from 1. An Offset of 0 while will start from 1 because you are saying skip 0 rows, likewise, 10 will start from 11, saying skip 10 rows\n- actually I am not using id which starts from 1. I am using id as uuid. which is alphanumeric number\n- Yes, it will still work.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":256,"estimatedTokens":1722}}892{"id":"stack-60833520","source":"stackoverflow","questionId":60833520,"title":"How can I use raw SQL in NestJS instead of TypeOrm or Sequelize?","tags":["sql","orm","sequelize.js","nestjs","typeorm"],"text":"Title: How can I use raw SQL in NestJS instead of TypeOrm or Sequelize?\nTags: sql, orm, sequelize.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAs of today TypeOrm has 1.493 issues over 282.102 weekly downloads and Sequelize 783 issues over 571.781 weekly downloads in Github. \n\nAs I read over the TypeOrm and Sequelize Github issues, I want to avoid those major problemas by coding raw SQL instead of dealing with major issues like losing data, columns being dropped when you synchronize entities or types being changed due to default ORM types. \n\nI use NestJs 7.0.3 with TypeGraphQL, PostgreSQL v12.2 and TypeScript.\nSince 2019, I've had two issues raised with TypeOrm. \n\nI understand the advantages of using an ORM but I wonder if NestJS can work efficiently if I use raw SQL in order to replace TypeORM or Sequelize entirely?\n\nThanks so much for your insights.\nRon\n\n========================================\n\nComments:\n- I cheched your github repo and the zeldaPlay source code is amazing. You created your own Dynamic Module. After all you have done with the node-pg package, would you replace in your developments an ORM in order to avoid those issues I mentioned above or would you rather deal with the trade off and use Typeorm/Sequelize ?\n- There's a lot of refactoring going on behind the scenes. Gonna be removing the transient scope and instead working with all singletons, just by creating new provider tokens instead of using the same class name (similar to how the TypeOrm package for Nest works). It should make testing easier, but it'll be a while before I get to that\n- I usually avoid ORMs as I don't feel they bring as many advantages as they do negatives in the end of things. Plus, this way, I **know** what is being executed on my SQL server.\n- Thanks so much for sharing your experience. As a summary, in order to go this \"raw-sql\" route I should start (1) reading the manual for node-pg (2) reading nestjs Dynamic Module (3) creating my own Dynamic Module (4) Compare my code with your working code. Would you suggest any additional readings before I enter this unplanned journey?\n- You don't necessarily have to use my code as a comparison, I do use a few helper packages to make things easier; however, this article is really well written and starts getting into some of the working of Dynamic Modules. John has a lot of good Nest articles so find some stuff that interests you from him if you want as well. Here's another of his\n- All these related pieces were the direction I was looking for: Thank you for sharing so much information Best regards.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":26,"estimatedTokens":646}}893{"id":"stack-74461152","source":"stackoverflow","questionId":74461152,"title":"NestJS ValidationPipe is not working properly for @Query()","tags":["javascript","node.js","nestjs","dto"],"text":"Title: NestJS ValidationPipe is not working properly for @Query()\nTags: javascript, node.js, nestjs, dto\nSource: Stack Overflow\n\nQuestion:\nI'm trying to transform some query params from string to int using the in-build NestJS ValidationPipe, but it doesn't seem to be working correctly,\n\nHere is my controller :\n\n```\nimport {\n..., ValidationPipe\n} from '@nestjs/common';\n\n...\n\n@UseGuards(JwtAuthGuard)\n@Get()\nfindAll(@Req() req, @Query(new ValidationPipe({\n transform: true,\n transformOptions: { enableImplicitConversion: true },\n forbidNonWhitelisted: true,\n})) query: GetTestDto) {\n return this.testService.findAll(query, req.user.id);\n}\n```\n\nHere is my DTO :\n\n```\nimport { IsInt, IsOptional, IsString } from 'class-validator';\nimport { Transform } from 'class-transformer';\n\nexport class GetTestDto {\n @IsOptional()\n @IsString()\n public search: string;\n\n @IsOptional()\n @Transform(({value}) => {\n console.log(typeof value); // => string / I'm just testing here\n return value\n })\n @IsInt()\n public page: number;\n\n @IsOptional()\n @IsInt()\n public limit: number;\n}\n```\n\nmain.ts :\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport cookieParser from 'cookie-parser';\nimport { ValidationPipe } from '@nestjs/common';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.setGlobalPrefix('api');\n app.use(cookieParser());\n app.useGlobalPipes(new ValidationPipe());\n await app.listen(3000);\n}\n\nbootstrap();\n```\n\nwhen I try to call `GET http://127.0.0.1:3000/api/test?page=1&limit=10` I get this\n\n```\nvalidation error from the DTO I think:\n{\n \"statusCode\": 400,\n \"message\": [\n \"page must be an integer number\",\n \"limit must be an integer number\"\n ],\n \"error\": \"Bad Request\"\n}\n```\n\nI've tried deleting node_modules and dist folders, but nothing changed.\nI don't want to use @Transform() in the DTO as a solution, I would prefer for the pipe to do the changing with the `enableImplicitConversion: true`\n\nCan I please get some help?\n\nThank you\n\n========================================\n\nTop Answer:\nQuery (`@Query()`) and URL (`@Param()`) parameters always come in as strings. To force them to resolve to numbers you can add `@Type(() => Number)` so that `class-transformer` turns them into a number and `class-validator` then reads the correct value\n\n========================================\n\nCode:\n```text\nimport {\n..., ValidationPipe\n} from '@nestjs/common';\n\n...\n\n@UseGuards(JwtAuthGuard)\n@Get()\nfindAll(@Req() req, @Query(new ValidationPipe({\n    transform: true,\n    transformOptions: { enableImplicitConversion: true },\n    forbidNonWhitelisted: true,\n})) query: GetTestDto) {\n    return this.testService.findAll(query, req.user.id);\n}\n```\n\n```text\nimport { IsInt, IsOptional, IsString } from 'class-validator';\nimport { Transform } from 'class-transformer';\n\nexport class GetTestDto {\n    @IsOptional()\n    @IsString()\n    public search: string;\n\n    @IsOptional()\n    @Transform(({value}) => {\n        console.log(typeof value); // => string / I'm just testing here\n        return value\n    })\n    @IsInt()\n    public page: number;\n\n    @IsOptional()\n    @IsInt()\n    public limit: number;\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport cookieParser from 'cookie-parser';\nimport { ValidationPipe } from '@nestjs/common';\n\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    app.setGlobalPrefix('api');\n    app.use(cookieParser());\n    app.useGlobalPipes(new ValidationPipe());\n    await app.listen(3000);\n}\n\nbootstrap();\n```\n\n```text\nvalidation error from the DTO I think:\n{\n    \"statusCode\": 400,\n    \"message\": [\n        \"page must be an integer number\",\n        \"limit must be an integer number\"\n    ],\n    \"error\": \"Bad Request\"\n}\n```\n\n```text\nGET http://127.0.0.1:3000/api/test?page=1&limit=10\n```\n\n```text\nenableImplicitConversion: true\n```\n\n```js\napp.useGlobalPipes(\n    new ValidationPipe({\n      transform: true,\n      transformOptions: {\n        enableImplicitConversion: true,\n      },\n      whitelist: true,\n    })\n  );\n```\n\n```js\n@UseGuards(JwtAuthGuard)\n@Get()\nfindAll(@Req() req, @Query() query: GetTestDto) {\n    return this.testService.findAll(query, req.user.id);\n}\n```\n\n```text\nmain.ts\n```\n\n```text\n@Transform\n```\n\n```text\n@Query\n```\n\n```text\n@Query()\n```\n\n```text\n@Param()\n```\n\n```text\n@Type(() => Number)\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n========================================\n\nComments:\n- If I use the `@Type(() => Number)` approach, I won't be needing the `ValidationPipe()` in the `@Query()` with the `{ enableImplicitConversion: true }` though, no? instead of setting up the conversion in the DTO explicitly, I want the inbuilt NestJS ValidationPipe to do it for me. by the way, I'm following this guy's answer: link\n- Yes, the error I was getting comes from the global validation pipe, in which I didn't enable transform and implicit conversion.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":235,"estimatedTokens":1245}}894{"id":"stack-61413914","source":"stackoverflow","questionId":61413914,"title":"Env Variables in NestJS not visible in every module?","tags":["nestjs"],"text":"Title: Env Variables in NestJS not visible in every module?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nIm keeping my configuration in `.env` file when I develop my app.\n\nThis is my `app.module.ts`:\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRoot({\n autoLoadEntities: true,\n database: process.env.TYPEORM_DATABASE,\n host: process.env.TYPEORM_HOST,\n password: process.env.TYPEORM_PASSWORD,\n port: (process.env.TYPEORM_PORT as unknown) as number,\n type: 'postgres',\n username: process.env.TYPEORM_USERNAME,\n }),\n AuthModule,\n (...)\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nAnd `typeorm` use proper values from `process.env.TYPEORM_...` variables.\n\nThis is my `auth.module.ts`:\n\n```\n@Module({\n providers: [JwtStrategy, (...)],\n imports: [\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n (...)\n }),\n (...)\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\nAnd Im getting error from JwtModule, that `secret` can not be empty. Of course `JWT_SECRET` is set in `.env` file.\n\nThis is my `jwt.strategy.ts`:\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n secretOrKey: process.env.JWT_SECRET,\n (...)\n });\n }\n (...)\n}\n```\n\nAnd here, `process.env.JWT_SECRET` is properly loaded.\n\nI cant understand why my env vars are not available everywhere in my app.\n\n========================================\n\nTop Answer:\nFor JwtModule access to env variables you can use **registerAsync**, your code should be something like this:\n\n```\nJwtModule.registerAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: (config: ConfigService) => ({\n secret: config.get('JWT_SECRET_KEY'),\n signOptions: { expiresIn: '1h' },\n }),\n })\n```\n\n========================================\n\nCode:\n```js\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true }),\n    TypeOrmModule.forRoot({\n      autoLoadEntities: true,\n      database: process.env.TYPEORM_DATABASE,\n      host: process.env.TYPEORM_HOST,\n      password: process.env.TYPEORM_PASSWORD,\n      port: (process.env.TYPEORM_PORT as unknown) as number,\n      type: 'postgres',\n      username: process.env.TYPEORM_USERNAME,\n    }),\n    AuthModule,\n    (...)\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```js\n@Module({\n  providers: [JwtStrategy, (...)],\n  imports: [\n    JwtModule.register({\n      secret: process.env.JWT_SECRET,\n      (...)\n    }),\n    (...)\n  ],\n  controllers: [AuthController],\n})\nexport class AuthModule {}\n```\n\n```js\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      secretOrKey: process.env.JWT_SECRET,\n      (...)\n    });\n  }\n  (...)\n}\n```\n\n```text\n.env\n```\n\n```text\napp.module.ts\n```\n\n```text\ntypeorm\n```\n\n```text\nprocess.env.TYPEORM_...\n```\n\n```text\nauth.module.ts\n```\n\n```text\nsecret\n```\n\n```text\nJWT_SECRET\n```\n\n```text\n.env\n```\n\n```text\njwt.strategy.ts\n```\n\n```text\nprocess.env.JWT_SECRET\n```\n\n```js\nimport { config } from 'dotenv';\nconfig();\n```\n\n```js\nTypeOrmModule.forRootAsync({\n  inject: [ConfigService],\n  useFactory: (config: ConfigService) => ({\n    autoLoadEntities: true,\n    database: config.get<string>('TYPEORM_DATABASE'),\n    host: config.get<string>('TYPEORM_HOST'),\n    password: config.get<string>('TYPEORM_PASSWORD'),\n    port: config.get<number>('TYPEORM_PORT'),\n    type: 'postgres',\n    username: config.get<string>('TYPEORM_USERNAME'),\n  })\n})\n```\n\n```text\ndotenv\n```\n\n```text\nconfig()\n```\n\n```text\n@Module()\n```\n\n```text\nmain.ts\n```\n\n```text\n.env\n```\n\n```text\nprocess.env\n```\n\n```text\nConfigModule\n```\n\n```text\nJwtModule.registerAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) => ({\n        secret: config.get('JWT_SECRET_KEY'),\n        signOptions: { expiresIn: '1h' },\n      }),\n    })\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":238,"estimatedTokens":977}}895{"id":"stack-72217232","source":"stackoverflow","questionId":72217232,"title":"how to inject plain database (without ORM) within nestJS framework?","tags":["database","nestjs"],"text":"Title: how to inject plain database (without ORM) within nestJS framework?\nTags: database, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use NestJS framework. But prefer to write SQL queries by myself, and not use the heavy interface of ORMs.\n\nI found some tutorials with examples of direct access to database, but they don't use the injection mechanism of NestJS.\nSo, I'm trying to learn how to write a thin layers of controller and services provider which gives me the freedom to supply the query as a text parameter.\nWill appriciate your advices\n\n========================================\n\nCode:\n```text\nimport { Module } from \"@nestjs/common\";\nimport { Pool } from \"pg\";\nimport { PG_CONNECTION } from \"../constants\";\n\n\nexport const PG_CONNECTION = 'PG_CONNECTION';\n\nconst dbProvider = {\n  provide: PG_CONNECTION,\n  useValue: new Pool({\n    user: \"postgres\",\n    host: \"localhost\",\n    database: \"somedb\",\n    password: \"meh\",\n    port: 5432,\n  }),\n};\n\n@Module({\n  providers: [dbProvider],\n  exports: [dbProvider],\n})\nexport class DbModule {}\n```\n\n```text\n@Module({\n  providers: [AppService],\n  imports : [DbModule]\n})\nexport class AppModule {}\n```\n\n```text\nimport { Injectable, Inject } from '@nestjs/common';\nimport { PG_CONNECTION from './constants'; \n\n@Injectable()\nexport class AppService { \n  constructor(@Inject(PG_CONNECTION) private conn: any) {}\n    \n  async getUsers() { \n    const res = await this.conn.query('SELECT * FROM users');\n    return res.rows;\n  }\n\n\n}\n```\n\n========================================\n\nComments:\n- Thanks Afaq. your answer clarify well this issue :)\n- Please keep in mind that using database such way makes your applicetion vulnerable to SQL injections.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":70,"estimatedTokens":424}}896{"id":"stack-54748691","source":"stackoverflow","questionId":54748691,"title":"Is there a way to collect all methods and their paths from NestJS application?","tags":["typescript","nestjs"],"text":"Title: Is there a way to collect all methods and their paths from NestJS application?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to write middleware to process requests, but some of paths should be excluded. I don't want manually hardcode all of them, so I have an idea:\n\nCreate special decorator, which will tag methods to exclude, something like this:\n\n```\nimport { ReflectMetadata } from '@nestjs/common';\nexport const Exclude = () =>\n ReflectMetadata('exclude', 'true');\n```\n\nIs there a way after creating NestJS application somehow recursively get all methods, annotated with this decorator, to automatically add their paths to exclude in my middleware?\n\n========================================\n\nTop Answer:\nSo... help yourself.\n\nAfter digging into NestJS sources I found a way, here is direction for those who interested:\n\n```\nimport * as pathToRegexp from 'path-to-regexp';\nimport { INestApplication, RequestMethod } from '@nestjs/common';\nimport { NestContainer } from '@nestjs/core/injector/container';\nimport { MetadataScanner } from '@nestjs/core/metadata-scanner';\nimport { PATH_METADATA, MODULE_PATH, METHOD_METADATA } from '@nestjs/common/constants';\n\nconst trimSlashes = (str: string) => {\n if (str != null && str.length) {\n while (str.length && str[str.length - 1] === '/') {\n str = str.slice(0, str.length - 1);\n }\n }\n return str || '';\n};\n\nconst joinPath = (...p: string[]) =>\n '/' + trimSlashes(p.map(trimSlashes).filter(x => x).join('/'));\n\n// ---------------8 {\n let modulePath = metatype ? Reflect.getMetadata(MODULE_PATH, metatype) : undefined;\n modulePath = modulePath ? modulePath + globalPrefix : globalPrefix;\n\n routes.forEach(({ instance, metatype }, controllerName) => {\n const controllerPath = Reflect.getMetadata(PATH_METADATA, metatype);\n const isExcludeController = Reflect.getMetadata('exclude', metatype) === 'true';\n const instancePrototype = Object.getPrototypeOf(instance);\n\n scanner.scanFromPrototype(instance, instancePrototype, method => {\n const targetCallback = instancePrototype[method];\n const isExcludeMethod = Reflect.getMetadata('exclude', targetCallback) === 'true';\n\n if (isExcludeController || isExcludeMethod) {\n const requestMethod: RequestMethod = Reflect.getMetadata(METHOD_METADATA, targetCallback);\n const routePath = Reflect.getMetadata(PATH_METADATA, targetCallback);\n\n // add request method to map, if doesn't exist already\n if (!excludes[RequestMethod[requestMethod]]) {\n excludes[RequestMethod[requestMethod]] = [];\n }\n\n // add path to excludes\n excludes[RequestMethod[requestMethod]].push(\n // transform path to regexp to match it later in middleware\n pathToRegexp(joinPath(modulePath, controllerPath, routePath)),\n );\n }\n });\n });\n});\n\n// now you can use `excludes` map in middleware\n```\n\n========================================\n\nCode:\n```js\nimport { ReflectMetadata } from '@nestjs/common';\nexport const Exclude = () =>\n  ReflectMetadata('exclude', 'true');\n```\n\n```text\n// Inject the service\nconstructor(private readonly discover: DiscoveryService) { }\n\n// Discover all controller methods decorated with guest roles or \n// belonging to controllers with guest roles\n\nconst allMethods = this.discover.methodsAndControllerMethodsWithMeta<string[]>(\n  rolesMetaKey,\n  x => x.includes('guest')\n);\n```\n\n```text\nconst fullPaths = allGuestMethods.map(x => {\n  const controllerPath = Reflect.getMetadata(\n    PATH_METADATA,\n    x.component.metatype\n  );\n\n  const methodPath = Reflect.getMetadata(PATH_METADATA, x.handler);\n  const methodHttpVerb = Reflect.getMetadata(\n    METHOD_METADATA,\n    x.handler\n  );\n\n  return {\n    verb: methodHttpVerb,\n    path: `${controllerPath}/${methodPath}`\n  }\n});\n```\n\n```text\nexpect(fullPaths).toContainEqual({verb: RequestMethod.GET, path: 'guest/route-path-one'});\nexpect(fullPaths).toContainEqual({verb: RequestMethod.GET, path: 'super/route-path-two'});\nexpect(fullPaths).toContainEqual({verb: RequestMethod.POST, path: 'admin/route-path-three'});\n```\n\n```text\n@nestjs-plus/common\n```\n\n```text\nDiscoveryService\n```\n\n```text\n@nestjs-plus/rabbitmq\n```\n\n```text\n@Roles\n```\n\n```text\nDiscoveryModule\n```\n\n```text\nDiscoverService\n```\n\n```text\nmethodsAndControllerMethodsWithMeta\n```\n\n```text\nRequestMethod\n```\n\n```text\npath\n```\n\n```js\nimport * as pathToRegexp from 'path-to-regexp';\nimport { INestApplication, RequestMethod } from '@nestjs/common';\nimport { NestContainer } from '@nestjs/core/injector/container';\nimport { MetadataScanner } from '@nestjs/core/metadata-scanner';\nimport { PATH_METADATA, MODULE_PATH, METHOD_METADATA } from '@nestjs/common/constants';\n\nconst trimSlashes = (str: string) => {\n  if (str != null && str.length) {\n    while (str.length && str[str.length - 1] === '/') {\n      str = str.slice(0, str.length - 1);\n    }\n  }\n  return str || '';\n};\n\nconst joinPath = (...p: string[]) =>\n  '/' + trimSlashes(p.map(trimSlashes).filter(x => x).join('/'));\n\n// ---------------8<----------------\n\nconst app = await NestFactory.create(AppModule);\n\n// ---------------8<----------------\n\nconst excludes = Object.create(null);\nconst container: NestContainer = (app as any).container; // this is \"protected\" field, so a bit hacky here\nconst modules = container.getModules();\nconst scanner = new MetadataScanner();\n\nmodules.forEach(({ routes, metatype }, moduleName) => {\n  let modulePath = metatype ? Reflect.getMetadata(MODULE_PATH, metatype) : undefined;\n  modulePath = modulePath ? modulePath + globalPrefix : globalPrefix;\n\n  routes.forEach(({ instance, metatype }, controllerName) => {\n    const controllerPath = Reflect.getMetadata(PATH_METADATA, metatype);\n    const isExcludeController = Reflect.getMetadata('exclude', metatype) === 'true';\n    const instancePrototype = Object.getPrototypeOf(instance);\n\n    scanner.scanFromPrototype(instance, instancePrototype, method => {\n      const targetCallback = instancePrototype[method];\n      const isExcludeMethod = Reflect.getMetadata('exclude', targetCallback) === 'true';\n\n      if (isExcludeController || isExcludeMethod) {\n        const requestMethod: RequestMethod = Reflect.getMetadata(METHOD_METADATA, targetCallback);\n        const routePath = Reflect.getMetadata(PATH_METADATA, targetCallback);\n\n        // add request method to map, if doesn't exist already\n        if (!excludes[RequestMethod[requestMethod]]) {\n          excludes[RequestMethod[requestMethod]] = [];\n        }\n\n        // add path to excludes\n        excludes[RequestMethod[requestMethod]].push(\n          // transform path to regexp to match it later in middleware\n          pathToRegexp(joinPath(modulePath, controllerPath, routePath)),\n        );\n      }\n    });\n  });\n});\n\n// now you can use `excludes` map in middleware\n```\n\n========================================\n\nComments:\n- what does the 'path-to-regexp' content sample look like ?\n- Wow what an old post you've resurrected. Sorry, I don't understand your question, can you rephrase it maybe?\n- 'path-to-regexp' is just a NPM package npmjs.com/package/path-to-regexp\n- Thank you for your response. Iโ€™ve moved past it and have found directions from your snippet. Many thanks ๐Ÿ™\n- thank you for (app as any).container, it's really a bit hacky even now\n- I have two questions: 1. In my real case I use decorator @Roles, which attaches array of roles (strings) to method or class. And I want to find all methods, containing role 'guest', and all methods from classes, containing role 'guest'. Can you show an example, how to use your library for that? 2. How can I get **full** URL paths for handler, after I get it with `discoveryService.discoverHandlersWithMeta`? Because I need full path inside middleware, to match against `req.url`\n- I'll take a crack at updating the answer/providing a working example repo for your use case later today. Busy day at work. The short answer is that the data you get back from `discoverHandlersWithMeta` includes whatever meta information was attached\n- @yumaa I'm making some tweaks to the library to help you out. Controllers are treated differently from other Providers in Nest apps so a few things need to be added before this will work for your scenario. I'll update you with a better example once the new version of the package is published\n- @yumaa I've updated the answer to show you how what you're looking to do could be accomplished using the DiscoveryService. Let me know if you have any feedback\n- That doesn't look like a lot less code, than mine, but definitely much cleaner :) I'll accept it for now and will try to test tomorrow. Thank you!\n- Yeah because your actual scenario is a bit more advanced there's still a bit of boilerplate to pull out all the stuff you need. But the focus was on having a clean API for interacting with the underlying container that didn't require casting to `any` to access protected members etc. Most of the boilerplate comes from the fact that your decorator can be used both on controllers and individual methods so I might see if that pattern can be further hidden behind the Discovery API. If you do try it feel free to give feedback and I'll continue to make improvements\n- This is somewhat common in NestJS, I guess, for example you can add Guard, Interceptor, Pipe or Filter on controller or individual method.\n- Yeah I'm thinking that I might add another discovery option that finds all handlers based on the decorator being applied at the per method level or on the parent controller/injectable. That way getting to the `allGuestMethods` point in the code sample above would just be a one liner\n- @yumaa After looking at it I think that this use case comes up often enough that it deserves it's own utility method. Internally it just composes a bunch of other discovery together (like in the previous edit) but this way there's a simple public API to consume. I've released the new version on NPM and updated the sample code here. Lemme know what you think\n- Cool, thank you :) I tried, and in my case it works like charm. I see you get controller from method like `x.component`, is it possible to get module further? In NestJS they have MODULE_PATH also, on module level (github.com/nestjs/nest/issues/1520), and it is used in `nest-router` package.\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":246,"estimatedTokens":2552}}897{"id":"stack-67547502","source":"stackoverflow","questionId":67547502,"title":"Nestjs - Typeorm custom connection name","tags":["node.js","nestjs","connection","typeorm"],"text":"Title: Nestjs - Typeorm custom connection name\nTags: node.js, nestjs, connection, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a Nestjs db Module and it works perfectly\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: () => {\n return {\n name: 'default', // if I change the connection name to anything else rather then 'default' say 'test' I get an error\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: () => {\n return {\n name: 'test', // The error seams to only show up if I use TypeOrmModule.forRootAsync\nFor TypeOrmModule.forRoot if works!\n\nIs there any different way to indicate the connection name? I need to add another connection and can't do it because of this error. Really would like to use 'forRootAsync'\n\n========================================\n\nCode:\n```text\n@Module({\n    imports: [\n        TypeOrmModule.forRootAsync({\n            useFactory: () => {\n                return {\n                    name: 'default', // <=== here\n                    type: \"mysql\",\n                    ...\n                };\n            },\n        }),\n\n        TypeOrmModule.forFeature(entities, 'default'), // <=== here\n    ],\n    exports: [TypeOrmModule],\n})\nexport class DBModule {}\n```\n\n```text\n@Module({\n    imports: [\n        TypeOrmModule.forRootAsync({\n            useFactory: () => {\n                return {\n                    name: 'test', // <=== here\n                    type: \"mysql\",\n                    ...\n                };\n            },\n        }),\n\n        TypeOrmModule.forFeature(entities, 'test'), // <=== here\n    ],\n    exports: [TypeOrmModule],\n})\nexport class DBModule {}\n```\n\n```text\n[Nest] 10746   - 05/15/2021, 5:55:34 PM   [ExceptionHandler] Nest can't resolve dependencies of the test_UserEntityRepository (?). Please make sure that the argument testConnection at index [0] is available in the TypeOrmModule context.\n\nPotential solutions:\n- If testConnection is a provider, is it part of the current TypeOrmModule?\n- If testConnection is exported from a separate @Module, is that module imported within TypeOrmModule?\n  @Module({\n    imports: [ /* the Module containing testConnection */ ]\n  })\n```\n\n```text\n@Module({\nimports: [\n    TypeOrmModule.forRootAsync({\n        name: 'test', // <=== here\n        useFactory: () => {\n            return {\n                type: \"mysql\",\n                ...\n            };\n        },\n    }),\n\n    TypeOrmModule.forFeature(entities, 'test'), // <=== here\n    ],\n    exports: [TypeOrmModule],\n})\nexport class DBModule {}\n```\n\n========================================\n\nComments:\n- Thanks that was the solution!\n- @levansuper glad it solved the issue. you can always get into the function definition files to check what parameters it accepts. also, you can accept this solution.\n- seems to be deprecated. any other solution?","metadata":{"transformedAt":"2026-08-18T18:33:02.476Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":106,"estimatedTokens":709}}898{"id":"stack-54963357","source":"stackoverflow","questionId":54963357,"title":"How to test a service with multiple constructor parameters in NestJS","tags":["node.js","typescript","testing","jestjs","nestjs"],"text":"Title: How to test a service with multiple constructor parameters in NestJS\nTags: node.js, typescript, testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\n### Background\n\nWhen I'm testing a service that requires one parameter in the constructor, I have to initialize the service as a provider using an object rather than simply passing the service through as a provider:\n\n**auth.service.ts** (example)\n\n```\n@Injectable()\nexport class AuthService {\n\n constructor(\n @InjectRepository(Admin)\n private readonly adminRepository: Repository,\n ) { }\n\n // ...\n\n}\n```\n\n**auth.service.spec.ts** (example)\n\n```\ndescribe('AuthService', () => {\n let authService: AuthService\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n providers: [\n AuthService,\n {\n provide: getRepositoryToken(Admin),\n useValue: mockRepository,\n },\n ],\n }).compile()\n\n authService = module.get(AuthService)\n })\n\n // ...\n\n})\n```\n\nSee this issue on GitHub for the source of this explanation.\n\n### My issue\n\nI have a service that requires 2 parameters in the constructor:\n\n**auth.service.ts**\n\n```\n@Injectable()\nexport class AuthService {\n constructor(\n private readonly jwtService: JwtService,\n private readonly authHelper: AuthHelper,\n ) {}\n\n // ...\n\n}\n```\n\n**How do I initialize this service in the test environment?** I can't pass multiple values to `useValue` in the `providers` array. My `AuthService` constructor has 2 parameters and I need to pass them both in order for the test to work.\n\nHere's my current (not working) setup:\n\n**auth.service.spec.ts**\n\n```\ndescribe('AuthService', () => {\n let service: AuthService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [AuthService],\n }).compile()\n\n service = module.get(AuthService)\n })\n\n it('should be defined', () => {\n expect(service).toBeDefined()\n })\n\n // ...\n\n})\n```\n\nWhen I don't pass them in, I get the following error:\n\n```\nโ— AuthService โ€บ should be defined\n\n Nest can't resolve dependencies of the AuthService (?, AuthHelper). Please make sure that the argument at index [0] is available in the TestModule context.\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class AuthService {\n\n  constructor(\n    @InjectRepository(Admin)\n    private readonly adminRepository: Repository<Admin>,\n  ) { }\n\n  // ...\n\n}\n```\n\n```text\ndescribe('AuthService', () => {\n  let authService: AuthService\n\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n        providers: [\n          AuthService,\n          {\n            provide: getRepositoryToken(Admin),\n            useValue: mockRepository,\n          },\n        ],\n      }).compile()\n\n    authService = module.get<AuthService>(AuthService)\n  })\n\n  // ...\n\n})\n```\n\n```text\n@Injectable()\nexport class AuthService {\n  constructor(\n    private readonly jwtService: JwtService,\n    private readonly authHelper: AuthHelper,\n  ) {}\n\n  // ...\n\n}\n```\n\n```text\ndescribe('AuthService', () => {\n  let service: AuthService\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [AuthService],\n    }).compile()\n\n    service = module.get<AuthService>(AuthService)\n  })\n\n  it('should be defined', () => {\n    expect(service).toBeDefined()\n  })\n\n  // ...\n\n})\n```\n\n```text\nโ— AuthService โ€บ should be defined\n\n    Nest can't resolve dependencies of the AuthService (?, AuthHelper). Please make sure that the argument at index [0] is available in the TestModule context.\n```\n\n```text\nuseValue\n```\n\n```text\nproviders\n```\n\n```text\nAuthService\n```\n\n```text\nbeforeEach(async () => {\n  const module: TestingModule = await Test.createTestingModule({\n    providers: [\n      AuthService,\n      {provide: JwtService, useValue: jwtServiceMock},\n      {provide: AuthHelper, useValue: authHelperMock},\n    ],\n  }).compile()\n```\n\n```text\nproviders\n```\n\n```text\nAuthService\n```\n\n```text\nTest.createTestingModule()\n```\n\n```text\nAppModule\n```\n\n```text\nproviders\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":229,"estimatedTokens":999}}899{"id":"stack-58181006","source":"stackoverflow","questionId":58181006,"title":"pass string variable to 'type' in TypeOrmModuleOptions","tags":["javascript","node.js","nestjs","typeorm","dotenv"],"text":"Title: pass string variable to 'type' in TypeOrmModuleOptions\nTags: javascript, node.js, nestjs, typeorm, dotenv\nSource: Stack Overflow\n\nQuestion:\nI want to setup a database connection for my NestJs app using TypeORM. I have a config file which reads all values from the `.env` file\n\n```\nimport { DotenvConfigOutput, config } from 'dotenv';\n\nconst envFound: DotenvConfigOutput = config();\n\nif (!envFound) {\n throw new Error('.env file was not found.');\n}\n\nprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';\n\nexport const DATABASE_TYPE: string = process.env.DATABASE_TYPE || 'postgres';\nexport const DATABASE_USERNAME: string = process.env.DATABASE_USERNAME || 'admin';\nexport const DATABASE_PASSWORD: string = process.env.DATABASE_PASSWORD || 'myPW';\nexport const DATABASE_HOST: string = process.env.DATABASE_HOST || 'localhost';\nexport const DATABASE_PORT: number = Number(process.env.DATABASE_PORT) || 5432;\nexport const DATABASE_NAME: string = process.env.DATABASE_NAME || 'myDB';\nexport const DATABASE_SYNCHRONIZE: boolean = Boolean(process.env.DATABASE_SYNCHRONIZE) || true;\n```\n\nI am setting up the connection in the app.module, so on application startup.\n\n```\nimport {\n DATABASE_TYPE,\n DATABASE_HOST,\n DATABASE_PORT,\n DATABASE_USERNAME,\n DATABASE_PASSWORD,\n DATABASE_NAME,\n DATABASE_SYNCHRONIZE,\n} from './config';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: DATABASE_TYPE,\n host: DATABASE_HOST,\n port: DATABASE_PORT,\n username: DATABASE_USERNAME,\n password: DATABASE_PASSWORD,\n database: DATABASE_NAME,\n entities: [],\n synchronize: DATABASE_SYNCHRONIZE,\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nUnfortunately I get this error at the `type` field\n\n Type 'string' is not assignable to type '\"mysql\" | \"mariadb\" |\n \"postgres\" | \"cockroachdb\" | \"sqlite\" | \"mssql\" | \"oracle\" | \"cordova\"\n | \"nativescript\" | \"react-native\" | \"sqljs\" | \"mongodb\" |\n \"aurora-data-api\" | \"expo\"'.ts(2322) MysqlConnectionOptions.d.ts(12,\n 14): The expected type comes from property 'type' which is declared\n here on type 'TypeOrmModuleOptions'\n\nI don't want to pass in a hardcoded string like `'postgres'` because I want it to keep dynamic. I prefer Postgres but some customers use oracle databases and I have to support MSSQL too.\n\nHow can I fix that configuration problem?\n\n========================================\n\nTop Answer:\nThis worked for me:\n\n```\nTypeOrmModule.forRoot({\n type: \"sqlite\" as any,\n host: \"localhost\",\n database: \"./database/sqlite\"\n})\n```\n\nI spent a whole weekend trying to figure out this issue but got stumped.\n\nDoes anybody have a better solution or explanation?\n\n========================================\n\nCode:\n```text\nimport { DotenvConfigOutput, config } from 'dotenv';\n\nconst envFound: DotenvConfigOutput = config();\n\nif (!envFound) {\n  throw new Error('.env file was not found.');\n}\n\nprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';\n\nexport const DATABASE_TYPE: string = process.env.DATABASE_TYPE || 'postgres';\nexport const DATABASE_USERNAME: string = process.env.DATABASE_USERNAME || 'admin';\nexport const DATABASE_PASSWORD: string = process.env.DATABASE_PASSWORD || 'myPW';\nexport const DATABASE_HOST: string = process.env.DATABASE_HOST || 'localhost';\nexport const DATABASE_PORT: number = Number(process.env.DATABASE_PORT) || 5432;\nexport const DATABASE_NAME: string = process.env.DATABASE_NAME || 'myDB';\nexport const DATABASE_SYNCHRONIZE: boolean = Boolean(process.env.DATABASE_SYNCHRONIZE) || true;\n```\n\n```text\nimport {\n  DATABASE_TYPE,\n  DATABASE_HOST,\n  DATABASE_PORT,\n  DATABASE_USERNAME,\n  DATABASE_PASSWORD,\n  DATABASE_NAME,\n  DATABASE_SYNCHRONIZE,\n} from './config';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: DATABASE_TYPE,\n      host: DATABASE_HOST,\n      port: DATABASE_PORT,\n      username: DATABASE_USERNAME,\n      password: DATABASE_PASSWORD,\n      database: DATABASE_NAME,\n      entities: [],\n      synchronize: DATABASE_SYNCHRONIZE,\n    }),\n  ],\n  controllers: [],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\n.env\n```\n\n```text\ntype\n```\n\n```text\n'postgres'\n```\n\n```text\nexport const DATABASE_TYPE: any = String(process.env.DATABASE_TYPE) || 'postgres';\n```\n\n```text\nTypeOrmModule.forRoot({\n  type: \"sqlite\" as any,\n  host: \"localhost\",\n  database: \"./database/sqlite\"\n})\n```\n\n========================================\n\nComments:\n- sorry no, that didn't work for me. The error still remains\n- please check my updated answer, I changed the type to `any` hope this helps\n- hm the error is gone :) I can remove the cast to a string, `any` seems to be enough\n- Did you ever find a solution to this issue?\n- In my case making `type` value as **any** solves the problem, e.g. `type: 'postgres' as any`","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":174,"estimatedTokens":1184}}900{"id":"stack-65687512","source":"stackoverflow","questionId":65687512,"title":"Nestjs and Google Recaptcha","tags":["recaptcha","nestjs"],"text":"Title: Nestjs and Google Recaptcha\nTags: recaptcha, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement a server-side validation for reCaptcha using Nestjs and I want to if I should implement this as a module or as a service for modules(such as a self written user authentication module) that would require the use of reCaptcha.\n\n========================================\n\nTop Answer:\nImport `HttpModule`\n\n```\nimport { Module } from '@nestjs/common';\nimport { HttpModule } from \"@nestjs/axios\";\n\n@Module({\n imports: [HttpModule],\n ...\n})\n```\n\nThen create a service to validate captcha value\n\n**NOTE**: You have to get the secret/site key from **here** (site key will get used in the client)\n\n```\nimport { HttpService, Inject, Injectable } from \"@nestjs/common\";\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\nimport { map } from 'rxjs/operators'\n\n@Injectable()\nexport class CaptchaService {\n constructor(\n @Inject(REQUEST) private readonly request: Request,\n private httpService: HttpService) { }\n\n public validate(value:string): Promise {\n const remoteAddress = this.request.socket.remoteAddress\n const secretKey = \"XXXXXXXXX\"\n const url = \"https://www.google.com/recaptcha/api/siteverify?secret=\" + secretKey + \"&response=\" + value + \"&remoteip=\" + remoteAddress;\n\n return this.httpService.post(url).pipe(map(response => {\n return response['data']\n })).toPromise()\n }\n \n}\n```\n\nthen in your controller :\n\n```\nconst value=\"XXXXX\" // client send this for you\n const result = await this.captchService.validate(value)\n if (!result.success) throw new BadRequestException()\n```\n\n**Client Side**\n\nIf you are using angular you can use **this**\n\n========================================\n\nCode:\n```ts\n// recaptcha.guard.ts\nimport {\n  Injectable,\n  CanActivate,\n  ExecutionContext,\n  HttpService,\n  ForbiddenException,\n} from \"@nestjs/common\";\n\n@Injectable()\nexport class RecaptchaGuard implements CanActivate {\n  constructor(private readonly httpService: HttpService) {}\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const { body } = context.switchToHttp().getRequest();\n\n    const { data } = await this.httpService\n      .post(\n        `https://www.google.com/recaptcha/api/siteverify?response=${body.recaptchaValue}&secret=${process.env.RECAPTCHA_SECRET}`\n      )\n      .toPromise();\n\n    if (!data.success) {\n      throw new ForbiddenException();\n    }\n\n    return true;\n  }\n}\n```\n\n```ts\n// app.controller.ts\nimport { Controller, Post, UseGuard } from '@nestjs/common';\nimport { RecaptchaGuard } from './recaptcha.guard.ts'\n    \n@Controller()\nexport class AppController {\n\n @Post()\n @UseGuard(RecaptchaGuard)\n async postForm(){\n  //\n }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { HttpModule } from \"@nestjs/axios\";\n\n@Module({\n    imports: [HttpModule],\n    ...\n})\n```\n\n```text\nimport { HttpService, Inject, Injectable } from \"@nestjs/common\";\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\nimport { map } from 'rxjs/operators'\n\n@Injectable()\nexport class CaptchaService {\n    constructor(\n        @Inject(REQUEST) private readonly request: Request,\n        private httpService: HttpService) { }\n\n    public validate(value:string): Promise<any> {\n        const remoteAddress = this.request.socket.remoteAddress\n        const secretKey = \"XXXXXXXXX\"\n        const url = \"https://www.google.com/recaptcha/api/siteverify?secret=\" + secretKey + \"&response=\" + value + \"&remoteip=\" + remoteAddress;\n\n        return this.httpService.post(url).pipe(map(response => {\n            return response['data']\n        })).toPromise()\n    }\n    \n}\n```\n\n```text\nconst value=\"XXXXX\" // client send this for you\n const result = await this.captchService.validate(value)\n if (!result.success) throw new BadRequestException()\n```\n\n```text\nHttpModule\n```\n\n```js\nconst googleRecaptchaFactory = (\n      applicationConfigService: ApplicationConfigService,\n    ) => ({\n      secretKey: applicationConfigService.auth.recaptcha.secretKey,\n      response: (req) => req.headers.recaptcha || '',\n      skipIf: applicationConfigService.auth.recaptcha.bypassVerification,\n    });\n    \n    @Module({\n      controllers: [/* ... */],\n      imports: [\n        /* ... */\n        GoogleRecaptchaModule.forRootAsync({\n          imports: [],\n          inject: [ApplicationConfigService],\n          useFactory: googleRecaptchaFactory,\n        }),\n      ],\n      providers: [/* ... */],\n      exports: [/* ... */],\n    })\n    export class Module {}\n```\n\n```text\nAppModule\n```\n\n```text\n@Recapcha\n```\n\n========================================\n\nComments:\n- Today `HttpService` is not found in `@nestjs&#47;common`. You should use `@nestjs&#47;axios axios` or alternatives","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":196,"estimatedTokens":1184}}901{"id":"stack-70006100","source":"stackoverflow","questionId":70006100,"title":"Class-validator: remove a property on validation, based on the value of another property","tags":["typescript","validation","nestjs","class-validator"],"text":"Title: Class-validator: remove a property on validation, based on the value of another property\nTags: typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nUsing `class-validator` with NestJS, I have this working:\n\n```\nexport class MatchDeclineReason {\n @IsString()\n @IsEnum(MatchDeclineReasonType)\n @ApiProperty()\n type: MatchDeclineReasonType;\n\n @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)\n @IsString()\n @ApiProperty()\n freeText: string;\n}\n```\n\nso that if the `delinceReason.type === Other`, I expect to get a `freeText` string value.\n\nHowever, if the `declineReason.type` is any different from `Other`, I want the `freeText` property to be stripped away.\n\nIs there any way to achieve this kind of behaviour without writing a `CustomValidator`?\n\nMy `ValidationPipe` configuration:\n\n```\napp.useGlobalPipes(\n new ValidationPipe({\n disableErrorMessages: false,\n whitelist: true,\n transform: true,\n }),\n );\n```\n\n========================================\n\nCode:\n```text\nexport class MatchDeclineReason {\n  @IsString()\n  @IsEnum(MatchDeclineReasonType)\n  @ApiProperty()\n  type: MatchDeclineReasonType;\n\n  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)\n  @IsString()\n  @ApiProperty()\n  freeText: string;\n}\n```\n\n```text\napp.useGlobalPipes(\n    new ValidationPipe({\n      disableErrorMessages: false,\n      whitelist: true,\n      transform: true,\n    }),\n  );\n```\n\n```text\nclass-validator\n```\n\n```text\ndelinceReason.type === Other\n```\n\n```text\nfreeText\n```\n\n```text\ndeclineReason.type\n```\n\n```text\nOther\n```\n\n```text\nfreeText\n```\n\n```text\nCustomValidator\n```\n\n```text\nValidationPipe\n```\n\n```text\n@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)\n  @Transform((params) =>\n    (params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)\n  )\n  @IsString()\n  @ApiProperty()\n  freeText: string;\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":107,"estimatedTokens":474}}902{"id":"stack-72580969","source":"stackoverflow","questionId":72580969,"title":"NestJS + TypeORM Error during migration run: Unable to open file","tags":["nestjs","typeorm"],"text":"Title: NestJS + TypeORM Error during migration run: Unable to open file\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS to make an API and TypeORM to interface with my database.\n\nI've configured my database as follows\n\napp.modules.ts:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'pass',\n database: 'test',\n autoLoadEntities: true,\n synchronize: true,\n migrations:['migrations/*{.ts,.js}']\n }),\nCamerasModule\n],\n})\nexport class AppModule {}\n```\n\nAll I want to do is run a migration by typing:\n\n```\ntypeorm migration:run -d .\\migrations\\1654907799338-Camera.ts\n```\n\nI think part of the problem is that TypeORM isn't registering a DataSource, because if I just type\n\n```\ntypeorm migration:run\n```\n\nit doesn't know where to look.\n\nAnyways, the error I get is:\n\n```\nError during migration run:\nError: Unable to open file: \"C:\\Users\\sean\\Documents\\Git\\db-api\\migrations\\1654907799338-Camera.ts\". Cannot use import statement outside a module\n at Function.loadDataSource (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\CommandUtils.js:22:19)\n at async Object.handler (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\MigrationRunCommand.js:34:26)\n```\n\nWhy is Nest failing to communicate with TypeORM?\n\n========================================\n\nTop Answer:\nThere several things or checklists to ensure before you run migration. I also got the above error, and this is how I resolved it\n\nMake sure you have built your project\nFor some reason typeORM cannot read a .ts file, so build your project to a /dist folder and access it in your migration command.\n\nExample: Run build:\n`tsc`\n\nRun migration:\n`yarn typeorm migration:run -d dist/`\n\n- Make sure your DB instance is running and you have created the DB you are trying to connect to.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n    type: 'mysql',\n    host: 'localhost',\n    port: 3306,\n    username: 'root',\n    password: 'pass',\n    database: 'test',\n    autoLoadEntities: true,\n    synchronize: true,\n    migrations:['migrations/*{.ts,.js}']\n   }),\nCamerasModule\n],\n})\nexport class AppModule {}\n```\n\n```text\ntypeorm migration:run -d .\\migrations\\1654907799338-Camera.ts\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\nError during migration run:\nError: Unable to open file: \"C:\\Users\\sean\\Documents\\Git\\db-api\\migrations\\1654907799338-Camera.ts\". Cannot use import statement outside a module\n    at Function.loadDataSource (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\CommandUtils.js:22:19)\n    at async Object.handler (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\MigrationRunCommand.js:34:26)\n```\n\n```text\n\"typeorm\": \"npx typeorm-ts-node-commonjs --dataSource src/data-source.ts\",\n\"typeorm:migrate\": \"yarn typeorm migration:run\",\n\"typeorm:generate\": \"yarn typeorm migration:generate src/database/migrations/Migration --timestamp\",\n\"typeorm:revert\": \"yarn typeorm migration:revert\"\n```\n\n```text\ntypeorm migration:run -d .\\migrations\\1654907799338-Camera.ts\n```\n\n```text\n-d\n```\n\n```text\nsrc\n```\n\n```text\nDataSourceOptions\n```\n\n```text\ncli\n```\n\n```text\ntsc\n```\n\n```text\nyarn typeorm migration:run -d dist/<link your data-source.js file>\n```\n\n========================================\n\nComments:\n- Very helpful answer. It worked for me after building the project, then running migrations pointing the data-source.js file, found in the build folder (/dist). Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":149,"estimatedTokens":898}}903{"id":"stack-67598005","source":"stackoverflow","questionId":67598005,"title":"Logs in the console stuck saying [12:06:59 PM] File change detected. Starting incremental compilation in nestjs","tags":["javascript","node.js","backend","nestjs"],"text":"Title: Logs in the console stuck saying [12:06:59 PM] File change detected. Starting incremental compilation in nestjs\nTags: javascript, node.js, backend, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen I start the nest application, then it successfully starts and shows the logs given below.\n\nI've used command `npm run dev:start` to start the project.\n\n```\n[11:55:17 AM] File change detected. Starting incremental compilation...\n\n[11:55:17 AM] Found 0 errors. Watching for file changes.\n\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [NestFactory] Starting Nest application...\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [InstanceLoader] AppModule dependencies initialized +106ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [InstanceLoader] TypeOrmCoreModule dependencies initialized +24ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [RouterExplorer] Mapped {/auth/signup, POST} route +2ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [RoutesResolver] PostController {/post}: +1ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [RouterExplorer] Mapped {/post/create, POST} route +0ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [RouterExplorer] Mapped {/post, GET} route +1ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [RoutesResolver] CategoryController {/category}: +0ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [RouterExplorer] Mapped {/category/create, POST} route +0ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [NestApplication] Nest application successfully started +2ms\n[Nest] 23860 - 05/19/2021, 11:55:18 AM [bootstrap] Application started at localhost:5001\n```\n\nNow if I send any request to the end points, it successfully sends the request and data get stored in the database and also returns the data but the problem is code gets recompiled and in console it displays\n\n```\n[12:06:59 PM] File change detected. Starting incremental compilation...\n```\n\nand it doesn't show the log messages. How can I fix this?\n\n========================================\n\nTop Answer:\nAs mentioned in NestJs Documentation in **Windows** operating system for Typescript version 9+ we need to add following after **compilerOptions** in tsconfig file:\n\n\"watchOptions\": {\n\"watchFile\": \"fixedPollingInterval\"\n}\n\n========================================\n\nCode:\n```text\n[11:55:17 AM] File change detected. Starting incremental compilation...\n\n[11:55:17 AM] Found 0 errors. Watching for file changes.\n\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [NestFactory] Starting Nest application...\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [InstanceLoader] AppModule dependencies initialized +106ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [InstanceLoader] TypeOrmCoreModule dependencies initialized +24ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [RouterExplorer] Mapped {/auth/signup, POST} route +2ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [RoutesResolver] PostController {/post}: +1ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [RouterExplorer] Mapped {/post/create, POST} route +0ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [RouterExplorer] Mapped {/post, GET} route +1ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [RoutesResolver] CategoryController {/category}: +0ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [RouterExplorer] Mapped {/category/create, POST} route +0ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [NestApplication] Nest application successfully started +2ms\n[Nest] 23860   - 05/19/2021, 11:55:18 AM   [bootstrap] Application started at localhost:5001\n```\n\n```text\n[12:06:59 PM] File change detected. Starting incremental compilation...\n```\n\n```text\nnpm run dev:start\n```\n\n```text\n\"include\": [\n    \"src\"\n]\n```\n\n```text\ntsconfig.json\n```\n\n```text\n{\n      \"extends\": \"./tsconfig.json\",\n      \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"],\n      \"include\": [\"./src\"]\n    }\n```\n\n```json\n\"devDependencies\": {\n  ...,\n  \"typescript\": \"4.8.3\",\n  ...\n}\n```\n\n```text\nnpm i\nnpm run start:dev\n```\n\n```text\nnpm audit fix\n```\n\n========================================\n\nComments:\n- problably because you are writing to some file that TSC is watching. To solve this stackoverflow.com/questions/59211211\n- What does this do?\n- Doesnt work! Can you explain what this does?\n- This doesn't work.\n- To those who are wondering what this does, - it forces the TypeScript compiler to only consider files from the `src` folder (and all its subfolders) for the compilation. This means that the files outside of `src` (for example, the ones in the sibling `dist` folder) won't be taken into the compilation.\n- Tried to find root cause for 2 days and finally found this answer with 0 votes. Thank you man!","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":1187}}904{"id":"stack-62797984","source":"stackoverflow","questionId":62797984,"title":"How to download pdf from puppeteer using Nest js as Server Side and React in Client Side?","tags":["javascript","reactjs","pdf","puppeteer","nestjs"],"text":"Title: How to download pdf from puppeteer using Nest js as Server Side and React in Client Side?\nTags: javascript, reactjs, pdf, puppeteer, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using Nest in backend to generate a pdf file with Puppeteer. Puppeteer is working fine when I give it the path to create pdf on disk.\n\nI am currently returning the pdf.\n\nThis is the code generating the pdf:\n\n```\nconst browser = await puppeteer.launch({ headless: true });\n const page = await browser.newPage();\n await page.goto('https://blog.risingstack.com', {waitUntil: 'networkidle0'});\n\n var options = {\n width: '1230px',\n displayHeaderFooter: false,\n margin: {\n top: \"10px\",\n bottom: \"30px\"\n },\n printBackground: true,\n }\n\n const pdf = await page.pdf(options);\n \n await browser.close();\n return pdf\n```\n\nAnd this is the controller that calls the previous function:\n\n```\n@Header('Content-Type', 'application/pdf')\n async Printpdf(@Body() message: any) {\n console.log(message);\n return this.PrintpdfService.printpdf();\n }\n```\n\nIn React I am calling this with axios like this:\n\n```\nreturn axios.post(`http://localhost:3000/printpdf`,data, {\n responseType: 'arraybuffer',\n headers: {\n 'Accept': 'application/pdf'\n }\n });\n```\n\nI am trying to download the pdf with this:\n\n```\ngetBuildingReport(data).then((response) => {\n console.log(response);\n const blob = new Blob([response.data], {type: 'application/pdf'})\n const link = document.createElement('a')\n link.href = window.URL.createObjectURL(blob)\n link.download = `name.pdf`\n link.click();\n })\n .catch(err => {\n console.log(err)\n });\n```\n\nI followed this tutorial.\nhttps://blog.risingstack.com/pdf-from-html-node-js-puppeteer/#option3\n\nBut the downloaded pdf is build correctly and is imposible to open it as I get \"Failed to load PDF document.\"\n\n========================================\n\nCode:\n```text\nconst browser = await puppeteer.launch({ headless: true });\n    const page = await browser.newPage();\n    await page.goto('https://blog.risingstack.com', {waitUntil: 'networkidle0'});\n\n\n    var options = {\n      width: '1230px',\n      displayHeaderFooter: false,\n      margin: {\n        top: \"10px\",\n        bottom: \"30px\"\n      },\n      printBackground: true,\n    }\n\n    const pdf = await page.pdf(options);\n  \n    await browser.close();\n    return pdf\n```\n\n```text\n@Header('Content-Type', 'application/pdf')\n  async Printpdf(@Body() message: any) {\n    console.log(message);\n    return this.PrintpdfService.printpdf();\n  }\n```\n\n```text\nreturn axios.post(`http://localhost:3000/printpdf`,data, {\n    responseType: 'arraybuffer',\n    headers: {\n      'Accept': 'application/pdf'\n    }\n  });\n```\n\n```text\ngetBuildingReport(data).then((response) => {\n      console.log(response);\n      const blob = new Blob([response.data], {type: 'application/pdf'})\n       const link = document.createElement('a')\n       link.href = window.URL.createObjectURL(blob)\n       link.download = `name.pdf`\n       link.click();\n    })\n    .catch(err => {\n      console.log(err)\n    });\n```\n\n```text\nasync generatePDF(): Promise<Buffer> {\n    const content = fs.readFileSync(\n      path.resolve(__dirname, './templates/invoice.html'),\n      'utf-8'\n    )\n\n    const browser = await puppeteer.launch({ headless: true })\n    const page = await browser.newPage()\n    await page.setContent(content)\n\n    const buffer = await page.pdf({\n      format: 'A4',\n      printBackground: true,\n      margin: {\n        left: '0px',\n        top: '0px',\n        right: '0px',\n        bottom: '0px'\n      }\n    })\n\n    await browser.close()\n\n    return buffer\n  }\n```\n\n```text\n@Get('/:uuid/pdf')\n  async getInvoicePdfByUUID(\n    @Param('uuid', ParseUUIDPipe) uuid: string,\n    @GetUser() user: User,\n    @Res() res: Response,\n  ): Promise<void> {\n\n    // ...\n\n    const buffer = await this.invoicesService.generatePDF()\n\n    res.set({\n      // pdf\n      'Content-Type': 'application/pdf',\n      'Content-Disposition': 'attachment; filename=invoice.pdf',\n      'Content-Length': buffer.length,\n\n      // prevent cache\n      'Cache-Control': 'no-cache, no-store, must-revalidate',\n      'Pragma': 'no-cache',\n      'Expires': 0,\n    })\n\n    res.end(buffer)\n  }\n```\n\n========================================\n\nComments:\n- I had to import puppeter like this: `import * as puppeteer from \"puppeteer\"`","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":190,"estimatedTokens":1074}}905{"id":"stack-68700352","source":"stackoverflow","questionId":68700352,"title":"The underlying table for model 'Order' does not exist. Error code: P1014 (Prisma)","tags":["nestjs","prisma","prisma2"],"text":"Title: The underlying table for model 'Order' does not exist. Error code: P1014 (Prisma)\nTags: nestjs, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have such problem as below\n\n```\n$ prisma migrate dev --name \"ok\"\n \nError: P3006\n \nMigration `2021080415559_order_linking` failed to apply clearnly to the shadow database.\nError code: P1014\nError:\nThe underlying table for model 'Order' does not exist.\n```\n\n**How to fix it?**\n\n========================================\n\nTop Answer:\nIt looks like your migrations were corrupted somehow. There was probably changes to your database that was not recorded in the migration history.\n\nYou could try one of these:\n\n- If you're okay with losing the data in the database, try resetting the database with `prisma migrate reset`. More info\n\n- Try running introspection to capture any changes to the database with `prisma introspect` before applying a new migration. More info\n\n========================================\n\nCode:\n```text\n$ prisma migrate dev --name \"ok\"\n    \nError: P3006\n    \nMigration `2021080415559_order_linking` failed to apply clearnly to the shadow database.\nError code: P1014\nError:\nThe underlying table for model 'Order' does not exist.\n```\n\n```text\n*delete the migrations folder*\n\n$ prisma generate\n\n$ prisma migrate dev --name \"ok\"\n\n*it works*\n```\n\n```text\nprisma migrate reset\n```\n\n```text\nprisma introspect\n```\n\n========================================\n\nComments:\n- be aware, deleting all migration files could negatively impact on your further development","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":67,"estimatedTokens":381}}906{"id":"stack-66225288","source":"stackoverflow","questionId":66225288,"title":"NestJs: Make sure your class is decorated with an appropriate decorator","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: NestJs: Make sure your class is decorated with an appropriate decorator\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using `graphql-request` as a GraphQL client to query a headless CMS to fetch stuff, modify and return to the original request/query. headless cms is hosted separately fyi.\n\nI have the following code :\n\n```\n@Query(returns => BlogPost)\n async test() {\n const endpoint = 'https://contentxx.com/api/content/project-dev/graphql'\n const graphQLClient = new GraphQLClient(endpoint, {\n headers: {\n authorization: 'Bearer xxxxxxx',\n },\n })\n const query = gql`\n {\n findContentContent(id: \"9f5dde89-7f9b-4b9c-8669-1f0425b2b55d\") {\n id\n flatData {\n body\n slug\n subtitle\n title\n }\n }\n }`\n\n return await graphQLClient.request(query);\n }\n```\n\n`BlogPost` is a model having the types :\n\n```\nimport { Field, ObjectType } from '@nestjs/graphql';\nimport { BaseModel } from './base.model';\nimport FlatDateType from '../resolvers/blogPost/types/flatDatatype.type';\n\n@ObjectType()\nexport class BlogPost extends BaseModel {\n @Field({ nullable: true })\n id!: string;\n\n @Field((type) => FlatDateType)\n flatData: FlatDateType;\n}\n```\n\nand `FlatDateType` has the following code\n\n```\nexport default class FlatDateType {\n body: string;\n slug: string;\n subtitle: string;\n title: string;\n}\n```\n\nit throws the following exception :\n\nError: Cannot determine a GraphQL output type for the \"flatData\". Make\nsure your class is decorated with an appropriate decorator.\n\nWhat is missing in here?\n\n========================================\n\nTop Answer:\n`FlatDataType` is not defined as `@ObjectType()`, therefore type-graphql (or @nestjs/graphql) can't take it as an output in GraphQL.\n\n========================================\n\nCode:\n```text\n@Query(returns => BlogPost)\n  async test() {\n    const endpoint = 'https://contentxx.com/api/content/project-dev/graphql'\n    const graphQLClient = new GraphQLClient(endpoint, {\n      headers: {\n        authorization: 'Bearer xxxxxxx',\n      },\n    })\n    const query = gql`\n      {\n        findContentContent(id: \"9f5dde89-7f9b-4b9c-8669-1f0425b2b55d\") {\n          id\n          flatData {\n            body\n            slug\n            subtitle\n            title\n          }\n        }\n      }`\n\n    return await graphQLClient.request(query);\n  }\n```\n\n```text\nimport { Field, ObjectType } from '@nestjs/graphql';\nimport { BaseModel } from './base.model';\nimport FlatDateType from '../resolvers/blogPost/types/flatDatatype.type';\n\n@ObjectType()\nexport class BlogPost extends BaseModel {\n  @Field({ nullable: true })\n  id!: string;\n\n  @Field((type) => FlatDateType)\n  flatData: FlatDateType;\n}\n```\n\n```text\nexport default class FlatDateType {\n  body: string;\n  slug: string;\n  subtitle: string;\n  title: string;\n}\n```\n\n```text\ngraphql-request\n```\n\n```text\nBlogPost\n```\n\n```text\nFlatDateType\n```\n\n```text\nFlatDataType\n```\n\n```text\n@ObjectType()\n```\n\n```text\n@Field()\n```\n\n```text\nFlatDataType\n```\n\n```text\n@ObjectType()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":159,"estimatedTokens":749}}907{"id":"stack-55224483","source":"stackoverflow","questionId":55224483,"title":"Loading a 'bit' Mysql field from TypeOrm","tags":["nestjs","typeorm"],"text":"Title: Loading a 'bit' Mysql field from TypeOrm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to map a Mysql bit data column against a `boolean` property with TypeOrm. I'm using the NestJs framework and can't figure out how to do it. As far as I've seen, the Mysql `bit` datatype is not supported by the framework, but I don't know any way to workaround it. According to this discussion it should be enough to declare a boolean typed field in the entity and do not decorate it with nothing but `@Column`:\n\n```\n@Column()\n enable: boolean;\n```\n\nHowever, with this I get `true` value in every single instance of the entity. Also tried adding the `import 'reflect-metadata';` either in the entity and in `app.module.ts`, with the same result.\n\nAnother choice would be to use the `tinyint` type:\n\n```\n@Column({\n type: 'tinyint',\n })\n enable: boolean;\n```\n\nWith this, I get this kind of data, where the `data` field holds the current boolean value stored:\n\n```\n\"enable\":{\"type\":\"Buffer\",\"data\":[1]}\n```\n\nDo I need to make some kind of hack to get this converted into a proper boolean value or is there another cleaner choice to do it?\n\n**EDIT 1**\n\nChanging the DB column data type to `int` seems to produce the proper output. However, it's not the most proper solution, since the `bit` type is the one that best suits here.\n\n**Versions being used:**\n\n- \"@nestjs/typeorm\": \"5.1.0\"\n\n- \"typeorm\": \"0.2.13\"\n\n- \"reflect-metadata\": \"0.1.12\"\n\n- Mysql Engine: 5.7.25\n\n**EDIT 2**\n\nI've tried updating the `typeorm` related packages to their latest versions, the same keeps happening. Also with Mysql 8.0 engine. Tried also with these decorators:\n\n```\n@Column()\n @IsBoolean()\n enable: boolean;\n```\n\nI'm in Xubuntu 16.04, BTW.\n\n========================================\n\nTop Answer:\nI'm solving this in the following way\n\n```\n@Column({\n name: 'FIELD_NAME',\n type: 'bit',\n transformer: { from: (v: Buffer) => !!v.readInt8(0), to: (v) => v },\n })\n readonly field: boolean;\n```\n\n========================================\n\nCode:\n```text\n@Column()\n  enable: boolean;\n```\n\n```text\n@Column({\n    type: 'tinyint',\n  })\n  enable: boolean;\n```\n\n```text\n\"enable\":{\"type\":\"Buffer\",\"data\":[1]}\n```\n\n```text\n@Column()\n  @IsBoolean()\n  enable: boolean;\n```\n\n```text\nboolean\n```\n\n```text\nbit\n```\n\n```text\n@Column\n```\n\n```text\ntrue\n```\n\n```text\nimport 'reflect-metadata';\n```\n\n```text\napp.module.ts\n```\n\n```text\ntinyint\n```\n\n```text\ndata\n```\n\n```text\nint\n```\n\n```text\nbit\n```\n\n```text\ntypeorm\n```\n\n```text\nimport {ValueTransformer} from 'typeorm';\nclass BoolBitTransformer implements ValueTransformer {\n  // To db from typeorm\n  to(value: boolean | null): Buffer | null {\n    if (value === null) {\n      return null;\n    }\n    const res = new Buffer(1);\n    res[0] = value ? 1 : 0;\n    return res;\n  }\n  // From db to typeorm\n  from(value: Buffer): boolean | null {\n    if (value === null) {\n      return null;\n    }\n    return value[0] === 1;\n  }\n}\n```\n\n```text\n@Column({\n    type: 'bit',\n    nullable: false,\n    default: () => `\"'b'1''\"`,\n    name: 'can_read',\n    transformer: new BoolBitTransformer()\n  })\n  can_read!: boolean;\n```\n\n```js\n@Column({\n    name: 'FIELD_NAME',\n    type: 'bit',\n    transformer: { from: (v: Buffer) => !!v.readInt8(0), to: (v) => v },\n  })\n  readonly field: boolean;\n```\n\n```text\n@Column({\n    name: 'FIELD_NAME',\n    type: 'bit',\n    transformer: { from: (v: Buffer) => !!v?.readInt8(0), to: (v) => v },\n  })\n  field: boolean;\n```\n\n========================================\n\nComments:\n- It looks to me like bit is supported as of this PR: github.com/typeorm/typeorm/pull/3310\n- @JesseCarter tried updating `typeorm` and `@nestjs&#47;typeorm` to their latest versions.. no luck. Also tried with Mysql engine 8.0, no luck. It keeps returning `true` for everything.","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":196,"estimatedTokens":944}}908{"id":"stack-58892667","source":"stackoverflow","questionId":58892667,"title":"Talking to Nest.js microservice over tcp in docker-compose","tags":["docker","tcp","docker-compose","microservices","nestjs"],"text":"Title: Talking to Nest.js microservice over tcp in docker-compose\nTags: docker, tcp, docker-compose, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nCode and more documentation can be found in this repo\n\n**Expected behavior:** \n\nReceive a response when running the app with and without docker.\n\n**What I got:** \n\nA response when running the app without docker but not inside docker.\n\n**What I think the problem could be:** \n\nThe app seems to be working inside docker but the port just not passing through correctly.\n\n**What I already tried:**\n\n- Making a hybrid app. Make a GET request that is then internally passed to the TCP micro-service (this worked but is not the behavior I want).\n\n- Run `yarn start:dev` inside the docker container instead of `yarn start:prod`. This did nothing, but then again the ports that where used where the same.\n\n- Exposing the port like so: (this did nothing)\n\n```\n- target: 3000\n published: 3000\n protocol: tcp\n mode: host\n```\n\n========================================\n\nTop Answer:\ntry adding this to your compose:\n\n```\nmyservice:\n expose:\n - \"3000\"\n ports:\n - \"3000:3000\"\n```\n\n========================================\n\nCode:\n```text\n- target: 3000\n  published: 3000\n  protocol: tcp\n  mode: host\n```\n\n```text\nyarn start:dev\n```\n\n```text\nyarn start:prod\n```\n\n```js\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.TCP,\n  options: {\n    host: '0.0.0.0',\n    port: 3000\n  }\n});\n```\n\n```text\n0.0.0.0\n```\n\n```text\nmyservice:\n  expose:\n    - \"3000\"\n  ports:\n    - \"3000:3000\"\n```\n\n========================================\n\nComments:\n- this will actually work with any resolvable by client host","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":91,"estimatedTokens":417}}909{"id":"stack-62424075","source":"stackoverflow","questionId":62424075,"title":"Materialized View from NestJS/TypeORM project","tags":["nestjs","typeorm"],"text":"Title: Materialized View from NestJS/TypeORM project\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a Materialized view from my NestJS app using TypeORM.\nThe database is a Postgres.\n\nView Entities unfortunately doesn't match requirements: https://www.bookstack.cn/read/TypeORM/view-entities.md\n\nWished behaviour: just like models, a materialized view is defined in the NestJS project, with the option 'synchronize:true' : the project creates the view on running if it doesn't exist, if it exist, it just sync with it (just like models).\n\nIs there any leads that would help me achieving this?\n\n========================================\n\nCode:\n```text\n{materialized:true}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":20,"estimatedTokens":176}}910{"id":"stack-73520301","source":"stackoverflow","questionId":73520301,"title":"How to select fields from joined table using TypeORM repository?","tags":["typescript","database","orm","nestjs","typeorm"],"text":"Title: How to select fields from joined table using TypeORM repository?\nTags: typescript, database, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have 2 models with `one-to-many` connection - Post and User:\n\n```\nentities/post.entity.ts\n@Entity()\nexport class Post {\n ...\n @ManyToOne(() => User, (user) => user.posts) user: User;\n}\n\nentities/user.entity.ts\n@Entity()\nexport class User {\n ...\n @OneToMany(() => Post, (post) => post.user) posts: Post[];\n}\n```\n\nTo get data from database I use repositories, and my question is - how can I get only `userId` field from this query.\n\n```\nconstructor(\n @InjectRepository(Post) private postRepository: Repository\n) {}\n\nfindAll(): Promise {\n return this.postRepository.find({\n relations: ['user']\n });\n}\n```\n\nNow response looks like this:\n\n```\n{\n \"id\": 1,\n \"title\": \"Nam fringilla volutpat venenatis. Nulla et sem.\",\n \"content\": \"Aliquam tr...\",\n \"preview\": \"p1\",\n \"createdAt\": \"2022-08-28T11:52:44.833Z\",\n \"updatedAt\": \"2022-08-28T11:52:44.833Z\",\n \"user\": {\n \"id\": 1,\n \"firstName\": \"Timber\",\n \"lastName\": \"Saw\",\n \"createdAt\": \"2022-08-28T11:52:44.827Z\",\n \"updatedAt\": \"2022-08-28T11:52:44.827Z\"\n }\n },\n```\n\nCause now I just get the whole entity, but I want only `id` of user. I know, I can use `createQueryBuilder`, but is it possible to do using repositories?\n\n========================================\n\nTop Answer:\nThere can also be a case where you have **a chain of joins** and you need to select a field on the other end. I could not find the solution to this in TypeORM docs, so I thought this might help some people.\n\nSay joined tables are entity_1 and entity_2 in that order. Following is an example on how you would select specific properties of entity_2.\n\nAn important note here is that **you have to select entity_1_id** even if you don't actually need it. Without its presence, the join to entity_2 would fail. entity_0_id is similarly mandatory for this selection to happen.\n\n```\nthis.entity_0_repository.find({\n relations: { entity_1: { entity_2: true } },\n select: {\n entity_0_id: true, // => mandatory\n some_property: true,\n entity_1: {\n entity_1_id: true, // => mandatory\n some_property: true,\n entity_2: {\n some_property: true\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nentities/post.entity.ts\n@Entity()\nexport class Post {\n  ...\n  @ManyToOne(() => User, (user) => user.posts) user: User;\n}\n\nentities/user.entity.ts\n@Entity()\nexport class User {\n  ...\n  @OneToMany(() => Post, (post) => post.user) posts: Post[];\n}\n```\n\n```text\nconstructor(\n  @InjectRepository(Post) private postRepository: Repository<Post>\n) {}\n\nfindAll(): Promise<Post[]> {\n  return this.postRepository.find({\n    relations: ['user']\n  });\n}\n```\n\n```text\n{\n    \"id\": 1,\n    \"title\": \"Nam fringilla volutpat venenatis. Nulla et sem.\",\n    \"content\": \"Aliquam tr...\",\n    \"preview\": \"p1\",\n    \"createdAt\": \"2022-08-28T11:52:44.833Z\",\n    \"updatedAt\": \"2022-08-28T11:52:44.833Z\",\n    \"user\": {\n      \"id\": 1,\n      \"firstName\": \"Timber\",\n      \"lastName\": \"Saw\",\n      \"createdAt\": \"2022-08-28T11:52:44.827Z\",\n      \"updatedAt\": \"2022-08-28T11:52:44.827Z\"\n    }\n  },\n```\n\n```text\none-to-many\n```\n\n```text\nuserId\n```\n\n```text\nid\n```\n\n```text\ncreateQueryBuilder\n```\n\n```js\nthis.postRepository.find({\n    relations: {\n      user: true\n    },\n    select: {\n      user: {\n        id: true\n      }\n    }\n  });\n```\n\n```text\nthis.entity_0_repository.find({\n  relations: { entity_1: { entity_2: true } },\n  select: {\n    entity_0_id: true,     // => mandatory\n    some_property: true,\n    entity_1: {\n      entity_1_id: true,   // => mandatory\n      some_property: true,\n      entity_2: {\n        some_property: true\n      }\n    }\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":179,"estimatedTokens":924}}911{"id":"stack-53450075","source":"stackoverflow","questionId":53450075,"title":"Request-Scoped Services","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Request-Scoped Services\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nFrom what I understood now nestjs creates all the services when the application starts, maybe I'm using it wrong is there a way to configure NestJs to create services based on request? Like each time a request is done some services which are used on that request are recreated?\n\n========================================\n\nTop Answer:\nIt is possible with a build-in request-scope dependency injection mechanism ย \nhttps://docs.nestjs.com/fundamentals/injection-scopes ย \nbut it has serious drawbacks according to the documentation:\n\nScope bubbles up the injection chain. A controller that depends on a request-scoped provider will, itself, be request-scoped.\n\nUsing request-scoped providers will have an impact on application performance. While Nest tries to cache as much metadata as possible, it will still have to create an instance of your class on each request. Hence, it will slow down your average response time and overall benchmarking result. Unless a provider must be request-scoped, it is strongly recommended that you use the default singleton scope.\n\nRecently I have created request-scope implementation for NestJS free from bubbling up the injection chain and performance impact.\n\nhttps://github.com/kugacz/nj-request-scope\n\nTo use it first you have to add import of RequestScopeModule in the module class decorator:\n\n```\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\nย  ย  imports: [RequestScopeModule],\n})\n```\n\nNext, there are two ways of request-scope injection:\n\n- Inject express request object into class constructor with NJRS_REQUEST token:\n\n```\nimport { NJRS_REQUEST } from 'nj-request-scope';\n[...]\nconstructor(@Inject(NJRS_REQUEST) private readonly request: Request) {}\n```\n\n- Change class inject scope to request-scope with @RequestScope() decorator:\n\n```\nimport { RequestScope } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestScopeService {\n```\n\nYou can find example implementations in this repository: https://github.com/kugacz/nj-request-scope-example\nNestJS what is the best practice to initialise and pass request context\nI think you can use nj-request-scope package I wrote. It's free from bubbles up injection chain and performance issues:\n\nhttps://github.com/kugacz/nj-request-scope\n\nFirst, you have to add import of `RequestScopeModule` in the module class decorator:\n\n```\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\nย  ย  imports: [RequestScopeModule],\n})\n```\n\nand then your `RequestContext` class can be written like this:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\nimport { RequestScope } from 'nj-request-scope';\nimport { NJRS_REQUEST } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestContext {\nย  ย  public headers: IncomingHttpHeaders;\nย  ย  ....\n\nย  ย  constructor(@Inject(NJRS_REQUEST) private readonly request: Request) {\nย  ย  ย  ย  this.headers = request.headers;\nย  ย  }\n}\n```\n\nIn that case, a new instance of `RequestContext` class will be created for every request. So, you can store any request-scope information inside this class. Injecting this class into any part of your application won't cause a bubble up injection chain.\n\nAnother approach is like this:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\nimport { NJRS_REQUEST } from 'nj-request-scope';\n\n@Injectable()\nexport class RequestContext {\n\nย  ย  constructor(@Inject(NJRS_REQUEST) private readonly request: Request) {\nย  ย  }\n\nย  ย  public get headers(): IncomingHttpHeaders {\nย  ย  ย  ย  return this.request.headers;\nย  ย  }\n}\n```\n\nIn that case `RequestContext` class is singleton-scope and only `request` field is request-scope. So, you can't store any request-scoped information directly in `RequestContext` class rather you have to read request-scoped data directly from the request object via getters. Also, injecting this class into any part of your application won't cause a bubble up injection chain.\n\nSimple nj-request-scope package usage examples you can find here: https://github.com/kugacz/nj-request-scope-example\n\n========================================\n\nCode:\n```text\n@Injectable({ scope: Scope.REQUEST })\nexport class UsersService {}\n```\n\n```text\n{\n  provide: 'CACHE_MANAGER',\n  useClass: CacheManager,\n  scope: Scope.TRANSIENT,\n}\n```\n\n```text\nUsersController\n```\n\n```text\nUsersService\n```\n\n```text\nOtherService\n```\n\n```text\nUsersController\n```\n\n```text\nUsersService\n```\n\n```text\n@Injectable()\n```\n\n```text\nSingleScope\n```\n\n```text\nSingleScope\n```\n\n```text\ncls-hooked\n```\n\n```text\nasync-hooks\n```\n\n```text\ntypeorm\n```\n\n```text\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\nย  ย  imports: [RequestScopeModule],\n})\n```\n\n```text\nimport { NJRS_REQUEST } from 'nj-request-scope';\n[...]\nconstructor(@Inject(NJRS_REQUEST) private readonly request: Request) {}\n```\n\n```text\nimport { RequestScope } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestScopeService {\n```\n\n```text\nimport { RequestScopeModule } from 'nj-request-scope';\n\n@Module({\nย  ย  imports: [RequestScopeModule],\n})\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\nimport { RequestScope } from 'nj-request-scope';\nimport { NJRS_REQUEST } from 'nj-request-scope';\n\n@Injectable()\n@RequestScope()\nexport class RequestContext {\nย  ย  public headers: IncomingHttpHeaders;\nย  ย  ....\n\nย  ย  constructor(@Inject(NJRS_REQUEST) private readonly request: Request) {\nย  ย  ย  ย  this.headers = request.headers;\nย  ย  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Request } from 'express';\nimport { IncomingHttpHeaders } from 'http';\nimport { NJRS_REQUEST } from 'nj-request-scope';\n\n@Injectable()\nexport class RequestContext {\n\nย  ย  constructor(@Inject(NJRS_REQUEST) private readonly request: Request) {\nย  ย  }\n\nย  ย  public get headers(): IncomingHttpHeaders {\nย  ย  ย  ย  return this.request.headers;\nย  ย  }\n}\n```\n\n```text\nRequestScopeModule\n```\n\n```text\nRequestContext\n```\n\n```text\nRequestContext\n```\n\n```text\nRequestContext\n```\n\n```text\nrequest\n```\n\n```text\nRequestContext\n```\n\n========================================\n\nComments:\n- Be aware - In the current version `Scope.REQUEST` services doesn't work for `nest&#47;cqrs` Commands and Queries\n- I guess transient scope bubbles up the injection chain too, doesn't it?\n- @fabianski Yes, it will also bubble up. The impact on the performance is negligible though as the instantiation is done on startup and not on *every* request. I will rephrase though, this is not clear.\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":273,"estimatedTokens":1750}}912{"id":"stack-57599204","source":"stackoverflow","questionId":57599204,"title":"Using NestJS and TypeOrm, the tables are not being created automatically after I run the NestJS application","tags":["postgresql","typescript","config","nestjs","typeorm"],"text":"Title: Using NestJS and TypeOrm, the tables are not being created automatically after I run the NestJS application\nTags: postgresql, typescript, config, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nUsing a postgres DB, I am able to connect to the database, however even when following tutorials step-by-step, after creating the user.entity.ts file (code below), nothing in the database changes. \n\npostgres/typeorm are installed correctly as far as im aware with latest versions.\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity()\nexport class Users {\n\n @PrimaryGeneratedColumn('uuid')\n id: number\n\n @Column({\n length: 50\n })\n firstName: string;\n}\n```\n\nHere is the ormconfig.json\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": \"5432\",\n \"username\": \"postgres\",\n \"password\": \"pw\",\n \"database\": \"metabook\",\n \"synchronise\": true,\n \"logging\": true,\n \"entities\": [\"./dist/**/*.entity{.ts,.js}\"]\n}\n```\n\nIt should be adding the 'users' table with 2 columns (id and firstName). In the console, logging, as its set to true in the ormconfig.json, should show the sql queries being run to create the table, but nothing happens other than the success of running the application (output below).\n\nOutput\n\nExpected output from tutorial video\n\nAnyone know if I am missing something?\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity()\nexport class Users {\n\n    @PrimaryGeneratedColumn('uuid')\n    id: number\n\n    @Column({\n        length: 50\n    })\n    firstName: string;\n}\n```\n\n```text\n{\n    \"type\": \"postgres\",\n    \"host\": \"localhost\",\n    \"port\": \"5432\",\n    \"username\": \"postgres\",\n    \"password\": \"pw\",\n    \"database\": \"metabook\",\n    \"synchronise\": true,\n    \"logging\": true,\n    \"entities\": [\"./dist/**/*.entity{.ts,.js}\"]\n}\n```\n\n========================================\n\nComments:\n- I think the key value is `synchronize` right?\n- Your completly right. Too used to UK spelling, thanks for pointing it out! Working as expected now","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":87,"estimatedTokens":512}}913{"id":"stack-53361713","source":"stackoverflow","questionId":53361713,"title":"Select AuthGuard type on the fly","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: Select AuthGuard type on the fly\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy app will use two different auth strategies - one for users using a browser and another for the *public* API. I'll set a `header` for those using a browser, and then my app will set the auth strategy based on the value of that `header`.\n\nI have set up the two auth strategies, and given them names. I can now do this in my controller methods:\n\n```\n@Get()\n@UseGuards(AuthGuard('strategy_name'))\nasync find() { }\n```\n\nWhat I would like to do, is NOT have to specify the auth guard type next to every controller method, nor the logic for determining which type to use. Instead, I'd like to put this logic in one place, which will be read by ALL calls to `AuthGuard()`.\n\nWhat's the best way to do this? Is there some kind of filter/hook/interceptor for `AuthGuard`?\n\n========================================\n\nCode:\n```text\n@Get()\n@UseGuards(AuthGuard('strategy_name'))\nasync find() { }\n```\n\n```text\nheader\n```\n\n```text\nheader\n```\n\n```text\nAuthGuard()\n```\n\n```text\nAuthGuard\n```\n\n```text\n@Injectable()\nexport class MyAuthGuard implements CanActivate {\n  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {\n    const guard = this.getAuthGuard(context);\n    return guard.canActivate(context);\n  }\n\n  private getAuthGuard(context: ExecutionContext): IAuthGuard {\n    const request = context.switchToHttp().getRequest();\n\n    // Here should be your logic to determine the proper strategy.\n    if (request.header('myCondition')) {\n      return new (AuthGuard('jwt'))();\n    } else {\n      return new (AuthGuard('other-strategy'))();\n    }\n  }\n```\n\n```text\n@UseGuards(MyAuthGuard)\n@Get('user')\ngetUser(@User() user) {\n  return {user};\n}\n```\n\n```text\nGuard\n```\n\n```text\nAuthGuard\n```\n\n```text\nAuthStrategy\n```\n\n```text\nAuthGuard\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":87,"estimatedTokens":471}}914{"id":"stack-61767281","source":"stackoverflow","questionId":61767281,"title":"NestJs unit testing on typeorm pagination getting error queryBuilder.take(...).skip is not a function","tags":["unit-testing","jestjs","nestjs","typeorm"],"text":"Title: NestJs unit testing on typeorm pagination getting error queryBuilder.take(...).skip is not a function\nTags: unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock createQueryBuilder to unit test pagination part, But i am getting below error\n\n queryBuilder.take(...).skip is not a function\n\nMy Mock for createQueryBuilder \n\n```\ncreateQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n orderBy : jest.fn().mockReturnThis(),\n take : skip => ({\n skip: 5\n }), \n }))\n```\n\nUnit Test for Find all\n\n```\nit(\"Find All\", async () => {\n const pageData: PaginationDto = {\n page: 1,\n limit: 10,\n sortBy: \"id\",\n sortOrder: -1,\n relatinalData: relatinalData.no\n\n };\n expect(await service.getGroups(pageData)).toEqual({\n docs: [{\n groupName: \"group123\",\n description: \"Group Description\",\n roleId: 1\n },\n {\n groupName: \"group123\",\n description: \"Group Description\",\n roleId: 1\n }]\n });\n});\n```\n\nServices\n\n```\nimport { paginate } from 'nestjs-typeorm-paginate';\n\nasync getGroups(paginationDto: PaginationDto) {\n const pageOptions = await this.databaseService.preparePageData(paginationDto, 'groups');\n const queryBuilder = this.groupModel.createQueryBuilder('groups');\n const flag = paginationDto.relatinalData;\n if (relatinalData.yes === flag) {\n queryBuilder.leftJoinAndSelect(\"groups.role\", \"role\");\n }\n queryBuilder.orderBy(pageOptions.order);\n pageOptions['route'] = environment.hostname + \"groups\";\n return await paginate(queryBuilder,pageOptions);\n}\n```\n\nPagination page option Prepare function\n\n```\nasync preparePageData(paginationDto, modelName) {\n const sort = {};\n if (paginationDto.sortBy && paginationDto.sortOrder) {\n const sortValue = paginationDto.sortBy\n const sortOrder = paginationDto.sortOrder;\n if (paginationDto.relatinalData && relatinalData.yes === paginationDto.relatinalData) {\n sort[modelName + '.' + sortValue] = sortOrder;\n } else {\n sort[sortValue] = sortOrder;\n }\n }\n const options = {\n page: paginationDto.page ? Number(paginationDto.page) : constant.pageLimit,\n limit: paginationDto.limit ? Number(paginationDto.limit) : constant.limit,\n order: sort ? sort : constant.sort\n };\n return options;\n}\n```\n\nCan any one please help me to mock **nestjs-typeorm-paginate**\n\n========================================\n\nTop Answer:\nin your code `skip` is a parameter passed to function `take`. If you want `skip` to be a property of child object you have to enhance code in this way\n\n```\ncreateQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n orderBy : jest.fn().mockReturnThis(),\n take : () => ({\n skip: (cnt) => ({\n skip: cnt\n }), \n })\n }))\n```\n\n========================================\n\nCode:\n```text\ncreateQueryBuilder: jest.fn(() => ({\n      delete: jest.fn().mockReturnThis(),\n      innerJoinAndSelect: jest.fn().mockReturnThis(),\n      innerJoin: jest.fn().mockReturnThis(),\n      from: jest.fn().mockReturnThis(),\n      where: jest.fn().mockReturnThis(),\n      execute: jest.fn().mockReturnThis(),\n      getOne: jest.fn().mockReturnThis(),\n      orderBy : jest.fn().mockReturnThis(),\n      take : skip => ({\n       skip: 5\n      }), \n  }))\n```\n\n```text\nit(\"Find All\", async () => {\n    const pageData: PaginationDto = {\n      page: 1,\n      limit: 10,\n      sortBy: \"id\",\n      sortOrder: -1,\n      relatinalData: relatinalData.no\n\n    };\n    expect(await service.getGroups(pageData)).toEqual({\n      docs: [{\n        groupName: \"group123\",\n        description: \"Group Description\",\n        roleId: 1\n      },\n      {\n        groupName: \"group123\",\n        description: \"Group Description\",\n        roleId: 1\n      }]\n    });\n});\n```\n\n```text\nimport { paginate } from 'nestjs-typeorm-paginate';\n\nasync getGroups(paginationDto: PaginationDto) {\n        const pageOptions = await this.databaseService.preparePageData(paginationDto, 'groups');\n        const queryBuilder = this.groupModel.createQueryBuilder('groups');\n        const flag = paginationDto.relatinalData;\n        if (relatinalData.yes === flag) {\n            queryBuilder.leftJoinAndSelect(\"groups.role\", \"role\");\n        }\n        queryBuilder.orderBy(pageOptions.order);\n        pageOptions['route'] = environment.hostname + \"groups\";\n        return await paginate(queryBuilder,pageOptions);\n}\n```\n\n```text\nasync preparePageData(paginationDto, modelName) {\n    const sort = {};\n    if (paginationDto.sortBy && paginationDto.sortOrder) {\n        const sortValue = paginationDto.sortBy\n        const sortOrder = paginationDto.sortOrder;\n        if (paginationDto.relatinalData && relatinalData.yes === paginationDto.relatinalData) {\n            sort[modelName + '.' + sortValue] = sortOrder;\n        } else {\n            sort[sortValue] = sortOrder;\n        }\n    }\n    const options = {\n        page: paginationDto.page ? Number(paginationDto.page) : constant.pageLimit,\n        limit: paginationDto.limit ? Number(paginationDto.limit) : constant.limit,\n        order: sort ? sort : constant.sort\n    };\n    return options;\n}\n```\n\n```text\ncreateQueryBuilder: jest.fn(() => ({\n    leftJoinAndSelect: jest.fn().mockReturnThis(),\n    orderBy: jest.fn().mockReturnThis(),\n    take: jest.fn().mockReturnThis(),\n    skip: jest.fn().mockReturnThis(),\n    getManyAndCount: jest.fn().mockResolvedValue([groupPageResponse]),\n  }))\n```\n\n```js\ncreateQueryBuilder: jest.fn(() => ({\n      delete: jest.fn().mockReturnThis(),\n      innerJoinAndSelect: jest.fn().mockReturnThis(),\n      innerJoin: jest.fn().mockReturnThis(),\n      from: jest.fn().mockReturnThis(),\n      where: jest.fn().mockReturnThis(),\n      execute: jest.fn().mockReturnThis(),\n      getOne: jest.fn().mockReturnThis(),\n      orderBy : jest.fn().mockReturnThis(),\n      take : () => ({\n         skip: (cnt) => ({\n           skip: cnt\n         }), \n      })\n  }))\n```\n\n```text\nskip\n```\n\n```text\ntake\n```\n\n```text\nskip\n```\n\n========================================\n\nComments:\n- Sorry, But its not working i am getting same error \"queryBuilder.take is not a function\". I think its related to nestjs-typeorm-paginate because of this i am not able to mock paginate\n- this means that function `skip` was called not after `take`\n- Can you the code where you actually mocked createQueryBuilder","metadata":{"transformedAt":"2026-08-18T18:33:02.477Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":247,"estimatedTokens":1666}}915{"id":"stack-66942658","source":"stackoverflow","questionId":66942658,"title":"NestJS losing context of this inside function method in service class","tags":["javascript","node.js","this","nestjs","es6-class"],"text":"Title: NestJS losing context of this inside function method in service class\nTags: javascript, node.js, this, nestjs, es6-class\nSource: Stack Overflow\n\nQuestion:\nI have a nestJS project with a monorepo structure and face difficulties with `this` and `context`.\n\nI have an app file: `app.service.ts` and an inner lib generated via **Nest CLI**.\n`app.services.ts` has the following code logic:\n\n```\n//import dependencies\n\n@Injectable()\nexport class AppService implements OnApplicationBootstrap {\n private readonly logger = new Logger('SomeName');\n\n private readonly ENV_VARIABLE = config.from();\n\n private ws: WebSocket;\n\n constructor(\n @InjectRepository(RowEntity) //Repository from TypeORM\n private readonly postgresRepository: Repository,\n private readonly otherService: LibService, // import from @app/lib\n ) {}\n\n async onApplicationBootstrap(): Promise {\n await this.loadInitial();\n }\n\n async loadInitial() {\n this.ws = new WebSocket(url); // standart web socket connection\n\n const connection = new this.ws() // connection works fine\n\n addListener(connection, this.logger, this.ProblemSave); //such as Listener\n\n /**\n * BUT! \n * await this.LibService.getMethod(input.toLowerCase()); \n * works well here!\n */\n }\n\n async ProblemSave(input: string) {\n /**\n * PROBLEM HERE!\n * NestJS losing context of this keyword when executing via Listener\n */\n const data = await this.LibService.getMethod(input.toLowerCase()); // drops with error, since this undefined\n console.log(data);\n await this.postgresRepository.save(data);\n }\n```\n\nSo my problem is shown above. I have a functional method inside class service, created in Nest, which is called as a function inside another method. But somehow in one case, `this` inside class methods works fine. But if I pass it in another method, the context of `this` lost and my function fails, with `this.LibService is undefined` error.\n\n**What should I do to solve the problem?**\n\nThe listener code is below if someone is interested.\n\n```\nexport function addListener(\n connection: connectionInterface,\n logger: Logger,\n saveFunc: FunctionInterface,\n): void {\n connection.events({}, async (error: ErrnoException, {\n returnValues,\n }: {\n returnValues: ObjectInterface\n }) => {\n if (error) {\n logger.log(error);\n return;\n }\n\n try {\n\n //Execution works fine, but fails, because saveFunction doesn't have this context\n await saveFunc({\n input\n });\n\n logger.log(`Event created with id ${id}`);\n return;\n } catch (e) {\n console.error('ERROR', e);\n logger.log(e);\n }\n })\n .on('connected', (subscriptionId: string) => {\n logger.log(`subscribed to events with id ${subscriptionId}`);\n })\n .on('error', (error: ErrnoException) => {\n logger.log('error');\n logger.log(error);\n });\n}\n```\n\n========================================\n\nCode:\n```text\n//import dependencies\n\n@Injectable()\nexport class AppService implements OnApplicationBootstrap {\n  private readonly logger = new Logger('SomeName');\n\n  private readonly ENV_VARIABLE = config.from();\n\n  private ws: WebSocket;\n\n  constructor(\n    @InjectRepository(RowEntity) //Repository from TypeORM\n    private readonly postgresRepository: Repository<RowEntity>,\n    private readonly otherService: LibService, // import from @app/lib\n  ) {}\n\n  async onApplicationBootstrap(): Promise<void> {\n    await this.loadInitial();\n  }\n\n  async loadInitial() {\n    this.ws = new WebSocket(url); // standart web socket connection\n\n    const connection = new this.ws() // connection works fine\n\n    addListener(connection, this.logger, this.ProblemSave);  //such as Listener\n\n    /**\n     * BUT! \n     * await this.LibService.getMethod(input.toLowerCase()); \n     * works well here!\n     */\n  }\n\n  async ProblemSave(input: string) {\n    /**\n     * PROBLEM HERE!\n     * NestJS losing context of this keyword when executing via Listener\n     */\n    const data = await this.LibService.getMethod(input.toLowerCase()); // drops with error, since this undefined\n    console.log(data);\n    await this.postgresRepository.save(data);\n  }\n```\n\n```text\nexport function addListener(\n  connection: connectionInterface,\n  logger: Logger,\n  saveFunc: FunctionInterface,\n): void {\n  connection.events({}, async (error: ErrnoException, {\n    returnValues,\n  }: {\n    returnValues: ObjectInterface\n  }) => {\n    if (error) {\n      logger.log(error);\n      return;\n    }\n\n    try {\n\n      //Execution works fine, but fails, because saveFunction doesn't have this context\n      await saveFunc({\n        input\n      });\n\n      logger.log(`Event created with id ${id}`);\n      return;\n    } catch (e) {\n      console.error('ERROR', e);\n      logger.log(e);\n    }\n  })\n    .on('connected', (subscriptionId: string) => {\n      logger.log(`subscribed to events with id ${subscriptionId}`);\n    })\n    .on('error', (error: ErrnoException) => {\n      logger.log('error');\n      logger.log(error);\n    });\n}\n```\n\n```text\nthis\n```\n\n```text\ncontext\n```\n\n```text\napp.service.ts\n```\n\n```text\napp.services.ts\n```\n\n```text\nthis\n```\n\n```text\nthis\n```\n\n```text\nthis.LibService is undefined\n```\n\n```js\nexport class AppService {\n\n  constructor () {\n    this.ProblemSave = this.ProblemSave.bind(this);\n  }\n\n   ProblemSave () {\n     //stuff\n   }\n}\n```\n\n```js\nexport class AppService {\n\n  constructor () {}\n\n   ProblemSave  = () => {\n     //stuff\n   }\n}\n```\n\n```text\nbind\n```\n\n```text\nProblemSave\n```\n\n========================================\n\nComments:\n- Thank you, for clarifying this to me, but seems I have lost my mind during the day. I take the arrow `=>` function.","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":255,"estimatedTokens":1371}}916{"id":"stack-59562092","source":"stackoverflow","questionId":59562092,"title":"mock a toPromise function in jest - got .toPromise is not a function","tags":["node.js","promise","jestjs","nestjs"],"text":"Title: mock a toPromise function in jest - got .toPromise is not a function\nTags: node.js, promise, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an httpService from nestjs/common \n\nand I am using like the following:\n\n```\nconst response = await this.httpService.post(`${this.api}/${action}`, data).toPromise();\n```\n\nand in my jest spec file ( unit testing) . i am trying to mock this service \n\n```\nhttpServiceMock = {\n post: jest.fn()\n };\n\nit('should start', async () => {\n\n const serviceResult = await service.start(data);\n\n});\n```\n\nand I have got this error :\n\n```\nTypeError: this.httpService.post(...).toPromise is not a function\n```\n\nI am also trying to add a promise result like :\n\n```\nconst promise = Promise.resolve('result');\n httpServiceMock.post.mockResolvedValue(promise);\n```\n\ntried also :\n\n```\nit('should start', async () => {\n\n const mockObservable = Promise.resolve({\n toPromise: () => {\n console.log('toPromise called');\n }\n })\n\n httpServiceMock.post.mockImplementation(() => mockObservable);\n\n const serviceResult = await service.start();\n\n});\n```\n\n**My question is how can I mock the promise and return a response or exception**\n\n========================================\n\nTop Answer:\nI had a similar problem that could not be solved by accepted answer. So I bring here another solution just in case it could help someone else.\n\nIf you have jasmine, just use `jasmine.createSpyObj()`. If not, here is what I needed to do :\n\nFirst, I implemented a `jasmine.createSpyObj()` equivalent (based on this answer with little modifications) :\n\n```\nexport class TestUtilsService {\n static createSpyObj (baseName:string, methodNames:string[]): SpyObject {\n let obj: any = {};\n\n for (let i = 0; i obj};\n };\n}\n\nexport class SpyObject {\n [key: string]: ()=>{[key:string]:jest.Mock} ;\n}\n```\n\nThen I used it in my unit test :\n\n```\nconst spyHttpClient: SpyObject = TestUtilsService.createSpyObj('get',['toPromise']);\n```\n\nAdd it in test module providers :\n\n```\n{provide: HttpClient, useValue: spyHttpClient}\n```\n\nFinally, mock the toPromise implementation in order to return a mocked response :\n\n```\nconst mockedResponse = {...};\nspyHttpClient.get().toPromise.mockImplementationOnce(()=>Promise.resolve(mockedResponse));\nawait service.myRealMethodThatCallsHttpClient();\nexpect(service.someUpdatedProp).toBeTruthy();\n```\n\nPlease notice parenthesis after method get.\n\n========================================\n\nCode:\n```text\nconst response = await this.httpService.post(`${this.api}/${action}`, data).toPromise();\n```\n\n```text\nhttpServiceMock = {\n      post: jest.fn()\n    };\n\nit('should start', async () => {\n\n    const serviceResult = await service.start(data);\n\n});\n```\n\n```text\nTypeError: this.httpService.post(...).toPromise is not a function\n```\n\n```text\nconst promise = Promise.resolve('result');\n httpServiceMock.post.mockResolvedValue(promise);\n```\n\n```text\nit('should start', async () => {\n\n    const mockObservable = Promise.resolve({\n        toPromise: () => {\n          console.log('toPromise called');\n        }\n      })\n\n    httpServiceMock.post.mockImplementation(() => mockObservable);\n\n    const serviceResult = await service.start();\n\n});\n```\n\n```text\nconst mockObservable = {\n  toPromise: () => Promise.resolve('result')\n}\nhttpServiceMock.post.mockImplementation(() => mockObservable);\n```\n\n```text\nObservable<AxiosResponse<T>>\n```\n\n```text\npost\n```\n\n```text\ntoPromise\n```\n\n```text\nexport class TestUtilsService {\n  static createSpyObj (baseName:string, methodNames:string[]): SpyObject {\n    let obj: any = {};\n\n    for (let i = 0; i < methodNames.length; i++) {\n      obj[methodNames[i]] = jest.fn();\n    }\n    return {[baseName]:()=>obj};\n  };\n}\n\nexport class SpyObject {\n  [key: string]: ()=>{[key:string]:jest.Mock} ;\n}\n```\n\n```text\nconst spyHttpClient: SpyObject = TestUtilsService.createSpyObj('get',['toPromise']);\n```\n\n```text\n{provide: HttpClient, useValue: spyHttpClient}\n```\n\n```text\nconst mockedResponse = {...};\nspyHttpClient.get().toPromise.mockImplementationOnce(()=>Promise.resolve(mockedResponse));\nawait service.myRealMethodThatCallsHttpClient();\nexpect(service.someUpdatedProp).toBeTruthy();\n```\n\n```text\njasmine.createSpyObj()\n```\n\n```text\njasmine.createSpyObj()\n```\n\n```text\nconst mockPromise = {\n        toPromise: () => Promise.resolve(ical)\n    }\n\n    mockHttpService.get = jest.fn( () => {return mockPromise});\n```\n\n========================================\n\nComments:\n- Have you checked that the `httpService.post` uses the mock, and not the real function? You could try putting a console log after the `const response = await this.httpService.post(`${this.api}/${action}`, data).toPromise();` line, e.g. `console.log(this.httpService.post`)\n- If you haven't already, you will need to import the httpService module, and mock it with `jest.mock`\n- Your `mockObservable` probably shouldn't return a promise","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":223,"estimatedTokens":1215}}917{"id":"stack-67969667","source":"stackoverflow","questionId":67969667,"title":"how to scan all decorators value at runtime in nestjs","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: how to scan all decorators value at runtime in nestjs\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have to collect all decorator value that appears in different place in my app as string and then saving them to database at runtime, i don't have to add them twice (in database and in code),\n\ni have tried to do it but i could not figure out i use\n\n`Reflector` api from nestjs as following\n\n```\nthis.reflector.getAll('access', context.getHandler())\n```\n\nbut i could not get `context.getHandler()` during run time\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useGlobalPipes(new ValidationPipe());\n \n\n // Here is where i want to save\n\n await app.listen(3000);\n\n}\nbootstrap();\n```\n\nhere is my decorator\n\n```\n@HashPermission('access_value')\n```\n\nPlease assist\n\n========================================\n\nCode:\n```text\nthis.reflector.getAll<string>('access', context.getHandler())\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe());\n   \n\n  // Here is where i want to save\n\n  await app.listen(3000);\n\n}\nbootstrap();\n```\n\n```text\n@HashPermission('access_value')\n```\n\n```text\nReflector\n```\n\n```text\ncontext.getHandler()\n```\n\n```text\nDiscoveryService\n```\n\n```text\n@golevelup/nestjs-discovery\n```\n\n```text\nthis.discoveryService.methodsAndControllerMethodsWithMetaAtKey\n```\n\n========================================\n\nComments:\n- thanks for your answer, please can you write a blog article on how to create nestjs module as npm package from scratch (i mean that can be added as npm dependency), i think this approach we will make it usefully and promoting others to write more modules\n- You mean like this one?\n- yeas like the one you create above","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":90,"estimatedTokens":452}}918{"id":"stack-65336917","source":"stackoverflow","questionId":65336917,"title":"When should I use worker-threads?","tags":["node.js","nestjs"],"text":"Title: When should I use worker-threads?\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am currently working on a backend which provides rest endpoints for my frontend with nestjs. In some endpoints I receive e.g. an array of elements which I need to process.\n\nConcrete Example:\nI receive an array of 50 elements. For each element I need to make a SQL request. Therefore I need to loop over the array and do stuff in SQL.\n\nI always ask myself: At what amount of elements should I use for example worker threads to not block the event loop?\n\nMaybe I misunderstood the blocking of the event loop and someone can enlight me.\n\n========================================\n\nTop Answer:\nOnly use them if you need to do CPU-intensive tasks with large amounts of data. They allow you to avoid the serialization step of the data. 50 Is not enough I believe\n\n========================================\n\nCode:\n```text\nconst dbQueryPromises = [];\n\nfor(const entry of data) {\n   dbQueryPromises.push(dbConnection.query(buildQuery(entry)));\n}\n\nawait Promise.all(dbQueryPromises);\n```\n\n```text\nPromise.all\n```\n\n========================================\n\nComments:\n- SQL queries already don't block the event loop, so that would not be a good example for using worker threads. One example would be using them to increase the throughput of your server responses by delegating each entire HTTP request to separate threads using some sort of distribution strategy like round-robin.\n- Using worker threads for the example you have shown would most certainly be slower, even if that loop were 1000's. I would even say using for entire Http requests like mentioned by @PatrickRoberts is debatatable as that would negate aggressive caching schemes you could use. A better example might be were you did some fancy image processing, maybe like some AI upscaling etc, a worker thread would really help here.\n- @Keith higher throughput =/= faster. In fact the cost of parallelism is often higher latency. So yes it's slower, but because it can block multiple event loops handling multiple requests in parallel, it will be able to offer higher throughput than a single-threaded server. Also I'd argue against implementing caching in Node.js. That's what proxy servers are for.\n- @PatrickRoberts A Proxy server is for proxying HTTP requests. Let's take a very simple example, lets say you have some static data stored on your SQL server, and every request requires access to this. By not using caching in node this DB query will now need doing for all requests. It really is one of the biggest benefits of Node, say compared to PHP were things like MemCached have to be used, and that's way slower than internal caching inside node. If you did want to cluster, personally I would go for Sticky Session's rather than round robbin.\n- if your request is taking like 5-10+ minutes then you should implement an async search with `start`, `check`, `getresults` apis. maybe using worker of another service.","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":744}}919{"id":"stack-63811940","source":"stackoverflow","questionId":63811940,"title":"How to send response from middleware created in a Nest fastify server?","tags":["nestjs","fastify","nestjs-fastify"],"text":"Title: How to send response from middleware created in a Nest fastify server?\nTags: nestjs, fastify, nestjs-fastify\nSource: Stack Overflow\n\nQuestion:\nI've created a NestJs project with Fastify, and have created a middleware for it, but I can't figure out how to send a response to the client, similar to how we could do in express, any help would be appreciated, thanks!, here's my middleware code:\n\n```\nimport {\n Injectable,\n NestMiddleware,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\n\n@Injectable()\nexport class LoggerMiddleware implements NestMiddleware {\n use(req: any, res: any, next: Function) {\n console.log('Request...', res);\n // throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);\n next();\n }\n}\n```\n\n========================================\n\nTop Answer:\nAn example with adaptation of Daniel code to kill execution after middleware validations (cache) using express\n\n```\nimport { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response, NextFunction } from 'express';\n\n@Injectable()\nexport class CacheMiddleware implements NestMiddleware {\n\n constructor(\n private cacheService: CacheService\n ){}\n\n async use(req: Request, res: Response, next: NextFunction) {\n\n const cache = await this.cacheService.getCache(req.url)\n if(cache){\n res.writeHead(200, { 'content-type': 'application/json' })\n res.write(cache)\n res.end()\n return\n }\n\n next();\n }\n}\n```\n\n========================================\n\nCode:\n```ts\nimport {\n  Injectable,\n  NestMiddleware,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\n\n@Injectable()\nexport class LoggerMiddleware implements NestMiddleware {\n  use(req: any, res: any, next: Function) {\n    console.log('Request...', res);\n    // throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);\n    next();\n  }\n}\n```\n\n```text\n// app.middleware.ts\n\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport { ServerResponse, IncomingMessage } from 'http';\n\n@Injectable()\nexport class AppMiddleware implements NestMiddleware {\n  use(req: IncomingMessage, res: ServerResponse, next: Function) {\n    res.writeHead(200, { 'content-type': 'application/json' })\n    res.write(JSON.stringify({ test: \"test\" }))\n    res.end()\n  }\n}\n```\n\n```text\n// app.module.ts\n\nimport { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppMiddleware } from './app.middleware';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [],\n})\nexport class AppModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(AppMiddleware)\n      .forRoutes({ path: '*', method: RequestMethod.ALL }); // apply on all routes\n  }\n}\n```\n\n```text\nFastify\n```\n\n```text\nhttp\n```\n\n```text\nres\n```\n\n```text\nimport { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response, NextFunction } from 'express';\n\n@Injectable()\nexport class CacheMiddleware implements NestMiddleware {\n\n  constructor(\n     private cacheService: CacheService\n  ){}\n\n  async use(req: Request, res: Response, next: NextFunction) {\n\n    const cache = await this.cacheService.getCache(req.url)\n    if(cache){\n      res.writeHead(200, { 'content-type': 'application/json' })\n      res.write(cache)\n      res.end()\n      return\n    }\n\n    next();\n  }\n}\n```\n\n========================================\n\nComments:\n- Have you tried `res.send()`, `res.json()` or `res.json()`?\n- @Daniel yep, but they are giving me undefined errors\n- Tested it locally and `res.send()` worked exactly like in express. See answer bellow\n- @Daniel note that I am overriding the default express setup with fastify plugin, so my project is using fastify: docs.nestjs.com/techniques/performance, did you use fastify as well?\n- My bad. But I have the correct answer now :) (Sorry for the confusion)\n- @Daniel Its working now! Thank you so much!","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":161,"estimatedTokens":976}}920{"id":"stack-64854333","source":"stackoverflow","questionId":64854333,"title":"NestJS/TypeORM: Cannot read property 'createQueryBuilder' of undefined","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS/TypeORM: Cannot read property 'createQueryBuilder' of undefined\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nCalling 'localhost:3000/contacts' (with or without parameters) at postman returns me this error and i don't know why. My backend is connected to a PostgreSQL db.\n\n```\nTypeError: Cannot read property 'createQueryBuilder' of undefined\n at ContactsRepository.Repository.createQueryBuilder (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\typeorm\\repository\\Repository.js:17:29)\n at ContactsRepository.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.repository.js:17:34)\n at ContactsService.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.service.js:24:39)\n at ContactsController.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.controller.js:25:37)\n at ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (internal/process/task_queues.js:93:5)\n at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\nMy code looks like this:\n\n```\n@EntityRepository(Contact)\nexport class ContactsRepository extends Repository {\n\n async getContacts(filterDto: GetContactsFilterDto): Promise {\n const { name, search } = filterDto;\n // const query = this.createQueryBuilder('contacts');\n const query = await this.createQueryBuilder()\n .select('contacts')\n .from(Contact, 'contacts');\n\n if (name) {\n query.andWhere('contacts.name = :name', { name });\n }\n\n if (search) {\n query.andWhere(\n '(contacts.email LIKE :search OR contacts.telephone LIKE :search)',\n { search: `%${search}%` },\n );\n }\n\n const contacts = await query.getMany();\n return contacts;\n }\n```\n\n```\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'contacts' })\nexport class Contact extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n email: string;\n\n @Column()\n html_de: string;\n\n @Column()\n html_en: string;\n\n @Column()\n name: string;\n\n @Column()\n telephone: string;\n}\n```\n\n```\nexport class ContactsController {\n constructor(private contactsService: ContactsService) {}\n\n @Get()\n getContacts(\n @Query(ValidationPipe) filterDto: GetContactsFilterDto,\n ): Promise {\n return this.contactsService.getContacts(filterDto);\n }\n```\n\n```\n@Injectable()\nexport class ContactsService {\n constructor(\n @InjectRepository(ContactsRepository)\n private contactsRepository: ContactsRepository,\n ) {}\n\n async getContacts(filterDto: GetContactsFilterDto): Promise {\n return this.contactsRepository.getContacts(filterDto);\n }\n```\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { ContactsController } from './contacts.controller';\nimport { ContactsRepository } from './contacts.repository';\nimport { ContactsService } from './contacts.service';\n\n@Module({\n controllers: [ContactsController],\n imports: [TypeOrmModule.forFeature([ContactsRepository])],\n providers: [ContactsRepository, ContactsService],\n exports: [ContactsRepository, ContactsService],\n})\nexport class ContactsModule {}\n```\n\nSomebody know how i can fix this? Regards\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read property 'createQueryBuilder' of undefined\n    at ContactsRepository.Repository.createQueryBuilder (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\typeorm\\repository\\Repository.js:17:29)\n    at ContactsRepository.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.repository.js:17:34)\n    at ContactsService.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.service.js:24:39)\n    at ContactsController.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.controller.js:25:37)\n    at ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)\n    at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n    at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\n@EntityRepository(Contact)\nexport class ContactsRepository extends Repository<Contact> {\n\n  async getContacts(filterDto: GetContactsFilterDto): Promise<Contact[]> {\n    const { name, search } = filterDto;\n    // const query = this.createQueryBuilder('contacts');\n    const query = await this.createQueryBuilder()\n      .select('contacts')\n      .from(Contact, 'contacts');\n\n    if (name) {\n      query.andWhere('contacts.name = :name', { name });\n    }\n\n    if (search) {\n      query.andWhere(\n        '(contacts.email LIKE :search OR contacts.telephone LIKE :search)',\n        { search: `%${search}%` },\n      );\n    }\n\n    const contacts = await query.getMany();\n    return contacts;\n  }\n```\n\n```text\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'contacts' })\nexport class Contact extends BaseEntity {\n  @PrimaryGeneratedColumn('uuid')\n  id: string;\n\n  @Column()\n  email: string;\n\n  @Column()\n  html_de: string;\n\n  @Column()\n  html_en: string;\n\n  @Column()\n  name: string;\n\n  @Column()\n  telephone: string;\n}\n```\n\n```text\nexport class ContactsController {\n  constructor(private contactsService: ContactsService) {}\n\n  @Get()\n  getContacts(\n    @Query(ValidationPipe) filterDto: GetContactsFilterDto,\n  ): Promise<ContactDto[]> {\n    return this.contactsService.getContacts(filterDto);\n  }\n```\n\n```text\n@Injectable()\nexport class ContactsService {\n  constructor(\n    @InjectRepository(ContactsRepository)\n    private contactsRepository: ContactsRepository,\n  ) {}\n\n  async getContacts(filterDto: GetContactsFilterDto): Promise<Contact[]> {\n    return this.contactsRepository.getContacts(filterDto);\n  }\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { ContactsController } from './contacts.controller';\nimport { ContactsRepository } from './contacts.repository';\nimport { ContactsService } from './contacts.service';\n\n@Module({\n  controllers: [ContactsController],\n  imports: [TypeOrmModule.forFeature([ContactsRepository])],\n  providers: [ContactsRepository, ContactsService],\n  exports: [ContactsRepository, ContactsService],\n})\nexport class ContactsModule {}\n```\n\n```text\nContactsRepository\n```\n\n```text\nTypeOrmModule.forFeature()\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n```text\nContactsRepository\n```\n\n```text\nRepository\n```\n\n========================================\n\nComments:\n- In a older version i didnt use the alias 'contacts'. Back then I named my entity 'contacts' to fit the table name 'contacts'. Wanted to make it more consistent, because an entity should be singular. It worked. Does it have something to do with it? Because right now i tried it with getManager, and it works again. const query = await getManager().createQueryBuilder(Contact, 'contacts'); github.com/typeorm/typeorm/blob/master/docs/&hellip;\n- Can you also show your `ContactsModule`?\n- I brought it back to working using TypeORM's Connection in the service: `this.contactsRepository = this.connection.getCustomRepository(ContactsRepository);` Still i'm wondering why i am not able to use Dependency Injection anymore. It must be because of the Alias used in the Entity: `@Entity({ name: 'contacts' })`\n- StackOverflow comments don't do multiline formatting. Can you add it to your question body instead of the comment?\n- I edited my post and added the module.\n- I think you need to remove `ContactsRepository` from the `providers` and `exports` arrays. That way, when Nest finds the `ContactsRepository` injection token via `@InjectRepository()` it will know this is a TypeORM related class and get it from the TypeORM system\n- I removed the exports and its working again. thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":260,"estimatedTokens":2116}}921{"id":"stack-62526828","source":"stackoverflow","questionId":62526828,"title":"How to create a NestJs Pipe with a config object and dependency?","tags":["nestjs"],"text":"Title: How to create a NestJs Pipe with a config object and dependency?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI would Like to pass a configuration string to a Pipe but also want to inject a service. The NesJs docs describe how to do both of these independent of each other but not together. Take the following example:\n\npipe.ts\n\n```\n@Injectable()\nexport class FileExistsPipe implements PipeTransform {\n\n constructor(private filePath: string, db: DatabaseService) { }\n\n async transform(value: any, metadata: ArgumentMetadata) {\n const path = value[this.filePath];\n const doesExist = await this.db.file(path).exists()\n if(!doesExist) throw new BadRequestException();\n return value;\n }\n}\n```\n\ncontroller.ts\n\n```\n@Controller('transcode')\nexport class TranscodeController {\n\n @Post()\n async transcode ( \n @Body( new FileExistsPipe('input')) transcodeRequest: JobRequest) {\n return await this.videoProducer.addJob(transcodeRequest);\n }\n```\n\nBasically, I want to be able to pass a property name to my pipe (e.g.`'input'`) and then have the pipe look up the value of the property in the request (e.g.`const path = value[this.filePath]`) and then look to see if the file exists or not in the database. If it doesn't, throw a Bad Request error, otherwise continue.\n\nThe issue I am facing is that I need NestJs to inject my DataBaseService. With the current example, It won't and my IDE gives me an error that `new FileExistsPipe('input')` only has one argument passed but was expecting two (e.g. DatabaseService).\n\nIs there anyway to achieve this?\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class FileExistsPipe implements PipeTransform {\n\n  constructor(private filePath: string, db: DatabaseService) { }\n\n  async transform(value: any, metadata: ArgumentMetadata) {\n    const path = value[this.filePath];\n    const doesExist =  await this.db.file(path).exists()\n    if(!doesExist)  throw new BadRequestException();\n    return value;\n  }\n}\n```\n\n```js\n@Controller('transcode')\nexport class TranscodeController {\n\n  @Post()\n  async transcode ( \n    @Body( new FileExistsPipe('input')) transcodeRequest: JobRequest) {\n    return await this.videoProducer.addJob(transcodeRequest);\n  }\n```\n\n```text\n'input'\n```\n\n```text\nconst path = value[this.filePath]\n```\n\n```text\nnew FileExistsPipe('input')\n```\n\n```js\nexport const FileExistPipe: (filePath: string) => PipeTransform = memoize(\n  createFileExistPipe\n);\n\nfunction createFileExistPipe(filePath: string): Type<PipeTransform> {\n  class MixinFileExistPipe implements PipeTransform {\n    constructor(\n      // use forwardRef here\n      @Inject(forwardRef(() => DatabaseService)) private db: DatabaseService \n    ) {\n      console.log(db);\n    }\n\n    async transform(value: ITranscodeRequest, metadata: ArgumentMetadata) {\n      console.log(filePath, this.db);\n      const doesExist = await this.db.checkFileExists(filePath);\n      if (!doesExist) throw new BadRequestException();\n      return value;\n    }\n  }\n\n  return mixin(MixinFileExistPipe);\n}\n```\n\n```js\nexport const FileExistPipe: (filePath: string) => PipeTransform = memoize(createFileExistPipe);\n\nfunction createFileExistPipe(filePath: string) {\n    class MixinFileExistPipe implements PipeTransform {\n        constructor(private db: DatabaseService) {}\n        ...\n    }\n\n    return mixin(MixinFileExistPipe);\n}\n```\n\n```js\n@Controller('transcode')\nexport class TranscodeController {\n\n@Post()\nasync transcode (\n    // notice, there's no \"new\"\n    @Body(FileExistsPipe('input')) transcodeRequest: JobRequest) {\n    return await this.videoProducer.addJob(transcodeRequest);\n}\n```\n\n```text\nDatabaseService\n```\n\n```text\nundefined\n```\n\n```text\nFIleExistPipe\n```\n\n```text\nAppController\n```\n\n```text\nAppController\n```\n\n```text\nDatabaseModule\n```\n\n```text\nforwardRef()\n```\n\n```text\nDatabaseService\n```\n\n```text\nAppController\n```\n\n```text\nMixin\n```\n\n```text\ninjectable\n```\n\n```text\nmemoize\n```\n\n```text\nfilePath\n```\n\n```text\nfilePath\n```\n\n```text\nmixin\n```\n\n```text\nnestjs/common\n```\n\n```text\nMixinFileExistPipe\n```\n\n```text\nDatabaseService\n```\n\n========================================\n\nComments:\n- This solution doesn't work because it does not inject the DatabaseService.\n- @tommyc38 you'd probably need to provide some repro here because it works for me. Check updated answer for screenshot\n- Updated answer to include forwardRef","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":213,"estimatedTokens":1090}}922{"id":"stack-63048014","source":"stackoverflow","questionId":63048014,"title":"In nestjs how DI will work if Injectable is not mentioned in service but the service is registered as a provider in every module","tags":["dependencies","decorator","nestjs","code-injection","injectable"],"text":"Title: In nestjs how DI will work if Injectable is not mentioned in service but the service is registered as a provider in every module\nTags: dependencies, decorator, nestjs, code-injection, injectable\nSource: Stack Overflow\n\nQuestion:\nWhat will happen if I declare a service as provider in a module but did not use @Injectable decorator in the service?\n\n```\n//Module\nmodule({\ncontroller: [catController],\nprovider: [catService]\n})\n\n//Service\n//@Injectable()\nexport class catService{\n}\n```\n\nWhat I think is that a token will be registered but not be used and new instance will be shared every time. Am I correct?\n\n========================================\n\nCode:\n```text\n//Module\nmodule({\ncontroller: [catController],\nprovider: [catService]\n})\n\n//Service\n//@Injectable()\nexport class catService{\n}\n```\n\n```text\n@Injectable()\n```\n\n========================================\n\nComments:\n- meaning that this class does not depend on anyone or no class depends on this one?\n- Meaning the class has no dependencies itself, there is nothing injected via its decorator.","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":47,"estimatedTokens":265}}923{"id":"stack-54283033","source":"stackoverflow","questionId":54283033,"title":"How to integrate dependency injection with custom decorators?","tags":["typescript","dependency-injection","nestjs"],"text":"Title: How to integrate dependency injection with custom decorators?\nTags: typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a decorator that requires dependency injection.\nFor example:\n\n```\n@Injectable()\nclass UserService{\n @TimeoutAndCache(1000)\n async getUser(id:string):Promise{\n // Make a call to db to get all Users\n }\n}\n```\n\nThe @TimeoutAndCache returns a new promise which does the following:\n\n- If a call takes longer than 1000ms, returns a rejection and when the call completes, it stores to Redis (so that it can be fetched next time).\n\n- If call takes less than 1000ms, simply returns the result\n\n```\nexport const TimeoutAndCache = function timeoutCache(ts: number, namespace) {\n return function log(\n target: object,\n propertyKey: string,\n descriptor: TypedPropertyDescriptor,\n ) {\n const originalMethod = descriptor.value; // save a reference to the original method\n descriptor.value = function(...args: any[]) {\n // pre\n let timedOut = false;\n // run and store result\n const result: Promise = originalMethod.apply(this, args);\n const task = new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n if (!timedOut) {\n timedOut = true;\n console.log('timed out before finishing');\n reject('timedout');\n }\n }, ts);\n result.then(res => {\n if (timedOut) {\n // store in cache\n console.log('store in cache');\n } else {\n clearTimeout(timer);\n // return the result\n resolve(res);\n }\n });\n });\n return task;\n };\n return descriptor;\n };\n};\n```\n\nI need to inject a RedisService to save the evaluated result.\nOne way I could inject Redis Service in to the UserService, but seems kind ugly.\n\n========================================\n\nCode:\n```text\n@Injectable()\nclass UserService{\n  @TimeoutAndCache(1000)\n  async getUser(id:string):Promise<User>{\n     // Make a call to db to get all Users\n  }\n}\n```\n\n```text\nexport const TimeoutAndCache = function timeoutCache(ts: number, namespace) {\n  return function log(\n    target: object,\n    propertyKey: string,\n    descriptor: TypedPropertyDescriptor<any>,\n  ) {\n    const originalMethod = descriptor.value; // save a reference to the original method\n    descriptor.value = function(...args: any[]) {\n      // pre\n      let timedOut = false;\n      // run and store result\n      const result: Promise<object> = originalMethod.apply(this, args);\n      const task = new Promise((resolve, reject) => {\n        const timer = setTimeout(() => {\n          if (!timedOut) {\n            timedOut = true;\n            console.log('timed out before finishing');\n            reject('timedout');\n          }\n        }, ts);\n        result.then(res => {\n          if (timedOut) {\n            // store in cache\n            console.log('store in cache');\n          } else {\n            clearTimeout(timer);\n            // return the result\n            resolve(res);\n          }\n        });\n      });\n      return task;\n    };\n    return descriptor;\n  };\n};\n```\n\n```js\nimport {\n  ExecutionContext,\n  Injectable,\n  mixin,\n  NestInterceptor,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { TestService } from './test/test.service';\n\n@Injectable()\nexport abstract class CacheInterceptor implements NestInterceptor {\n  protected abstract readonly cacheDuration: number;\n\n  constructor(private readonly testService: TestService) {}\n\n  intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    // Whatever your logic needs to be\n\n    return call$;\n  }\n}\n\nexport const makeCacheInterceptor = (cacheDuration: number) =>\n  mixin(\n    // tslint:disable-next-line:max-classes-per-file\n    class extends CacheInterceptor {\n      protected readonly cacheDuration = cacheDuration;\n    },\n  );\n```\n\n```js\n@Injectable()\nclass UserService{\n  @UseInterceptors(makeCacheInterceptor(1000))\n  async getUser(id:string):Promise<User>{\n     // Make a call to db to get all Users\n  }\n}\n```\n\n```text\nInterceptor\n```\n\n```text\nmixin\n```\n\n========================================\n\nComments:\n- I having a tough time getting the interceptor to work, even the simple logging interceptor on NestJS docs does not work on any method in a class. It seems to only work on my @Controller annotated methods? Would you be kind enough to add a test case to this?\n- @jesse-carter Where did you learn about the `mixin` function? I haven't seen it in the docs (docs.nestjs.com)\n- Please, remove or edit your answer not to confuse people. It's not possible to apply an interceptor for something that is not a controller github.com/nestjs/nest/issues/1923","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":177,"estimatedTokens":1139}}924{"id":"stack-73957354","source":"stackoverflow","questionId":73957354,"title":"Filter query with Prisma using fields of relation (One-to-Many relation)","tags":["typescript","nestjs","prisma"],"text":"Title: Filter query with Prisma using fields of relation (One-to-Many relation)\nTags: typescript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI am having trouble writing a query with prisma that includes a filter on a model's relation's key.\n\n```\nmodel Car {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n plate String @unique\n place String\n\n bookings Booking[]\n\n @@map(\"cars\")\n}\n```\n\nMy booking model is the following :\n\n```\nmodel Booking{\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n place String\n\n startDate DateTime\n endDate DateTime\n\n carId Int\n car Car @relation(fields: [carId], references: [id])\n\n @@map(\"bookings\")\n}\n```\n\nI am having trouble expressing a query returning every car that respect a given criteria on startDate and endDate within their bookings relation/key. I would appreciate any idea or clue, thank you in advance.\n\n========================================\n\nCode:\n```text\nmodel Car {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  plate     String  @unique\n  place     String\n\n  bookings  Booking[]\n\n  @@map(\"cars\")\n}\n```\n\n```text\nmodel Booking{\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  place String\n\n  startDate DateTime\n  endDate   DateTime\n\n  carId Int\n  car   Car @relation(fields: [carId], references: [id])\n\n  @@map(\"bookings\")\n}\n```\n\n```js\nprisma.booking.findMany({ where: { startDate, endDate }, include: { car: true }})\n```\n\n```js\nprisma.car.findMany({ where: { bookings: { some: { startDate, endDate } } } });\n```\n\n```js\nprisma.car.findMany({\n  where: {\n    bookings: { some: { startDate: { gte: startDate }, endDate: { lte: endDate } } },\n  },\n});\n```\n\n```text\nstartDate\n```\n\n```text\nendDate\n```\n\n========================================\n\nComments:\n- You mean like: `prisma.booking.findMany({ where: { startDate, endDate }, include: { car: true }})`?\n- More like `prisma.car.findMany(}include bookings : {where: {condition on (startDate, endDate) }})` but can't figure it out...","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":550}}925{"id":"stack-58455804","source":"stackoverflow","questionId":58455804,"title":"NestJs Swagger how to add custom favicon","tags":["swagger","favicon","nestjs"],"text":"Title: NestJs Swagger how to add custom favicon\nTags: swagger, favicon, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to add a custom favicon to my NestJs documentation. However, I am a bit lost on how the path file gets resolved and not sure how to achieve this.\n\nI am using nestjs/swagger module version 3.1.0 and trying to pass the path file like so when initializing the Swagger Module.\n\nMy **main.ts** file\n\n```\nSwaggerModule.setup('/v1/docs', app, document, {\n customCss: CUSTOM_STYLE,\n customSiteTitle: 'My API Documentation',\n customfavIcon: './public/favicon.jpg'\n});\n```\n\nSearched on the github issues and didn't find anything useful. And as you can see from the code I was able to modify the CSS styles, but I cannot figure out how to make the favicon custom.\n\nAppreciate any help\n\n========================================\n\nTop Answer:\nAlternative solution, just host your favicon and reference it with external url\n\n```\nSwaggerModule.setup('api', app, getSwaggerDocument(app), {\n ...\n customfavIcon:\n 'https://[your-bucket-url].com/.../anything.png',\n });\n```\n\n========================================\n\nCode:\n```text\nSwaggerModule.setup('/v1/docs', app, document, {\n    customCss: CUSTOM_STYLE,\n    customSiteTitle: 'My API Documentation',\n    customfavIcon: './public/favicon.jpg'\n});\n```\n\n```text\nconst app: NestExpressApplication = await NestFactory.create(...)\n```\n\n```text\napp.useStaticAssets(join(__dirname, '..', 'public'));\n```\n\n```text\nSwaggerModule.setup('/v1/docs', app, document, {\n    customCss: CUSTOM_STYLE,\n    customSiteTitle: 'My API Documentation',\n    customfavIcon: '../favicon.jpg'\n});\n```\n\n```text\nmain.ts\n```\n\n```text\nNestExpressApplication\n```\n\n```text\nmain.ts\n```\n\n```text\nfavicon.jpg\n```\n\n```text\nmain.ts\n```\n\n```text\n../favicon.jpg\n```\n\n```text\nmain.ts\n```\n\n```text\nsrc\n```\n\n```text\nSwaggerModule.setup('api', app, getSwaggerDocument(app), {\n    ...\n    customfavIcon:\n      'https://[your-bucket-url].com/.../anything.png',\n  });\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ServeStaticModule } from '@nestjs/serve-static';\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    // Host static files in ../public under the /static path.\n    ServeStaticModule.forRoot({\n      /**\n       * Config options are documented:\n       * https://github.com/nestjs/serve-static/blob/master/lib/interfaces/serve-static-options.interface.ts\n       */\n      rootPath: join(__dirname, '..', '..', 'public'),\n      serveRoot: '/static',\n    }),\n    // ... \n})\nexport class AppModule {}\n```\n\n```text\nSwaggerModule.setup('/v1/docs', app, document, {\n    customfavIcon: '/static/favicon.jpg'\n});\n```\n\n```text\n{\"statusCode\":404,\"message\":\"ENOENT: no such file or directory, stat '/Users/me/my-project/public/index.html'\"}\n```\n\n```text\n@nestjs/serve-static\n```\n\n```text\nsrc/app.module.ts\n```\n\n```text\n/public/\n```\n\n```text\n/static/*\n```\n\n```json\n{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"deleteOutDir\": true,\n    \"assets\": [\"public/**/*\"]\n  }\n}\n```\n\n```text\n\"assets\": [\"public/**/*\"]\n```\n\n```text\ncompilerOptions\n```\n\n```text\nnest-cli.json\n```\n\n```text\nnest-cli.json\n```\n\n```text\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    ServeStaticModule.forRoot({\n          rootPath: join(__dirname, '..', 'assets'), // Path to your assets directory\n    }),\n```\n\n```text\n\"targets\": {\n    \"build\": {\n      \"options\": {\n        \"assets\": [\"apps/backend/src/assets/**/*\"],  \n      }          \n    }        \n  }\n```\n\n========================================\n\nComments:\n- Do you have static resources set up for your server?\n- Hey thanks for the reply! I was not using the useStaticAssets function. I've added it now. Shouldn't customFavIcon be **\"../public/favicon.jpg\"** ? Anyway I've tried both like that and as you present your example and they both result in an error of type: *GET localhost:3000/v1/public/favicon.jpg 404 (Not Found)* . What confuses me is how are the /v1/docs and /v1/public work together for handling the requests. Appreciate any help.\n- if you are using static serving, then your URL should be `GET localhost:3000&#47;favicon.jpg`\n- Worked by configuring it like so on Swagger Options: `customfavIcon: '&#47;favicon.png'`. Thank you!!!","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":205,"estimatedTokens":1077}}926{"id":"stack-64203055","source":"stackoverflow","questionId":64203055,"title":"TypeORM insert basic master data (types, status,..) after creating the table","tags":["typescript","nestjs","typeorm"],"text":"Title: TypeORM insert basic master data (types, status,..) after creating the table\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have question for you. I am using NestJS and typeORM. I am trying to insert default values to tables after creating the tables. For example i have a priority table and i need to insert High/Medium/Low values. I tried everything from typeorm and nestJS documentation and I read related questions and answers from here. I could not do it yet.\n\n```\nimport {getConnection} from \"typeorm\";\n\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n { firstName: \"Timber\", lastName: \"Saw\" }, \n { firstName: \"Phantom\", lastName: \"Lancer\" }\n ])\n .execute();\n```\n\nI have found above code and i think the way is this. But i could not find in which file should i use this code chunk. If you help me i will be very happy. Thanks.\n\n========================================\n\nTop Answer:\nI use migrations for this purpose. We can write static query or we can also load data from CSV and then save it in DB in a loop.\n\nyou can create an empty migration with `npx typeorm migration:create -n InsertMasterDataInDB`\n\nand then you can use below query to insert data\n\n`await queryRunner.manager.query(INSERT QUERY HERE IN SINGLE QUOTES);`\n\nand then `npx typeorm migration:run`\n\n========================================\n\nCode:\n```text\nimport {getConnection} from \"typeorm\";\n\nawait getConnection()\n    .createQueryBuilder()\n    .insert()\n    .into(User)\n    .values([\n        { firstName: \"Timber\", lastName: \"Saw\" }, \n        { firstName: \"Phantom\", lastName: \"Lancer\" }\n     ])\n    .execute();\n```\n\n```text\nnpx typeorm migration:create -n InsertMasterDataInDB\n```\n\n```text\nawait queryRunner.manager.query(INSERT QUERY HERE IN SINGLE QUOTES);\n```\n\n```text\nnpx typeorm migration:run\n```\n\n========================================\n\nComments:\n- Thanks for your reply. In documentation i could not see any sample like my case. Do you have a working sample? or it will be a good article somewhere on the web.\n- Here is a good practical guide for using this technique. But there is a nuance. QueryRunner has no methods for inserting data into the database. I found a useful closed issue that says how to access QueryBuilder through a reference to the Entities Manager.","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":70,"estimatedTokens":579}}927{"id":"stack-64002621","source":"stackoverflow","questionId":64002621,"title":"How to use onDelete: 'CASCADE' on one-to-one relationship","tags":["mysql","typescript","nestjs","typeorm"],"text":"Title: How to use onDelete: 'CASCADE' on one-to-one relationship\nTags: mysql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI try to delete user's profile when user was deleted. But it's delete nothing on profile.\n\nUser Entity\n\n```\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile, profile => profile.user, \n { eager: true, cascade: true, onDelete: 'CASCADE' })\n @JoinColumn()\n profile: Profile;\n\n}\n```\n\nProfile Entity\n\n```\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n @OneToOne(type => User, user => user.profile)\n user: User;\n\n}\n```\n\nHow I delete a user.\n\n```\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: [\"profile\"] });\n\nawait user.remove()\n```\n\nUser was removed but nothing happen on user's profile.\n\nCan anyone explain how to delete relationship on one-to-one?\n\n========================================\n\nTop Answer:\n### Solution\n\nI recently found myself in the same spot. I created a inheritance relationship in my database. Multiple entities reference one common entity which provides basic attributes for each specialized table. For example: Common attribute holder table \"Car\" and specialized tables \"Truck\", \"Bus\". Now I wanted to delete the corresponding \"Car\"-entity whenever a \"Truck\" or \"Bus\" is deleted.\n\nIn typeorm the specialized tables should reference the common attribute table. To make the `CASCADE DELETE` work, you have to specify the side which holds the id using the `@JoinColumn()` annotation. Then you have to specify the `onDelete: \"CASCADE\"` on the One-to-One relationship of the same side as the `@JoinColumn()` annotation.\n\nTo validate the created table you can use `SHOW CREATE TABLE table_name` in your database. There you will see if the `CASCADE DELETE` is present on the correct foreign key constraint. (It should be on the table holding the foreign key).\n\nThat means, it is not required to set the `CASCADE DELETE` on both sides.\n\n### Code example\n\n(see Gaurav Sharma's answer - modified)\n\n```\n// referenced table\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n // you can use eager on the none-owning side\n // this can be very helpful for inheritance\n @OneToOne(type => Profile, profile => profile.user, { eager: true })\n profile: Profile;\n}\n\n// owning side - foreign key in this table\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n // specify onDelete here because owning side FK constraint would fail \n // and it needs to know what is going to happen\n @OneToOne(type => User, user => user.profile, { onDelete: \"CASCADE\" })\n @JoinColumn()\n user: User;\n\n}\n```\n\nFrom here on you would create a new user. Set the saved user in the profile to save and save the profile.\nDeleting the profile will not delete the user.\nDeleting the user will delete the profile.\n\nI also looked into `CASCADE DELETE` from both sides. From what I have found, you would have to specify the `@JoinColumn()` annotation on both sides, declaring `onDelete: \"CASCADE\"` on both sides. This will require at least two saves for new entities and I did not find further information in the docs concerning the bidirectional `CASCADE DELETE`. I would consider deleting manually in these situations because it might become very unclear what is going to happen and when entities need to be saved.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @OneToOne(type => Profile, profile => profile.user, \n              { eager: true, cascade: true, onDelete: 'CASCADE' })\n    @JoinColumn()\n    profile: Profile;\n\n}\n```\n\n```text\n@Entity()\nexport class Profile {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    gender: string;\n\n    @Column()\n    photo: string;\n\n    @OneToOne(type => User, user => user.profile)\n    user: User;\n\n}\n```\n\n```text\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: [\"profile\"] });\n\nawait user.remove()\n```\n\n```text\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @OneToOne(type => Profile, profile => profile.user, \n              { eager: true, onDelete: 'CASCADE' })\n    @JoinColumn()\n    profile: Profile;\n}\n```\n\n```text\n@Entity()\nexport class Profile {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    gender: string;\n\n    @Column()\n    photo: string;\n\n    @OneToOne(type => User, user => user.profile, { onDelete: \"CASCADE\" })\n    user: User;\n\n}\n```\n\n```text\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'} });\n\nconst profileRepository = connection.getRepository(Profile);\nconst profile = await profileRepository.findOne({ where: {id: user.profile.id} });\n\nawait profileRepository.remove(profile)\n```\n\n```text\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: [\"profile\"] });\n\nconst profileRepository = connection.getRepository(Profile);\nconst profile = await profileRepository.findOne({where: {id: user.profile.id}}).getOne()\n\nawait profile.remove()\nawait user.remove()\n```\n\n```js\n// referenced table\n@Entity()\nexport class User {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    // you can use eager on the none-owning side\n    // this can be very helpful for inheritance\n    @OneToOne(type => Profile, profile => profile.user, { eager: true })\n    profile: Profile;\n}\n\n\n// owning side - foreign key in this table\n@Entity()\nexport class Profile {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    gender: string;\n\n    @Column()\n    photo: string;\n\n    // specify onDelete here because owning side FK constraint would fail \n    // and it needs to know what is going to happen\n    @OneToOne(type => User, user => user.profile, { onDelete: \"CASCADE\" })\n    @JoinColumn()\n    user: User;\n\n}\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nonDelete: \"CASCADE\"\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nSHOW CREATE TABLE table_name\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nonDelete: \"CASCADE\"\n```\n\n```text\nCASCADE DELETE\n```\n\n========================================\n\nComments:\n- If you look at the actual tables in your SQL database, is there an actual cascade configured?\n- here is in Users --> CONSTRAINT `FK_ef7a0cc61d7873284f1cedc5d5d` FOREIGN KEY (`profileId`) REFERENCES `profile` (`id`) ON DELETE CASCADE\n- and this --> UNIQUE KEY `REL_ef7a0cc61d7873284f1cedc5d5` (`profileId`) @AluanHaddad\n- In SQL, the `cascade` specification belongs on the child or dependent table in the relationship. I assume that `Profile` depends on `User`, so you probably need to put the cascade specification on the other end of the relationship in the decorator.\n- `user.remove()` is this syntax correct? remove does not exist on user entity.\n- I try to define onDelete: \"CASCADE\" in both entities. profile still not remove. Should I change its to Many-to-one ?\n- Sorry, I forgot to mention some points. Check my answer again\n- That is a really counterintuitive API. Specifying it on both ends makes the code read as if deleting either end will cascade delete the other, I assume the owner is not subject to deletion if the owned entity is deleted.\n- Sadly, That's how it is working. I'll raise an issue on typeorm github.\n- See my answer again. I ran that code on my machine.","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":321,"estimatedTokens":1980}}928{"id":"stack-71347810","source":"stackoverflow","questionId":71347810,"title":"Why does NestJS with Swagger report all my DTO properties as required?","tags":["swagger","nestjs"],"text":"Title: Why does NestJS with Swagger report all my DTO properties as required?\nTags: swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have this DTO class defined.\n\n```\nimport { ApiProperty } from \"@nestjs/swagger\"\n\nexport class FormDTO {\n @ApiProperty()\n id: string\n\n @ApiProperty()\n type: string\n\n @ApiProperty()\n fieldValues?: Record\n\n @ApiProperty()\n parentFormId?: string\n}\n```\n\nI expected that the generated OpenAPI spec would indicate that `fieldValues` and `parentFormId` would be optional, but they are required.\n\nhttps://i.sstatic.net/lQDQH.png\n\nAccording to the example in the docs here they should be optional. What am I missing?\n\nThe only method using that DTO looks like this, but I didn't think it would matter:\n\n```\n@Post(\":id\")\ncreateForm(@Body() createFormDto: FormDTO) {\n if (this.formService.hasForm(createFormDto.id)) {\n throw new ConflictException(\n undefined,\n `A form with the id ${createFormDto.id} already exists.`\n )\n }\n return this.formService.createOrUpdateForm(createFormDto)\n}\n```\n\nIf it matters, here is the code for the `DocumentBuilder`\n\n```\nconst config = new DocumentBuilder()\n .setTitle(\"API\")\n .setDescription(\n \"description.\"\n )\n .setVersion(\"1.0\")\n .addBearerAuth(\n {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description: \"Paste a valid access token here.\"\n },\n JWTGuard.name\n )\n .build()\n```\n\n========================================\n\nCode:\n```js\nimport { ApiProperty } from \"@nestjs/swagger\"\n\nexport class FormDTO {\n    @ApiProperty()\n    id: string\n\n    @ApiProperty()\n    type: string\n\n    @ApiProperty()\n    fieldValues?: Record<string, unknown>\n\n    @ApiProperty()\n    parentFormId?: string\n}\n```\n\n```js\n@Post(\":id\")\ncreateForm(@Body() createFormDto: FormDTO) {\n    if (this.formService.hasForm(createFormDto.id)) {\n        throw new ConflictException(\n            undefined,\n            `A form with the id ${createFormDto.id} already exists.`\n        )\n    }\n    return this.formService.createOrUpdateForm(createFormDto)\n}\n```\n\n```js\nconst config = new DocumentBuilder()\n    .setTitle(\"API\")\n    .setDescription(\n        \"description.\"\n    )\n    .setVersion(\"1.0\")\n    .addBearerAuth(\n        {\n            type: \"http\",\n            scheme: \"bearer\",\n            bearerFormat: \"JWT\",\n            description: \"Paste a valid access token here.\"\n        },\n        JWTGuard.name\n    )\n    .build()\n```\n\n```text\nfieldValues\n```\n\n```text\nparentFormId\n```\n\n```text\nDocumentBuilder\n```\n\n```text\n@ApiProperty()\n```\n\n```text\n@ApiPropertyOptional()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":139,"estimatedTokens":627}}929{"id":"stack-66335078","source":"stackoverflow","questionId":66335078,"title":"URL input validation NestJs","tags":["node.js","nestjs","class-validator"],"text":"Title: URL input validation NestJs\nTags: node.js, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI am trying an input validation on a website URL. I used the URL decorator but when I don't input any URL it gives me my error message. what should I do to make it accept empty string also?\n\n```\n@ApiProperty()\n @IsString()\n @IsUrl(undefined, { message: 'Company URL is not valid.' })\n companyURL: string;\n```\n\n========================================\n\nTop Answer:\nI had to add @Validateif() to check if it had a value.\n\n```\n@ApiProperty()\n @ValidateIf(o => o. companyUrl\n === 'value')\n @IsString()\n @IsUrl(undefined, { message: 'Company Url is not valid.' })\n companyUrl: string;\n```\n\n========================================\n\nCode:\n```text\n@ApiProperty()\n  @IsString()\n  @IsUrl(undefined, { message: 'Company URL is not valid.' })\n  companyURL: string;\n```\n\n```text\n@IsOptional()\n```\n\n```text\n@IsDefined(value: any)\n```\n\n```text\n@IsOptional()\n```\n\n```text\n@IsDefined(value: any)\n```\n\n```text\n@ApiProperty()\n@IsOptional()\n  @IsString({ message: 'Must be a string!' })\n  @IsUrl(undefined, { message: 'Company URL is not valid.' })\n  companyURL: string;\n```\n\n```text\n@ApiProperty()\n  @ValidateIf(o => o.  companyUrl\n    === 'value')\n  @IsString()\n  @IsUrl(undefined, { message: 'Company Url is not valid.' })\n  companyUrl: string;\n```\n\n========================================\n\nComments:\n- Why do you pass `undefined` as a parameter to `@IsUrl` decorator?","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":366}}930{"id":"stack-73266455","source":"stackoverflow","questionId":73266455,"title":"Inject list of interfaces to a class - NestJs","tags":["typescript","dependency-injection","nestjs"],"text":"Title: Inject list of interfaces to a class - NestJs\nTags: typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nLet's say I have this interface:\n\n```\nexport interface IParser {\n parse(text: string):string\n}\n```\n\nand a couple of classes implementing the interface:\n\n```\n@Injectable()\nexport class FirstParser implements IParser {\n public parse(text: string): string {\n return text + 'first';\n }\n}\n\n@Injectable()\nexport class SecondParser implements IParser {\n public parse(text: string): string {\n return text + 'second';\n }\n}\n```\n\nNow, I have a service that I'm trying to inject to him list of parsers:\n\n```\n@Injectable()\nexport class ParserService {\n constructor(private readonly parsers: IParser[]) {}\n\n public parse(text: string): string {\n let parsedText = text;\n parsedText = this.parsers.reduce((acc: string, result) => {\n return result.parse(acc);\n }, parsedText);\n return parsedText;\n }\n}\n```\n\nI'm trying to make the app module (in this case the parser-service.module.ts) to work\nby injecting array/list of the class including FirstParser, SecondParser.\n\n```\n@Module({\n providers: [\n ParserService,\n {\n provide: Array,\n useClass: ???,\n },\n ],\n})\nexport class ParserServiceModule {}\n```\n\nAny ideas? is it possible at all in NestJs?\n\nThanks.\n\n========================================\n\nCode:\n```text\nexport interface IParser {\n  parse(text: string):string\n}\n```\n\n```text\n@Injectable()\nexport class FirstParser implements IParser {\n   public parse(text: string): string {\n     return text + 'first';\n   }\n}\n\n@Injectable()\nexport class SecondParser implements IParser {\n   public parse(text: string): string {\n     return text + 'second';\n   }\n}\n```\n\n```text\n@Injectable()\nexport class ParserService {\n    constructor(private readonly parsers: IParser[]) {}\n\n    public parse(text: string): string {\n        let parsedText = text;\n        parsedText = this.parsers.reduce((acc: string, result) => {\n            return result.parse(acc);\n        }, parsedText);\n        return parsedText;\n    }\n}\n```\n\n```text\n@Module({\n    providers: [\n        ParserService,\n        {\n          provide: Array<IParser>,\n          useClass: ???,\n        },\n    ],\n})\nexport class ParserServiceModule {}\n```\n\n```js\n@Module({\n    providers: [\n        FirstParser,\n        SecondParser,\n        {\n          provide: 'Parser',\n          useFactory: (...parsers) => new ParserService(parsers),\n          inject: [FirstParser, SecondParser],\n        },\n    ],\n})\nexport class ParserServiceModule {}\n```\n\n```text\nfactory provider\n```\n\n```text\nIParser\n```\n\n========================================\n\nComments:\n- So the module name is 'Parser' also when I'm using it in the test module. `service = module.get('Parser');`\n- @yairabr correct, you access this custom provider by its token - `Parser`.","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":149,"estimatedTokens":699}}931{"id":"stack-53561491","source":"stackoverflow","questionId":53561491,"title":"How to set up typeorm .env file?","tags":["javascript","node.js","environment-variables","nestjs","typeorm"],"text":"Title: How to set up typeorm .env file?\nTags: javascript, node.js, environment-variables, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI've created a `ormconfig.env` file in the nestjs starter project and put the variables from this documentation in there and added this line here\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n TaskModule,\n ],\n})\nexport class AppModule {\n}`\n```\n\nAnd the console shows this error:\n\n`Error: EACCES: permission denied, scandir '/Library/Application Support/Apple/AssetCache/Data' at Object.fs.readdirSync (fs.js:904:18)`\n\nHow should I properly set up typeorm .env file in nestjs?\n\n========================================\n\nTop Answer:\nI had the same problem as in the question. As the other answer didn't solve my problem, I had to look around. I will leave my solution for those who also have similar troubles with Webpack + TypeORM, as I had.\n\nHere is what I needed to do to make it work.\n\n```\nimport { createConnection, getConnectionManager } from \"typeorm\";\n\n// For hot reload to work need to require files\nimport { Job } from \"../jobs/job.entity\";\nimport { JobAction } from \"../jobs/jobaction.entity\";\n\nexport const databaseProviders = [\n {\n provide: \"DATABASE_CONNECTION\",\n keepConnectionAlive: true,\n useFactory: async () => {\n try {\n const conn = await createConnection({\n ...connectionOption,\n // add entitities manually\n entities: [Job, JobAction],\n });\n return conn;\n } catch (err) {\n // If AlreadyHasActiveConnectionError occurs, return already existent connection\n if (err.name === \"AlreadyHasActiveConnectionError\") {\n const existentConn = getConnectionManager().get(\"default\");\n return existentConn;\n }\n throw err;\n }\n },\n },\n];\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forRoot(),\n    TaskModule,\n  ],\n})\nexport class AppModule {\n}`\n```\n\n```text\normconfig.env\n```\n\n```text\nError: EACCES: permission denied, scandir '/Library/Application Support/Apple/AssetCache/Data' at Object.fs.readdirSync (fs.js:904:18)\n```\n\n```text\nTYPEORM_ENTITIES = src/**/**.entity.ts\n```\n\n```text\nTYPEORM_ENTITIES\n```\n\n```text\n.entity.ts\n```\n\n```text\nsrc\n```\n\n```text\nimport { createConnection, getConnectionManager } from \"typeorm\";\n\n// For hot reload to work need to require files\nimport { Job } from \"../jobs/job.entity\";\nimport { JobAction } from \"../jobs/jobaction.entity\";\n\nexport const databaseProviders = [\n  {\n    provide: \"DATABASE_CONNECTION\",\n    keepConnectionAlive: true,\n    useFactory: async () => {\n      try {\n        const conn = await createConnection({\n          ...connectionOption,\n          // add entitities manually\n          entities: [Job, JobAction],\n        });\n        return conn;\n      } catch (err) {\n        // If AlreadyHasActiveConnectionError occurs, return already existent connection\n        if (err.name === \"AlreadyHasActiveConnectionError\") {\n          const existentConn = getConnectionManager().get(\"default\");\n          return existentConn;\n        }\n        throw err;\n      }\n    },\n  },\n];\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.478Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":132,"estimatedTokens":760}}932{"id":"stack-74526743","source":"stackoverflow","questionId":74526743,"title":"NestJS use service without constructor","tags":["nestjs"],"text":"Title: NestJS use service without constructor\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nThis is my BaseRepository\n\n```\nexport class BaseRepository extends Repository {\n constructor(\n private readonly helperService: HelperService,\n target: EntityTarget,\n entityManager: EntityManager,\n ) {\n super(target, entityManager);\n }\n \n async createEntity(entity: E) {\n //\n }\n \n async getEntities(getEntitiesDto: GetEntitiesDto) {\n //\n }\n \n test() {\n // use function of HelperService\n }\n }\n```\n\nThis is my UserRepository which extent BaseRepository\n\n```\n@Injectable()\n export class UserRepository extends BaseRepository {\n constructor(helperService: HelperService, entityManager: EntityManager) {\n super(helperService, User, entityManager);\n }\n }\n```\n\nI wonder is there any way to remove HelperService from constructor of UserRepository but UserRepository still use function test(), may be can change both Repository. I'd like UserRepository looks like:\n\n```\n@Injectable()\n export class UserRepository extends BaseRepository {\n constructor(entityManager: EntityManager) {\n super(User, entityManager);\n }\n }\n```\n\nor\n\n```\n@Injectable()\n export class UserRepository extends BaseRepository {\n // no constructor :)\n }\n```\n\nThank for your attention.\n\n========================================\n\nCode:\n```js\nexport class BaseRepository<E> extends Repository<E> {\n      constructor(\n        private readonly helperService: HelperService,\n        target: EntityTarget<E>,\n        entityManager: EntityManager,\n      ) {\n        super(target, entityManager);\n      }\n    \n      async createEntity(entity: E) {\n        //\n      }\n    \n      async getEntities(getEntitiesDto: GetEntitiesDto) {\n        //\n      }\n    \n      test() {\n        // use function of HelperService\n      }\n    }\n```\n\n```js\n@Injectable()\n    export class UserRepository extends BaseRepository<User> {\n      constructor(helperService: HelperService, entityManager: EntityManager) {\n        super(helperService, User, entityManager);\n      }\n    }\n```\n\n```js\n@Injectable()\n    export class UserRepository extends BaseRepository<User> {\n      constructor(entityManager: EntityManager) {\n        super(User, entityManager);\n      }\n    }\n```\n\n```js\n@Injectable()\n    export class UserRepository extends BaseRepository<User> {\n      // no constructor :)\n    }\n```\n\n```text\n@Injectable()\nexport class UserRepository extends BaseRepository<User> {\n  @Inject()\n  private helperService: HelperService;\n\n  constructor(entityManager: EntityManager) {\n    super(User, entityManager);\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":127,"estimatedTokens":634}}933{"id":"stack-62664587","source":"stackoverflow","questionId":62664587,"title":"Nestjs applyDecorators for multiple decorators","tags":["nestjs","class-validator","class-transformer"],"text":"Title: Nestjs applyDecorators for multiple decorators\nTags: nestjs, class-validator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI'd like to create custom decorator with `applyDecorators` imported from `@nestjs/common`\n\n```\n...\n\napplyDecorators(\n @Field(),\n @MinLength(2)\n)\n\n...\n```\n\nBut I got typescript lint errors. How can I create a custom decorator which wraps several decorators?\n\nhttps://docs.nestjs.com/custom-decorators\n\n```\n\"class-validator\": \"^0.11.0\"\n\"@nestjs/common\": \"^7.0.9\"\n```\n\n========================================\n\nCode:\n```text\n...\n\napplyDecorators(\n  @Field(),\n  @MinLength(2)\n)\n\n...\n```\n\n```text\n\"class-validator\": \"^0.11.0\"\n\"@nestjs/common\": \"^7.0.9\"\n```\n\n```text\napplyDecorators\n```\n\n```text\n@nestjs/common\n```\n\n```text\nexport const NameField = (options?: FieldOptions) =>\n  applyDecorators(\n    Field() as PropertyDecorator, // convert to PropertyDecorator\n    MinLength(2) as PropertyDecorator // convert to PropertyDecorator\n  )\n)\n```\n\n```text\napplyDecorators\n```\n\n```text\napplyDecorators\n```\n\n```text\nPropertyDecorator\n```\n\n```text\nPropertyDecorator\n```\n\n========================================\n\nComments:\n- This not works. Doesn't trigger any error, but the param doesn't appear on Swagger doc","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":83,"estimatedTokens":309}}934{"id":"stack-66980521","source":"stackoverflow","questionId":66980521,"title":"How to add a where clause dynamically to query which is generated using nestjs Query Builder?","tags":["node.js","nestjs","query-builder","typeorm"],"text":"Title: How to add a where clause dynamically to query which is generated using nestjs Query Builder?\nTags: node.js, nestjs, query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am working on an API for which the requirement from UI is based on the value of the search field I shall receive the filtered results. There are many search fields on UI.\n\nExample code -\n\n```\nasync getRoomsByMember(active: boolean, email: string): Promise {\n return await getRepository(Room)\n .createQueryBuilder('room')\n .innerJoinAndSelect('room.member', 'member')\n .where(\"room.active = :active\", {active: active})\n .andWhere(\"member.email = :email\", { email: email })\n .getMany();\n }\n```\n\nI shall be able to filter room members dynamically if values entered by a user on filter fields like - member phone number, city, state, country, and zip.\n\n========================================\n\nCode:\n```text\nasync getRoomsByMember(active: boolean, email: string): Promise<any[]> {\n      return await getRepository(Room)\n      .createQueryBuilder('room')\n      .innerJoinAndSelect('room.member', 'member')\n      .where(\"room.active = :active\", {active: active})\n      .andWhere(\"member.email = :email\", { email: email })\n      .getMany();\n  }\n```\n\n```js\nasync getRoomsByMember(active: boolean, email: string): Promise<any[]> {\n  const query = getRepository(Room)\n    .createQueryBuilder('room')\n    .innerJoinAndSelect('room.member', 'member')\n    .where(\"room.active = :active\", {active: active});\n  // Keep adding your other fields like member phone number, city, state, country, and zip, like below\n  if(email) {\n    query.andWhere(\"member.email = :email\", { email: email })\n  }\n  return query.getMany();\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":423}}935{"id":"stack-73150528","source":"stackoverflow","questionId":73150528,"title":"how to prevent file upload when body validation fails in nestjs","tags":["node.js","validation","file-upload","nestjs","nest"],"text":"Title: how to prevent file upload when body validation fails in nestjs\nTags: node.js, validation, file-upload, nestjs, nest\nSource: Stack Overflow\n\nQuestion:\nI have the multipart form to be validated before file upload in nestjs application. the thing is that I don't want the file to be uploaded if validation of body fails.\nhere is how I wrote the code for.\n\n```\n// User controller method for create user with upload image\n@Post()\n@UseInterceptors(FileInterceptor('image'))\ncreate(\n @Body() userInput: CreateUserDto,\n @UploadedFile(\n new ParseFilePipe({\n validators: [\n // some validator here\n ]\n })\n ) image: Express.Multer.File,\n) {\n return this.userService.create({ ...userInput, image: image.path });\n}\n```\n\nTried so many ways to turn around this issue, but didn't reach to any solution\n\n========================================\n\nTop Answer:\nThis is how I created the whole filter\n\n```\nimport { isArray } from 'lodash';\nimport {\n ExceptionFilter,\n Catch,\n ArgumentsHost,\n BadRequestException,\n} from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport * as fs from 'fs';\n\n@Catch(BadRequestException)\nexport class DeleteFileOnErrorFilter implements ExceptionFilter {\n catch(exception: BadRequestException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n const status = exception.getStatus();\n\n const getFiles = (files: Express.Multer.File[] | unknown | undefined) => {\n if (!files) return [];\n if (isArray(files)) return files;\n return Object.values(files);\n };\n\n const filePaths = getFiles(request.files);\n\n for (const file of filePaths) {\n fs.unlink(file.path, (err) => {\n if (err) {\n console.error(err);\n return err;\n }\n });\n }\n response.status(status).json(exception.getResponse());\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// User controller method for create user with upload image\n@Post()\n@UseInterceptors(FileInterceptor('image'))\ncreate(\n    @Body() userInput: CreateUserDto,\n    @UploadedFile(\n        new ParseFilePipe({\n          validators: [\n             // some validator here\n          ]\n        })\n    ) image: Express.Multer.File,\n) {\n    return this.userService.create({ ...userInput, image: image.path });\n}\n```\n\n```text\nunlink\n```\n\n```js\nimport { isArray } from 'lodash';\nimport {\n  ExceptionFilter,\n  Catch,\n  ArgumentsHost,\n  BadRequestException,\n} from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport * as fs from 'fs';\n\n@Catch(BadRequestException)\nexport class DeleteFileOnErrorFilter implements ExceptionFilter {\n  catch(exception: BadRequestException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n    const status = exception.getStatus();\n\n    const getFiles = (files: Express.Multer.File[] | unknown | undefined) => {\n      if (!files) return [];\n      if (isArray(files)) return files;\n      return Object.values(files);\n    };\n\n    const filePaths = getFiles(request.files);\n\n    for (const file of filePaths) {\n      fs.unlink(file.path, (err) => {\n        if (err) {\n          console.error(err);\n          return err;\n        }\n      });\n    }\n    response.status(status).json(exception.getResponse());\n  }\n}\n```\n\n```text\nimport {\n    CallHandler,\n    ExecutionContext,\n    Injectable,\n    NestInterceptor,\n} from '@nestjs/common';\nimport { Observable, throwError, tap } from 'rxjs';\nimport { writeFile, existsSync, mkdirSync } from 'fs';\nimport { join } from 'path';\nimport { Request } from 'express';\n\n@Injectable()\nexport class SaveFileInterceptor implements NestInterceptor {\n\n    saveFile(file: Express.Multer.File) {\n        const fileType = file.mimetype ? file.mimetype.split('/')[0] : 'others';\n        const destination = join(__dirname, `../../src/public/upload/${fileType}`);\n        if (!existsSync(destination)) {\n            mkdirSync(destination, { recursive: true });\n        }\n        writeFile(\n            `${destination}/${file.filename}`,\n            file.buffer,\n            err => {\n                if (err) {\n                    console.log(err);\n                    throwError(err);\n                }\n            }\n        )\n    }\n\n    generateFilePath(file: Express.Multer.File) {\n        const fileType = file.mimetype ? file.mimetype.split('/')[0] : 'others';\n        file.path = `/upload/${fileType}/${file.filename}`; // path served as static file\n    }\n\n    generateFileName(file: Express.Multer.File) {\n        file.filename = Date.now() + '-' + Math.round(Math.random() * 1E9);\n    }\n\n    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n\n        const req: Request = context.switchToHttp().getRequest();\n        \n        if (req.file) {\n            this.generateFileName(req.file);\n            this.generateFilePath(req.file);\n        }\n        if (req.files) {\n            if (Array.isArray(req.files)) {\n                req.files.forEach(file => {\n                    this.generateFileName(file);\n                    this.generateFilePath(file);\n                });\n            }\n            else {\n                Object.values(req.files).flat().forEach(file => {\n                    this.generateFileName(file);\n                    this.generateFilePath(file);\n                });\n            }\n        }\n\n        return next.handle().pipe(tap(() => {\n            \n            if (req.file) {\n                this.saveFile(req.file);\n            }\n            if (req.files) {\n                if (Array.isArray(req.files)) {\n                    req.files.forEach(file => this.saveFile(file));\n                }\n                else {\n                    Object.values(req.files).flat().forEach(file => this.saveFile(file));\n                }\n            }\n        }));\n    }\n}\n```\n\n```text\nimport {\n    Controller,\n    Post,\n    Body,\n    UseInterceptors,\n    UploadedFile,\n    UploadedFiles,\n    ParseFilePipeBuilder,\n    HttpStatus,\n} from '@nestjs/common';\nimport { Public } from '../auth/public.decorator';\nimport {\n    FileFieldsInterceptor,\n    FileInterceptor,\n    FilesInterceptor,\n} from '@nestjs/platform-express';\nimport { FileTypeValidator, FileSizeValidator } from 'src/common';\nimport { SaveFileInterceptor } from 'src/interceptors/save-file.interceptor';\nimport { UploadOneFileDto } from './upload.dto';\n\n@Public()\n@Controller('upload')\nexport class UploadController {\n\n    @Post('/one-file')\n    @UseInterceptors(\n        FileInterceptor('file'),\n        SaveFileInterceptor\n    )\n    uploadOneFile(\n        @UploadedFile(\n            new ParseFilePipeBuilder()\n                .addMaxSizeValidator({ maxSize: 1024 * 1024 })\n                .addFileTypeValidator({ fileType: /.(jpg|jpeg|png)$/ })\n                .build({ errorHttpStatusCode: HttpStatus.BAD_REQUEST }),\n        ) file: Express.Multer.File,\n        @Body() body: UploadOneFileDto\n    ) {\n        console.log(file);\n    }\n}\n```\n\n========================================\n\nComments:\n- You are right, but how can I check for validation errors inside exception filter. I can not do it, I seems like no way I can check for validation errors before they are thrown\n- I edited my code I want to right a validator class which would check for validation errors if exists. if it exists then unlink the file.\n- The `ParseFilePipe` would throw a `BadRequestException`, so you could verify that that is the error type you are receiving in the filter\n- I did it using an exception filter on BadRequestException, Thanks\n- ElZombieIsra has written a good answer but he hasn't explained how to bind this BadRequestException in Nest.js. There are three major ways to do it: Global Scope Controller Scope Method Scope. This article explatins how to do it. freecodecamp.org/news/exception-filters-in-nestjs\n- Hi there! Thanks for sharing your solution on StackOverflow. However, using screenshots of code can make it challenging for others to copy, modify, or understand your solution effectively. Consider replacing the screenshots with actual code blocks for better readability and accessibility. Feel free to edit your answer to make the code more accessible to everyone.\n- using `MemoryStorage` is not recommended in general bec your server will be susceptible to out-of-memory exceptions.\n- @MohamedSalah thanks for pointing that out, I wanted to validate file type based on the buffer so i needed to use memory storage. multer disk storage sadly doesn't provide file's buffer;","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":276,"estimatedTokens":2127}}936{"id":"stack-66848688","source":"stackoverflow","questionId":66848688,"title":"what is req.user and where is it populated from?","tags":["javascript","node.js","express","nestjs"],"text":"Title: what is req.user and where is it populated from?\nTags: javascript, node.js, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying my hands on Nestjs and i was a bit confused about the req.user. Where do we get this from and do we need to manually req.user? what actually is req.user and what benefit can we have from it? Do i need to assign payload to it manually?\n\nI have tried searching stackoverflow and nestjs documentaion but did not get a clear insight.\n\n```\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const User = createParamDecorator((data, req) => req.user);\n```\n\nLike in this example where do i get the req from??\n\n========================================\n\nCode:\n```text\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const User = createParamDecorator((data, req) => req.user);\n```\n\n```text\nreq.user\n```\n\n```text\nreq\n```\n\n```text\nreq\n```\n\n```text\nreq.user\n```\n\n```text\nreq.body.yourKey\n```\n\n========================================\n\nComments:\n- this is an old API (nestjs v6). Please read this: docs.nestjs.com/custom-decorators and this migration guide","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":50,"estimatedTokens":279}}937{"id":"stack-68524064","source":"stackoverflow","questionId":68524064,"title":"I got an error while running dist file in nestjs project, please help me","tags":["node.js","typescript","graphql","backend","nestjs"],"text":"Title: I got an error while running dist file in nestjs project, please help me\nTags: node.js, typescript, graphql, backend, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\n(node:8356) UnhandledPromiseRejectionWarning: Error: No type definitions were found with the specified file name patterns: \"./**/*.graphql\". Please make sure there is at least one file that matches the given patterns.\n at GraphQLTypesLoader. (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\@nestjs\\graphql\\dist\\graphql-types.loader.js:38:23)\n at Generator.next ()\n at fulfilled (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\tslib\\tslib.js:114:62)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n(node:8356) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async \nfunction without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n(node:8356) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n========================================\n\nTop Answer:\nhttps://docs.nestjs.com/cli/monorepo#assets\n\nThere is `assets` option in nestjs.\nThis is the right way to do it in nestjs.\n\n========================================\n\nCode:\n```text\n(node:8356) UnhandledPromiseRejectionWarning: Error: No type definitions were found with the specified file name patterns: \"./**/*.graphql\". Please make sure there is at least one file that matches the given patterns.\n    at GraphQLTypesLoader.<anonymous> (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\@nestjs\\graphql\\dist\\graphql-types.loader.js:38:23)\n    at Generator.next (<anonymous>)\n    at fulfilled (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\tslib\\tslib.js:114:62)\n    at processTicksAndRejections (internal/process/task_queues.js:97:5)\n(node:8356) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async \nfunction without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n(node:8356) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nassets\n```\n\n========================================\n\nComments:\n- Very nice, Thank you very much!\n- Thanks. I think that this solution is the better because it is integrate with the framework.\n- I confirm this resolves the issue","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":773}}938{"id":"stack-69272891","source":"stackoverflow","questionId":69272891,"title":"NestJS Mongoose Schema Inheritence","tags":["node.js","mongodb","mongoose","nestjs"],"text":"Title: NestJS Mongoose Schema Inheritence\nTags: node.js, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am attempting to inherit Mongoose Schemas or SchemaDefitions within NestJS but I am not having much luck.\nI am doing this so I can Base and Common Schema Definition Details such as a virtual('id') and a nonce, we have attached to each of the entities. Each schema definition should have its own collection in Mongo, so discriminators will not work.\n\nI tried to implement this in the following different ways\n\nFirst, I have the following Base Schema Definition defined:\n\n**base.schema.ts**\n\n```\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types } from 'mongoose';\nimport { TimeStamps } from './timestamps.schema';\n\nexport type BaseDocument = BaseSchemaDefinition & Document;\n\n@Schema({\n toJSON: {\n virtuals: true,\n transform: function (doc: any, ret: any) {\n delete ret._id;\n delete ret.__v;\n return ret;\n },\n },\n})\nexport class BaseSchemaDefinition {\n @Prop({\n type: Types.ObjectId,\n required: true,\n default: Types.ObjectId,\n })\n nonce: Types.ObjectId;\n\n @Prop()\n timestamps: TimeStamps;\n}\n```\n\nI then inherit the schema definition and create the schema so it can be used later in my services and controllers by the following:\n\n**person.schema.ts**\n\n```\nimport { Prop, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Document } from 'mongoose';\nimport { Address } from './address.schema';\nimport { BaseSchemaDefinition } from './base.schema';\n\nexport type PersonDocument = PersonSchemaDefintion & Document;\n\nexport class PersonSchemaDefintion extends BaseSchemaDefinition {\n @Prop({ required: true })\n first_name: string;\n\n @Prop({ required: true })\n last_name: string;\n\n @Prop()\n middle_name: string;\n\n @Prop()\n data_of_birth: Date;\n\n @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Address' }] })\n addresses: [Address];\n}\n\nconst PersonSchema = SchemaFactory.createForClass(PersonSchemaDefintion);\n\nPersonSchema.virtual('id').get(function (this: PersonDocument) {\n return this._id;\n});\n\nexport { PersonSchema };\n```\n\nThis results in only allowing me to create and get properties defined in the BaseSchemaDefinition.\n\n{\n\"timestamps\": {\n\"deleted\": null,\n\"updated\": \"2021-09-21T16:55:17.094Z\",\n\"created\": \"2021-09-21T16:55:17.094Z\"\n},\n\"_id\": \"614a0e75eb6cb52aa0ccd026\",\n\"nonce\": \"614a0e75eb6cb52aa0ccd028\",\n\"__v\": 0 }\n\nSecond, I then tried to implement inheritance by using the method described here\nInheriting Mongoose schemas (different MongoDB collections)\n\n**base.schema.ts**\n\n```\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types } from 'mongoose';\nimport { TimeStamps } from './timestamps.schema';\n\nexport type BaseDocument = BaseSchemaDefinition & Document;\n\n@Schema({\n toJSON: {\n virtuals: true,\n transform: function (doc: any, ret: any) {\n delete ret._id;\n delete ret.__v;\n return ret;\n },\n },\n})\nexport class BaseSchemaDefinition {\n @Prop({\n type: Types.ObjectId,\n required: true,\n default: Types.ObjectId,\n })\n nonce: Types.ObjectId;\n\n @Prop()\n timestamps: TimeStamps;\n}\n\nconst BaseSchema = SchemaFactory.createForClass(BaseSchemaDefinition);\n\nBaseSchema.virtual('id').get(function (this: BaseDocument) {\n return this._id;\n});\n\nexport { BaseSchema };\n```\n\n**person.schema.ts**\n\n```\nimport { Prop } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Document } from 'mongoose';\nimport { Address } from './address.schema';\nimport { BaseSchema, BaseSchemaDefinition } from './base.schema';\n\nexport type PersonDocument = PersonSchemaDefintion & Document;\n\nexport class PersonSchemaDefintion extends BaseSchemaDefinition {\n @Prop({ required: true })\n first_name: string;\n\n @Prop({ required: true })\n last_name: string;\n\n @Prop()\n middle_name: string;\n\n @Prop()\n data_of_birth: Date;\n\n @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Address' }] })\n addresses: [Address];\n}\n\nexport const PersonSchema = Object.assign(\n {},\n BaseSchema.obj,\n PersonSchemaDefintion,\n);\n```\n\nResults in the same output. Not sure why the inheritance is not taking\n\nThe following is the service code that uses the schemas and builds the models\n\n**person.service.ts**\n\n```\nimport { Model } from 'mongoose';\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport {\n PersonSchemaDefintion,\n PersonDocument,\n} from 'src/schemas/person.schema';\nimport { TimeStamps } from 'src/schemas/timestamps.schema';\n\n@Injectable()\nexport class PersonService {\n constructor(\n @InjectModel(PersonSchemaDefintion.name)\n private personModel: Model,\n ) {}\n\n async create(\n personModel: PersonSchemaDefintion,\n ): Promise {\n personModel.timestamps = new TimeStamps();\n const createdPerson = new this.personModel(personModel);\n\n return createdPerson.save();\n }\n\n async update(\n id: string,\n changes: Partial,\n ): Promise {\n const existingPerson = this.personModel\n .findByIdAndUpdate(id, changes)\n .exec()\n .then(() => {\n return this.personModel.findById(id);\n });\n if (!existingPerson) {\n throw Error('Id does not exist');\n }\n return existingPerson;\n }\n\n async findAll(): Promise {\n return this.personModel.find().exec();\n }\n\n async findOne(id: string): Promise {\n return this.personModel.findById(id).exec();\n }\n\n async delete(id: string): Promise {\n return this.personModel.deleteOne({ _id: id }).then(() => {\n return Promise.resolve(`${id} has been deleted`);\n });\n }\n}\n```\n\nI can provide additional details if it is needed\n\n========================================\n\nTop Answer:\nI think I have same issue.\n\nThis is my solution:\n\nFirst, you need custom @Schema decorator.\n\n**schema.decorator.ts**\n\n```\nimport * as mongoose from 'mongoose';\nimport { TypeMetadataStorage } from '@nestjs/mongoose/dist/storages/type-metadata.storage';\nimport * as _ from 'lodash';\n\nexport type SchemaOptions = mongoose.SchemaOptions & {\n inheritOption?: boolean\n}\n\nfunction mergeOptions(parentOptions: SchemaOptions, childOptions: SchemaOptions) {\n for (const key in childOptions) {\n if (Object.prototype.hasOwnProperty.call(childOptions, key)) {\n parentOptions[key] = childOptions[key];\n }\n }\n return parentOptions;\n}\n\nexport function Schema(options?: SchemaOptions): ClassDecorator {\n return (target: Function) => {\n const isInheritOptions = options.inheritOption;\n\n if (isInheritOptions) {\n let parentOptions = TypeMetadataStorage.getSchemaMetadataByTarget((target as any).__proto__).options;\n parentOptions = _.cloneDeep(parentOptions) \n options = mergeOptions(parentOptions, options);\n }\n\n TypeMetadataStorage.addSchemaMetadata({\n target,\n options\n })\n }\n}\n```\n\nThis is base schema.\n\n**cat.schema.ts**\n\n```\nimport { Prop, SchemaFactory } from \"@nestjs/mongoose\";\nimport { Schema } from '../../common/decorators/schema.decorator'\nimport { Document } from \"mongoose\";\n\nexport type CatDocument = Cat & Document;\n\n@Schema({\n timestamps: true,\n toJSON: {\n virtuals: true,\n transform: function (doc: any, ret: any) {\n delete ret._id;\n delete ret.__v;\n return ret;\n },\n },\n})\nexport class Cat {\n @Prop()\n name: string;\n\n @Prop()\n age: number;\n\n @Prop()\n breed: string;\n}\n\nconst CatSchema = SchemaFactory.createForClass(Cat);\n\nCatSchema.virtual(\"id\").get(function (this: CatDocument) {\n return this._id;\n});\n\nexport { CatSchema };\n```\n\n**england-cat.schema.ts**\n\n```\nimport { Prop, SchemaFactory } from \"@nestjs/mongoose\";\nimport { Schema } from \"../../common/decorators/schema.decorator\";\nimport { Document } from \"mongoose\";\nimport { Cat } from \"../../cats/schemas/cat.schema\";\n\nexport type EnglandCatDocument = EnglandCat & Document;\n\n@Schema({\n inheritOption: true\n})\nexport class EnglandCat extends Cat {\n @Prop()\n numberLegs: number;\n}\n\nexport const EnglandCatSchema = SchemaFactory.createForClass(EnglandCat)\n```\n\nEnglandCat is subclass of Cat and it inherits all options from Cat, you can overwrite some options if you want.\n\n========================================\n\nCode:\n```text\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types } from 'mongoose';\nimport { TimeStamps } from './timestamps.schema';\n\nexport type BaseDocument = BaseSchemaDefinition & Document;\n\n@Schema({\n  toJSON: {\n    virtuals: true,\n    transform: function (doc: any, ret: any) {\n      delete ret._id;\n      delete ret.__v;\n      return ret;\n    },\n  },\n})\nexport class BaseSchemaDefinition {\n  @Prop({\n    type: Types.ObjectId,\n    required: true,\n    default: Types.ObjectId,\n  })\n  nonce: Types.ObjectId;\n\n  @Prop()\n  timestamps: TimeStamps;\n}\n```\n\n```text\nimport { Prop, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Document } from 'mongoose';\nimport { Address } from './address.schema';\nimport { BaseSchemaDefinition } from './base.schema';\n\nexport type PersonDocument = PersonSchemaDefintion & Document;\n\nexport class PersonSchemaDefintion extends BaseSchemaDefinition {\n  @Prop({ required: true })\n  first_name: string;\n\n  @Prop({ required: true })\n  last_name: string;\n\n  @Prop()\n  middle_name: string;\n\n  @Prop()\n  data_of_birth: Date;\n\n  @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Address' }] })\n  addresses: [Address];\n}\n\nconst PersonSchema = SchemaFactory.createForClass(PersonSchemaDefintion);\n\nPersonSchema.virtual('id').get(function (this: PersonDocument) {\n  return this._id;\n});\n\nexport { PersonSchema };\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types } from 'mongoose';\nimport { TimeStamps } from './timestamps.schema';\n\nexport type BaseDocument = BaseSchemaDefinition & Document;\n\n@Schema({\n  toJSON: {\n    virtuals: true,\n    transform: function (doc: any, ret: any) {\n      delete ret._id;\n      delete ret.__v;\n      return ret;\n    },\n  },\n})\nexport class BaseSchemaDefinition {\n  @Prop({\n    type: Types.ObjectId,\n    required: true,\n    default: Types.ObjectId,\n  })\n  nonce: Types.ObjectId;\n\n  @Prop()\n  timestamps: TimeStamps;\n}\n\nconst BaseSchema = SchemaFactory.createForClass(BaseSchemaDefinition);\n\nBaseSchema.virtual('id').get(function (this: BaseDocument) {\n  return this._id;\n});\n\nexport { BaseSchema };\n```\n\n```text\nimport { Prop } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { Document } from 'mongoose';\nimport { Address } from './address.schema';\nimport { BaseSchema, BaseSchemaDefinition } from './base.schema';\n\nexport type PersonDocument = PersonSchemaDefintion & Document;\n\nexport class PersonSchemaDefintion extends BaseSchemaDefinition {\n  @Prop({ required: true })\n  first_name: string;\n\n  @Prop({ required: true })\n  last_name: string;\n\n  @Prop()\n  middle_name: string;\n\n  @Prop()\n  data_of_birth: Date;\n\n  @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Address' }] })\n  addresses: [Address];\n}\n\nexport const PersonSchema = Object.assign(\n  {},\n  BaseSchema.obj,\n  PersonSchemaDefintion,\n);\n```\n\n```text\nimport { Model } from 'mongoose';\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport {\n  PersonSchemaDefintion,\n  PersonDocument,\n} from 'src/schemas/person.schema';\nimport { TimeStamps } from 'src/schemas/timestamps.schema';\n\n@Injectable()\nexport class PersonService {\n  constructor(\n    @InjectModel(PersonSchemaDefintion.name)\n    private personModel: Model<PersonDocument>,\n  ) {}\n\n  async create(\n    personModel: PersonSchemaDefintion,\n  ): Promise<PersonSchemaDefintion> {\n    personModel.timestamps = new TimeStamps();\n    const createdPerson = new this.personModel(personModel);\n\n    return createdPerson.save();\n  }\n\n  async update(\n    id: string,\n    changes: Partial<PersonSchemaDefintion>,\n  ): Promise<PersonSchemaDefintion> {\n    const existingPerson = this.personModel\n      .findByIdAndUpdate(id, changes)\n      .exec()\n      .then(() => {\n        return this.personModel.findById(id);\n      });\n    if (!existingPerson) {\n      throw Error('Id does not exist');\n    }\n    return existingPerson;\n  }\n\n  async findAll(): Promise<PersonSchemaDefintion[]> {\n    return this.personModel.find().exec();\n  }\n\n  async findOne(id: string): Promise<PersonSchemaDefintion> {\n    return this.personModel.findById(id).exec();\n  }\n\n  async delete(id: string): Promise<string> {\n    return this.personModel.deleteOne({ _id: id }).then(() => {\n      return Promise.resolve(`${id} has been deleted`);\n    });\n  }\n}\n```\n\n```text\nimport { Prop, Schema } from '@nestjs/mongoose';\nimport { Document, Types } from 'mongoose';\nimport { TimeStamps } from './timestamps.schema';\n\nexport type BaseDocument = Base & Document;\n\n@Schema()\nexport class Base {\n  @Prop({\n    type: Types.ObjectId,\n    required: true,\n    default: Types.ObjectId,\n  })\n  nonce: Types.ObjectId;\n\n  @Prop()\n  timestamps: TimeStamps;\n}\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Types } from 'mongoose';\nimport { Address } from './address.schema';\nimport { Base } from './base.schema';\n\nexport type PersonDocument = Person & Document;\n\n@Schema({\n  toJSON: {\n    virtuals: true,\n    transform: function (doc: any, ret: any) {\n      delete ret._id;\n      delete ret.__v;\n      return ret;\n    },\n  },\n})\nexport class Person extends Base {\n  @Prop({ required: true })\n  first_name: string;\n\n  @Prop({ required: true })\n  last_name: string;\n\n  @Prop()\n  middle_name: string;\n\n  @Prop()\n  data_of_birth: Date;\n\n  @Prop({ type: [{ type: Types.ObjectId, ref: 'Address' }] })\n  addresses: [Address];\n}\nconst PersonSchema = SchemaFactory.createForClass(Person);\n\nPersonSchema.virtual('id').get(function (this: PersonDocument) {\n  return this._id;\n});\n\nexport { PersonSchema };\n```\n\n```text\nimport * as mongoose from 'mongoose';\nimport { TypeMetadataStorage } from '@nestjs/mongoose/dist/storages/type-metadata.storage';\nimport * as _ from 'lodash';\n\nexport type SchemaOptions = mongoose.SchemaOptions & {\n    inheritOption?: boolean\n}\n\nfunction mergeOptions(parentOptions: SchemaOptions, childOptions: SchemaOptions) {\n    for (const key in childOptions) {\n        if (Object.prototype.hasOwnProperty.call(childOptions, key)) {\n            parentOptions[key] = childOptions[key];\n        }\n    }\n    return parentOptions;\n}\n\nexport function Schema(options?: SchemaOptions): ClassDecorator {\n    return (target: Function) => {\n        const isInheritOptions = options.inheritOption;\n\n        if (isInheritOptions) {\n            let parentOptions = TypeMetadataStorage.getSchemaMetadataByTarget((target as any).__proto__).options;\n            parentOptions = _.cloneDeep(parentOptions)  \n            options = mergeOptions(parentOptions, options);\n        }\n\n        TypeMetadataStorage.addSchemaMetadata({\n            target,\n            options\n        })\n    }\n}\n```\n\n```text\nimport { Prop, SchemaFactory } from \"@nestjs/mongoose\";\nimport { Schema } from '../../common/decorators/schema.decorator'\nimport { Document } from \"mongoose\";\n\nexport type CatDocument = Cat & Document;\n\n@Schema({\n    timestamps: true,\n    toJSON: {\n        virtuals: true,\n        transform: function (doc: any, ret: any) {\n            delete ret._id;\n            delete ret.__v;\n            return ret;\n        },\n    },\n})\nexport class Cat {\n    @Prop()\n    name: string;\n\n    @Prop()\n    age: number;\n\n    @Prop()\n    breed: string;\n}\n\nconst CatSchema = SchemaFactory.createForClass(Cat);\n\nCatSchema.virtual(\"id\").get(function (this: CatDocument) {\n    return this._id;\n});\n\nexport { CatSchema };\n```\n\n```text\nimport { Prop, SchemaFactory } from \"@nestjs/mongoose\";\nimport { Schema } from \"../../common/decorators/schema.decorator\";\nimport { Document } from \"mongoose\";\nimport { Cat } from \"../../cats/schemas/cat.schema\";\n\nexport type EnglandCatDocument = EnglandCat & Document;\n\n@Schema({\n    inheritOption: true\n})\nexport class EnglandCat extends Cat {\n    @Prop()\n    numberLegs: number;\n}\n\nexport const EnglandCatSchema = SchemaFactory.createForClass(EnglandCat)\n```\n\n========================================\n\nComments:\n- I will test this out when I can. Thanks\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":710,"estimatedTokens":4054}}939{"id":"stack-61685106","source":"stackoverflow","questionId":61685106,"title":"With nest.js, how can I inject a Provider that has a constructor?","tags":["javascript","node.js","typescript","dependency-injection","nestjs"],"text":"Title: With nest.js, how can I inject a Provider that has a constructor?\nTags: javascript, node.js, typescript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have `conversations.module.ts` that has:\n\n```\n@Module({\n imports: [ImageModule, YoutubeModule],\n controllers: [ConversationsController],\n providers: [ConversationsService, ParticipantsService, StreamsService]\n})\nexport class ConversationsModule { }\n```\n\nand within my `conversations.controller.ts`, I have:\n\n```\n@Controller('conversations')\nexport class ConversationsController {\n constructor(private conversationsService: ConversationsService, private imageService: ImageService, private youtubeService: YoutubeService, private participantsService: ParticipantsService, private streamsService: StreamsService) { }\n```\n\nBut what I want to do is inject the AWS S3 module:\n\n```\nconst secretsmanager = new S3({ region: 'us-east-1' })\n```\n\nthat requires it to be instantiated. How can I accomplish this?\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [ImageModule, YoutubeModule],\n  controllers: [ConversationsController],\n  providers: [ConversationsService, ParticipantsService, StreamsService]\n})\nexport class ConversationsModule { }\n```\n\n```text\n@Controller('conversations')\nexport class ConversationsController {\n    constructor(private conversationsService: ConversationsService, private imageService: ImageService, private youtubeService: YoutubeService, private participantsService: ParticipantsService, private streamsService: StreamsService) { }\n```\n\n```text\nconst secretsmanager = new S3({ region: 'us-east-1' })\n```\n\n```text\nconversations.module.ts\n```\n\n```text\nconversations.controller.ts\n```\n\n```js\n{\n  provide: 'SECRETS_MANAGER',\n  useValue: new S3({ region: 'us-east-1' }),\n}\n```\n\n```js\nconstructor(@Inject('SECRETS_MANAGER') private readonly manager: S3) {}\n```\n\n```text\nprovide\n```\n\n```text\nuseClass\n```\n\n```text\nuseValue\n```\n\n```text\nuseFactory\n```\n\n```text\n@Inject()\n```\n\n```text\nnew S3()\n```\n\n========================================\n\nComments:\n- Where do I do this? The `module`?\n- In the `@Module()`'s `providers` array. It's a custom provider\n- @JayMcDoniel Had a similar issue but had a service with a constructor having a Mongoose Model like this constructor(@InjectModel(Blog.name) private blogModel: Model) { } What value can I provide the useValue method { provide: 'blogService', useValue: ??, }\n- You should probably be using `useFactory` and setting up the `inject` array to use `getModelToken(Blog.name)` so that the factory can take in the mongoose model and pass it to the service\n- Ok. did do something like this but it gives \"Nest can't resolve dependencies of the blogService (?). Please make sure that the argument BlogModel at index [0] is available in the AppModule context.\" error providers: [AppService, { provide: 'blogService', useFactory: () => BlogService, inject: [getModelToken(Blog.name)] }],\n- Please create a new question or use our Discord Server to avoid unnecessary debugging in the comments","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":106,"estimatedTokens":763}}940{"id":"stack-71723151","source":"stackoverflow","questionId":71723151,"title":"QueryFailedError: malformed array literal: \"[]\" in typeORM","tags":["postgresql","nestjs","typeorm"],"text":"Title: QueryFailedError: malformed array literal: \"[]\" in typeORM\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a new row to a table in postgres using TypeORM, but receive the issue related to array literals. The problem occurs with a `subscriptions` field\n\nEntity format:\n\n```\nexport class User {\n @PrimaryColumn()\n userId: string;\n\n @Column(\"varchar\")\n email: string;\n\n @Column(\"text\", { array: true })\n userCookieIds: string[];\n\n @Column(\"varchar\", { array: true })\n userLocalIds: string[]\n\n @Column(\"jsonb\", { array: true })\n subscriptions: object[] \n}\n```\n\nThe code of typeORM insert:\n\n```\nuser = new User()\n user.userId = uuidv4()\n user.email = ''\n user.userCookieIds = [userCookieId]\n user.subscriptions = []\n user.userLocalIds = [] \n await this.usersRepository.save(user)\n```\n\nI checked all similar questions on StackOverflow, but it didn't help :-(\n\nAny help is highly appreciated\n\n========================================\n\nCode:\n```text\nexport class User {\n  @PrimaryColumn()\n  userId: string;\n\n  @Column(\"varchar\")\n  email: string;\n\n  @Column(\"text\", { array: true })\n  userCookieIds: string[];\n\n  @Column(\"varchar\", { array: true })\n  userLocalIds: string[]\n\n  @Column(\"jsonb\", { array: true })\n  subscriptions: object[]  \n}\n```\n\n```text\nuser = new User()\n        user.userId = uuidv4()\n        user.email = ''\n        user.userCookieIds = [userCookieId]\n        user.subscriptions = []\n        user.userLocalIds = []        \n        await this.usersRepository.save(user)\n```\n\n```text\nsubscriptions\n```\n\n```text\narray: true\n```\n\n```text\n@Column\n```\n\n========================================\n\nComments:\n- guessing you fixed this already but can you the error text with us? I think you can drop [] from the data types when you specify {array:true}","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":92,"estimatedTokens":450}}941{"id":"stack-68831072","source":"stackoverflow","questionId":68831072,"title":"NestJs + TypeScript + Jest - TypeError: Class extends value undefined is not a constructor or null","tags":["typescript","unit-testing","jestjs","nestjs"],"text":"Title: NestJs + TypeScript + Jest - TypeError: Class extends value undefined is not a constructor or null\nTags: typescript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI ran into an error when was trying to add some tests to my NestJs App.\nThere is auto generated test file named *app.controller.spec.ts* which is a unit test. When i try to run tests with the *yarn test* command it throws an Error stating:\n\nTest suite failed to run\nTypeError: Class extends value undefined is not a constructor or null\n\n```\nat Object. (../node_modules/@nestjs/testing/services/testing-logger.service.js:7:38)\n at Object. (../node_modules/@nestjs/testing/testing-module.builder.js:9:34)\n```\n\nMy tsconfig configuration:\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"skipLibCheck\": true\n },\n \"exclude\": [\n \"node_modules\",\n \"./node_modules\",\n \"./node_modules/*\",\n \"./node_modules/@types/node/index.d.ts\",\n ]\n}\n```\n\nyarn test command:\n`\"test\": \"jest\"`\n\nContent of the unit test file:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport {ConfigModule} from './config/config.module';\n\ndescribe('AppController', () => {\n let appController: AppController;\n\n beforeEach(async () => {\n const app: TestingModule = await Test.createTestingModule({\n imports: [ConfigModule],\n controllers: [AppController],\n providers: [AppService],\n }).compile();\n\n appController = app.get(AppController);\n });\n\n describe('root', () => {\n it('should return \"pong\"', () => {\n expect(appController.getHello()).toBe('pong');\n });\n });\n});\n```\n\n========================================\n\nCode:\n```text\nat Object.<anonymous> (../node_modules/@nestjs/testing/services/testing-logger.service.js:7:38)\n at Object.<anonymous> (../node_modules/@nestjs/testing/testing-module.builder.js:9:34)\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true\n  },\n  \"exclude\": [\n    \"node_modules\",\n    \"./node_modules\",\n    \"./node_modules/*\",\n    \"./node_modules/@types/node/index.d.ts\",\n  ]\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport {ConfigModule} from './config/config.module';\n\ndescribe('AppController', () => {\n  let appController: AppController;\n\n  beforeEach(async () => {\n    const app: TestingModule = await Test.createTestingModule({\n      imports: [ConfigModule],\n      controllers: [AppController],\n      providers: [AppService],\n    }).compile();\n\n    appController = app.get<AppController>(AppController);\n  });\n\n  describe('root', () => {\n    it('should return \"pong\"', () => {\n      expect(appController.getHello()).toBe('pong');\n    });\n  });\n});\n```\n\n```text\n\"test\": \"jest\"\n```\n\n```text\n@nestjs/testing\n```\n\n```text\n@nestjs/common\n```\n\n```text\n@nestjs/core\n```\n\n```text\n@nestjs/\n```\n\n```text\n@nestjs/testing\n```\n\n========================================\n\nComments:\n- What are you `@nestjs&#47;` package versions? Can you add those to your question?\n- Thank you for your reply! Here they are: \"@nestjs/common\": \"6.7.2\", \"@nestjs/core\": \"6.7.2\", \"@nestjs/jwt\": \"6.1.1\", \"@nestjs/mongoose\": \"6.1.2\", \"@nestjs/passport\": \"6.1.0\", \"@nestjs/platform-express\": \"6.7.2\", \"@nestjs/typeorm\": \"6.2.0\", \"jest\": \"24.9.0\" NodeJs version: v14.17.4\n- Furthermore, utils that i used to find circular dependencies (first, i thought it was causing the problem) say there's no circular dependencies in the project.\n- Oh wow, back on Nest v6. What about your dev deps for `@nestjs&#47;` as well\n- \"@nestjs/cli\": \"6.9.0\", \"@nestjs/schematics\": \"6.7.0\", \"@nestjs/testing\": \"^8.0.6\" I really appreciate your feedback, yet i suppose the question is not relevant for me anymore. As we had no time for searching for a solution, we decided just to write API tests with postman. We can still work around it, so it would help others who is facing a similar problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":165,"estimatedTokens":1110}}942{"id":"stack-57055996","source":"stackoverflow","questionId":57055996,"title":"How to catch a Typeorm transaction error in NestJs","tags":["javascript","graphql","nestjs","typeorm"],"text":"Title: How to catch a Typeorm transaction error in NestJs\nTags: javascript, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a server side written in node.js and nestJs, querying with typeorm.\n\nI'm trying to wrap some query's to the database with transaction as suggested here with some changes inspired by typeorm's docs, like this:\n\n```\ngetManager().transaction(async transactionalEntityManager => {\n transactionalEntityManager.save(newEntity)\n transactionalEntityManager.save(newEntity1)\n});\n```\n\nThe transaction works well and rollback the database if there was an error.\ntested this way: \n\n```\ngetManager().transaction(async transactionalEntityManager => {\n transactionalEntityManager.save(newEntity)\n throw 'There is an error'\n transactionalEntityManager.save(newEntity1)\n});\n```\n\nThe execution of the transaction is inside a graphQL Mutation, so I should return an error to the client if something went wrong, the problem is that I can't catch the errors from the transaction.\n\nTried doing this: \n\n```\n@Mutation(returns => Entity)\n async create(): Promise {\n let entity = null;\n let error = null;\n getManager().transaction(async transactionalEntityManager => {\n try {\n entity = await transactionalEntityManager.save(newEntity)\n await transactionalEntityManager.save(newEntity1);\n } catch (err) {\n error = err\n }\n })\n if (error) {\n return error\n }\n return entity\n }\n```\n\nwhen I throw error I catch it successfully, but when a real error occurs I can `console.log()` it in the server but it never reaches to return to the client.\n\n========================================\n\nCode:\n```text\ngetManager().transaction(async transactionalEntityManager => {\n    transactionalEntityManager.save<Entity>(newEntity)\n    transactionalEntityManager.save<Entity1>(newEntity1)\n});\n```\n\n```text\ngetManager().transaction(async transactionalEntityManager => {\n    transactionalEntityManager.save<Entity>(newEntity)\n    throw 'There is an error'\n    transactionalEntityManager.save<Entity1>(newEntity1)\n});\n```\n\n```text\n@Mutation(returns => Entity)\n  async create(): Promise<Entity> {\n    let entity = null;\n    let error = null;\n    getManager().transaction(async transactionalEntityManager => {\n      try {\n        entity = await transactionalEntityManager.save<Entity>(newEntity)\n        await transactionalEntityManager.save<Entity1>(newEntity1);\n      } catch (err) {\n        error = err\n      }\n    })\n    if (error) {\n      return error\n    }\n    return entity\n  }\n```\n\n```text\nconsole.log()\n```\n\n```text\nawait getManager().transaction(async transactionalEntityManager => {\n  ...\n  throw 'ERROR THAT SHOULD BE CATCHED'\n}\n```\n\n```text\nconst ok = await getManager().transaction(async transactionalEntityManager => {\n  await transactionalEntityManager.save<Entity>(newEntity)\n  await transactionalEntityManager.save<Entity>(newEntity2)\n  return 'OK'\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":109,"estimatedTokens":716}}943{"id":"stack-51994374","source":"stackoverflow","questionId":51994374,"title":"Nest.js project with TypeORM Active Record implementation","tags":["nestjs","typeorm"],"text":"Title: Nest.js project with TypeORM Active Record implementation\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a project with Nest.js and TypeORM. I like the Active Record approach in TypeORM\n\nI define an entity as follows, with some static helper methods:\n\n```\nexport class Book extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @Column()\n description: string;\n\n static async createNew(attributes: BookDto): Promise {\n const entity = new Book();\n entity.name = attributes.name;\n entity.description = attributes.description;\n\n return entity.save();\n }\n\n static async findByName(name: string): Promise {\n return Book.findOne({\n where: { name },\n });\n }\n}\n```\n\nI'm trying to the patterns in the Nest docs to inject it into my service:\n\n```\n@Injectable()\nexport class BookService {\n constructor(\n @InjectRepository(Book)\n private readonly bookRepository: Repository,\n ) {}\n\n async create(bookAttrs: BookDto): Promise {\n return Book.createNew(bookAttrs);\n }\n}\n```\n\nBut as you can see in my service, I am only using the static methods. In this case, do I even need to inject the dependencies? Is there a better pattern I should be following?\n\n========================================\n\nCode:\n```js\nexport class Book extends BaseEntity {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  name: string;\n\n  @Column()\n  description: string;\n\n  static async createNew(attributes: BookDto): Promise<Book> {\n    const entity = new Book();\n    entity.name = attributes.name;\n    entity.description = attributes.description;\n\n    return entity.save();\n  }\n\n  static async findByName(name: string): Promise<Book> {\n    return Book.findOne({\n      where: { name },\n    });\n  }\n}\n```\n\n```js\n@Injectable()\nexport class BookService {\n  constructor(\n    @InjectRepository(Book)\n    private readonly bookRepository: Repository<Book>,\n  ) {}\n\n  async create(bookAttrs: BookDto): Promise<Book> {\n    return Book.createNew(bookAttrs);\n  }\n}\n```\n\n```text\nRepository\n```\n\n```text\nTypeOrmModule.forFeature([User])\n```\n\n========================================\n\nComments:\n- Thanks for this, I was assuming this wasn't the very \"Nest\" way to do it. However I do like the Active Record approach and this seemed to be the only way to do it like this. I'd love to see some code examples of implementing like this. The docs only seem to show static methods on the Active Record entity type: typeorm.io/#/active-record-data-mapper.\n- The more \"nest\" way to do it would be to the data mapper pattern, so you can define your scopes on your repository, not the model itself, and then mock the repository's functionality in your tests.","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":111,"estimatedTokens":669}}944{"id":"stack-73097067","source":"stackoverflow","questionId":73097067,"title":"NestJS Mock RabbitMQ in Jest","tags":["jestjs","rabbitmq","nestjs"],"text":"Title: NestJS Mock RabbitMQ in Jest\nTags: jestjs, rabbitmq, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an AppModule file as follows:\n\n```\nimport { Module } from '@nestjs/common'\nimport { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'\n\n@Module({\n imports: [\n RabbitMQModule.forRoot(RabbitMQModule, {\n exchanges: [\n {\n name: 'my_rabbit',\n type: 'direct',\n },\n ],\n uri: process.env.RABBITMQ_URI,\n connectionInitOptions: { wait: true },\n }),\n ],\n})\nexport class AppModule {}\n```\n\nI have tried to mock rabbitmq using `@golevelup/nestjs-rabbitmq` like this:\n\n```\nimport { Module } from '@nestjs/common'\nimport { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'\n\nbeforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [\n AppModule\n ],\n })\n .overrideProvider(AmqpConnection)\n .useValue(createMock())\n .compile()\n })\n```\n\nThis is giving me error:\n\n```\n[Nest] 2745 - 24/07/2022, 17:02:54 ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default)\nError: connect ECONNREFUSED 127.0.0.1:5672\n```\n\nIf i mock the whole rabbitmq module like:\n\n```\njest.mock('@golevelup/nestjs-rabbitmq')\n```\n\nI will get errors like:\n\n```\nNest cannot create the AppModule instance.\n The module at index [0] of the AppModule \"imports\" array is undefined.\n```\n\nHas anyone successfully mocked RabbitMQ? Please assist if possible.\n\n========================================\n\nTop Answer:\nI solve this problem mocking an AmqpConnection like this.\n\n```\nimport { AmqpConnection } from \"@nestjs-plus/rabbitmq\";\n import { TestingModule, Test } from \"@nestjs/testing\";\n import { IntegrationQueueService } from \"./integration-queue.service\";\n\n describe('IntegrationQueueService', () => {\n\n type MockType = {\n [P in keyof T]?: jest.Mock;\n };\n \n\n const mockFactory: () => MockType = jest.fn(() => ({\n publish: jest.fn(() => AmqpConnection),\n }))\n\n \n let service: IntegrationQueueService;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n IntegrationQueueService,\n {\n provide: AmqpConnection,\n useFactory: mockFactory,\n },\n ],\n\n })\n .compile();\n\n service = module.get (IntegrationQueueService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n})\n```\n\n========================================\n\nCode:\n```js\nimport { Module } from '@nestjs/common'\nimport { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'\n\n@Module({\n    imports: [\n        RabbitMQModule.forRoot(RabbitMQModule, {\n            exchanges: [\n                {\n                    name: 'my_rabbit',\n                    type: 'direct',\n                },\n            ],\n            uri: process.env.RABBITMQ_URI,\n            connectionInitOptions: { wait: true },\n        }),\n    ],\n})\nexport class AppModule {}\n```\n\n```js\nimport { Module } from '@nestjs/common'\nimport { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'\n\nbeforeEach(async () => {\n        const module: TestingModule = await Test.createTestingModule({\n            imports: [\n                AppModule\n            ],\n        })\n            .overrideProvider(AmqpConnection)\n            .useValue(createMock<AmqpConnection>())\n            .compile()\n    })\n```\n\n```text\n[Nest] 2745  - 24/07/2022, 17:02:54   ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default)\nError: connect ECONNREFUSED 127.0.0.1:5672\n```\n\n```js\njest.mock('@golevelup/nestjs-rabbitmq')\n```\n\n```text\nNest cannot create the AppModule instance.\n    The module at index [0] of the AppModule \"imports\" array is undefined.\n```\n\n```text\n@golevelup/nestjs-rabbitmq\n```\n\n```js\nimport { AmqpConnection } from '@golevelup/nestjs-rabbitmq'\nimport { mock } from 'jest-mock-extended'\n\nbeforeEach(async () => {\n    const module = await Test.createTestingModule({\n        imports: [],\n        providers: [\n            { provide: AmqpConnection, useValue: mock<AmqpConnection>() }\n    })\n    .compile()\n})\n```\n\n```js\nimport { mock } from 'jest-mock-extended'\n\n// create a deeply mocked module\nconst rmq = jest.createMockFromModule<typeof import('@golevelup/nestjs-rabbitmq')>(\n    '@golevelup/nestjs-rabbitmq',\n)\n\n// all the mocked methods from #createMockFromModule will return undefined\n// but in this case, #forRoot needs to return mocked providers\n// specifically AmqpConnection, and this is how it is done:\nrmq.RabbitMQModule.forRoot = jest.fn(() => ({\n    module: rmq.RabbitMQModule,\n    providers: [\n        {\n            provide: rmq.AmqpConnection,\n            useValue: mock<typeof rmq.AmqpConnection>(),\n        },\n    ],\n    exports: [rmq.AmqpConnection],\n}))\n\nmodule.exports = rmq\n```\n\n```js\nimport { AmqpConnection } from '@golevelup/nestjs-rabbitmq'\nimport { mock } from 'jest-mock-extended'\nimport { GenericContainer } from 'testcontainers'\n\nconst rmq = jest.createMockFromModule<typeof import('@golevelup/nestjs-rabbitmq')>(\n    '@golevelup/nestjs-rabbitmq',\n)\n\nrmq.RabbitMQModule.forRoot = jest.fn(() => ({\n    module: rmq.RabbitMQModule,\n    providers: [\n        {\n            provide: rmq.AmqpConnection,\n            useFactory: async () => {\n                const RABBITMQ_DEFAULT_USER = 'RABBITMQ_DEFAULT_USER'\n                const RABBITMQ_DEFAULT_PASS = 'RABBITMQ_DEFAULT_PASS'\n                const PORT = 5672\n\n                const rmqContainer = new GenericContainer('rabbitmq:3.11.6-alpine')\n                    .withEnvironment({\n                        RABBITMQ_DEFAULT_USER,\n                        RABBITMQ_DEFAULT_PASS,\n                    })\n                    .withExposedPorts(PORT)\n\n                const rmqInstance = await rmqContainer.start()\n                const port = rmqInstance.getMappedPort(PORT)\n\n                return new AmqpConnection({\n                    uri: `amqp://${RABBITMQ_DEFAULT_USER}:${RABBITMQ_DEFAULT_PASS}@localhost:${port}`,\n                })\n            },\n        },\n    ],\n    exports: [rmq.AmqpConnection],\n}))\n\nmodule.exports = rmq\n```\n\n```text\nAppModule\n```\n\n```text\nRabbitMQModule\n```\n\n```text\noverrideProvider\n```\n\n```text\nRabbitMQModule\n```\n\n```text\nAppModule\n```\n\n```text\nAppModule\n```\n\n```text\nRabbitMQModule\n```\n\n```text\nAmqpConnection\n```\n\n```text\n__mocks__\n```\n\n```text\n@golevelup/nestjs-rabbitmq\n```\n\n```text\nsrc/__mocks__/@golevelup/nestjs-rabbitmq.ts\n```\n\n```text\n__mocks__\n```\n\n```text\nnode_modules\n```\n\n```text\nsrc/__mocks__/@golevelup/nestjs-rabbitmq.ts\n```\n\n```js\nimport { AmqpConnection } from \"@nestjs-plus/rabbitmq\";\n    import { TestingModule, Test } from \"@nestjs/testing\";\n    import { IntegrationQueueService } from \"./integration-queue.service\";\n\n    describe('IntegrationQueueService', () => {\n\n      type MockType<T> = {\n         [P in keyof T]?: jest.Mock<{}>;\n      };\n  \n\n      const mockFactory: () => MockType<AmqpConnection> = jest.fn(() => ({\n         publish: jest.fn(() => AmqpConnection),\n      }))\n\n \n      let service: IntegrationQueueService;\n\n      beforeEach(async () => {\n         const module: TestingModule = await Test.createTestingModule({\n            providers: [\n                IntegrationQueueService,\n                {\n                    provide: AmqpConnection,\n                    useFactory: mockFactory,\n                },\n            ],\n\n         })\n            .compile();\n\n        service = module.get<IntegrationQueueService> (IntegrationQueueService);\n    });\n\n\n    it('should be defined', () => {\n        expect(service).toBeDefined();\n    });\n\n})\n```\n\n```text\nimport { AmqpConnection } from '@golevelup/nestjs-rabbitmq';\n\nAmqpConnection.prototype.init = jest.fn();\nAmqpConnection.prototype.close = jest.fn();\n\ndescribe('AppController (e2e)', () => {\n```\n\n========================================\n\nComments:\n- Did you solve this? The answer below didn't quite work for me.\n- @Scott-MEARN-Developer I just posted my answer. Please see below\n- @Scott-MEARN-Developer I just found a simple solution for it - see my answer below\n- Thanks for exploring this. Have you tried to see if this will run into memory leaks? Jest has the problem of memory leaks if modules are monkey patched like this.\n- @Calvintwr thanks for the info. Yes, I've applied it at the same time I posted this solution and so far so good on our side.","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":369,"estimatedTokens":2037}}945{"id":"stack-71915205","source":"stackoverflow","questionId":71915205,"title":"How to Unit Test a method inside a module in NestJs (Jest)","tags":["node.js","typescript","unit-testing","jestjs","nestjs"],"text":"Title: How to Unit Test a method inside a module in NestJs (Jest)\nTags: node.js, typescript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm adding tests on a project and improving coverage. I would like to know how can I test a method defined inside a module definition in NestJs.\n\n```\nimport { MiddlewareConsumer, Module } from '@nestjs/common';\nimport { AppController } from './controllers/app.controller';\nimport { LoggerController } from './controllers/logger.controller';\nimport { LoggingModule } from './logging/logging.module';\nimport LogsMiddleware from './logging/logging.middleware';\n\n@Module({\n imports: [\n LoggingModule,\n ],\n controllers: [\n LoggerController,\n AppController\n ],\n})\nexport class AppModule {\n // Middleware to log the request and respone for each RestFul/GraphQl routes\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(LogsMiddleware).forRoutes('*');\n }\n}\n```\n\nI want to unit test the `configure` method inside the AppModule class but I cannot find any documentation online how it is to be done. Any help would be appreciated. Below is my basic test case to see if the module compiles.\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppModule } from './app.module';\n\ndescribe('AppModule', () => {\n let testModule: TestingModule;\n\n beforeEach(async () => {\n testModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n });\n\n it('should validate the app module', () => {\n expect(testModule).toBeDefined();\n });\n});\n```\n\n========================================\n\nTop Answer:\nIf you want to increase the coverage, you can just ignore the module.ts files by\nadding following in the jest.json file\n\n```\n\"coveragePathIgnorePatterns\": [\n \".module.ts\",\n ]\n```\n\n========================================\n\nCode:\n```text\nimport { MiddlewareConsumer, Module } from '@nestjs/common';\nimport { AppController } from './controllers/app.controller';\nimport { LoggerController } from './controllers/logger.controller';\nimport { LoggingModule } from './logging/logging.module';\nimport LogsMiddleware from './logging/logging.middleware';\n\n@Module({\n  imports: [\n    LoggingModule,\n  ],\n  controllers: [\n    LoggerController,\n    AppController\n  ],\n})\nexport class AppModule {\n  // Middleware to log the request and respone for each RestFul/GraphQl routes\n  configure(consumer: MiddlewareConsumer) {\n    consumer.apply(LogsMiddleware).forRoutes('*');\n  }\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppModule } from './app.module';\n\ndescribe('AppModule', () => {\n  let testModule: TestingModule;\n\n  beforeEach(async () => {\n    testModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n  });\n\n  it('should validate the app module', () => {\n    expect(testModule).toBeDefined();\n  });\n});\n```\n\n```text\nconfigure\n```\n\n```text\nimport { createMock } from '@golevelup/ts-jest';\nimport { MiddlewareConsumer } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { AppModule } from './app.module';\nimport LogsMiddleware from './logging/logging.middleware';\n\ndescribe('AppModule', () => {\n  let testModule: TestingModule;\n\n  const middlewareConsumer = createMock<MiddlewareConsumer>();\n  beforeEach(async () => {\n    testModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n  });\n\n  it('should validate the app module', () => {\n    expect(testModule).toBeDefined();\n  });\n\n  it('should configure the middleware', () => {\n    const app = new AppModule();\n    app.configure(middlewareConsumer);\n    expect(middlewareConsumer.apply).toHaveBeenCalledWith(LogsMiddleware);\n  });\n});\n```\n\n```text\nAppModule\n```\n\n```text\nconfigure\n```\n\n```text\n\"coveragePathIgnorePatterns\": [\n    \".module.ts\",\n  ]\n```\n\n========================================\n\nComments:\n- that `configure` method is called by the framework, there's no reason to write an *unit* test for it, AFIAK.\n- @MicaelLevi I need to test it to increases the coverage for the project\n- add `&#47;* istanbul ignore next *&#47;` right above `configure` then. Or you could do something like `new AppModule().configure(middlewareConsumerMock)` and then check if `middlewareConsumerMock.apply` is called","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":163,"estimatedTokens":1064}}946{"id":"stack-68897564","source":"stackoverflow","questionId":68897564,"title":"AWS Secrets manager in Nest JS microservice (lambda) fails periodically","tags":["amazon-web-services","aws-lambda","nestjs","aws-secrets-manager"],"text":"Title: AWS Secrets manager in Nest JS microservice (lambda) fails periodically\nTags: amazon-web-services, aws-lambda, nestjs, aws-secrets-manager\nSource: Stack Overflow\n\nQuestion:\nI'm having a lambda function made with NestJS's microservice. It uses a database connection and I'm using a secret service to fetch connection details for it.\n\nHere's my app module:\n\n```\n@Module({\n imports: [\n ConfigModule,\n TypeOrmModule.forRootAsync({\n useClass: SecretsService,\n inject: [],\n imports: [ConfigModule],\n }),\n PropertyModule,\n ],\n})\nexport class AppModule {}\n```\n\nAnd this is a Secret Service (a part of the `ConfigModule`):\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { SecretsManager } from 'aws-sdk';\nimport { GetSecretValueResponse } from 'aws-sdk/clients/secretsmanager';\nimport { MysqlConnectionOptions } from 'typeorm/driver/mysql/MysqlConnectionOptions';\n\n@Injectable()\nexport class SecretsService /* ๐Ÿ‘๐Ÿ”ซ๐Ÿฉธ */ {\n\n private secretsManager: SecretsManager;\n\n constructor() {\n this.secretsManager = new SecretsManager();\n }\n\n async createTypeOrmOptions(): Promise {\n console.log('before getting secret');\n const { SecretString }: GetSecretValueResponse =\n await this.secretsManager.getSecretValue({ SecretId: 'rds/prod' }).promise();\n const secret = JSON.parse(SecretString);\n console.log('after getting a secret', SecretString);\n\n return {\n /* database config */\n };\n }\n}\n```\n\nAnd it turns out that the code doesn't always get to the โ€œafter getting a secretโ€ part. Here are some cases\n\nI change something in the code and deploy a new version of the lambda and it just keeps hanging at the โ€œbefore getting secretโ€ forever. I wait for 5 minutes and fire that function again, then I wait 10 minutes.\nSame result.\n\nThen I wait like 20 minutes and the request slips through. After that, I can fire the same function several times in a row and I see โ€œafter getting secretโ€ every time.\n\nSo it is in fact not fails periodically, but works periodically. Seems like there's some sort of throttling and/or caching, but I don't see it in the code.\n\nPlease help me to solve this issue. How can I get my secrets every time I want them?\n\n========================================\n\nTop Answer:\nYou should use client-side caching and backoff/retry when accessing Secrets Manager from AWS Lambda.\n\nFor more, see Secrets Manager Best Practices.\n\n========================================\n\nCode:\n```js\n@Module({\n  imports: [\n    ConfigModule,\n    TypeOrmModule.forRootAsync({\n      useClass: SecretsService,\n      inject: [],\n      imports: [ConfigModule],\n    }),\n    PropertyModule,\n  ],\n})\nexport class AppModule {}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { SecretsManager } from 'aws-sdk';\nimport { GetSecretValueResponse } from 'aws-sdk/clients/secretsmanager';\nimport { MysqlConnectionOptions } from 'typeorm/driver/mysql/MysqlConnectionOptions';\n\n@Injectable()\nexport class SecretsService /* ๐Ÿ‘๐Ÿ”ซ๐Ÿฉธ */ {\n\n  private secretsManager: SecretsManager;\n\n  constructor() {\n    this.secretsManager = new SecretsManager();\n  }\n\n  async createTypeOrmOptions(): Promise<MysqlConnectionOptions> {\n    console.log('before getting secret');\n    const { SecretString }: GetSecretValueResponse =\n      await this.secretsManager.getSecretValue({ SecretId: 'rds/prod' }).promise();\n    const secret = JSON.parse(SecretString);\n    console.log('after getting a secret', SecretString);\n\n    return {\n      /* database config */\n    };\n  }\n}\n```\n\n```text\nConfigModule\n```\n\n========================================\n\nComments:\n- I wasn't able to find any documentation about the throttling of the secrets manager calls. Or any built-in caching system that can affect different deployments.\n- I made some extra debugging and found out that it fails with `Socket timed out without establishing a connection` error.\n- I was of course about to wrap it with cache after I'm done developing. But it says that I โ€œshouldโ€ use it. It never says that it is a must. It doesn't throw any 429 error, it just hangs forever.\n- Is this Lambda configured for VPC? If yes, are you using NAT or a VPC Endpoint to route to the Secrets Manager API endpoint. Also, I've seen numerous, perhaps historical, delay issues related to dual stack and the use of IPv6. Just mention that in case it triggers something. Should also mention this Lambda Extensions technique.\n- It was the issue with subnets' configuration. Took me a lot of digging to find it.\n- Related answer on Lambda Intermittent Connectivity here.","metadata":{"transformedAt":"2026-08-18T18:33:02.479Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":133,"estimatedTokens":1122}}947{"id":"stack-60785768","source":"stackoverflow","questionId":60785768,"title":"prefix url in Swagger module","tags":["node.js","typescript","swagger","nestjs"],"text":"Title: prefix url in Swagger module\nTags: node.js, typescript, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using nest js and swagger as documentation but Swagger module ignores setGlobalPrefix().\nin my environemnt the api prefix is API_PREFIX=/api/v2 , I have no problem when testing it with postman cause the endpoints/url does work which is http://localhost:5000/api/v2/user/profile\n\nbut the swagger cant get the /api/v2 prefix , the swagger request url is http://localhost:5000/user/profile which is wrong.\n\nAny idea ? Thank you for any help.\n\n### settings\n\n```\n```const SWAGGER_PREFIX = '/docs';\n\nasync function bootstrap(): Promise {\n const app = await NestFactory.create(AppModule);\n\n if (!process.env.SWAGGER_ENABLE || process.env.SWAGGER_ENABLE === '1') {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n createSwagger(app);\n }\n\n app.use(bodyParser.json());\n app.use(helmet());\n app.use(\n cors({\n origin: process.env.API_CORS || '*'\n })\n );\n\n app.setGlobalPrefix(process.env.API_PREFIX || API_DEFAULT_PREFIX);\n\n const logInterceptor = app.select(CommonModule).get(LogInterceptor);\n app.useGlobalInterceptors(logInterceptor);\n\n await app.listen(process.env.API_PORT || API_DEFAULT_PORT);\n}\n\nfunction createSwagger(app: INestApplication) {\n const version = require('../package.json').version || '';\n\n const options = new DocumentBuilder()\n .setTitle(SWAGGER_TITLE)\n .setDescription(SWAGGER_DESCRIPTION)\n .setVersion(version)\n .setBasePath(process.env.API_PREFIX || API_DEFAULT_PREFIX)\n .addBearerAuth()\n .build();\n\n const document = SwaggerModule.createDocument(app, options);\n SwaggerModule.setup(SWAGGER_PREFIX, app, document);[![enter image description here][1]][1]\n\n//swagger - the request url is http://localhost:5000/user/profile\nwhich is supposed to be http://localhost:5000/api/v2/user/profile\n```\n\n========================================\n\nTop Answer:\nYou should create the swagger (call to `createSwagger` in function `bootstrap`) after having set the global prefix of your api (call to `setGlobalPrefix` in function `bootstrap`). It will then find the api prefix on its own a prepend any request with it.\n\n\r\n\r\n\n```\nasync function bootstrap(): Promise {\n\n const app = await NestFactory.create(ApplicationModule);\n\n app.setGlobalPrefix(process.env.API_PREFIX || API_DEFAULT_PREFIX);\n\n if (!process.env.SWAGGER_ENABLE || process.env.SWAGGER_ENABLE === 'true') {\n createSwagger(app);\n }\n\n await app.listen(process.env.API_PORT || API_DEFAULT_PORT);\n}\n\nfunction createSwagger(app: INestApplication) {\n\n const version = require('../package.json').version || '';\n\n const options = new DocumentBuilder()\n .setTitle(SWAGGER_TITLE)\n .setDescription(SWAGGER_DESCRIPTION)\n .setVersion(version)\n .build();\n\n const document = SwaggerModule.createDocument(app, options);\n SwaggerModule.setup(SWAGGER_PREFIX, app, document);\n}\n```\n\n========================================\n\nCode:\n```text\n```const SWAGGER_PREFIX = '/docs';\n\nasync function bootstrap(): Promise<void> {\n  const app = await NestFactory.create(AppModule);\n\n  if (!process.env.SWAGGER_ENABLE || process.env.SWAGGER_ENABLE === '1') {\n    // eslint-disable-next-line @typescript-eslint/no-use-before-define\n    createSwagger(app);\n  }\n\n  app.use(bodyParser.json());\n  app.use(helmet());\n  app.use(\n    cors({\n      origin: process.env.API_CORS || '*'\n    })\n  );\n\n  app.setGlobalPrefix(process.env.API_PREFIX || API_DEFAULT_PREFIX);\n\n  const logInterceptor = app.select(CommonModule).get(LogInterceptor);\n  app.useGlobalInterceptors(logInterceptor);\n\n  await app.listen(process.env.API_PORT || API_DEFAULT_PORT);\n}\n\nfunction createSwagger(app: INestApplication) {\n  const version = require('../package.json').version || '';\n\n  const options = new DocumentBuilder()\n    .setTitle(SWAGGER_TITLE)\n    .setDescription(SWAGGER_DESCRIPTION)\n    .setVersion(version)\n    .setBasePath(process.env.API_PREFIX || API_DEFAULT_PREFIX)\n    .addBearerAuth()\n    .build();\n\n  const document = SwaggerModule.createDocument(app, options);\n  SwaggerModule.setup(SWAGGER_PREFIX, app, document);[![enter image description here][1]][1]\n\n\n//swagger - the request url is http://localhost:5000/user/profile\nwhich is supposed to be  http://localhost:5000/api/v2/user/profile\n```\n\n```text\napp.setGlobalPrefix(process.env.API_PREFIX || API_DEFAULT_PREFIX);\n```\n\n```text\n.setBasePath(process.env.API_PREFIX || API_DEFAULT_PREFIX)\n```\n\n```html\nasync function bootstrap(): Promise<void> {\n\n    const app = await NestFactory.create(ApplicationModule);\n\n    app.setGlobalPrefix(process.env.API_PREFIX || API_DEFAULT_PREFIX);\n\n    if (!process.env.SWAGGER_ENABLE || process.env.SWAGGER_ENABLE === 'true') {\n        createSwagger(app);\n    }\n\n    await app.listen(process.env.API_PORT || API_DEFAULT_PORT);\n}\n\nfunction createSwagger(app: INestApplication) {\n\n    const version = require('../package.json').version || '';\n\n    const options = new DocumentBuilder()\n        .setTitle(SWAGGER_TITLE)\n        .setDescription(SWAGGER_DESCRIPTION)\n        .setVersion(version)\n        .build();\n\n    const document = SwaggerModule.createDocument(app, options);\n    SwaggerModule.setup(SWAGGER_PREFIX, app, document);\n}\n```\n\n```text\ncreateSwagger\n```\n\n```text\nbootstrap\n```\n\n```text\nsetGlobalPrefix\n```\n\n```text\nbootstrap\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":197,"estimatedTokens":1320}}948{"id":"stack-70287250","source":"stackoverflow","questionId":70287250,"title":"How to make OneToOne relationship optional for multiple inherited classes?","tags":["typescript","nestjs","entity","typeorm","ts-node"],"text":"Title: How to make OneToOne relationship optional for multiple inherited classes?\nTags: typescript, nestjs, entity, typeorm, ts-node\nSource: Stack Overflow\n\nQuestion:\nSuppose I have a class `Animal` which are inherited by `Dog` and `Cat`.\n\n```\nexport class Animal extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n}\n\n@Entity()\nexport class Cat extends Animal{\n ...\n}\n\n@Entity()\nexport class Dog extends Animal{\n ...\n}\n```\n\nNow, I want to show a `OneToOne` relationship with their owner.\n\n```\n@Entity\nexport class Owner extends BaseEntity{\n ....\n \n @OneToOne()\n pet:???\n}\n```\n\n`Owner` is a class which has an attribute `pet` that can either be a Cat or a Dog.\nHow can I achieve this using typeorm?\n\nOr am I doing it wrong?\n\n========================================\n\nTop Answer:\nYou can use @ChildEntity() for children and @Entity() for main class in typeorm.\n\n========================================\n\nCode:\n```text\nexport class Animal extends BaseEntity{\n    @PrimaryGeneratedColumn()\n    id:number;\n}\n\n@Entity()\nexport class Cat extends Animal{\n   ...\n}\n\n@Entity()\nexport class Dog extends Animal{\n   ...\n}\n```\n\n```text\n@Entity\nexport class Owner extends BaseEntity{\n   ....\n \n   @OneToOne()\n   pet:???\n}\n```\n\n```text\nAnimal\n```\n\n```text\nDog\n```\n\n```text\nCat\n```\n\n```text\nOneToOne\n```\n\n```text\nOwner\n```\n\n```text\npet\n```\n\n```text\n@Entity()\n@TableInheritance({ column: { type: \"varchar\", name: \"type\" } })\nexport class Content {\n    \n    @PrimaryGeneratedColumn()\n    id: number;\n \n    @Column()\n    title: string;\n    \n    @Column()\n    description: string;\n    \n}\n```\n\n```text\n@ChildEntity()\nexport class Photo extends Content {\n    \n    @Column()\n    size: string;\n    \n}\n```\n\n```text\n@ChildEntity()\nexport class Question extends Content {\n    \n    @Column()\n    answersCount: number;\n    \n}\n```\n\n```text\n@ChildEntity()\nexport class Post extends Content {\n    \n    @Column()\n    viewCount: number;\n    \n}\n```\n\n========================================\n\nComments:\n- I didn't get what should be done in Owner.pet, should pass the Animal entity? will Animal or the Child be stored on database with its relationship with Owner?","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":151,"estimatedTokens":534}}949{"id":"stack-68777905","source":"stackoverflow","questionId":68777905,"title":"Nestjs: Retrieve the request / context from a Decorator","tags":["node.js","typescript","express","nestjs","typescript-decorator"],"text":"Title: Nestjs: Retrieve the request / context from a Decorator\nTags: node.js, typescript, express, nestjs, typescript-decorator\nSource: Stack Overflow\n\nQuestion:\nI am working on a NestJS project,\nI'm trying to get the executionContext accessible in a logger to filter the logs by request.\n\nI have one logger instance per injectable, and I would like to keep this behavior (So the scope of the injectable is default).\n\nTo do this, I'm trying to create a decorator that gets the context from the request and passes it to the child services (as in the logger), to finally get the context in the logger...\n\nI'm not sure to be clear... For now, here is my code:\n\n```\nexport const Loggable = () => (constructor: Function) => {\n for (const propertyName of Reflect.ownKeys(constructor.prototype)) {\n let descriptor = Reflect.getOwnPropertyDescriptor(constructor.prototype, propertyName);\n const isMethod = descriptor.value instanceof Function;\n if (!isMethod)\n continue;\n\n const originalMethod = descriptor.value;\n const routeArgsMetada = Reflect.getMetadata(ROUTE_ARGS_METADATA, constructor, propertyName as string);\n\n descriptor.value = function (...args: any[]) {\n const result = originalMethod.apply(this, args);\n //TODO : retrieve the request / contextExecution\n //TODO : pass the request / contextExecution to children functions...\n return result;\n };\n Reflect.defineProperty(constructor.prototype, propertyName, descriptor);\n\n Reflect.defineMetadata(ROUTE_ARGS_METADATA, routeArgsMetada, constructor, propertyName as string);\n }\n};\n```\n\nThis @Loggable() decorator would be attached to all injectable classes that need to log or throw execution context\n\nIs that possible ? If not why ?\n\nPS: I'm wondering, how could the @Guard annotation get the context? and how could the @Req annotations get the request?\n\nhttps://github.com/nestjs/nest/tree/master/packages/common/decorators/http\n\nhttps://github.com/nestjs/nest/blob/master/packages/common/decorators/core/use-guards.decorator.ts\n\n========================================\n\nCode:\n```text\nexport const Loggable = () => (constructor: Function) => {\n  for (const propertyName of Reflect.ownKeys(constructor.prototype)) {\n    let descriptor = Reflect.getOwnPropertyDescriptor(constructor.prototype, propertyName);\n    const isMethod = descriptor.value instanceof Function;\n    if (!isMethod)\n      continue;\n\n    const originalMethod = descriptor.value;\n    const routeArgsMetada = Reflect.getMetadata(ROUTE_ARGS_METADATA, constructor, propertyName as string);\n\n    descriptor.value = function (...args: any[]) {\n      const result = originalMethod.apply(this, args);\n        //TODO : retrieve the request / contextExecution\n        //TODO : pass the request / contextExecution to children functions...\n      return result;\n    };\n    Reflect.defineProperty(constructor.prototype, propertyName, descriptor);\n\n    Reflect.defineMetadata(ROUTE_ARGS_METADATA, routeArgsMetada, constructor, propertyName as string);\n  }\n};\n```\n\n```text\nexport const Request: () => ParameterDecorator = createRouteParamDecorator(\n  RouteParamtypes.REQUEST,\n);\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return request.user;\n  },\n);\n```\n\n========================================\n\nComments:\n- I don't think this is going to be possible using the decorator approach you're laying out here. Why wouldn't you just use an Interceptor for this which will automatically have access to the context?\n- The goal would be to get the context in the logger service. If it's possible to throw it from the interceptor to the service, I don't get the solution...\n- See this answer which might give you a clue stackoverflow.com/a/63497934/5161361","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":98,"estimatedTokens":961}}950{"id":"stack-58799209","source":"stackoverflow","questionId":58799209,"title":"NestJS strategy for excluding fields for different user roles?","tags":["javascript","node.js","typescript","nestjs","class-transformer"],"text":"Title: NestJS strategy for excluding fields for different user roles?\nTags: javascript, node.js, typescript, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a base entity, `ShopsEntity`, that has a bunch of fields along with a secret property:\n\n```\n@ObjectType()\nclass ShopsEntity {\n\n @Field()\n name: string;\n\n @Field()\n rating: string;\n\n @Field()\n secret: string;\n}\n```\n\nI don't want the secret property to be serialised unless a user has a certain role defined through Nest Access Control (That module only allows for RoleGuards to be placed on the resolvers themselves, meaning I would need different routes per role).\n\nSo, following a request to the same endpoint with differing levels of authentication, an Admin would get:\n\n```\n{\n \"name\": \"name\",\n \"rating\": \"rating\",\n \"secret\": \"secret\"\n}\n```\n\nand a regular querying user would get:\n\n```\n{\n \"name\": \"name\",\n \"rating\": \"rating\"\n}\n```\n\nIs there a declarative way in which I can do property-level security here, or is the best solution having separate DTO's for each level of security?\n\n========================================\n\nCode:\n```js\n@ObjectType()\nclass ShopsEntity {\n\n   @Field()\n   name: string;\n\n   @Field()\n   rating: string;\n\n   @Field()\n   secret: string;\n}\n```\n\n```text\n{\n  \"name\": \"name\",\n  \"rating\": \"rating\",\n  \"secret\": \"secret\"\n}\n```\n\n```text\n{\n  \"name\": \"name\",\n  \"rating\": \"rating\"\n}\n```\n\n```text\nShopsEntity\n```\n\n```text\nimport {Exclude, Expose} from \"class-transformer\";\n\n@Exclude()\nexport class User {\n\n    @Expose({ groups: [\"admin\"] })\n    secret: string;\n}\n```\n\n```text\ngroups\n```\n\n```text\nClassSerializerInterceptor\n```\n\n========================================\n\nComments:\n- I use the `groups` feature of class-transformer, which I use for the serialization (or resp. class-validator for validation). I'm not sure if it interoperates with your access controll library. Have a look at github.com/typestack/&hellip; and stackoverflow.com/a/54057206/4694994\n- yep, looks like `groups` is the way to go! Integrates very nicely with access-control as I can reimport the roles used there.\n- How would you declare in the controller which groups it should serialize?\n- @Joel If the groups are static for the endpoint, you can use the following approach, see stackoverflow.com/a/54277187/4694994","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":108,"estimatedTokens":575}}951{"id":"stack-71851192","source":"stackoverflow","questionId":71851192,"title":"Access multipe parameters with a custom pipe in Nest.js","tags":["javascript","validation","nestjs"],"text":"Title: Access multipe parameters with a custom pipe in Nest.js\nTags: javascript, validation, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to write a custom validation pipe to validate a request with multiple parameters. And I want to validate one param with a custom pipe, but another param is also needed to be used in the validation, and I didn't find the way described in the document.\n\nFor example, this is my API, it requires a `chainId` and an `address` as input parameters. I need to validate that the address is valid, but I can't do this without `chainId`.\n\nHere's my code, I wrote the pipe followed by the document about custom pipe examples:\n\nController\n\n```\n@Put('/:chainId/tokens/:address')\n@ApiOperation({\n summary: 'Create a token',\n})\nasync create(\n @Param('chainId') chainId: number,\n @Param('address', new AddressValidationPipe()) address: string,\n): Promise {\n return await this.tokensService.save(chainId, address);\n}\n```\n\nValidation pipe\n\n```\n@Injectable()\nexport class AddressValidationPipe implements PipeTransform {\n async transform(address: string) {\n // chainId should be another param, but I don't know how to get it in this pipe\n const chainId = 4;\n\n if (!validator(chainId, address)) {\n throw new BadRequestException(\n 'Address is not valid, or it is not on this chain',\n );\n }\n return address;\n }\n}\n```\n\n========================================\n\nTop Answer:\nFor those who have happened into this query and answer, you can use the type like this if you would need a more constrained version of it in the future:\n\n`pipe.ts`\n\n```\n@Injectable()\nexport class AddressValidationPipe\n implements\n PipeTransform\n{\n constructor(private readonly configService: ConfigService) {}\n\n async transform(value: { chainId: string; address: string }): {\n chainId: number;\n address: string;\n } {\n const { chainId, address } = value;\n\n if (!validator(Number(chainId), address)) {\n throw new BadRequestException(\n \"Address is not valid, or it is not on this chain\"\n );\n }\n\n return { chainId: Number(chainId), address };\n }\n}\n```\n\n`controller.ts`\n\n```\nasync create(\n @Param(AddressValidationPipe) param: { chainId: string; address: string } & { chainId: number; address: string }, // This will be in shape (params) & (return type of the pipe)\n): Promise {\n const { chainId, address } = param;\n return await this.tokensService.save(chainId, address);\n}\n```\n\nWith this kind of structure, if you want to build a custom pipe with different input and output type, it will be useful as well.\n\n========================================\n\nCode:\n```text\n@Put('/:chainId/tokens/:address')\n@ApiOperation({\n  summary: 'Create a token',\n})\nasync create(\n  @Param('chainId') chainId: number,\n  @Param('address', new AddressValidationPipe()) address: string,\n): Promise<Token> {\n  return await this.tokensService.save(chainId, address);\n}\n```\n\n```text\n@Injectable()\nexport class AddressValidationPipe implements PipeTransform {\n  async transform(address: string) {\n    // chainId should be another param, but I don't know how to get it in this pipe\n    const chainId = 4;\n\n    if (!validator(chainId, address)) {\n      throw new BadRequestException(\n        'Address is not valid, or it is not on this chain',\n      );\n    }\n    return address;\n  }\n}\n```\n\n```text\nchainId\n```\n\n```text\naddress\n```\n\n```text\nchainId\n```\n\n```text\n@Injectable()\nexport class AddressValidationPipe implements PipeTransform {\n  constructor(private readonly configService: ConfigService) {}\n  async transform(value: { chainId: string; address: string }) {\n    const { chainId, address } = value;\n\n    if (!validator(Number(chainId), address)) {\n      throw new BadRequestException(\n        'Address is not valid, or it is not on this chain',\n      );\n    }\n\n    return { chainId: Number(chainId), address };\n  }\n}\n```\n\n```text\n@ApiParam({\n  name: 'address',\n  description: 'Address of the token',\n  type: String,\n})\n@ApiParam({\n  name: 'chainId',\n  description: 'Chain ID of the token',\n  type: Number,\n})\n@Put('/:chainId/tokens/:address')\n@ApiOperation({\n  summary: 'Create a token',\n})\nasync create(\n  @Param(AddressValidationPipe) param: { chainId: number; address: string },\n): Promise<Token> {\n  const { chainId, address } = param;\n  return await this.tokensService.save(chainId, address);\n}\n```\n\n```text\nchainId\n```\n\n```none\n@Injectable()\nexport class AddressValidationPipe\n  implements\n    PipeTransform<\n      { chainId: string; address: string },\n      { chainId: number; address: string }\n    >\n{\n  constructor(private readonly configService: ConfigService) {}\n\n  async transform(value: { chainId: string; address: string }): {\n    chainId: number;\n    address: string;\n  } {\n    const { chainId, address } = value;\n\n    if (!validator(Number(chainId), address)) {\n      throw new BadRequestException(\n        \"Address is not valid, or it is not on this chain\"\n      );\n    }\n\n    return { chainId: Number(chainId), address };\n  }\n}\n```\n\n```none\nasync create(\n  @Param(AddressValidationPipe) param: { chainId: string; address: string } & { chainId: number;  address: string }, // This will be in shape (params) & (return type of the pipe)\n): Promise<Token> {\n  const { chainId, address } = param;\n  return await this.tokensService.save(chainId, address);\n}\n```\n\n```text\npipe.ts\n```\n\n```text\ncontroller.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":224,"estimatedTokens":1323}}952{"id":"stack-51845997","source":"stackoverflow","questionId":51845997,"title":"NestJS Nest can't resolve dependencies of the RolesService (+, +, ?)","tags":["javascript","node.js","dependency-injection","dependencies","nestjs"],"text":"Title: NestJS Nest can't resolve dependencies of the RolesService (+, +, ?)\nTags: javascript, node.js, dependency-injection, dependencies, nestjs\nSource: Stack Overflow\n\nQuestion:\nHi I'm programming using the NestJS framework (with MongoDB) and have build some modules now. When I try to import a model from another module it returns this error:\n\n Nest can't resolve dependencies of the RolesService (+, +, ?).\n\nNow, I've implemented the code like this:\n\napp.module.ts\n\n```\nimport { GroupsModule } from './groups/groups.module';\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { UsersModule } from 'users/users.module';\nimport { RolesModule } from 'roles/roles.module';\n\n@Module({\n imports: [\n MongooseModule.forRoot('mongodb://localhost:27017/example'),\n UsersModule,\n GroupsModule,\n RolesModule,\n ],\n providers: [],\n})\nexport class AppModule {}\n```\n\nusers.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { UsersController } from './users.controller';\n\nimport { UsersService } from './users.service';\nimport { RolesService } from 'roles/roles.service';\n\nimport { UserSchema } from './schemas/user.schema';\nimport { RoleSchema } from 'roles/schemas/role.schema';\n\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n ],\n controllers: [UsersController],\n providers: [UsersService, RolesService],\n exports: [UsersService],\n })\n\nexport class UsersModule {}\n```\n\nusers.service.ts\n\n```\nimport { Model } from 'mongoose';\nimport { ObjectID } from 'mongodb';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\n\nimport { User } from './interfaces/user.interface';\n\n@Injectable()\nexport class UsersService {\n constructor(@InjectModel('User') private readonly userModel: Model) {}\n}\n```\n\ngroups.module.ts\n\n```\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { GroupsController } from './groups.controller';\n\nimport { RolesService } from '../roles/roles.service';\nimport { GroupsService } from './groups.service';\n\nimport { GroupSchema } from './schemas/group.schema';\nimport { UserSchema } from '../users/schemas/user.schema';\nimport { RoleSchema } from '../roles/schemas/role.schema';\n\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'Group', schema: GroupSchema }]),\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n ],\n controllers: [GroupsController],\n providers: [GroupsService, RolesService],\n exports: [GroupsService],\n})\n```\n\ngroups.service.ts\n\n```\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { ObjectID } from 'mongodb';\nimport { Model } from 'mongoose';\n\nimport { Group } from './interfaces/group.interface';\nimport { User } from '../users/interfaces/user.interface';\n\nimport { CreateGroupDto } from './dto/create-group.dto';\nimport { RolesDto } from 'roles/dto/roles.dto';\nimport { Role } from '../roles/interfaces/role.interface';\n\n@Injectable()\nexport class GroupsService {\n constructor(@InjectModel('Group') private readonly groupModel: Model,\n @InjectModel('Role') private readonly roleModel: Model) {} }\n```\n\nroles.module.ts\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { RolesController } from './roles.controller';\n\nimport { RolesService } from './roles.service';\n\nimport { RoleSchema } from './schemas/role.schema';\nimport { UserSchema } from '../users/schemas/user.schema';\nimport { GroupSchema } from '../groups/schemas/group.schema';\n\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n MongooseModule.forFeature([{ name: 'Group', schema: GroupSchema }]),\n ],\n controllers: [RolesController],\n providers: [RolesService],\n exports: [RolesService],\n })\n\nexport class RolesModule {}\n```\n\nroles.service.ts\n\n```\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { ObjectID } from 'mongodb';\nimport { Model } from 'mongoose';\n\nimport { Role } from './interfaces/role.interface';\nimport { User } from '../users/interfaces/user.interface';\nimport { Group } from '../groups/interfaces/group.interface';\n\nimport { CreateRoleDto } from './dto/create-role.dto';\nimport { RolesDto } from './dto/roles.dto';\n\n@Injectable()\nexport class RolesService {\n constructor( @InjectModel('Role') private readonly roleModel: Model,\n @InjectModel('User') private readonly userModel: Model,\n @InjectModel('Group') private readonly groupModel: Model ) {} }\n```\n\nWhile the DI in the users and roles works fine, the error arise when I try to import the Group Model in the roles service. Please tell me if you see anything wrong, I've the same schema from users with groups but unfortunately can't see where the error lives.\n\nThanks in advance.\n\nUPDATE: OK I think my error is when I try to use a module service function outside the module. I mean I modified (in order to simplify) I'll modify the code this way:\n\nusers.module.ts\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n RolesModule,\n ],\n controllers: [UsersController],\n providers: [UsersService, RolesService],\n exports: [UsersService],\n })\n\nexport class UsersModule {}\n```\n\nusers.controller.ts\n\n```\nexport class UsersController {\n\n constructor(private readonly usersService: UsersService,\n private readonly rolesService: RolesService){}\n\n async addRoles(@Param('id') id: string, @Body() userRolesDto: UserRolesDto): Promise {\n try {\n return this.rolesService.setRoles(id, userRolesDto);\n } catch (e){\n const message = e.message.message;\n if ( e.message.error === 'NOT_FOUND'){\n throw new NotFoundException(message);\n } else if ( e.message.error === 'ID_NOT_VALID'){\n throw new BadRequestException(message);\n }\n }\n\n }\n\n}\n```\n\nroles.module.ts\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n ],\n controllers: [RolesController],\n providers: [RolesService],\n exports: [RolesService],\n })\n\nexport class RolesModule {}\n```\n\nroles.service.ts\n\n```\n@Injectable()\nexport class RolesService {\n userModel: any;\n constructor( @InjectModel('Role') private readonly roleModel: Model ) {}\n\n // SET USER ROLES\n async setRoles(id: string, rolesDto: RolesDto): Promise {\n if ( !ObjectID.isValid(id) ){\n throw new HttpException({error: 'ID_NOT_VALID', message: `ID ${id} is not valid`, status: HttpStatus.BAD_REQUEST}, 400);\n }\n try {\n const date = moment().valueOf();\n const resp = await this.userModel.updateOne({\n _id: id,\n }, {\n $set: {\n updated_at: date,\n roles: rolesDto.roles,\n },\n });\n if ( resp.nModified === 0 ){\n throw new HttpException({ error: 'NOT_FOUND', message: `ID ${id} not found or entity not modified`, status: HttpStatus.NOT_FOUND}, 404);\n } else {\n let user = await this.userModel.findOne({ _id: id });\n user = _.pick(user, ['_id', 'email', 'roles', 'created_at', 'updated_at']);\n return user;\n }\n } catch (e) {\n if ( e.message.error === 'NOT_FOUND' ){\n throw new HttpException({ error: 'NOT_FOUND', message: `ID ${id} not found or entity not modified`, status: HttpStatus.NOT_FOUND}, 404);\n } else {\n throw new HttpException({error: 'ID_NOT_VALID', message: `ID ${id} is not valid`, status: HttpStatus.BAD_REQUEST}, 400);\n }\n }\n }\n```\n\nThat's it, as you can see when I try to use from users.controller the roles.service setRole method it returns me an error:\n\nNest can't resolve dependencies of the RolesService (?). Please make sure that the argument at index [0]is available in the current context.\n\nI don't understand where the problem is because I'm injecting the Role model in the roles.module already and it don't understand it. In fact if I don't create the call from users.module to this dependency everything goes fine.\n\nAny tip?\n\n(I've red the suggestion from stackoverflow, I'll don't do it again)\n\n========================================\n\nCode:\n```text\nimport { GroupsModule } from './groups/groups.module';\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { UsersModule } from 'users/users.module';\nimport { RolesModule } from 'roles/roles.module';\n\n@Module({\n  imports: [\n          MongooseModule.forRoot('mongodb://localhost:27017/example'),\n          UsersModule,\n          GroupsModule,\n          RolesModule,\n        ],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { UsersController } from './users.controller';\n\nimport { UsersService } from './users.service';\nimport { RolesService } from 'roles/roles.service';\n\nimport { UserSchema } from './schemas/user.schema';\nimport { RoleSchema } from 'roles/schemas/role.schema';\n\n@Module({\n    imports: [\n      MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n      MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n    ],\n    controllers: [UsersController],\n    providers: [UsersService, RolesService],\n    exports: [UsersService],\n  })\n\nexport class UsersModule {}\n```\n\n```text\nimport { Model } from 'mongoose';\nimport { ObjectID } from 'mongodb';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\n\nimport { User } from './interfaces/user.interface';\n\n@Injectable()\nexport class UsersService {\n  constructor(@InjectModel('User') private readonly userModel: Model<User>) {}\n}\n```\n\n```text\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { GroupsController } from './groups.controller';\n\nimport { RolesService } from '../roles/roles.service';\nimport { GroupsService } from './groups.service';\n\nimport { GroupSchema } from './schemas/group.schema';\nimport { UserSchema } from '../users/schemas/user.schema';\nimport { RoleSchema } from '../roles/schemas/role.schema';\n\n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: 'Group', schema: GroupSchema }]),\n    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n    MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n  ],\n  controllers: [GroupsController],\n  providers: [GroupsService, RolesService],\n  exports: [GroupsService],\n})\n```\n\n```text\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { ObjectID } from 'mongodb';\nimport { Model } from 'mongoose';\n\nimport { Group } from './interfaces/group.interface';\nimport { User } from '../users/interfaces/user.interface';\n\nimport { CreateGroupDto } from './dto/create-group.dto';\nimport { RolesDto } from 'roles/dto/roles.dto';\nimport { Role } from '../roles/interfaces/role.interface';\n\n@Injectable()\nexport class GroupsService {\n    constructor(@InjectModel('Group') private readonly groupModel: Model<Group>,\n                @InjectModel('Role') private readonly roleModel: Model<Role>) {} }\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\nimport { RolesController } from './roles.controller';\n\nimport { RolesService } from './roles.service';\n\nimport { RoleSchema } from './schemas/role.schema';\nimport { UserSchema } from '../users/schemas/user.schema';\nimport { GroupSchema } from '../groups/schemas/group.schema';\n\n@Module({\n    imports: [\n      MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n      MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n      MongooseModule.forFeature([{ name: 'Group', schema: GroupSchema }]),\n    ],\n    controllers: [RolesController],\n    providers: [RolesService],\n    exports: [RolesService],\n  })\n\nexport class RolesModule {}\n```\n\n```text\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { ObjectID } from 'mongodb';\nimport { Model } from 'mongoose';\n\nimport { Role } from './interfaces/role.interface';\nimport { User } from '../users/interfaces/user.interface';\nimport { Group } from '../groups/interfaces/group.interface';\n\nimport { CreateRoleDto } from './dto/create-role.dto';\nimport { RolesDto } from './dto/roles.dto';\n\n@Injectable()\nexport class RolesService {\n    constructor( @InjectModel('Role') private readonly roleModel: Model<Role>,\n                 @InjectModel('User') private readonly userModel: Model<User>,\n                 @InjectModel('Group') private readonly groupModel: Model<Group> ) {} }\n```\n\n```text\n@Module({\n    imports: [\n      MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n      RolesModule,\n    ],\n    controllers: [UsersController],\n    providers: [UsersService, RolesService],\n    exports: [UsersService],\n  })\n\nexport class UsersModule {}\n```\n\n```text\nexport class UsersController {\n\n    constructor(private readonly usersService: UsersService,\n                private readonly rolesService: RolesService){}\n\n    async addRoles(@Param('id') id: string, @Body() userRolesDto: UserRolesDto): Promise<User> {\n        try {\n            return this.rolesService.setRoles(id, userRolesDto);\n        } catch (e){\n            const message = e.message.message;\n            if ( e.message.error === 'NOT_FOUND'){\n                throw new NotFoundException(message);\n            } else if ( e.message.error === 'ID_NOT_VALID'){\n                throw new BadRequestException(message);\n            }\n        }\n\n    }\n\n}\n```\n\n```text\n@Module({\n    imports: [\n      MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),\n    ],\n    controllers: [RolesController],\n    providers: [RolesService],\n    exports: [RolesService],\n  })\n\nexport class RolesModule {}\n```\n\n```text\n@Injectable()\nexport class RolesService {\n    userModel: any;\n    constructor( @InjectModel('Role') private readonly roleModel: Model<Role> ) {}\n\n    // SET USER ROLES\n    async setRoles(id: string, rolesDto: RolesDto): Promise<User> {\n        if ( !ObjectID.isValid(id) ){\n            throw new HttpException({error: 'ID_NOT_VALID', message: `ID ${id} is not valid`, status: HttpStatus.BAD_REQUEST}, 400);\n        }\n        try {\n            const date = moment().valueOf();\n            const resp = await this.userModel.updateOne({\n              _id: id,\n            }, {\n              $set: {\n                  updated_at: date,\n                  roles: rolesDto.roles,\n              },\n            });\n            if ( resp.nModified === 0 ){\n              throw new HttpException({ error: 'NOT_FOUND', message: `ID ${id} not found or entity not modified`, status: HttpStatus.NOT_FOUND}, 404);\n            } else {\n              let user = await this.userModel.findOne({ _id: id });\n              user = _.pick(user, ['_id', 'email', 'roles', 'created_at', 'updated_at']);\n              return user;\n            }\n        } catch (e) {\n          if ( e.message.error === 'NOT_FOUND' ){\n            throw new HttpException({ error: 'NOT_FOUND', message: `ID ${id} not found or entity not modified`, status: HttpStatus.NOT_FOUND}, 404);\n          } else {\n            throw new HttpException({error: 'ID_NOT_VALID', message: `ID ${id} is not valid`, status: HttpStatus.BAD_REQUEST}, 400);\n          }\n        }\n    }\n```\n\n```text\nMongooseModule.forFeature([{ name: 'User', schema: UserSchema }]\n```\n\n```text\nproviders: [RolesService]\n```\n\n```text\n@Module({\n    imports: [MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }])]\n    controllers: [RolesController],\n    providers: [RolesService],\n    exports: [RolesService],\n  })\n\nexport class RolesModule {}\n```\n\n```text\n@Module({\n    imports: [\n      RolesModule,\n      MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])\n    ],\n    controllers: [UsersController],\n    providers: [UsersService],\n    exports: [UsersService],\n  })\n```\n\n```text\nexport\n```\n\n```text\nRolesService\n```\n\n```text\nUsersSerivce\n```\n\n```text\nUserModel\n```\n\n```text\nfowardRef(() => UserService)\n```\n\n```text\nRolesService\n```\n\n```text\nRolesModule\n```\n\n```text\nRolesService\n```\n\n========================================\n\nComments:\n- Thanks Kim, I've been trying to do what you comment but unfortunately I couldn't find the solution. I did try to call the line you comment just once and call it from the module where it's needed (RolesService for example). In this case if you can tell me how to implement it, should be very helpful. I'm not going to use circular-dependency, I've red a lot of docs but couldn't find the solution ... (little desperate by now)\n- It's very hard to tell how you should implement it because I don't what you want to implement. I can only assume, that you want to check if a user has a certain role. You can check out the RolesGuard example in the docs. In this case they attach the roles to the authorized user in the response (e.g. from a JWT).\n- Hi Kim again thanks for your answers, sorry but I can't understand the way DI works (i've read a millions of times the docs). But it works for me in some cases and other not. Specifically when I import a module from another module it seems to not recognize the stuff imported by itself. Sorry, a little bit confusing my requirement maybe ... I found nestjs a great framework but a little bit \"misty\" in this sense (or maybe is my lack of understanding about it) Thanks anyway\n- When you import a module it will only import the exported providers. If you update your code in your question, I'll have a look at it again. Also consider stackoverflow.com/help/someone-answers :-)\n- Remove the RolesService from the UserModule's providers array. You're importing the module and with that all its exported providers. If you provide the RolesService again, it will look for its dependcies (the Roles model) and not find it in the UsersModule.\n- AWESOME, a newbie error from my part, it works indeed. Just one more question, can I use just Roles Service calling it from providers without import RolesModule?\n- Great, I'm glad it works now. :-) If you think my answer was helpful, you can accept/upvote it. - No, you have to import the RolesModule. (Except within the RolesModule itself, here you can use it e.g. in the RolesController.)","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":595,"estimatedTokens":4604}}953{"id":"stack-70780736","source":"stackoverflow","questionId":70780736,"title":"Pass multipart form data from nest js server to another java server endpoint","tags":["javascript","node.js","angular","nestjs"],"text":"Title: Pass multipart form data from nest js server to another java server endpoint\nTags: javascript, node.js, angular, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a client-side application using Angular and server-side is Nest JS. I need to pass file data from client -> Nest JS -> Java end point (3rd party API).\n\nHow to pass buffered data from Nest JS server to Java end point\n\nHere is my code\n\n**Client side**\n\n```\nlet fData: FormData = new FormData;\nif(this.formService.model['uploadChecklist']) {\n fData.append('clientmanagedFacilityfile',this.formService.model['uploadChecklist']);\n fData.append('ticketID', this.ticketId);\n fData.append('employeeID', this.eid);\n this.gbtService.uploadtoNestJS(fData).subscribe((data) => {console.log(data)}) \n}\n```\n\n```\nuploadtoNestJS(fData):Observable {\n return this.http.post('/api/file/upload/newpoint',fData);\n }\n```\n\n**Nest JS Server side**\n\n```\n@Post('file/upload/newpoint')\n @UseInterceptors(FileInterceptor('clientmanagedFacilityfile'))\n uploadFile(@UploadedFile() clientmanagedFacilityfile, @Headers() headers, @Body() body: {ticketID: string, employeeID: string}) {\n console.log(clientmanagedFacilityfile, '--------', headers, '--------', body.employeeID, body.ticketID); // Receiving all the values as expected \n return this.fileService.uploadFiletoJava(clientmanagedFacilityfile,body,headers);\n }\n```\n\n```\nuploadFiletoJava(files, bodyData: {ticketID: string, employeeID: string} , headers: Headers) {\nconsole.log('----UPLOAD FILE TO JAVA END POINT----');\nconsole.log(files, '------', headers)\nconst formData = new FormData(); \nformData.append(files.fieldname, files.buffer, files.originalname);\nformData.append('ticketID', bodyData.ticketID);\nformData.append('employeeID', bodyData.employeeID)\nconst baseApiUrl = 'https://api/v1.0.0/sendFileAttachment'\nthis.httpService.post(baseApiUrl, formData, {headers: headers}).pipe().toPromise();\n}\n```\n\n- Is this my approach is right or wrong?\n\n- `uploadFiletoJava` Do I need to convert again into formData\n\nupload file to java end point\n\n```\n{\n fieldname: 'clientmanagedFacilityfile',\n originalname: 'Annamma-cough.pdf',\n encoding: '7bit',\n mimetype: 'application/pdf',\n buffer: ,\n size: 763932\n} ------ {\n 'accept-language': 'en-US,en;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n referer: 'http://localhost:4200/send',\n 'sec-fetch-dest': 'empty',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-site': 'same-origin',\n origin: 'http://localhost:4200',\n 'sec-ch-ua-platform': '\"Windows\"',\n 'source-id': 'abcder',\n 'trace-id': '90f3d61e-xysde2-418f-b0e2-af90122621d7',\n uuid: '90f3d61e-xysde2-418f-b0e2-af90122621d7',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',\n accept: 'application/json',\n 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryUk4sy5LBUCZm8qkx',\n ......\n }\n```\n\n========================================\n\nCode:\n```text\nlet fData: FormData = new FormData;\nif(this.formService.model['uploadChecklist']) {\n   fData.append('clientmanagedFacilityfile',this.formService.model['uploadChecklist']);\n   fData.append('ticketID', this.ticketId);\n   fData.append('employeeID', this.eid);\n   this.gbtService.uploadtoNestJS(fData).subscribe((data) => {console.log(data)}) \n}\n```\n\n```text\nuploadtoNestJS(fData):Observable<any> {\n        return this.http.post('/api/file/upload/newpoint',fData);\n    }\n```\n\n```text\n@Post('file/upload/newpoint')\n    @UseInterceptors(FileInterceptor('clientmanagedFacilityfile'))\n    uploadFile(@UploadedFile() clientmanagedFacilityfile, @Headers() headers,  @Body() body: {ticketID: string, employeeID: string}) {\n        console.log(clientmanagedFacilityfile, '--------', headers, '--------', body.employeeID, body.ticketID); // Receiving all the values as expected \n        return this.fileService.uploadFiletoJava(clientmanagedFacilityfile,body,headers);\n    }\n```\n\n```text\nuploadFiletoJava(files, bodyData: {ticketID: string, employeeID: string} , headers: Headers) {\nconsole.log('----UPLOAD FILE TO JAVA END POINT----');\nconsole.log(files, '------', headers)\nconst formData = new FormData(); \nformData.append(files.fieldname, files.buffer, files.originalname);\nformData.append('ticketID', bodyData.ticketID);\nformData.append('employeeID', bodyData.employeeID)\nconst baseApiUrl = 'https://api/v1.0.0/sendFileAttachment'\nthis.httpService.post(baseApiUrl, formData, {headers: headers}).pipe().toPromise();\n}\n```\n\n```text\n{\n  fieldname: 'clientmanagedFacilityfile',\n  originalname: 'Annamma-cough.pdf',\n  encoding: '7bit',\n  mimetype: 'application/pdf',\n  buffer: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 e2 e3 cf d3 0a 31 20 30 20 6f 62 6a 0a 3c 3c 2f 54 79 70 65 2f 58 4f 62 6a 65 63 74 2f 53 75 62 74 79 70 65 2f 49 6d 61 ... 763882 more bytes>,\n  size: 763932\n} ------ {\n  'accept-language': 'en-US,en;q=0.9',\n  'accept-encoding': 'gzip, deflate, br',\n  referer: 'http://localhost:4200/send',\n  'sec-fetch-dest': 'empty',\n  'sec-fetch-mode': 'cors',\n  'sec-fetch-site': 'same-origin',\n  origin: 'http://localhost:4200',\n  'sec-ch-ua-platform': '\"Windows\"',\n  'source-id': 'abcder',\n  'trace-id': '90f3d61e-xysde2-418f-b0e2-af90122621d7',\n  uuid: '90f3d61e-xysde2-418f-b0e2-af90122621d7',\n  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',\n  accept: 'application/json',\n  'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryUk4sy5LBUCZm8qkx',\n  ......\n }\n```\n\n```text\nuploadFiletoJava\n```\n\n```ts\n/* or import from http if the target is based on HTTP */\nimport { request} from 'https';\nimport { Req, Res } from '@nestjs/common';\nimport { Request, Response } from 'express';\n\n@Post('file/upload/newpoint')\nuploadFile(@Req req: Request, @Res res: Response) {\n  const proxy = request(\n    {\n      hostname: <hostName>,\n      port: <port>,\n      method: 'post',\n      path: <path>,\n      headers: {\n        'content-type': req.headers['content-type'],\n        'content-length': req.headers['content-length'],\n        // add any other headers as needed\n      },\n    },\n    (resp) => {\n      // pipe the target(i.e. Java server) response to client\n      resp.pipe(res);\n    },\n  );\n\n  // pipe incoming request to the target(i.e. Java server)\n  req.pipe(proxy);\n}\n```\n\n```ts\n// ...\nreq.on('end', () => {\n   res.send(/* a response object */);\n});\n\nreq.pipe(proxy);\n```\n\n```text\nUploadedFile\n```\n\n```text\nFileInterceptor\n```\n\n```text\nresp.pipe(res)\n```\n\n========================================\n\nComments:\n- Do you want the Node.js server to act like a *proxy* server and pass the *multipart* request to the Java server? If I'm right so in this case, it wouldn't need the data to be parsed in the Node.js server.","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":214,"estimatedTokens":1684}}954{"id":"stack-70183995","source":"stackoverflow","questionId":70183995,"title":"NestJs can't resolve service dependencies on a circular dependency","tags":["node.js","dependency-injection","nestjs","circular-dependency"],"text":"Title: NestJs can't resolve service dependencies on a circular dependency\nTags: node.js, dependency-injection, nestjs, circular-dependency\nSource: Stack Overflow\n\nQuestion:\ni have the problem that i have a circular dependency in my project. Unfortunately I cannot solve this with forwardRef.\n\nThe following structure:\n\n**OrderModule**\n\n*OrderService*\n\n- *I have the following dependencies in the orderService*\n\n- PriceService\n\n- CustomerService\n\n- SalePriceService\n\n- ...\n\n**PriceModule**\n\n*PriceService*\n\n- *I have the following dependencies in the priceService*\n\n- OrderService\n\n- ProductService\n\n- ...\n\nI've tried all the options from the Official Documentation.\ndocs NestJs circular-dependency\n\nWhat has to be considered here if there are more dependencies in a service?\n\nMany thanks. Best regards.\n\n**Update:**\n\norder.module.ts\n\n```\n@Module({\n imports: [\n CustomerModule,\n ProductModule,\n MongooseModule.forFeature([{ name: 'Order', schema: OrderSchema }]),\n forwardRef(() => PriceModule),\n ],\n controllers: [OrderController],\n providers: [OrderService],\n exports: [OrderService],\n})\nexport class OrderModule {}\n```\n\norder.service.ts\n\n```\n@Injectable()\nexport class OrderService extends GenericCrudService {\n constructor(\n @InjectModel(Order.name) readonly order: Model,\n private readonly productService: ProductService,\n @Inject(forwardRef(() => PriceService))\n private readonly priceService: PriceService,\n ) {\n super(order);\n }\n}\n```\n\nprice.module.ts\n\n```\n@Module({\n imports: [\n CustomerModule,\n SalePriceModule,\n MongooseModule.forFeature([{ name: 'Price', schema: PriceSchema }]),\n forwardRef(() => OrderModule),\n ],\n controllers: [],\n providers: [PriceService],\n exports: [PriceService],\n})\nexport class PriceModule {}\n```\n\nprice.service.ts\n\n```\n@Injectable()\nexport class PriceService extends GenericCrudService {\n constructor(\n @InjectModel(Price.name) readonly price: Model,\n private readonly customerService: CustomerService,\n private readonly salePriceService: SalePriceService,\n @Inject(forwardRef(() => OrderService))\n private readonly orderService: OrderService,\n ) {\n super(price);\n }\n}\n```\n\nproduct.module.ts\n\n```\n@Module({\n imports: [\n PriceModule,\n MongooseModule.forFeature([{ name: 'Product', schema: ProductSchema }]),\n ],\n controllers: [ProductController],\n providers: [ProductService],\n exports: [ProductService],\n})\nexport class ProductModule {}\n```\n\nproduct.service.ts\n\n```\n@Injectable()\nexport class ProductService extends GenericCrudService {\n constructor(\n @InjectModel(Product.name) readonly product: Model,\n ) {\n super(product);\n }\n}\n```\n\nThe error I'm getting is:\n\n```\nThe module at index [1] of the OrderModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [AppModule -> ProductModule -> PriceModule]\nError: Nest cannot create the OrderModule instance.\nThe module at index [1] of the OrderModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [AppModule -> ProductModule -> PriceModule]\n```\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    CustomerModule,\n    ProductModule,\n    MongooseModule.forFeature([{ name: 'Order', schema: OrderSchema }]),\n    forwardRef(() => PriceModule),\n  ],\n  controllers: [OrderController],\n  providers: [OrderService],\n  exports: [OrderService],\n})\nexport class OrderModule {}\n```\n\n```text\n@Injectable()\nexport class OrderService extends GenericCrudService<OrderDocument> {\n  constructor(\n    @InjectModel(Order.name) readonly order: Model<OrderDocument>,\n    private readonly productService: ProductService,\n    @Inject(forwardRef(() => PriceService))\n    private readonly priceService: PriceService,\n  ) {\n    super(order);\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n    CustomerModule,\n    SalePriceModule,\n    MongooseModule.forFeature([{ name: 'Price', schema: PriceSchema }]),\n    forwardRef(() => OrderModule),\n  ],\n  controllers: [],\n  providers: [PriceService],\n  exports: [PriceService],\n})\nexport class PriceModule {}\n```\n\n```text\n@Injectable()\nexport class PriceService extends GenericCrudService<PriceDocument> {\n  constructor(\n    @InjectModel(Price.name) readonly price: Model<PriceDocument>,\n    private readonly customerService: CustomerService,\n    private readonly salePriceService: SalePriceService,\n    @Inject(forwardRef(() => OrderService))\n    private readonly orderService: OrderService,\n  ) {\n    super(price);\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n    PriceModule,\n    MongooseModule.forFeature([{ name: 'Product', schema: ProductSchema }]),\n  ],\n  controllers: [ProductController],\n  providers: [ProductService],\n  exports: [ProductService],\n})\nexport class ProductModule {}\n```\n\n```text\n@Injectable()\nexport class ProductService extends GenericCrudService<ProductDocument> {\n  constructor(\n    @InjectModel(Product.name) readonly product: Model<ProductDocument>,\n  ) {\n    super(product);\n  }\n}\n```\n\n```text\nThe module at index [1] of the OrderModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [AppModule -> ProductModule -> PriceModule]\nError: Nest cannot create the OrderModule instance.\nThe module at index [1] of the OrderModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [AppModule -> ProductModule -> PriceModule]\n```\n\n```text\nOrdersModule\n```\n\n```text\nPricesModule\n```\n\n```text\nforwardRef\n```\n\n```text\nOrdersModule\n```\n\n```text\nProductsModule\n```\n\n```text\nPricesModule\n```\n\n```text\nOrdersModule\n```\n\n```text\nOrdersModule\n```\n\n```text\nforwardRef\n```\n\n```text\nProductsModule\n```\n\n```text\nProductsModule\n```\n\n```text\nforwardRef\n```\n\n```text\nPricesModule\n```\n\n```text\nScope [AppModule -> ProductModule -> PriceModule]\n```\n\n========================================\n\nComments:\n- Can you elaborate why using `forwardRef` does not fix the issue?\n- Showing your code here, modules and services, would be very helpful in knowing what's happening\n- Hi @JayMcDoniel I've just added a updated the question with the code snippets and the error I'm getting.\n- Can you add the `ProductModule`?\n- Hi @JayMcDoniel, I've just added a updated the question and add the product module and product service, best regards\n- Hello @JayMcDoniel, I understand that works perfectly. Thanks for the quick help :)","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":328,"estimatedTokens":1789}}955{"id":"stack-65453289","source":"stackoverflow","questionId":65453289,"title":"How to use custom class file in nestjs maintaining the rule of nestjs","tags":["javascript","node.js","nestjs"],"text":"Title: How to use custom class file in nestjs maintaining the rule of nestjs\nTags: javascript, node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nThere is a Crypto class by custom made in nestjs.\n\n```\nimport * as bcrypt from 'bcrypt';\n\nexport class Crypto {\n constructor() {\n }\n\n public async hash(target: string, salt: number): Promise {\n return await bcrypt.hash(target, salt);\n }\n\n public async compareHash(\n target: string,\n hash: string,\n ): Promise {\n return await bcrypt.compare(target, hash);\n }\n}\n```\n\nAnd I made this instance in a service of nestjs as below.\n\n```\npublic async create(createConfigDto: CreateConfigDto): Promise {\n const crypto = new Crypto();\n const hashedPassword = await crypto.hash(createConfigDto.password, 10);\n\n const newConfig = await new this.configModel({\n ...createConfigDto,\n password: hashedPassword,\n });\n return newConfig.save();\n }\n\n public async read() {\n const crypto = new Crypto();\n const hashedPassword = await crypto.compare(createConfigDto.password, hash);\n ...\n }\n```\n\nor I can do this crypto instance outside of create and read method to avoid duplicate call instance.\n\nBut my major question is about there is more efficient maintaining covention of nestjs for this case.\n\nCould you give me some advice for me?\nThank you for reading my question.\n\n========================================\n\nCode:\n```text\nimport * as bcrypt from 'bcrypt';\n\nexport class Crypto {\n  constructor() {\n  }\n\n  public async hash(target: string, salt: number): Promise<string> {\n    return await bcrypt.hash(target, salt);\n  }\n\n  public async compareHash(\n    target: string,\n    hash: string,\n  ): Promise<boolean> {\n    return await bcrypt.compare(target, hash);\n  }\n}\n```\n\n```text\npublic async create(createConfigDto: CreateConfigDto): Promise<IConfig> {\n    const crypto = new Crypto();\n    const hashedPassword = await crypto.hash(createConfigDto.password, 10);\n\n    const newConfig = await new this.configModel({\n      ...createConfigDto,\n      password: hashedPassword,\n    });\n    return newConfig.save();\n  }\n\n  public async read() {\n      const crypto = new Crypto();\n    const hashedPassword = await crypto.compare(createConfigDto.password, hash);\n  ...\n  }\n```\n\n```text\nimport * as bcrypt from 'bcrypt';\n\n@Injectable()\nexport class Crypto {\n  constructor() {\n  }\n\n  public async hash(target: string, salt: number): Promise<string> {\n    return await bcrypt.hash(target, salt);\n  }\n\n  public async compareHash(\n    target: string,\n    hash: string,\n  ): Promise<boolean> {\n    return await bcrypt.compare(target, hash);\n  }\n}\n```\n\n```text\n@Module({\n  ...\n  providers: [Crypto],\n})\n```\n\n```text\nconstructor(private crypto: Crypto) {}\n    ....\n   \n    public async create(createConfigDto: CreateConfigDto): Promise<IConfig> {\n    const hashedPassword = await this.crypto.hash(createConfigDto.password, 10);\n\n    const newConfig = await new this.configModel({\n      ...createConfigDto,\n      password: hashedPassword,\n    });\n    return newConfig.save();\n  }\n\n  public async read() {\n    const hashedPassword = await this.crypto.compare(createConfigDto.password, hash);\n  ...\n  }\n```\n\n```text\nCrypto\n```\n\n```text\n@Injectable()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":152,"estimatedTokens":790}}956{"id":"stack-63468683","source":"stackoverflow","questionId":63468683,"title":"Jest with NestJS and async function","tags":["nestjs","typeorm","ts-jest"],"text":"Title: Jest with NestJS and async function\nTags: nestjs, typeorm, ts-jest\nSource: Stack Overflow\n\nQuestion:\nI'm trying to a test a async function of a `service` in **nestJS**.\n\nthis function is async... basically get a value (JSON) from database (using repository - TypeORM), and when successfully get the data, \"transform\" to a different class (DTO)...\nthe implementation:\n\n```\nasync getAppConfig(): Promise {\n return this.configRepository.findOne({\n key: Equal(\"APPLICATION\"),\n }).then(config => {\n if (config == null) {\n return new class implements ConfigAppDto {\n clientId = '';\n clientSecret = '';\n };\n }\n return JSON.parse(config.value) as ConfigAppDto;\n });\n}\n```\n\nusing a controller, I checked that this worked ok.\nNow, I'm trying to use Jest to do the tests, but with no success...\nMy problem is how to mock the `findOne` function from `repository`..\n\n**Edit**: I'm trying to use `@golevelup/nestjs-testing` to mock `Repository`!\n\nI already mocked the `repository`, but for some reason, the `resolve` is never called..\n\n```\ndescribe('getAppConfig', () => {\n const repo = createMock>();\n\n beforeEach(async () => {\n await Test.createTestingModule({\n providers: [\n ConfigService,\n {\n provide: getRepositoryToken(Config),\n useValue: repo,\n }\n ],\n }).compile();\n });\n\n it('should return ConfigApp parameters', async () => {\n const mockedConfig = new Config('APPLICATION', '{\"clientId\": \"foo\",\"clientSecret\": \"bar\"}');\n repo.findOne.mockResolvedValue(mockedConfig);\n expect(await repo.findOne()).toEqual(mockedConfig); // ok\n\n const expectedReturn = new class implements ConfigAppDto {\n clientId = 'foo';\n clientSecret = 'bar';\n };\n expect(await service.getAppConfig()).toEqual(expectedReturn);\n\n // jest documentation about async -> https://jestjs.io/docs/en/asynchronous\n // return expect(service.getAppConfig()).resolves.toBe(expectedReturn);\n });\n})\n```\n\n- the `expect(await repo.findOne()).toEqual(mockedConfig);` works great;\n\n- `expect(await service.getAppConfig()).toEqual(expectedReturn);` got a timeout => `Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout`;\n\nusing debug, I see that the `service.getAppConfig()` is called, the `repository.findOne()` too, but the `.then` of repository of findOne is never called.\n\n**Update**: I'm trying to mock the repository using `@golevelup/nestjs-testing`, and for some reason, the mocked result don't works on service.\nIf I mock the repository using only `jest` (like code below), the test works... so, I think my real problem it's `@golevelup/nestjs-testing`.\n\n```\n...\nprovide: getRepositoryToken(Config),\nuseValue: {\n find: jest.fn().mockResolvedValue([new Config()])\n},\n...\n```\n\n========================================\n\nTop Answer:\nI think `expect(await repo.findOne()).toEqual(mockedConfig);` works because you mocked it, so it returns right away.\nIn the case of `expect(await service.getAppConfig()).toEqual(expectedReturn);`, you did not mock it so it is probably taking more time, thus the `it` function returns before the `Promise` resolved completely.\n\nThe comments you posted from jest documentation should do the trick if you mock the call to `getAppConfig()`.\n\n```\nservice.getAppConfig = jest.fn(() => Promise.resolve(someFakeValue))\n```\n\nor\n\n```\nspyOn(service, 'getAppConfig').and.mockReturnValue(Promise.resolve(fakeValue))\n```\n\n========================================\n\nCode:\n```text\nasync getAppConfig(): Promise<ConfigAppDto> {\n  return this.configRepository.findOne({\n    key: Equal(\"APPLICATION\"),\n  }).then(config => {\n    if (config == null) {\n      return new class implements ConfigAppDto {\n        clientId = '';\n        clientSecret = '';\n      };\n    }\n    return JSON.parse(config.value) as ConfigAppDto;\n  });\n}\n```\n\n```text\ndescribe('getAppConfig', () => {\n  const repo = createMock<Repository<Config>>();\n\n  beforeEach(async () => {\n    await Test.createTestingModule({\n      providers: [\n        ConfigService,\n        {\n          provide: getRepositoryToken(Config),\n          useValue: repo,\n        }\n      ],\n    }).compile();\n  });\n\n  it('should return ConfigApp parameters', async () => {\n    const mockedConfig = new Config('APPLICATION', '{\"clientId\": \"foo\",\"clientSecret\": \"bar\"}');\n    repo.findOne.mockResolvedValue(mockedConfig);\n    expect(await repo.findOne()).toEqual(mockedConfig); // ok\n\n    const expectedReturn = new class implements ConfigAppDto {\n      clientId = 'foo';\n      clientSecret = 'bar';\n    };\n    expect(await service.getAppConfig()).toEqual(expectedReturn);\n\n    // jest documentation about async -> https://jestjs.io/docs/en/asynchronous\n    // return expect(service.getAppConfig()).resolves.toBe(expectedReturn);\n  });\n})\n```\n\n```text\n...\nprovide: getRepositoryToken(Config),\nuseValue: {\n  find: jest.fn().mockResolvedValue([new Config()])\n},\n...\n```\n\n```text\nservice\n```\n\n```text\nfindOne\n```\n\n```text\nrepository\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\nRepository\n```\n\n```text\nrepository\n```\n\n```text\nresolve\n```\n\n```text\nexpect(await repo.findOne()).toEqual(mockedConfig);\n```\n\n```text\nexpect(await service.getAppConfig()).toEqual(expectedReturn);\n```\n\n```text\nAsync callback was not invoked within the 5000 ms timeout specified by jest.setTimeout\n```\n\n```text\nservice.getAppConfig()\n```\n\n```text\nrepository.findOne()\n```\n\n```text\n.then\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\njest\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\n// i'm injecting Connection because I need for some transactions later;\nconstructor(@InjectRepository(Config) private readonly configRepo: Repository<Config>, private connection: Connection) {}\n\nasync getAppConfig(): Promise<ConfigApp> {\n  return this.configRepo.findOne({\n    key: Equal(\"APPLICATION\"),\n  }).then(config => {\n    if (config == null) {\n      return new ConfigApp();\n    }\n    return JSON.parse(config.value) as ConfigApp;\n  })\n}\n```\n\n```text\ndescribe('getAppConfig', () => {\n  const configApi = new Config();\n  configApi.key = 'APPLICATION';\n  configApi.value = '{\"clientId\": \"foo\", \"clientSecret\": \"bar\"}';\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      providers: [\n        ConfigAppService,\n        {\n          provide: getRepositoryToken(Config),\n          useValue: {\n            findOne: jest.fn().mockResolvedValue(new\n            Config(\"APPLICATION\", '{\"clientId\": \"foo\", \"clientSecret\": \"bar\"}')),\n          },\n        },\n        {\n          provide: getConnectionToken(),\n          useValue: {},\n        }\n      ],\n    }).compile();\n\n    service = module.get<ConfigAppService>(ConfigAppService);\n  });\n\n  it('should return ConfigApp parameters', async () => {\n    const expectedValue: ConfigApp = new ConfigApp(\"foo\", \"bar\");\n\n    return service.getAppConfig().then(value => {\n      expect(value).toEqual(expectedValue);\n    })\n  });\n})\n```\n\n```text\nRepository\n```\n\n```text\nNestJS\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\nJest\n```\n\n```text\nNestJS\n```\n\n```text\nservice.getAppConfig = jest.fn(() => Promise.resolve(someFakeValue))\n```\n\n```text\nspyOn(service, 'getAppConfig').and.mockReturnValue(Promise.resolve(fakeValue))\n```\n\n```text\nexpect(await repo.findOne()).toEqual(mockedConfig);\n```\n\n```text\nexpect(await service.getAppConfig()).toEqual(expectedReturn);\n```\n\n```text\nit\n```\n\n```text\nPromise\n```\n\n```text\ngetAppConfig()\n```\n\n```text\nusersRepository.findOneOrFail.mockResolvedValue({ userId: 1, email: \"some-random-email@email.com\" });\n```\n\n```js\ndescribe(\"UsersService\", () => {\n  let usersService: UsersService;\n  const usersRepository = createMock<Repository<User>>();\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        UsersService,\n        {\n          provide: getRepositoryToken(User),\n          useValue: usersRepository,\n        },\n    }).compile();\n\n    usersService = module.get(UsersService);\n  });\n\n  it(\"should be defined\", () => {\n    expect(usersService).toBeDefined();\n  });\n  it(\"finds a user\", async () => {\n    usersRepository.findOne.mockResolvedValue({ userId: 1, email: \"some-random-email@email.com\" });\n\n    expect(await usersRepository.findOne()).toBe({ userId: 1, email: \"some-random-email@email.com\" });\n  });\n});\n```\n\n```text\ncreateMock\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\ncreateMock\n```\n\n========================================\n\nComments:\n- What does your ConfigService look like?\n- It's the first part of the code in the question: `async getAppConfig(): Promise`\n- My question was on the implementation of the ConfigService ;) How do you load the env vars? Can you show us?\n- i don't get! no env vars used! the `ConfigService.APP_CONFIG_KEY` its just a static string with value `\"APPLICATION\"`. Almost the entire ConfigService it's here... the only part that I don't included its the static string, imports, and constructor (with `@InjectRepository`, because this is not related with the problem... I will update the code)\n- What if you comment ` expect(await repo.findOne()).toEqual(mockedConfig); // ok`? Maybe jest is mocking only in the first time, just guessing.\n- but I don't wanna mock `getAppConfig` function! I wanna test this function... I mocked the `findOne` because internally, the getAppConfig use this. About taking more time, I already configured Jest for timeout after 60 seconds, and still, the timeout occur, because the `then` is never called.\n- Ok, and if you try the example from jest documentation ? `return expect(service.getAppConfig()).resolves.toBe(expectedReturn)&zwnj;&#8203;;`\n- I already tried the example from jest documentation: `Timeout - Async callback was not invoked within the 60000 ms timeout specified by jest.setTimeout.Error:`","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":389,"estimatedTokens":2431}}957{"id":"stack-67131275","source":"stackoverflow","questionId":67131275,"title":"Do NestJS providers need to be stateless?","tags":["spring","nestjs"],"text":"Title: Do NestJS providers need to be stateless?\nTags: spring, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm a long-time Spring developer learning NestJS. The similarities are so striking, and I've loved how productive that's allowed me to be. Some documentation has me confused about one thing however.\n\nI try to liken Nest \"providers\" to Spring beans with default scope. For example I create @Injectable service classes and think of them as analogous to Spring @Services. As such I've assumed these service classes needed to be thread safe - no state, etc. However, the Nest documentation here is a little ambiguous to me and kind of implies this might not be necessary (emphasis mine):\n\nFor people coming from different programming language backgrounds, it might be unexpected to learn that in Nest, almost everything is shared across incoming requests. We have a connection pool to the database, singleton services with global state, etc. **Remember that Node.js doesn't the request/response Multi-Threaded Stateless Model in which every request is processed by a separate thread. Hence, using singleton instances is fully safe for our applications.**\n\nIf individual requests aren't handled in their own threads, is it OK for Nest providers to contain mutable state? It would be up to the app to ensure each incoming request started with a \"clean slate\" - e.g. initializing that state with a NestInterceptor, for example. But to me, that doc reads that providers are created as singletons, and thus can be used as something akin to a wrapper container for data, like a ThreadLocal in Java.\n\nAm I reading this wrong, or is this a difference in behavior between Nest and Spring?\n\n========================================\n\nComments:\n- Thanks so much. I was wondering if blocking IO could cause a new request to be handled. Spring has a lot of parallels to Nest but it executes each request in a separate thead, hencee an explicit need for thread safety in e.g. services with are singletons (in the default scope). Same net result of course.\n- I'm currently passing the request down to the Service tier but have an aversion to that due to strong separation-of-concerns opinions - only the Controller tier should know about HTTP & requests, Service tier should only know business logic, etc. Hence looking for a way to store state a la Java ThreadLocals.\n- I would avoid passing the request object to your services, for the most part for the reasons you stated (also ease of testing). But you can pass properties of that request from the controller to your services. Like the current user for example for when a service makes a change in the DB that needs to be attributed to a user, for example.","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":21,"estimatedTokens":674}}958{"id":"stack-63855891","source":"stackoverflow","questionId":63855891,"title":"How to get/set request/response header in middelware [Nest Fastify]?","tags":["node.js","nestjs","fastify","nestjs-fastify"],"text":"Title: How to get/set request/response header in middelware [Nest Fastify]?\nTags: node.js, nestjs, fastify, nestjs-fastify\nSource: Stack Overflow\n\nQuestion:\nHow to inject a request header in NestJS using Fastify.\n\n```\nimport { FastifyRequest, FastifyReply } from 'fastify'; // fastify types are not valid\n\n@Injectable()\nexport class TracingMiddleware implements NestMiddleware {\n use(req: any, res: any, next: () => void) {\n console.log('MyRequestHeaderKey', req.headers['MyRequestHeaderKey']); // find out how to get a header \n res.header('MyResponseHeaderKey', 'MyResponseHeaderValue'); // find out how to set headers\n next();\n }\n}\n```\n\nThere is no reference for fastify middleware on nest docs: https://docs.nestjs.com/middleware\n\nI have read fastify doc without success: https://www.fastify.io/docs/v1.13.x/Reply/\n& https://www.fastify.io/docs/v1.13.x/Request/\n\n========================================\n\nCode:\n```js\nimport { FastifyRequest, FastifyReply } from 'fastify'; // fastify types are not valid\n\n@Injectable()\nexport class TracingMiddleware implements NestMiddleware {\n  use(req: any, res: any, next: () => void) {\n    console.log('MyRequestHeaderKey', req.headers['MyRequestHeaderKey']); // find out how to get a header \n    res.header('MyResponseHeaderKey', 'MyResponseHeaderValue'); // find out how to set headers\n    next();\n  }\n}\n```\n\n```text\nreq.raw\n```\n\n```text\nres.raw\n```\n\n```text\nFastifyRequest\n```\n\n```text\nFastifyReply\n```\n\n```text\nreq.headers\n```\n\n```text\nheaders\n```\n\n```text\nIncoming Request\n```\n\n```text\nres.setHeader()\n```\n\n```text\nServerResponse\n```\n\n========================================\n\nComments:\n- Thanks! It would be nice to include that in nest documentation.\n- @Jay can you provide an example?\n- @FooBar example of what, specifically? using a guard or interceptor? Using the `ServerResponse` type object?","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":83,"estimatedTokens":461}}959{"id":"stack-50586417","source":"stackoverflow","questionId":50586417,"title":"NestJS. Custom provider, inject can't resolve dependencies of the useFactory","tags":["typescript","nestjs"],"text":"Title: NestJS. Custom provider, inject can't resolve dependencies of the useFactory\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI get the following error during app start:\n`Error: Nest can't resolve dependencies of the useFactory (?). Please verify whether [0] argument is available in the current context.`\n\n`ConfigService` is exported and `ConfigModule` is loaded as first module. Don't know if it's my fault or it's a bug in NestJS. \nMaybe somebody could find something) Thank you.\n\ndatabase.providers.ts:\n\n```\nimport { Sequelize } from 'sequelize-typescript';\nimport { SEQUELIZE_TOKEN } from './constants';\nimport { User } from '../users/user.entity';\nimport { ConfigService } from '../config/config.service';\n\nexport const databaseProviders = [\n {\n provide: SEQUELIZE_TOKEN,\n useFactory: async (configService: ConfigService) => {\n const sequelize = new Sequelize({\n dialect: 'mysql',\n host: 'localhost',\n port: 3306,\n username: configService.databaseUser,\n password: configService.databasePassword,\n database: configService.databaseName,\n operatorsAliases: false,\n logging: false,\n });\n sequelize.addModels([User]);\n await sequelize.sync({ force: process.env.NODE_ENV === 'local'\n || process.env.NODE_ENV === 'test',\n });\n return sequelize;\n },\n inject: [ConfigService],\n },\n];\n```\n\nPart app.module.ts:\n\n```\n@Module({\n imports: [\n ConfigModule,\n DatabaseModule,\n GraphQLModule,\n UsersModule,\n ],\n exports: [DatabaseModule],\n})\n```\n\nPart config.module.ts:\n\n```\n@Module({\n providers: [\n {\n provide: ConfigService,\n useValue: new ConfigService(`./config`),\n },\n ],\n exports: [ConfigService],\n})\n```\n\n========================================\n\nCode:\n```text\nimport { Sequelize } from 'sequelize-typescript';\nimport { SEQUELIZE_TOKEN } from './constants';\nimport { User } from '../users/user.entity';\nimport { ConfigService } from '../config/config.service';\n\nexport const databaseProviders = [\n {\n  provide: SEQUELIZE_TOKEN,\n  useFactory: async (configService: ConfigService) => {\n    const sequelize = new Sequelize({\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: configService.databaseUser,\n      password: configService.databasePassword,\n      database: configService.databaseName,\n      operatorsAliases: false,\n      logging: false,\n    });\n    sequelize.addModels([User]);\n    await sequelize.sync({ force: process.env.NODE_ENV === 'local'\n    || process.env.NODE_ENV === 'test',\n    });\n    return sequelize;\n  },\n  inject: [ConfigService],\n },\n];\n```\n\n```text\n@Module({\n imports: [\n  ConfigModule,\n  DatabaseModule,\n  GraphQLModule,\n  UsersModule,\n ],\n exports: [DatabaseModule],\n})\n```\n\n```text\n@Module({\n providers: [\n    {\n        provide: ConfigService,\n        useValue: new ConfigService(`./config`),\n    },\n ],\n exports: [ConfigService],\n})\n```\n\n```text\nError: Nest can't resolve dependencies of the useFactory (?). Please verify whether [0] argument is available in the current context.\n```\n\n```text\nConfigService\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigModule\n```\n\n```text\nDatabaseModule\n```\n\n========================================\n\nComments:\n- Thank you, works perfectly. Maybe add information about scope of providers to official docs (custom providers section)?\n- Yes, there are many custom decorators techniques available to . Reading out this in 2021 :).","metadata":{"transformedAt":"2026-08-18T18:33:02.480Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":155,"estimatedTokens":834}}960{"id":"stack-48719984","source":"stackoverflow","questionId":48719984,"title":"What's the best way to run method of Component (Service) just after bootstrap running?","tags":["nestjs"],"text":"Title: What's the best way to run method of Component (Service) just after bootstrap running?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS instance as microservice (without HTTP).\n\nI need to run Component's method that is infinity loop with some business logic just after bootstrap initialization.\n\nWhat is the best way to do it?\n\n**src/main.ts**\n\n```\nimport {NestFactory} from '@nestjs/core';\nimport {ApplicationModule} from './app.module';\nimport {Transport} from '@nestjs/microservices';\n\nasync function bootstrap() {\n const app = await NestFactory.create(ApplicationModule);\n app.connectMicroservice({\n transport: Transport.REDIS,\n url: 'redis://:redis_pass@localhost:6379',\n });\n await app.startAllMicroservicesAsync();\n\n // Probably here I must run startLoop method from app.service.ts\n \n}\nbootstrap();\n```\n\n**src/app.service.ts**\n\n```\nimport { Component } from '@nestjs/common';\n\n@Component()\nexport class AppService {\n\n startLoop() {\n let timerId = setTimeout(function loop() {\n console.log('Loop process');\n // Some business logic here\n timerId = setTimeout(loop, 1000);\n }, 1000);\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\nimport {NestFactory} from '@nestjs/core';\nimport {ApplicationModule} from './app.module';\nimport {Transport} from '@nestjs/microservices';\n\nasync function bootstrap() {\n    const app = await NestFactory.create(ApplicationModule);\n    app.connectMicroservice({\n        transport: Transport.REDIS,\n        url: 'redis://:redis_pass@localhost:6379',\n    });\n    await app.startAllMicroservicesAsync();\n\n    // Probably here I must run startLoop method from app.service.ts\n    \n}\nbootstrap();\n```\n\n```text\nimport { Component } from '@nestjs/common';\n\n@Component()\nexport class AppService {\n\n    startLoop() {\n        let timerId = setTimeout(function loop() {\n            console.log('Loop process');\n            // Some business logic here\n            timerId = setTimeout(loop, 1000);\n        }, 1000);\n    }\n\n}\n```\n\n```text\nOnModuleInit\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":93,"estimatedTokens":504}}961{"id":"stack-50236234","source":"stackoverflow","questionId":50236234,"title":"Create Proxy in NestJS","tags":["node.js","typescript","nestjs"],"text":"Title: Create Proxy in NestJS\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI created a proxy with the nestjs.\n\nAll requisitions pass normally. Except for POST requests.\n\nLook at my code:\n\n```\nimport { IncomingMessage } from 'http';\nimport { HttpUtils } from './../utils/http.utils';\nimport { Controller, Param, Req, Res, All } from '@nestjs/common';\nimport { Config } from './../system/config';\nimport { ServerResponse } from 'http';\nimport * as http from 'http';\nimport { CouchDB, Log } from 'system';\nimport { UsuarioModel } from 'model';\n\n@Controller('__api-proxy')\nexport class ApiProxyController {\n\n @All('*')\n root(@Param() param, @Req() c_req: IncomingMessage, @Res() c_res: ServerResponse): any {\n\n // habilito o cors\n HttpUtils.enableCors(c_req, c_res);\n\n const urlDetail = HttpUtils.getUrlDetail(Config.getConfig().endpoints.webapi);\n\n // modifico para o hostname em que eu estou fazendo o proxy\n c_req.headers.host = urlDetail.hostname;\n\n // faรงo o proxy\n var proxy = http.request({\n hostname: urlDetail.hostname,\n port: urlDetail.port,\n method: c_req.method,\n headers: c_req.headers,\n path: '/' + param[0],\n }, (res) => {\n res.pause();\n res.headers.Server = `Sync Server ${Config.getConfig().package.version}`;\n\n if (Config.getConfig().endpoints.log) {\n Log.print('[ api ] [' + c_req.connection.remoteAddress + '] : ' + c_req.method + ' ' + res.statusCode + ' ' + c_req.url);\n }\n\n c_res.writeHead(res.statusCode, res.headers);\n res.pipe(c_res, {end: true});\n res.resume();\n });\n\n c_req.pipe(proxy, {end: true});\n }\n}\n```\n\n NodeJS error\n\n```\nError: socket hang up\n at createHangUpError (_http_client.js:331:15)\n at Socket.socketOnEnd (_http_client.js:423:23)\n at emitNone (events.js:111:20)\n at Socket.emit (events.js:208:7)\n at endReadableNT (_stream_readable.js:1056:12)\n at _combinedTickCallback (internal/process/next_tick.js:138:11)\n at process._tickDomainCallback (internal/process/next_tick.js:218:9)\n```\n\nBefore it worked normally, after I put the proxy under NestJS only GET and OPTIONS requests work. Can you help me?\n\n========================================\n\nCode:\n```text\nimport { IncomingMessage } from 'http';\nimport { HttpUtils } from './../utils/http.utils';\nimport { Controller, Param, Req, Res, All } from '@nestjs/common';\nimport { Config } from './../system/config';\nimport { ServerResponse } from 'http';\nimport * as http from 'http';\nimport { CouchDB, Log } from 'system';\nimport { UsuarioModel } from 'model';\n\n@Controller('__api-proxy')\nexport class ApiProxyController {\n\n    @All('*')\n    root(@Param() param, @Req() c_req: IncomingMessage, @Res() c_res: ServerResponse): any {\n\n        // habilito o cors\n        HttpUtils.enableCors(c_req, c_res);\n\n        const urlDetail = HttpUtils.getUrlDetail(Config.getConfig().endpoints.webapi);\n\n        // modifico para o hostname em que eu estou fazendo o proxy\n        c_req.headers.host = urlDetail.hostname;\n\n        // faรงo o proxy\n        var proxy = http.request({\n            hostname: urlDetail.hostname,\n            port: urlDetail.port,\n            method: c_req.method,\n            headers: c_req.headers,\n            path: '/' + param[0],\n        }, (res) => {\n            res.pause();\n            res.headers.Server = `Sync Server ${Config.getConfig().package.version}`;\n\n            if (Config.getConfig().endpoints.log) {\n                Log.print('[ api ] [' + c_req.connection.remoteAddress + ']     : ' + c_req.method + ' ' + res.statusCode + ' ' + c_req.url);\n            }\n\n            c_res.writeHead(res.statusCode, res.headers);\n            res.pipe(c_res, {end: true});\n            res.resume();\n        });\n\n        c_req.pipe(proxy, {end: true});\n    }\n}\n```\n\n```text\nError: socket hang up\n    at createHangUpError (_http_client.js:331:15)\n    at Socket.socketOnEnd (_http_client.js:423:23)\n    at emitNone (events.js:111:20)\n    at Socket.emit (events.js:208:7)\n    at endReadableNT (_stream_readable.js:1056:12)\n    at _combinedTickCallback (internal/process/next_tick.js:138:11)\n    at process._tickDomainCallback (internal/process/next_tick.js:218:9)\n```\n\n```text\napp.use('__bank-agency-gateway', proxy(config.endpoints.bankAgencyGateway));\napp.use('__bank-account', proxy(config.endpoints.bankAcountCenter));\napp.use('__bank-safebox', proxy(config.endpoints.bankSafebox));\napp.use('__visa-proxy', proxy(config.endpoints.visaProxy));\n```\n\n```text\nconst app = await NestFactory.create(AppModule);\n```\n\n```text\nexpress-http-proxy\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":152,"estimatedTokens":1117}}962{"id":"stack-70440817","source":"stackoverflow","questionId":70440817,"title":"Nestjs ClassSerializerInterceptor doesn't display _id","tags":["javascript","node.js","mongodb","mongoose","nestjs"],"text":"Title: Nestjs ClassSerializerInterceptor doesn't display _id\nTags: javascript, node.js, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an issue properly exposing the _id using the Serializer.\n\nI use:\n\n```\n@UseInterceptors(ClassSerializerInterceptor)\n@SerializeOptions({ strategy: 'excludeAll' })\n```\n\nThe defined Class:\n\n```\nexport class UpdatedCounts {\n @Expose()\n _id: ObjectId;\n @Expose()\n aCount: number;\n @Expose()\n bCount: number;\n\n constructor(partial: Partial) {\n Object.assign(this, partial);\n }\n}\n```\n\nThe object in console.log() before it runs through the Serializer\n\n```\n{\n _id: new ObjectId(\"61c2256ee0385774cc85a963\"),\n bannerImage: 'placeholder2',\n previewImage: 'placeholder',\n aCount: 1,\n bCount: 0,\n}\n```\n\nThe object being returned:\n\n```\n{\n \"_id\": {},\n \"aCount\": 1,\n \"bCount\": 0\n}\n```\n\nSo what happened to my _id?\n\nI tried using string type instead of ObjectId but that also does not work\n\nI do not want to use @Exclude since there are 10 more props which I left out in the example console.log(), and it should be easier to exclude all and just use these 3\n\n========================================\n\nCode:\n```js\n@UseInterceptors(ClassSerializerInterceptor)\n@SerializeOptions({ strategy: 'excludeAll' })\n```\n\n```js\nexport class UpdatedCounts {\n    @Expose()\n    _id: ObjectId;\n    @Expose()\n    aCount: number;\n    @Expose()\n    bCount: number;\n\n    constructor(partial: Partial<MyDocument>) {\n        Object.assign(this, partial);\n    }\n}\n```\n\n```js\n{\n  _id: new ObjectId(\"61c2256ee0385774cc85a963\"),\n  bannerImage: 'placeholder2',\n  previewImage: 'placeholder',\n  aCount: 1,\n  bCount: 0,\n}\n```\n\n```js\n{\n  \"_id\": {},\n  \"aCount\": 1,\n  \"bCount\": 0\n}\n```\n\n```js\n@Expose()\n@Transform((params) => params.obj._id.toString())\n_id: ObjectId;\n```\n\n```text\n@Transform\n```\n\n========================================\n\nComments:\n- try using `@Type(() => ObjectId)` on `_id` field\n- @MicaelLevi I had another person tell me the same thing, but unfortunately that does not work, idk if I am doing it wrong =,=\n- I can't tell. I've never tried using the builtin serializer, tbh. I'm using automapperts.netlify.app instead\n- Ah yes this worked, thank you very much, I failed before seeing that I have to use the \"obj\"","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":117,"estimatedTokens":560}}963{"id":"stack-69012446","source":"stackoverflow","questionId":69012446,"title":"Documenting Graphql schema using Nestjs Code-first approach","tags":["typescript","graphql","nestjs","nest"],"text":"Title: Documenting Graphql schema using Nestjs Code-first approach\nTags: typescript, graphql, nestjs, nest\nSource: Stack Overflow\n\nQuestion:\nIs there a way to add comments to mutations and queries of your schema generated through code first approach of Nestjs?\n\n========================================\n\nCode:\n```text\n@ObjectType( {description : 'My class') )\nClass Person {\n    @Field ( () => ID, { description : ' ID of the user' } ) \n    Id: number\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":17,"estimatedTokens":115}}964{"id":"stack-59120875","source":"stackoverflow","questionId":59120875,"title":"NestJS: How to get User from the request in a GraphQL custom Guard which extends from JWT AuthGuard","tags":["typescript","graphql","nestjs"],"text":"Title: NestJS: How to get User from the request in a GraphQL custom Guard which extends from JWT AuthGuard\nTags: typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use Passport and GraphQL and if I do my own custom guard to get user's roles it just doesn't work. I don't have access to the user from the request in a Guard, is that intentional? I think it should be part of the request (I'm totally new to NestJS), so why I can't get it? I would like to get the user's roles directly from the user object and only allow users with Admin for specific routes like the full list of users. \n\nThis is my GraphQL guard, the console log always return undefined\n\n```\n@Injectable()\nexport class GraphqlPassportAuthGuard extends AuthGuard('jwt') {\n roles: string[];\n\n constructor(roles?: string | string[]) {\n super();\n this.roles = Array.isArray(roles) ? roles : [roles];\n }\n\n canActivate(context: ExecutionContext): boolean {\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n console.log('graphql guard user', req && req.user)\n return true;\n }\n\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n console.log('graphql guard user', req && req.user)\n return req;\n }\n}\n```\n\nand I try using it with following code\n\n```\nexport const CurrentUser = createParamDecorator(\n (data, [root, args, ctx, info]) => {\n return ctx.req.user;\n },\n);\n\n@Resolver()\nexport class UsersResolver {\n constructor() { } \n\n @Query(() => UserDto)\n @UseGuards(GraphqlPassportAuthGuard)\n whoAmI(@CurrentUser() user: User) {\n return user;\n }\n}\n```\n\n`app.module.ts`\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n autoSchemaFile: 'schema.gql',\n context: ({ req }) => ({ req }),\n }),\n // ...\n});\n```\n\nI can get the user from the `@CurrentUser()` with a Custom Decorator but I can't get the user object inside the guard. I'm trying to get the user from the request, but is that possible in a Guard or not? I tried so many things, I don't know what to do anymore.\n\nI also tried to do another Roles Guard with different code and again I'm trying to get the user from the request and I can't get the user from the request.\n\n```\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private readonly reflector: Reflector) { }\n\n canActivate(context: ExecutionContext): boolean {\n const handler = context.getHandler();\n const http = context.switchToHttp();\n const request = context.switchToHttp().getRequest();\n const roles = this.reflector.get('roles', context.getHandler());\n console.log('rolesGuard', roles, request && request.user)\n if (!roles || !request || !request.user) {\n return true;\n }\n const user = request && request.user;\n const hasRole = () =>\n user.roles.some(role => !!roles.find(item => item === role));\n\n return user && user.roles && hasRole();\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class GraphqlPassportAuthGuard extends AuthGuard('jwt') {\n  roles: string[];\n\n  constructor(roles?: string | string[]) {\n    super();\n    this.roles = Array.isArray(roles) ? roles : [roles];\n  }\n\n  canActivate(context: ExecutionContext): boolean {\n    const ctx = GqlExecutionContext.create(context);\n    const req = ctx.getContext().req;\n    console.log('graphql guard user', req && req.user)\n    return true;\n  }\n\n  getRequest(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    const req = ctx.getContext().req;\n    console.log('graphql guard user', req && req.user)\n    return req;\n  }\n}\n```\n\n```text\nexport const CurrentUser = createParamDecorator(\n  (data, [root, args, ctx, info]) => {\n    return ctx.req.user;\n  },\n);\n\n@Resolver()\nexport class UsersResolver {\n  constructor() { } \n\n  @Query(() => UserDto)\n  @UseGuards(GraphqlPassportAuthGuard)\n  whoAmI(@CurrentUser() user: User) {\n    return user;\n  }\n}\n```\n\n```text\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      autoSchemaFile: 'schema.gql',\n      context: ({ req }) => ({ req }),\n    }),\n    // ...\n});\n```\n\n```text\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private readonly reflector: Reflector) { }\n\n  canActivate(context: ExecutionContext): boolean {\n    const handler = context.getHandler();\n    const http = context.switchToHttp();\n    const request = context.switchToHttp().getRequest();\n    const roles = this.reflector.get<string[]>('roles', context.getHandler());\n    console.log('rolesGuard', roles, request && request.user)\n    if (!roles || !request || !request.user) {\n      return true;\n    }\n    const user = request && request.user;\n    const hasRole = () =>\n      user.roles.some(role => !!roles.find(item => item === role));\n\n    return user && user.roles && hasRole();\n  }\n}\n```\n\n```text\napp.module.ts\n```\n\n```text\n@CurrentUser()\n```\n\n```text\nGraphqlPassportAuthGuard.canActivate()\n```\n\n```text\nawait super.canActivate(context)\n```\n\n```text\nPromise<boolean>\n```\n\n```text\nAuthGuard\n```\n\n```text\nAuthGuard.handleRequest(err, user, info, context)\n```\n\n========================================\n\nComments:\n- Sorry for the delay, I just tried this and I still have the same result `undefined`, am I supposed to still calli the same 2 lines after the `super.canActivate`? That 2nd line `ctx.getContext().req` still doesn't have the user that I'm looking for. Would you mind providing the full code of the `canActive` method? Am I suppose to delete something or call something else? I'm totally new to NestJS, I'm a little confused. My main goal is the get the user's role and block the user if he doesn't have necessary role\n- You should `await` for super.canActivate since it returns a Promise, sorry I didn't mention in my original answer. So make your definition of `canActivate` `async` and call `await super.canActivate(context)`. Remember also to change the return type to `Promise`","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":211,"estimatedTokens":1474}}965{"id":"stack-67838554","source":"stackoverflow","questionId":67838554,"title":"Documentation of @nestjs/mongoose","tags":["mongodb","mongoose","nestjs","nest","nestjs-mongoose"],"text":"Title: Documentation of @nestjs/mongoose\nTags: mongodb, mongoose, nestjs, nest, nestjs-mongoose\nSource: Stack Overflow\n\nQuestion:\nI started learning NestJS, by reading documentation. currently, I'm using the @nestjs/mongoose package for MongoDB. unforunatley I can't find any documentation about this package.\nthe only docs **I found is this https://docs.nestjs.com/techniques/mongodb**\nhowever, it's missing lots of information, such as creating an index for the schema.\nwhere can I find additional information? how people on stack overflow know some of the answers if they are not in the documentation\n\nedit: I mean documentation of @nestjs/mongoose\n\n========================================\n\nCode:\n```text\n@nestjs/mongoose\n```\n\n```text\nmongoose\n```\n\n```text\n@Schema()\n```\n\n```text\n@Prop()\n```\n\n```text\nSchemaFactory.createForClass\n```\n\n```text\n@Prop()\n```\n\n========================================\n\nComments:\n- mongoosejs.com","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":43,"estimatedTokens":232}}966{"id":"stack-73277677","source":"stackoverflow","questionId":73277677,"title":"How to mock a nest-winston logger dependency in nestjs unit tests","tags":["typescript","unit-testing","jestjs","nestjs","nest-winston"],"text":"Title: How to mock a nest-winston logger dependency in nestjs unit tests\nTags: typescript, unit-testing, jestjs, nestjs, nest-winston\nSource: Stack Overflow\n\nQuestion:\nThis question already exists, but it is marked as solved and the solution doesn't work at all for me.\n\nI want to mock a nest-winston logger that is a dependency of a provider in nestjs.\n\n```\n@Controller('builder/instance')\nexport class InstanceController {\n private executor: Executor;\n\n constructor(\n @Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: Logger,\n private stripeService: StripeService,\n private instanceService: InstanceService,\n private organizationService: OrganizationService,\n private executorFactory: ExecutorFactory,\n private socketService: SocketService,\n private auditLogService: AuditLogService,\n) {\n this.logger.log(\"hello world!\", InstanceController.name);\n this.executor = this.executorFactory.getExecutor();\n // ...\n }\n}\n```\n\nThe authors solution was to pass in the loggers token as a provider to the module with an empty useValue. I assume it is because they didn't want to actually call it, but just supply the dependency for one of the providers they mock.\n\n```\ndescribe('InstanceController', () => {\nlet controller: InstanceController;\n\nconst mockStripeService = {};\nconst mockInstanceService = {};\nconst mockOrganizationService = {};\nconst mockExecutorFactory = {};\nconst mockSocketService = {};\nconst mockAuditLogService = {};\n\nbeforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n // imports: [AccountModule],\n controllers: [InstanceController],\n providers: [\n { provide: WINSTON_NEST_MODULE_PROVIDER, useValue: {} },\n StripeService,\n InstanceService,\n OrganizationService,\n ExecutorFactory,\n SocketService,\n AuditLogService,\n ],\n })\n .overrideProvider(StripeService)\n .useValue(mockStripeService)\n .overrideProvider(InstanceService)\n .useValue(mockInstanceService)\n .overrideProvider(OrganizationService)\n .useValue(mockOrganizationService)\n .overrideProvider(ExecutorFactory)\n .useValue(mockExecutorFactory)\n .overrideProvider(SocketService)\n .useValue(mockSocketService)\n .overrideProvider(AuditLogService)\n .useValue(mockAuditLogService)\n .compile();\n\n controller = module.get(InstanceController);\n});\n\nit('should be defined', () => {\n expect(controller).toBeDefined();\n});\n});\n```\n\nHowever, when trying to run the tests, it tries to find `this.logger.log` and when `this.logger` returns as `{}` it says `this.logger.log is not a function`.\nDoes anyone know of a way to **properly** mock the logger dependency and can help me with this? The auto mocking described in nestjs documentation did not work for me either.\n\nI am very new with jest and nestjs, and my plaster solution thusfar is to replace the empty useValue with\n\n```\n{\n log: jest.fn(),\n debug: jest.fn(),\n info: jest.fn(),\n warn: jest.fn(),\n error: jest.fn(),\n}\n```\n\n, which is just... awful. Help will be greatly appreciated!\n\n========================================\n\nTop Answer:\nJust an addition: if anyone uses `@golevelup/ts-jest`, you can mock the entire `LoggingService`, so that you don't need to add `jest.fn()` for each method you may be using in the class-under-test:\n\n```\nimport { createMock } from '@golevelup/ts-jest';\nimport { LoggerService } from '@nestjs/common';\n\n...\n\n{\n provide: WINSTON_MODULE_NEST_PROVIDER,\n useValue: createMock(),\n}\n```\n\n========================================\n\nCode:\n```text\n@Controller('builder/instance')\nexport class InstanceController {\n   private executor: Executor;\n\n   constructor(\n    @Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: Logger,\n    private stripeService: StripeService,\n    private instanceService: InstanceService,\n    private organizationService: OrganizationService,\n    private executorFactory: ExecutorFactory,\n    private socketService: SocketService,\n    private auditLogService: AuditLogService,\n) {\n    this.logger.log(\"hello world!\", InstanceController.name);\n    this.executor = this.executorFactory.getExecutor();\n    // ...\n  }\n}\n```\n\n```text\ndescribe('InstanceController', () => {\nlet controller: InstanceController;\n\nconst mockStripeService = {};\nconst mockInstanceService = {};\nconst mockOrganizationService = {};\nconst mockExecutorFactory = {};\nconst mockSocketService = {};\nconst mockAuditLogService = {};\n\nbeforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n        // imports: [AccountModule],\n        controllers: [InstanceController],\n        providers: [\n            { provide: WINSTON_NEST_MODULE_PROVIDER, useValue: {} },\n            StripeService,\n            InstanceService,\n            OrganizationService,\n            ExecutorFactory,\n            SocketService,\n            AuditLogService,\n        ],\n    })\n        .overrideProvider(StripeService)\n        .useValue(mockStripeService)\n        .overrideProvider(InstanceService)\n        .useValue(mockInstanceService)\n        .overrideProvider(OrganizationService)\n        .useValue(mockOrganizationService)\n        .overrideProvider(ExecutorFactory)\n        .useValue(mockExecutorFactory)\n        .overrideProvider(SocketService)\n        .useValue(mockSocketService)\n        .overrideProvider(AuditLogService)\n        .useValue(mockAuditLogService)\n        .compile();\n\n    controller = module.get<InstanceController>(InstanceController);\n});\n\nit('should be defined', () => {\n    expect(controller).toBeDefined();\n});\n});\n```\n\n```text\n{\n  log: jest.fn(),\n  debug: jest.fn(),\n  info: jest.fn(),\n  warn: jest.fn(),\n  error: jest.fn(),\n}\n```\n\n```text\nthis.logger.log\n```\n\n```text\nthis.logger\n```\n\n```text\n{}\n```\n\n```text\nthis.logger.log is not a function\n```\n\n```js\n{\n  provide: StripeService,\n  useValue: mockStripeService\n}\n```\n\n```js\n{\n  provide: WINSTON_NEST_MODULE_PROVIDER,\n  useValue: { log: jest.fn() }\n}\n```\n\n```text\noverride\n```\n\n```text\noverride*()\n```\n\n```text\nthis.logger.log\n```\n\n```text\nlog\n```\n\n```text\njest.fn()\n```\n\n```text\nimport { createMock } from '@golevelup/ts-jest';\nimport { LoggerService } from '@nestjs/common';\n\n...\n\n{\n  provide: WINSTON_MODULE_NEST_PROVIDER,\n  useValue: createMock<LoggerService>(),\n}\n```\n\n```text\n@golevelup/ts-jest\n```\n\n```text\nLoggingService\n```\n\n```text\njest.fn()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":269,"estimatedTokens":1558}}967{"id":"stack-68225742","source":"stackoverflow","questionId":68225742,"title":"'arraycontaining' does not exist on type 'jestmatchers'","tags":["typescript","jestjs","nestjs"],"text":"Title: 'arraycontaining' does not exist on type 'jestmatchers'\nTags: typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI write test for my controller in Nestjs. I expect an array of employees contains object `{id:1, firstname: 'john', lastname:'Dole'}`. So I write:\n\n```\nit('should get an employee', () => {\n return controller.findAll('john').then((data) => {\n expect(data).arrayContaining([\n {\n id: 1,\n firstname: 'john',\n lastname: 'Dole',\n },\n ]);\n });\n });\n```\n\nbut got error `roperty 'arrayContaining' does not exist on type 'JestMatchers'`\nShall I install additional package or update jest in Nestjs? I've install `\"@nestjs/testing\": \"^7.6.15\",`\n\n========================================\n\nCode:\n```text\nit('should get an employee', () => {\n    return controller.findAll('john').then((data) => {\n      expect(data).arrayContaining([\n        {\n          id: 1,\n          firstname: 'john',\n          lastname: 'Dole',\n        },\n      ]);\n    });\n  });\n```\n\n```text\n{id:1, firstname: 'john', lastname:'Dole'}\n```\n\n```text\nroperty 'arrayContaining' does not exist on type 'JestMatchers<Employee[]>'\n```\n\n```text\n\"@nestjs/testing\": \"^7.6.15\",\n```\n\n```text\nexpect(data).toEqual(expect.arrayContaining([\n        {\n          id: 1,\n          firstname: 'john',\n          lastname: 'Dole',\n        },\n      ]));\n```\n\n```text\narrayContaining\n```\n\n```text\ntoEqual\n```\n\n========================================\n\nComments:\n- Looking at the docs and examples you don't seem to be calling it right. jestjs.io/docs/expect#expectarraycontainingarray","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":388}}968{"id":"stack-62648027","source":"stackoverflow","questionId":62648027,"title":"NestJS Microservice Exception handling","tags":["microservices","nestjs"],"text":"Title: NestJS Microservice Exception handling\nTags: microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have setup a Microservice Architecture that looks the following:\n\n- api-gateway (`NestFactory.create(AppModule);`)\n\n- service 1 (`NestFactory.createMicroservice`)\nservice 2 (`NestFactory.createMicroservice`)\n...\n\nA Service looks like this:\n\n```\nservice.controller.ts\nservice.handler.ts\n```\n\nWhere `handler` is like a Service in a typical Monolith that handles the logic.\n\nCurrently, I am catching Exceptions the following way:\n\nThe handler makes a call to the database and fails due to a duplicated key (i.e. email).\n\nI catch this exception and convert it to an `RpcException`\n\nIn the ApiGateway I catch the `RpcException` like so:\n\n```\nreturn new Promise((resolve, reject) => {\n this.clientProxy\n .send('MessagePattern', { dto: DTO })\n .subscribe(resolve, (err) => {\n logger.error(err);\n reject(err);\n });\n });\n```\n\nAgain I have to catch the rejected Promise and `throw an HttpException` to have the `ExceptionFilter` sending a proper error response. Throwing an Error inside the Promise instead of rejecting it doesn't work)\n\nSo basically, I have 3 TryCatch Blocks for 1 Exception.\nThis looks very verbose to me.\n\nIs there any better way or best practice when it comes to NestJS Microservices?\n\nCan we have an `Interceptor` for the rebound messages received by `this.clientProxy.send` and pipe it to send send the error response to the client without catching it 2 times explicitly?\n\n========================================\n\nCode:\n```text\nservice.controller.ts\nservice.handler.ts\n```\n\n```text\nreturn new Promise<Type>((resolve, reject) => {\n       this.clientProxy\n        .send<Type>('MessagePattern', { dto: DTO })\n        .subscribe(resolve, (err) => {\n            logger.error(err);\n            reject(err);\n        });\n    });\n```\n\n```text\nNestFactory.create(AppModule);\n```\n\n```text\nNestFactory.createMicroservice<MicroserviceOptions>\n```\n\n```text\nNestFactory.createMicroservice<MicroserviceOptions>\n```\n\n```text\nhandler\n```\n\n```text\nRpcException\n```\n\n```text\nRpcException\n```\n\n```text\nthrow an HttpException\n```\n\n```text\nExceptionFilter\n```\n\n```text\nInterceptor\n```\n\n```text\nthis.clientProxy.send\n```\n\n```text\ntry {\n  const payload = { dto: DTO }; \n  const response = await this.clientProxy.send<Type>('MessagePattern', payload).toPromise();\n} catch (err) {\n  this.logger.error(err);\n}\n```\n\n```text\n@MessagePattern(messagePattern)\n@UseInterceptors(CatchExceptionInterceptor)\npublic async someMethod(...) { }\n```\n\n```text\n@Injectable()\nexport class CatchExceptionInterceptor implements NestInterceptor {\n    intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {\n        return stream$.pipe(\n            catchError(...)\n        );\n    }\n}\n```\n\n```text\n.subscribe\n```\n\n```text\nreject(...)\n```\n\n```text\nsend\n```\n\n```text\nObservable\n```\n\n```text\n.toPromise()\n```\n\n```text\nInterceptors\n```\n\n```text\nNestInterceptor\n```\n\n========================================\n\nComments:\n- Hi there, I moved away from microservices, so I had no chance the check your answer on the project so far. Being a better developer than I was, I would accept your answer. The best way to handle this case would be to intercept the exception or rethrow if needed. The interceptor should then convert the exception to the convention of the caller. Ideally, all microservices would an ISO convention for exceptions anyway.","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":167,"estimatedTokens":859}}969{"id":"stack-69256658","source":"stackoverflow","questionId":69256658,"title":"Sudden TypeORM FindConditions type errors","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Sudden TypeORM FindConditions type errors\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAfter reinstalling node_modules I am suddenly getting a FindOneOptions/ObjectID error in my NestJS service.\n\nWas building fine minutes ago beforehand.\nMakes me wonder, is this a code err or a typings err?\n\nUsing \"@nestjs/typeorm\": \"^7.1.5\"\n\nWhich seems to be using typeorm 0.2.35:\n\nLocal installed version: 0.2.35.\n\nGlobal installed TypeORM version: 0.2.37.\n\nThe actual code\n\n```\nasync getOne(id: number, userId?: string, type?: XPType, currentUser?: User) {\n const options: FindConditions = {\n id\n };\n userId && (options.userId = userId);\n type && (options.type = type);\n\n const post = await XP.findOne(options); // Here is the actual error:\n\n```\nNo overload matches this call.\n Overload 1 of 3, '(this: ObjectType, id?: string | number | Date | ObjectID, options?: FindOneOptions): Promise', gave the following error.\n Argument of type 'FindConditions' is not assignable to parameter of type 'string | number | Date | ObjectID'.\n Type 'FindConditions' is missing the following properties from type 'ObjectID': generationTime, equals, generate, getTimestamp, toHexString\n Overload 2 of 3, '(this: ObjectType, options?: FindOneOptions): Promise', gave the following error.\n Type 'FindConditions' has no properties in common with type 'FindOneOptions'.\n Overload 3 of 3, '(this: ObjectType, conditions?: FindConditions, options?: FindOneOptions): Promise', gave the following error.\n Argument of type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindConditions\").FindConditions' is not assignable to parameter of type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindConditions\").FindConditions'.\n Types of property 'userId' are incompatible.\n Type 'string | import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator' is not assignable to type 'string | import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator'.\n Type 'FindOperator' is not assignable to type 'string | FindOperator'.\n Type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator' is not assignable to type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator'.\n Types have separate declarations of a private property '_type'.ts(2769)\nconst options: FindConditions\n```\n\nSeems to be related to 4241 but am not sure. I'm hoping someone can help me understand this.\n\n========================================\n\nCode:\n```text\nasync getOne(id: number, userId?: string, type?: XPType, currentUser?: User) {\n    const options: FindConditions<XP> = {\n        id\n    };\n    userId && (options.userId = userId);\n    type && (options.type = type);\n\n    const post = await XP.findOne(options); // <-- error\n    ...\n```\n\n```text\nNo overload matches this call.\n  Overload 1 of 3, '(this: ObjectType<XP>, id?: string | number | Date | ObjectID, options?: FindOneOptions<XP>): Promise<...>', gave the following error.\n    Argument of type 'FindConditions<XP>' is not assignable to parameter of type 'string | number | Date | ObjectID'.\n      Type 'FindConditions<XP>' is missing the following properties from type 'ObjectID': generationTime, equals, generate, getTimestamp, toHexString\n  Overload 2 of 3, '(this: ObjectType<XP>, options?: FindOneOptions<XP>): Promise<XP>', gave the following error.\n    Type 'FindConditions<XP>' has no properties in common with type 'FindOneOptions<XP>'.\n  Overload 3 of 3, '(this: ObjectType<XP>, conditions?: FindConditions<XP>, options?: FindOneOptions<XP>): Promise<...>', gave the following error.\n    Argument of type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindConditions\").FindConditions<import(\"/Users/bracicot/dev/dev-server/packages/server-common/dist/entities/experience-post.entity\").XP>' is not assignable to parameter of type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindConditions\").FindConditions<import(\"/Users/bracicot/dev/dev-server/packages/server-common/dist/entities/experience-post.entity\").XP>'.\n      Types of property 'userId' are incompatible.\n        Type 'string | import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>' is not assignable to type 'string | import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>'.\n          Type 'FindOperator<string>' is not assignable to type 'string | FindOperator<string>'.\n            Type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>' is not assignable to type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>'.\n              Types have separate declarations of a private property '_type'.ts(2769)\nconst options: FindConditions<XP>\n```\n\n```text\n'string | import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>'\n```\n\n```text\n'string | import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>\n```\n\n```text\nFindConditions\n```\n\n```text\n(this: ObjectType<XP>, conditions?: FindConditions<XP>, options?: FindOneOptions<XP>): Promise<...>\n```\n\n```text\ndev-server\n```\n\n```text\nserver-common\n```\n\n```text\nnode_modules/typeorm/find-options/FindOperator\n```\n\n```text\nTypes have separate declarations of a private property '_type'.\n```\n\n```text\nserver-common\n```\n\n```text\nserver-common\n```\n\n```text\nAfter reinstalling node_modules\n```\n\n```text\n^\n```\n\n```text\n~\n```\n\n```text\nx\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- what's the type of `XP`? I'm using `FindConditions` type just like you but with custom repositories\n- Hey @MicaelLevi it's a class to model the data. Standard data stuff in it such as id, title, and many others. For now I've changed all instances of `FindConditions` to `any`. No idea what happened here.\n- Wow @Martin Gr&#246;nlund thank you for such a detailed and brilliant answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":147,"estimatedTokens":1627}}970{"id":"stack-68463496","source":"stackoverflow","questionId":68463496,"title":"How to execute predefined number of jobs at one time in Nestjs bull","tags":["redis","nestjs","bull"],"text":"Title: How to execute predefined number of jobs at one time in Nestjs bull\nTags: redis, nestjs, bull\nSource: Stack Overflow\n\nQuestion:\nI have 65 same named jobs to execute in one queue with 3 instances of consumers (A, B, C). I want to do at one time each consumer execute 10 jobs. After the 10 execution completed, if there are available jobs greater than 10 in the queue that consumer again execute 10 jobs. If not execute available jobs.\n\njobs 1 to 65\n\nConsumer A execute 1 to 10\nConsumer B execute 11 to 20\nConsumer C execute 21 to 30\n\nLets take B, A, C finished the execution in order.\nthen\n\nB - 31,32,33,.40\nA - 41,42,43,.50\nC - 51,52,53,.60\n\nif C finish the execution first, C execute the remaining 5 jobs.\nPlease can I know are there any ways to achieve this.\n\nproducer\n\n```\n@Injectable()\nexport class SampleQueueProducerService {\n constructor(@InjectQueue('sample-queue') private sampleQueue: Queue) {}\n\n async sendDataToJob(message: string) {\n await this.sampleQueue.add('job', { message });\n }\n}\n```\n\nconsumer\n\n```\n@Processor('sample-queue')\nexport class SampleQueueConsumerService {\n @Process({ name: 'job' })\n async sampleJob(job: Job) {\n console.log(job.data);\n }\n}\n```\n\nall 3 consumers are same as above.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class SampleQueueProducerService {\n  constructor(@InjectQueue('sample-queue') private sampleQueue: Queue) {}\n\n  async sendDataToJob(message: string) {\n    await this.sampleQueue.add('job', { message });\n  }\n}\n```\n\n```text\n@Processor('sample-queue')\nexport class SampleQueueConsumerService {\n  @Process({ name: 'job' })\n  async sampleJob(job: Job<any>) {\n    console.log(job.data);\n  }\n}\n```\n\n```text\n@OnGlobalQueueWaiting()\nasync onGlobalWaiting(jobId: number, result: any) {\n  const job = await this.myQueue.getJob(jobId);\n  this.jobArray.push(job)\n  if (this.jobArray.length >= 10) {\n       await this.processJobs(this.jobArray);\n       this.jobArray = [];\n   }\n}\n\nasync processJobs(jobs: Job[]){'\n   jobs.forEach(job => do something)\n}\n```\n\n```text\n@OnGlobalQueueWaiting()\n```\n\n```text\n@OnQueueWaiting()\n```\n\n========================================\n\nComments:\n- How can we achive like this bunch of jobs must be processed by the only worker, Like a task having 3 jobs and they are added in the queue sequencially, once first finish it will add another and they all must be processed by same worker only. Is it possible?\n- It's possible using the BullMQ-pro package, \"grouping\" feature docs.bullmq.io/bullmq-pro/groups\n- Hello, Is it possible with github.com/OptimalBits/bull?\n- According to this: github.com/OptimalBits/&hellip; Grouping is only available for the pro package","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":105,"estimatedTokens":670}}971{"id":"stack-67587213","source":"stackoverflow","questionId":67587213,"title":"Why 'new WebSocket()' doesn't work for nestjs?","tags":["javascript","websocket","nestjs"],"text":"Title: Why 'new WebSocket()' doesn't work for nestjs?\nTags: javascript, websocket, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am sending with `const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world');` from client and i receive log 'connected' log on the server but not 'hello world'. socket.send() not working for NestJS. When I look at chrome network. It sends the data but not receiving in server.\nhere is the code: **chat.gateway.ts**\n\n```\n@WebSocketGateway()\nexport class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {\n handleConnection(client: any, ...args: any[]): any {\n console.log('connected');\n }\n\n handleDisconnect(client: any): any {\n console.log(client);\n console.log('disconnected');\n }\n\n @SubscribeMessage('message')\n handleEvent(client: any, data: any): WsResponse {\n const event = 'events';\n return { event, data };\n }\n\n afterInit(server: any): any {\n console.log(server.path);\n }\n}\n```\n\n**main.ts**\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { WsAdapter } from '@nestjs/platform-ws';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.enableCors({\n origin: 'http://localhost:4200',\n credentials: true,\n });\n app.useWebSocketAdapter(new WsAdapter(app));\n await app.listen(3000);\n}\n\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\n@WebSocketGateway()\nexport class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {\n  handleConnection(client: any, ...args: any[]): any {\n    console.log('connected');\n  }\n\n  handleDisconnect(client: any): any {\n    console.log(client);\n    console.log('disconnected');\n  }\n\n  @SubscribeMessage('message')\n  handleEvent(client: any, data: any): WsResponse<any> {\n    const event = 'events';\n    return { event, data };\n  }\n\n  afterInit(server: any): any {\n    console.log(server.path);\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { WsAdapter } from '@nestjs/platform-ws';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.enableCors({\n    origin: 'http://localhost:4200',\n    credentials: true,\n  });\n  app.useWebSocketAdapter(new WsAdapter(app));\n  await app.listen(3000);\n}\n\nbootstrap();\n```\n\n```text\nconst socket = new WebSocket('ws://localhost:3000'); socket.send('hello world');\n```\n\n```js\nconst socket = new WebSocket('ws://localhost:80');\nsocket.onopen = () => {\n  console.log('Connected');\n  socket.send(\n    JSON.stringify({\n      event: 'message',\n      data: 'my very important message',\n    }),\n  );\n  socket.onmessage = (data) => {\n    console.log(data);\n  };\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":684}}972{"id":"stack-66881061","source":"stackoverflow","questionId":66881061,"title":"how to create how to create many to many relationship in typeorm, [NestJS]","tags":["mysql","nestjs","typeorm"],"text":"Title: how to create how to create many to many relationship in typeorm, [NestJS]\nTags: mysql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow can I save data in manytomany relationship??\n(user, book (MTM))\nhere is a many-to-many relationship between the user and the book.\nMy service is not correct.\nAlso, my code doesn't work.\nThe data is stored in the book table.\n\nI need your help, everything\nThank you in advance.\n\nMy Stack => NestJs, TypeORM, MySQL\n\nThere are my entities.\nenter image description here\n\nuser.entity\n\n```\n@Entity('User')\nexport class User {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column()\n real_name!: string;\n\n @Column()\n nick_name!: string;\n\n @Column()\n @IsEmail()\n email!: string;\n\n @Column()\n password!: string;\n\n @Column()\n phone_number!: string;\n\n @Column()\n image_url: string;\n\n @BeforeInsert()\n async hashPassword() {\n this.password = await argon2.hash(this.password, {type: argon2.argon2id, hashLength: 40});\n }\n}\n```\n\nbook.entity\n\n```\n@Entity('Book')\nexport class Book {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column()\n title: string;\n\n @Column()\n image_url: string;\n\n @Column()\n contents: string;\n\n @Column({ type: 'datetime'})\n datetime: string;\n\n @ManyToMany(() => User)\n @JoinTable()\n users: User[];\n}\n```\n\nbook.controller.ts\n\n```\n@UseGuards(JwtAuthGuard)\n @Post('bpc')\n savebpc(@Req() req: any, @Query('title') bookTitle: string){\n return this.BookService.addBpc(req, bookTitle);\n }\n```\n\nbook.service.ts\n\n```\nasync addBpc(req: any, bookTitle: string): Promise{\n const userId = req.user.id;\n const bookId = await getRepository('Book')\n .createQueryBuilder('book')\n .where({title:bookTitle})\n .getRawOne()\n\n if (!bookId){\n throw new NotFoundException('Not_found_book');\n }\n\n const user = await getRepository('User')\n .createQueryBuilder('user')\n .where({id: userId})\n .getRawOne()\n\n //bookId.user.push(user);\n //await this.bookRepository.save(bookId);\n\n let userdata = new User();\n userdata.id = user.user_id;\n userdata.real_name = user.user_real_name;\n userdata.nick_name = user.user_nick_name;\n userdata.email = user.user_email;\n userdata.password = user.user_password;\n userdata.image_url = user.user_image_url;\n console.log(userdata);\n \n\n let bookBpc = new Book();\n bookBpc.title = bookId.book_title;\n bookBpc.image_url = bookId.book_image_url;\n bookBpc.contents = bookId.book_contents;\n bookBpc.datetime = bookId.book_datetime;\n bookBpc.users = [user];\n console.log(bookBpc);\n\n await this.bookRepository.create([bookBpc]);\n return 'suceess';\n }\n```\n\n========================================\n\nCode:\n```text\n@Entity('User')\nexport class User {\n    @PrimaryGeneratedColumn()\n    id!: number;\n\n    @Column()\n    real_name!: string;\n\n    @Column()\n    nick_name!: string;\n\n    @Column()\n    @IsEmail()\n    email!: string;\n\n    @Column()\n    password!: string;\n\n    @Column()\n    phone_number!: string;\n\n    @Column()\n    image_url: string;\n\n    @BeforeInsert()\n    async hashPassword() {\n        this.password = await argon2.hash(this.password, {type: argon2.argon2id, hashLength: 40});\n    }\n}\n```\n\n```text\n@Entity('Book')\nexport class Book {\n    @PrimaryGeneratedColumn()\n    id!: number;\n\n    @Column()\n    title: string;\n\n    @Column()\n    image_url: string;\n\n    @Column()\n    contents: string;\n\n    @Column({ type: 'datetime'})\n    datetime: string;\n\n    @ManyToMany(() => User)\n    @JoinTable()\n    users: User[];\n}\n```\n\n```text\n@UseGuards(JwtAuthGuard)\n    @Post('bpc')\n    savebpc(@Req() req: any, @Query('title') bookTitle: string){\n        return this.BookService.addBpc(req, bookTitle);\n    }\n```\n\n```text\nasync addBpc(req: any, bookTitle: string): Promise<any>{\n        const userId = req.user.id;\n        const bookId = await getRepository('Book')\n        .createQueryBuilder('book')\n        .where({title:bookTitle})\n        .getRawOne()\n\n        if (!bookId){\n            throw new NotFoundException('Not_found_book');\n        }\n\n        const user = await getRepository('User')\n        .createQueryBuilder('user')\n        .where({id: userId})\n        .getRawOne()\n\n\n        //bookId.user.push(user);\n        //await this.bookRepository.save(bookId);\n\n        let userdata = new User();\n        userdata.id = user.user_id;\n        userdata.real_name = user.user_real_name;\n        userdata.nick_name = user.user_nick_name;\n        userdata.email = user.user_email;\n        userdata.password = user.user_password;\n        userdata.image_url = user.user_image_url;\n        console.log(userdata);\n        \n\n        let bookBpc = new Book();\n        bookBpc.title = bookId.book_title;\n        bookBpc.image_url = bookId.book_image_url;\n        bookBpc.contents = bookId.book_contents;\n        bookBpc.datetime = bookId.book_datetime;\n        bookBpc.users = [user];\n        console.log(bookBpc);\n\n        await this.bookRepository.create([bookBpc]);\n        return 'suceess';\n    }\n```\n\n```text\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n  @Column({ type: 'varchar', nullable: false, unique: true })\n  username: string;\n  // we need to add a default password and get it form the .env file\n  @Column({ type: 'varchar', nullable: true, default: '' })\n  password: string;\n  @Column({ type: 'varchar', nullable: true })\n  firstname: string;\n  @Column({ type: 'varchar', nullable: true })\n  lastname: string;\n  @Column({ type: 'varchar', nullable: false })\n  email: string;\n  @Column({ type: 'boolean', nullable: true, default: false })\n  connected: boolean;\n  @CreateDateColumn({ name: 'created_at' })\n  createdAt: Date;\n\n  @UpdateDateColumn({ name: 'updated_at' })\n  updatedAt: Date;\n\n  // new properties\n  @Column({ name: 'login_attempts', type: 'int', default: 0, nullable: true })\n  loginAttempts: number;\n  @Column({ name: 'lock_until', type: 'bigint', default: 0, nullable: true })\n  lockUntil: number;\n\n  //Many-to-many relation with role\n  @ManyToMany((type) => Role, {\n    cascade: true,\n  })\n  @JoinTable({\n    name: \"users_roles\",\n    joinColumn: { name: \"userId\", referencedColumnName: \"id\" },\n    inverseJoinColumn: { name: \"roleId\" }\n  })\n  roles: Role[];\n}\n```\n\n```text\n@Entity()\nexport class Role {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ type: 'varchar', nullable: false, unique: true })\n  profile: string;\n\n  @Column({ type: 'varchar', nullable: false })\n  description: string;\n\n  //Many-to-many relation with user\n  @ManyToMany((type) => User, (user) => user.roles)\n  users: User[];\n  @CreateDateColumn({ name: 'created_at' })\n  createdAt: Date;\n\n  @UpdateDateColumn({ name: 'updated_at' })\n  updatedAt: Date;\n}\n```\n\n```text\nlet entity = await this.userRepository.create(data); //here you create new dataobject that contain user columns \n\n  let entity2 = { ...entity, roles: data.selectedRoles } // you have to add the association roles here \n\n  const user = await this.userRepository.save(entity2);\n```\n\n========================================\n\nComments:\n- Thank you so much for your answer in the midst of busy. I got a hint from the answer and solved it with the code below It doesn't matter though it looks like a shortcut. await getConnection() .createQueryBuilder() .relation(Book, \"users\") .of(bookBpc) .add(userdata);","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":324,"estimatedTokens":1787}}973{"id":"stack-62958969","source":"stackoverflow","questionId":62958969,"title":"Circular dependency between modules in nestjs","tags":["node.js","module","nestjs","circular-dependency"],"text":"Title: Circular dependency between modules in nestjs\nTags: node.js, module, nestjs, circular-dependency\nSource: Stack Overflow\n\nQuestion:\nThe official doc is not clear about how modules in nestjs work and I'm having a problem with a circular dependency. It seems like my module structure is messed up I would like to understand what is wrong with it. The error I'm getting reads:\n\nNest cannot create the module instance. Often, this is because of a\ncircular dependency between modules. Use forwardRef() to avoid it.\n(Read more: https://docs.nestjs.com/fundamentals/circular-dependency)\nScope [**AppModule** -> **UsersModule** -> **CategoriesModule**]\n\nHere are the import parts of all the modules mentioned in the error message.\n\n**AppModule:**\n\n```\nUsersModule,\nSmsRegistrationModule,\nAuthModule,\nSubscriptionModule,\nEmailModule,\nEntriesModule,\nCategoriesModule,\nAwsModule,\nSharedModule\n```\n\n**UsersModule:**\n\n```\nCategoriesModule\n```\n\n**CategoriesModule:**\n\n```\nAwsModule,\nSharedModule,\n```\n\nThe error raised when I added `SharedModule` to the `CategoriesModule` module. Seems like I'm missing something on how these modules communicate and thus can't resolve this error.\n\nYour help would be much apprecicted.\n\nEDIT:\n\n**SharedModule:**\n\n```\n@Module({\n providers: [\n CacheService,\n CodeGenService,\n IsUniqueEmail,\n BasicFileService,\n ],\n imports: [\n CacheModule.registerAsync({\n imports: [ConfigModule],\n useClass: CacheConfigService,\n }),\n UsersModule,\n AwsModule,\n ],\n exports: [\n CacheService,\n CodeGenService,\n IsUniqueEmail,\n BasicFileService,\n ],\n})\nexport class SharedModule {}\n```\n\n========================================\n\nCode:\n```text\nUsersModule,\nSmsRegistrationModule,\nAuthModule,\nSubscriptionModule,\nEmailModule,\nEntriesModule,\nCategoriesModule,\nAwsModule,\nSharedModule\n```\n\n```text\nCategoriesModule\n```\n\n```text\nAwsModule,\nSharedModule,\n```\n\n```text\n@Module({\n  providers: [\n    CacheService,\n    CodeGenService,\n    IsUniqueEmail,\n    BasicFileService,\n  ],\n  imports: [\n    CacheModule.registerAsync({\n      imports: [ConfigModule],\n      useClass: CacheConfigService,\n    }),\n    UsersModule,\n    AwsModule,\n  ],\n  exports: [\n    CacheService,\n    CodeGenService,\n    IsUniqueEmail,\n    BasicFileService,\n  ],\n})\nexport class SharedModule {}\n```\n\n```text\nSharedModule\n```\n\n```text\nCategoriesModule\n```\n\n```text\nSharedModule\n```\n\n```text\nUserModule\n```\n\n```text\nAppModule -> UsersModule -> CategoriesModule -> SharedModule -> UsersModule -> CategoriesMOdule -> SharedModule -> ...\n```\n\n```text\nSharedModule\n```\n\n```text\nUsersModule\n```\n\n```text\nCategoriesModule\n```\n\n```text\nUserModule\n```\n\n```text\nUserModule\n```\n\n```text\nSharedModule\n```\n\n```text\nSharedModule\n```\n\n```text\nCategoriesModule\n```\n\n```text\nforwardRef\n```\n\n========================================\n\nComments:\n- There isn't enough here to know why you might have a circular dependency. What does `SharedModule` have in terms of import modules?\n- @JayMcDoniel I've just added info on `SharedModule`, please, have a look.\n- Well seems like I'll look into it more closely a tad later to figure out what led to this mess, for now I've found the way to exclude `UserModule` from `SharedModule` and it worked, thank you a lot for helping me!","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":187,"estimatedTokens":804}}974{"id":"stack-69708256","source":"stackoverflow","questionId":69708256,"title":"HTTP Pino logger and Elastic Common Schema (ecs) format in NestJS","tags":["node.js","nestjs","elk","pinojs","elastic-common-schema"],"text":"Title: HTTP Pino logger and Elastic Common Schema (ecs) format in NestJS\nTags: node.js, nestjs, elk, pinojs, elastic-common-schema\nSource: Stack Overflow\n\nQuestion:\nI am trying to apply @elastic/ecs-pino-format to nestjs-pino. Under the good nestjs-pino is using `http-pino`. I have noticed that `http-pino` adds the request object inside `[Symbol(pino.chindings)]` and I am assuming it's using a child logger.So I tried to write a custom formatter for extracting the req by calling `obj.res.log.bindings()` and putting at `http.request` to be compliant with **Elastic Common Schema (ecs)**. The problem I face is now my log contains duplicate the `req` and the `http.request` and can't find a way to remove it. Not sure if I am looking in the wrong direction but I have found a lot of issues trying to make nestjs-pino print **Elastic Common Schema (ecs)** format logs. Also I have noticed issues where @elastic/ecs-pino-format can't handle fastify. Has anyone had similar issues ?\n\n========================================\n\nCode:\n```text\nhttp-pino\n```\n\n```text\nhttp-pino\n```\n\n```text\n[Symbol(pino.chindings)]\n```\n\n```text\nobj.res.log.bindings()\n```\n\n```text\nhttp.request\n```\n\n```text\nreq\n```\n\n```text\nhttp.request\n```\n\n```js\ncustomAttributeKeys: {\nreq: 'http.request',\nres: 'http.response',\n}\n```\n\n```js\nserializers: {\nreq: (log) => {... return transform },\nres: (log) => {... return transform },\n}\n```\n\n```text\npino\n```\n\n```text\npino-http\n```\n\n```text\npino-http\n```\n\n```text\nnestjs-pino\n```\n\n```text\npino-http\n```\n\n```text\npino-http\n```\n\n```text\nreq\n```\n\n```text\nres\n```\n\n```text\nreq\n```\n\n```text\nres\n```\n\n```text\nhttp-pino\n```\n\n```text\nhttp-pino\n```\n\n========================================\n\nComments:\n- Hey Georgios, any chance you could a snippet of how you achieved this? I'm trying to do the exact same thing and it's not immediately obvious how to do so while still getting all the nestjs-pino features.\n- You can create a configuration like this and pass it to nestjs-pino options. gist.github.com/gkampitakis/b36819f38f8886598c20ed1af7245e3a\n- One comment is the Error passed to \"formatError\" should be \"err\" and not \"error\", though I'm not sure if this my setup vs. yours.","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":106,"estimatedTokens":547}}975{"id":"stack-62998727","source":"stackoverflow","questionId":62998727,"title":"NestJs Mailer Module error upon sending email","tags":["nestjs"],"text":"Title: NestJs Mailer Module error upon sending email\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJs Mailer Module, the latest stable version. You can find the documentation here.\n\nI've search a solution for this error but I found nothing:\n\n```\nError: self signed certificate in certificate chain\n```\n\napp.module.ts:\n\n```\n@Module({\n imports: [\n MailerModule.forRoot({\n transport: 'smtps://user@domain.com:pass@smtp.domain.com',\n defaults: {\n from:'\"nest-modules\" ',\n },\n template: {\n dir: __dirname + '/templates',\n adapter: new HandlebarsAdapter(),\n options: {\n strict: true,\n },\n },\n }),\n ],\n})\nexport class AppModule {}\n```\n\nsending the email:\n\n```\nthis.mailerService.sendMail({\n to: 'example@domain.com',\n subject: 'subject'\n text: 'blahblahblah'\n html: 'blahblahblah'\n }).then(() => {\n this.logger.log('Error email sent!', 'HttpExceptionFilter');\n }).catch(err => {\n this.logger.error('Error while sending error email.', err, 'HttpExceptionFilter');\n });\n```\n\n========================================\n\nCode:\n```text\nError: self signed certificate in certificate chain\n```\n\n```js\n@Module({\n  imports: [\n    MailerModule.forRoot({\n      transport: 'smtps://user@domain.com:pass@smtp.domain.com',\n      defaults: {\n        from:'\"nest-modules\" <modules@nestjs.com>',\n      },\n      template: {\n        dir: __dirname + '/templates',\n        adapter: new HandlebarsAdapter(),\n        options: {\n          strict: true,\n        },\n      },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```js\nthis.mailerService.sendMail({\n            to: 'example@domain.com',\n            subject: 'subject'\n            text: 'blahblahblah'\n            html: 'blahblahblah'\n        }).then(() => {\n            this.logger.log('Error email sent!', 'HttpExceptionFilter');\n        }).catch(err => {\n            this.logger.error('Error while sending error email.', err, 'HttpExceptionFilter');\n        });\n```\n\n```text\ntls: { rejectUnauthorized: false }\n```\n\n========================================\n\nComments:\n- Do you have a SSL vert installed on `domain.com`?\n- I do have a SSL certification but it's not self signed\n- If I add this in my transport:`tls: { rejectUnauthorized: false }` It does work, but I would like to know the consequences of having that feature turn off.","metadata":{"transformedAt":"2026-08-18T18:33:02.481Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":102,"estimatedTokens":569}}976{"id":"stack-54828220","source":"stackoverflow","questionId":54828220,"title":"Rxjs in nestjs - Observable subscription error","tags":["node.js","rxjs","observable","nestjs","behaviorsubject"],"text":"Title: Rxjs in nestjs - Observable subscription error\nTags: node.js, rxjs, observable, nestjs, behaviorsubject\nSource: Stack Overflow\n\nQuestion:\nI am newbie trying out rxjs and nestjs. The use case that I am currently trying to accomplish is for educational purpose. So I wanted to read a json file (throw an observable error in case of the file being empty or cannot be read) using the \"fs\" module. Now I create an observable by reading the file asynchronously, set the observer in the subject and then subscribe to the subject in the **controller**. Here is my code in the service\n\n```\n@Injectable()\nexport class NewProviderService {\n private serviceSubject: BehaviorSubject;\n // this is the variable that should be exposed. make the subject as private\n // this allows the service to be the sole propertier to modify the stream and\n // not the controller or components\n serviceSubject$: Observable;\n\n private serviceErrorSubject: BehaviorSubject;\n serviceErrorSubject$: Observable;\n filePath: string;\n httpResponseObjectArray: HttpResponseModel[];\n constructor() {\n this.serviceSubject = new BehaviorSubject([]);\n this.serviceSubject$ = this.serviceSubject.asObservable();\n\n this.serviceErrorSubject = new BehaviorSubject(null);\n this.serviceErrorSubject$ = this.serviceErrorSubject.asObservable();\n\n this.filePath = path.resolve(__dirname, './../../shared/assets/httpTest.json');\n }\n readFileFromJson() {\n return new Promise((resolve, reject) => {\n fs.exists(this.filePath.toString(), exists => {\n if (exists) {\n fs.readFile(this.filePath.toString(), 'utf-8' , (err, data) => {\n if (err) {\n logger.info('error in reading file', err);\n return reject('Error in reading the file' + err.message);\n }\n\n logger.info('file read without parsing fg', data.length);\n if ((data.length !== 0) && !isNullOrUndefined(data) && data !== null) {\n // this.httpResponseObjectArray = JSON.parse(data).HttpTestResponse;\n // logger.info('array obj is:', this.httpResponseObjectArray);\n logger.info('file read after parsing new', JSON.parse(data));\n return resolve(JSON.parse(data).HttpTestResponse);\n } else {\n return reject(new FileExceptionHandler('no data in file'));\n }\n });\n } else {\n return reject(new FileExceptionHandler('file cannot be read at the moment'));\n }\n });\n });\n }\n\n getData() {\n from(this.readFileFromJson()).pipe(map(data => {\n logger.info('data in obs', data);\n this.httpResponseObjectArray = data as HttpResponseModel[];\n return this.httpResponseObjectArray;\n }), catchError(error => {\n return Observable.throw(error);\n }))\n .subscribe(actualData => {\n this.serviceSubject.next(actualData);\n }, err => {\n logger.info('err in sub', typeof err, err);\n this.serviceErrorSubject.next(err);\n });\n }\n```\n\nNow this is the controller class\n\n```\n@Get('/getJsonData')\npublic async getJsonData(@Req() requestAnimationFrame,@Req() req, @Res() res) {\n\n await this.newService.getData();\n this.newService.serviceSubject$.subscribe(data => {\n logger.info('data subscribed', data, _.isEmpty(data));\n if (!isNullOrUndefined(data) && !_.isEmpty(data)) {\n logger.info('coming in');\n res.status(HttpStatus.OK).send(data);\n res.end();\n }\n });\n}\n```\n\nThe problem I face is that I can get the file details for the first time and the subscription is getting called once > its working fine. On the subsequent requests\n\n```\nError [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client\n at ServerResponse.setHeader (_http_outgoing.js:470:11)\n at ServerResponse.header (C:\\personal\\Node\\test-nest.js\\prj-sample\\node_modules\\express\\lib\\response.js:767:10)\n at Ser\n```\n\nand the endpoint /getJsonData results in an error. Could someone help me out. i believe the subscription is not getting properly after the first call, but not sure how to end that and how to resolve that\n\n========================================\n\nTop Answer:\nI would recommend to return the `Promise` directly to the controller. Here, you don't need an `Observable`. For the subscribers, you additionally emit the value of the `Promise` to your `serviceSubject`.\n\n```\nasync getData() {\n try {\n const data = await this.readFileFromJson();\n this.serviceSubject.next(data as HttpResponseModel[]);\n return data;\n } catch (error) {\n // handle error\n }\n}\n```\n\nIn your controller you can just return the `Promise`:\n\n```\n@Get('/getJsonData')\npublic async getJsonData() {\n return this.newService.getData();\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class NewProviderService {\n    private serviceSubject: BehaviorSubject<HttpResponseModel[]>;\n    // this is the variable that should be exposed. make the subject as private\n    // this allows the service to be the sole propertier to modify the stream and\n    // not the controller or components\n    serviceSubject$:  Observable<HttpResponseModel[]>;\n\n    private serviceErrorSubject: BehaviorSubject<any>;\n    serviceErrorSubject$: Observable<any>;\n    filePath: string;\n    httpResponseObjectArray: HttpResponseModel[];\n    constructor() {\n        this.serviceSubject = new BehaviorSubject<HttpResponseModel[]>([]);\n        this.serviceSubject$ = this.serviceSubject.asObservable();\n\n        this.serviceErrorSubject = new BehaviorSubject<any>(null);\n        this.serviceErrorSubject$ = this.serviceErrorSubject.asObservable();\n\n        this.filePath = path.resolve(__dirname, './../../shared/assets/httpTest.json');\n    }\n     readFileFromJson() {\n          return new Promise((resolve, reject) => {\n            fs.exists(this.filePath.toString(), exists => {\n                if (exists) {\n                    fs.readFile(this.filePath.toString(), 'utf-8' , (err, data) => {\n                        if (err) {\n                            logger.info('error in reading file', err);\n                            return reject('Error in reading the file' + err.message);\n                        }\n\n                        logger.info('file read without parsing fg', data.length);\n                        if ((data.length !== 0) && !isNullOrUndefined(data) && data !== null) {\n                            // this.httpResponseObjectArray = JSON.parse(data).HttpTestResponse;\n                            // logger.info('array obj is:', this.httpResponseObjectArray);\n                            logger.info('file read after parsing new', JSON.parse(data));\n                            return resolve(JSON.parse(data).HttpTestResponse);\n                        } else {\n                            return reject(new FileExceptionHandler('no data in file'));\n                        }\n                    });\n                } else {\n                    return reject(new FileExceptionHandler('file cannot be read at the moment'));\n                }\n            });\n          });\n    }\n\n\n        getData() {\n                 from(this.readFileFromJson()).pipe(map(data => {\n                        logger.info('data in obs', data);\n                        this.httpResponseObjectArray = data as HttpResponseModel[];\n                        return this.httpResponseObjectArray;\n                 }), catchError(error => {\n                     return Observable.throw(error);\n                 }))\n                 .subscribe(actualData => {\n                    this.serviceSubject.next(actualData);\n                }, err => {\n                    logger.info('err in sub', typeof err, err);\n                    this.serviceErrorSubject.next(err);\n                });\n            }\n```\n\n```text\n@Get('/getJsonData')\npublic async getJsonData(@Req() requestAnimationFrame,@Req() req, @Res() res) {\n\n  await this.newService.getData();\n  this.newService.serviceSubject$.subscribe(data => {\n    logger.info('data subscribed', data, _.isEmpty(data));\n    if (!isNullOrUndefined(data) && !_.isEmpty(data)) {\n      logger.info('coming in');\n      res.status(HttpStatus.OK).send(data);\n      res.end();\n    }\n  });\n}\n```\n\n```text\nError [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client\n    at ServerResponse.setHeader (_http_outgoing.js:470:11)\n    at ServerResponse.header (C:\\personal\\Node\\test-nest.js\\prj-sample\\node_modules\\express\\lib\\response.js:767:10)\n    at Ser\n```\n\n```text\n@Get('/getJsonData')\npublic async getJsonData() {\n  await this.newService.getData();\n  return this.newService.serviceSubject$.pipe(first())\n}\n```\n\n```text\nprivate serviceSubject: BehaviorSubject<HttpResponseModel[]>;\nget serviceSubject$(): Observable<HttpResponseModel[]> {\n   return this.serviceSubject;\n}\n```\n\n```text\nserviceSubject\n```\n\n```text\nfirst()\n```\n\n```text\nObservable\n```\n\n```text\nBehaviourSubject\n```\n\n```text\nSubject\n```\n\n```text\nObservable\n```\n\n```text\nSubject\n```\n\n```text\nObservable\n```\n\n```text\nnext()\n```\n\n```text\nasync getData() {\n  try {\n    const data = await this.readFileFromJson();\n    this.serviceSubject.next(data as HttpResponseModel[]);\n    return data;\n  } catch (error) {\n    // handle error\n  }\n}\n```\n\n```text\n@Get('/getJsonData')\npublic async getJsonData() {\n  return this.newService.getData();\n}\n```\n\n```text\nPromise\n```\n\n```text\nObservable\n```\n\n```text\nPromise\n```\n\n```text\nserviceSubject\n```\n\n```text\nPromise\n```\n\n```text\ngetData() {\n        return from(this.readFileFromJson()).pipe(map(data => {\n                logger.info('data in obs', data);\n                this.httpResponseObjectArray = data as HttpResponseModel[];\n                return this.httpResponseObjectArray;\n         }), publishLast(), refCount()\n          , catchError(error => {\n             return Observable.throw(error);\n         }));\n        //  .subscribe(actualData => {\n        //     this.serviceSubject.next(actualData);\n        // }, err => {\n        //     logger.info('err in sub', typeof err, err);\n        //     this.serviceErrorSubject.next(err);\n        // });\n    }\n```\n\n```text\npublic async getJsonData(@Req() req, @Res() res) {\n    let jsonData: HttpResponseModel[];\n    await this.newService.getData().subscribe(data => {\n      logger.info('dddd', data);\n      res.send(data);\n    });\n}\n```\n\n========================================\n\nComments:\n- Is there a reason why you don't return your `Observable` directly from `getData()` but instead subscribe to `serviceSubject$`? Also, you don't need to work with `@Req` and `@Res` in your controller. Remove those parameters and return the `Observable` directly. Nest.js will handle the subscription.\n- the actual implementation will have to have a subject capable of returning the latest updated data and seems Behaviorsubject satisfies it. Also the suggestions seem not to make the subject available to the subscribers (the controllers) and hence made use of a variable\n- I also wanted to learn the response in handling the data emitted by the observable. So is nestjs auto handling the response closure once an observable is emitted? Not sure why it fails the above test case. I would give it a try by returning the observable directly, but wanted to know the reason for failure\n- Auto handling: \"Nest will automatically subscribe to the source underneath and take the last emitted value (once the stream is completed).\" I'll have a look at your code in more detail later.\n- @KimKern Thank you so much. Also I wanted to know if nestjs will handle this or is it something that is isloated to AxiosResponse type. The observable that I am producing is not an axiosresponse but a plain old observable. So wanted to know if by default, nestjs tries to subscribe to the observable and produce a response and on the other hand , I manually try the same and that results in an error?\n- I think the problem is that you subscribe to the Observable to send the response but then you don't unsubscribe so it will try to send the response again when the next value is emitted. But since the response has already been sent you get the error\n- Nest would probably never send the response because your observable does not complete. I haven't tried it though\n- HI @KimKern I get an error while changing the method in the service from returning an observable to a promise. Argument of type '{}' is not assignable to parameter of type 'HttpResponseModel[]'. Type '{}' is missing the following properties from type 'HttpResponseModel[]': length, pop, push, concat, and 26 more.t\n- Also since it for purely educational purpose, I was wondering what it might take for the observable to be properly emitted. Just curious , wanted to know what actually should be done to close the emission on time and start a new subscription\n- I also see that Observables have a lot more advantages over promise and hence persisting on trying to use that. Is there a way that I could convert it to an Observable> instead of an observable , so that way when I return it, nestjs might automatically handle the response. and subscription closure?\n- The type error occurs because `readFileFromJson()` is not typed. See my edit, I've included a cast.\n- Yes, I also think rxjs is a great library. In your example, using an `Observable` just doesn't make much sense (at least for the controller) because it makes things unnecessarily complicated. But of course I understand the playing around aspect to get to know the library. :) I've added another answer that works with `Observables`, have a look.\n- I don't see how nest would handle an `AxiosResponse` differently than any other object. As far as I know, `AxiosResponse` is the return type when you make an http request with the `HttpModule`, but I'm not aware of any special handling by the nestjs controller.","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":356,"estimatedTokens":3359}}977{"id":"stack-67118563","source":"stackoverflow","questionId":67118563,"title":"How can I pass REDIS_URI for NestJS cache manager?","tags":["heroku","caching","redis","nestjs"],"text":"Title: How can I pass REDIS_URI for NestJS cache manager?\nTags: heroku, caching, redis, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn the official documentation this is the correct way to use the cache manager with Redis:\n\n```\nimport * as redisStore from 'cache-manager-redis-store';\nimport { CacheModule, Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\n\n@Module({\n imports: [\n CacheModule.register({\n store: redisStore,\n host: 'localhost',\n port: 6379,\n }),\n ],\n controllers: [AppController],\n})\nexport class AppModule {}\n```\n\nSource: https://docs.nestjs.com/techniques/caching#different-stores\n\nHowever, I did not find any documentation on how to pass Redis instance data using REDIS_URI. I need to use it with Heroku and I believe this is a common use case.\n\n========================================\n\nCode:\n```text\nimport * as redisStore from 'cache-manager-redis-store';\nimport { CacheModule, Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\n\n@Module({\n  imports: [\n    CacheModule.register({\n      store: redisStore,\n      host: 'localhost',\n      port: 6379,\n    }),\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```js\nCacheModule.register({\n  store: redisStore,\n  url: 'redis://localhost:6379'\n})\n```\n\n```text\nCacheModule.register\n```\n\n```text\nRedis#createClient\n```\n\n```text\nredis\n```\n\n```text\n{ store: redisStore, url: '...' }\n```\n\n```text\noptions\n```\n\n```text\nCacheModule.register\n```\n\n```text\noptions\n```\n\n```text\nCACHE_MODULE_OPTIONS\n```\n\n```text\noptions\n```\n\n```text\ncacheManager.caching\n```\n\n```text\ncacheManager\n```\n\n```text\ncache-manager\n```\n\n```text\ncacheManager.caching\n```\n\n```text\noptions\n```\n\n```text\nargs\n```\n\n```text\noptions.store\n```\n\n```text\nredisStore\n```\n\n```text\ncache-manager-redis-store\n```\n\n```text\nargs.store.create\n```\n\n```text\nredisStore.create\n```\n\n```text\nargs.store.create(args)\n```\n\n```text\nredisStore.create(options)\n```\n\n```text\nRedis.createClient passing this options\n```\n\n========================================\n\nComments:\n- looks like you have already found that limitation in `cache-manager-redis-store` package :p github.com/dabroek/node-cache-manager-redis-store/pull/&hellip;\n- Nice, this solves it for me.","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":154,"estimatedTokens":561}}978{"id":"stack-77173918","source":"stackoverflow","questionId":77173918,"title":"How to serve static files on nestjs?","tags":["javascript","express","nestjs"],"text":"Title: How to serve static files on nestjs?\nTags: javascript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a nestjs project, in the root of the site there is an uploads folder, there are files of different extensions there. How should I process them?\n\nhttp://localhost:7777/uploads/audio/85/0.mp3\nhttp://localhost:7777/uploads/movie/85/0.mp4\n\nWhen I do this I get an error:\n\n{\n\"statusCode\": 404,\n\"message\": \"ENOENT: no such file or directory, stat 'G:\\myproject\\uploads\\index.html'\"\n}\n\nIn App.module I did everything as in the nest documentation:\n\n```\nimport { ServeStaticModule } from '@nestjs/serve-static';\nimport { join } from 'path';\n\n@Module({\n imports: [\n ServeStaticModule.forRoot({\n rootPath: join(__dirname, '../../../', 'uploads'),\n }),\n UsersModule\n```\n\nMain.ts\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './App/app.module';\nimport { ConfigService } from '@nestjs/config';\nimport { ValidationPipe } from '@nestjs/common';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const configService = app.get(ConfigService);\n const port = configService.get('PORT'); \n app.enableCors();\n app.useGlobalPipes(new ValidationPipe()); \n await app.listen(port);\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nimport { ServeStaticModule } from '@nestjs/serve-static';\nimport { join } from 'path';\n\n\n@Module({\n   imports: [\n     ServeStaticModule.forRoot({\n       rootPath: join(__dirname, '../../../', 'uploads'),\n     }),\n     UsersModule\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './App/app.module';\nimport { ConfigService } from '@nestjs/config';\nimport { ValidationPipe } from '@nestjs/common';\n\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const configService = app.get(ConfigService);\n  const port = configService.get('PORT'); \n  app.enableCors();\n  app.useGlobalPipes(new ValidationPipe()); \n  await app.listen(port);\n}\nbootstrap();\n```\n\n```text\n@Module({\n  imports: [\n    ServeStaticModule.forRoot({\n      rootPath: join(__dirname, '..', '..', 'uploads'),\n      // Tell NestJS to serve the files under ~/uploads/\n      serveRoot: '/uploads/',\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nServeStaticModule.forRootAsync({\n      useFactory: () => {\n        const uploadsPath = join(__dirname, '..', '..', '..', 'uploads');\n        return [\n          {\n            rootPath: uploadsPath,\n            serveRoot: '/uploads/',\n          },\n        ];\n      },\n    }),\n```\n\n```text\nuploads\n```\n\n```text\nuploads\n```\n\n```text\nuploads\n```\n\n```text\nuploads\n```\n\n```text\ndist\n```\n\n```text\n..\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- Unfortunately, this didn't help. UPD link link\n- Are you sure you need two `..` in there? If `AppModule.ts` is directly under `src` not in a child filder, and `uploads` and `src` are both directly under `myproject`, then you need only one `..`\n- Here's how I wrote it - prnt.sc/fHFAE1GIVpv3\n- Yeah, looks like it might work with `join(__dirname, '..', 'uploads'),` -- that's a single `'..'` instead of 2.\n- It doesn't work with just one colon either. `rootPath: join(__dirname, '..', 'uploads') = error` `rootPath: join(__dirname, '.', 'uploads') = error` `rootPath: join(__dirname, 'uploads') = error` I've already tried everything I can, I can't understand why nothing works.\n- I updated my answer with the one `'..'` -- can you please show me the error in this case? Thanks.\n- prnt.sc/FhFmlUIy2WWY\n- Update screen - prnt.sc/E4KlQyzxp7Ve\n- Oh. Now that I see that `app.module.ts` is not directly under `src` but `src&#47;app` instead, your two `..` are actually correct. I assume you tried restarting the server? Also, do you have a global prefix like `app.setGlobalPrefix('api')`?\n- No, I didnโ€™t use the global prefix app.setGlobalPrefix Can you tell me how to register it correctly in my case?\n- I read about app.setGlobalPrefix and understood what it is for now, which means there is no need to register it. I didnโ€™t write it down))\n- I updated the topic, added the main.ts code\n- Are you saying that the answer works after your suggested edit? or were you meaning to edit your own question? Forgive me if it's a dumb question!\n- No, it does not work. I just added some extra code from my project. main.ts to show that I did not use app.setGlobalPrefix ))) Forgive me, I don't speak English well)\n- My repo - github.com/xonarin/youtube/tree/dev\n- Thanks a lot. I did some debugging for you and I think I found the issue. It's looking for uploads folder under dist not under the app itself. At least this is what I get when I start the app with npm run start. See this pic i.sstatic.net/RXV2z.png\n- Yes you are right. It actually looks for data in dist/uploads. prnt.sc/uPzNovDH5JSG Thanks, now I think I can solve this problem myself. THANK YOU SO MUCH FOR YOUR HELP!\n- Check my updated answer. I got it working and tested it!\n- For the production version it won't hurt you that it's in the `dist` folder, but it's probably a good idea to load it from the `env` file using the config service (I omitted this for simplicity). You can do this easily in the factory, just inject the config service into it.\n- Thank you so much, you saved me)) I wish you all the best, and most importantly health!)","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":162,"estimatedTokens":1339}}979{"id":"stack-68971749","source":"stackoverflow","questionId":68971749,"title":"Nest server not connecting to MongoDB cloud UnhandledPromiseRejectionWarning: MongoParseError: URI malformed","tags":["node.js","mongodb","mongoose","nestjs"],"text":"Title: Nest server not connecting to MongoDB cloud UnhandledPromiseRejectionWarning: MongoParseError: URI malformed\nTags: node.js, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy NestJS backend needs to connect to the mongodb cloud, I followed the docs from here\n\nThe following error threw up in the terminal:\n\n```\n(node:6920) UnhandledPromiseRejectionWarning: MongoParseError: URI malformed\n at new ConnectionString (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongodb-connection-string-url\\src\\index.ts:113:13)\n at Object.parseOptions (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongodb\\src\\connection_string.ts:249:15)\n at new MongoClient (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongodb\\src\\mongo_client.ts:332:22)\n at D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongoose\\lib\\connection.js:785:16\n at new Promise ()\n at NativeConnection.Connection.openUri (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongoose\\lib\\connection.js:782:19)\n at Mongoose.createConnection (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongoose\\lib\\index.js:275:10)\n at Function. (D:\\growth\\quizbackend\\quizbackend\\node_modules\\@nestjs\\mongoose\\dist\\mongoose-core.module.js:60:63)\n at Generator.next ()\n at D:\\growth\\quizbackend\\quizbackend\\node_modules\\@nestjs\\mongoose\\dist\\mongoose-core.module.js:20:71\n(Use `node --trace-warnings ...` to show where the warning was created)\n(node:6920) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)\n(node:6920) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, \npromise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nMy app module code:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UsersModule } from './users/users.module';\nimport {MongooseModule} from '@nestjs/mongoose'\n@Module({\n imports: [UsersModule,MongooseModule.forRoot('mongodb+srv://icfoajscijwq90j@cluster0.8rxa2.mongodb.net/nest-js-db?retryWrites=true&w=majority')],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nI doubled check my username and password but they are correct, is there any need for encoding them or why the error is throwing up any explanation would be appreciated.\n\n========================================\n\nCode:\n```text\n(node:6920) UnhandledPromiseRejectionWarning: MongoParseError: URI malformed\n    at new ConnectionString (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongodb-connection-string-url\\src\\index.ts:113:13)\n    at Object.parseOptions (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongodb\\src\\connection_string.ts:249:15)\n    at new MongoClient (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongodb\\src\\mongo_client.ts:332:22)\n    at D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongoose\\lib\\connection.js:785:16\n    at new Promise (<anonymous>)\n    at NativeConnection.Connection.openUri (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongoose\\lib\\connection.js:782:19)\n    at Mongoose.createConnection (D:\\growth\\quizbackend\\quizbackend\\node_modules\\mongoose\\lib\\index.js:275:10)\n    at Function.<anonymous> (D:\\growth\\quizbackend\\quizbackend\\node_modules\\@nestjs\\mongoose\\dist\\mongoose-core.module.js:60:63)\n    at Generator.next (<anonymous>)\n    at D:\\growth\\quizbackend\\quizbackend\\node_modules\\@nestjs\\mongoose\\dist\\mongoose-core.module.js:20:71\n(Use `node --trace-warnings ...` to show where the warning was created)\n(node:6920) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)\n(node:6920) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, \npromise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UsersModule } from './users/users.module';\nimport {MongooseModule} from '@nestjs/mongoose'\n@Module({\n  imports: [UsersModule,MongooseModule.forRoot('mongodb+srv://icfoajscijwq90j@cluster0.8rxa2.mongodb.net/nest-js-db?retryWrites=true&w=majority')],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n: / ? # [ ] @\n```\n\n========================================\n\nComments:\n- I suggest you to remove the connection string from the question. Anyone can connect to your database with it. You should change your creds.\n- @NenadMilosavljevic Thank you for your concern, Yes I will change the creds once the issue is resolved\n- @SamiurKhan Did you tried to change your password to something without special characters?\n- @LarsFlieger The issue was resolved once I changed the password without any special characters\n- @SamiurKhan Great. I found the part in their documentation. There you can see which characters are allowed and how to deal with illegal ones. I added it as an answer for everyone :)\n- thanks the issue is resolved, how do I close the question\n- You're welcome. You do not have to do anything nor close the question. If you marked an answer it's \"closed\"","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":94,"estimatedTokens":1475}}980{"id":"stack-59727358","source":"stackoverflow","questionId":59727358,"title":"Typeorm don't use ormconfig.json file","tags":["nestjs","typeorm"],"text":"Title: Typeorm don't use ormconfig.json file\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\ni'am configuring nestjs ormconfig.json but typeorm don't connect to mysql 8 database, it display this in cli\n\n```\n[Nest] 13324 - 2020-01-14 4:15:32 [NestFactory] Starting Nest application...\n[Nest] 13324 - 2020-01-14 4:15:32 [InstanceLoader] AppModule dependencies initialized +513ms\n[Nest] 13324 - 2020-01-14 4:15:32 [InstanceLoader] TypeOrmModule dependencies initialized +5ms\n[Nest] 13324 - 2020-01-14 4:15:36 [TypeOrmModule] Unable to connect to the database. Retrying (1)... +4061ms\nError: Cannot find module 'src/user/user.entity'\nRequire stack:\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\platform\\PlatformTools.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\driver\\sqlserver\\SqlServerDriver.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\migration\\MigrationExecutor.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\Connection.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\ConnectionManager.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.utils.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.decorators.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\app.module.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\main.ts\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)\n at Function.Module._load (internal/modules/cjs/loader.js:690:27)\n at Module.require (internal/modules/cjs/loader.js:852:19)\n at require (internal/modules/cjs/helpers.js:74:18)\n at Object. (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts:3:1)\n at Module._compile (internal/modules/cjs/loader.js:959:30)\n at Module.m._compile (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:806:23)\n at Module._extensions..js (internal/modules/cjs/loader.js:995:10)\n at Object.require.extensions. [as .ts] (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:809:12)\n at Module.load (internal/modules/cjs/loader.js:815:32)\n```\n\nall entities are in src folder but the console still say the're not\n\nand this is my code\n\n```\napp.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n ],\n})\nexport class AppModule {}\n```\n\normconfig.json\n\n```\n{\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"admin\",\n \"password\": \"\",\n \"database\": \"kissing_db\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\n \"src/**/*.entity.ts\",\n \"dist/**/*.entity.js\"\n ],\n \"migrationsTableName\": \"migration\",\n \"migrations\": [\n \"src/migration/*.ts\"\n ],\n \"cli\": {\n \"migrationsDir\": \"./src/migration\"\n },\n \"ssl\": false\n}\n```\n\nI don't post it with password for security reason hope you'll understand.\n\n========================================\n\nTop Answer:\nI think i've found a solution i've just create a `ormconfig.js` withouth `entities` field like this \n\n```\nmodule.exports = {\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"admin\",\n \"password\": \"\",\n \"database\": \"kissing_db\",\n \"synchronize\": true,\n \"logging\": true,\n};\n```\n\nand edit my `package.json` start scripts with `ts-node`, it seem like ts-node automatically find entity files.\n\n========================================\n\nCode:\n```text\n[Nest] 13324   - 2020-01-14 4:15:32   [NestFactory] Starting Nest application...\n[Nest] 13324   - 2020-01-14 4:15:32   [InstanceLoader] AppModule dependencies initialized +513ms\n[Nest] 13324   - 2020-01-14 4:15:32   [InstanceLoader] TypeOrmModule dependencies initialized +5ms\n[Nest] 13324   - 2020-01-14 4:15:36   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +4061ms\nError: Cannot find module 'src/user/user.entity'\nRequire stack:\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\platform\\PlatformTools.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\driver\\sqlserver\\SqlServerDriver.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\migration\\MigrationExecutor.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\Connection.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\ConnectionManager.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.utils.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.decorators.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\app.module.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\main.ts\n    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)\n    at Function.Module._load (internal/modules/cjs/loader.js:690:27)\n    at Module.require (internal/modules/cjs/loader.js:852:19)\n    at require (internal/modules/cjs/helpers.js:74:18)\n    at Object.<anonymous> (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts:3:1)\n    at Module._compile (internal/modules/cjs/loader.js:959:30)\n    at Module.m._compile (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:806:23)\n    at Module._extensions..js (internal/modules/cjs/loader.js:995:10)\n    at Object.require.extensions.<computed> [as .ts] (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:809:12)\n    at Module.load (internal/modules/cjs/loader.js:815:32)\n```\n\n```text\napp.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n      TypeOrmModule.forRoot(),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n{\n  \"type\": \"mysql\",\n  \"host\": \"localhost\",\n  \"port\": 3306,\n  \"username\": \"admin\",\n  \"password\": \"\",\n  \"database\": \"kissing_db\",\n  \"synchronize\": true,\n  \"logging\": true,\n  \"entities\": [\n    \"src/**/*.entity.ts\",\n    \"dist/**/*.entity.js\"\n  ],\n  \"migrationsTableName\": \"migration\",\n  \"migrations\": [\n    \"src/migration/*.ts\"\n  ],\n  \"cli\": {\n    \"migrationsDir\": \"./src/migration\"\n  },\n  \"ssl\": false\n}\n```\n\n```text\n.ts\n```\n\n```text\nsrc\n```\n\n```text\n.js\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\ndist/src/user/user.entity\n```\n\n```text\nsrc/**/*.entity.ts\n```\n\n```text\normconfig.json\n```\n\n```text\nmodule.exports = {\n   \"type\": \"mysql\",\n   \"host\": \"localhost\",\n   \"port\": 3306,\n   \"username\": \"admin\",\n   \"password\": \"\",\n   \"database\": \"kissing_db\",\n   \"synchronize\": true,\n   \"logging\": true,\n};\n```\n\n```text\normconfig.js\n```\n\n```text\nentities\n```\n\n```text\npackage.json\n```\n\n```text\nts-node\n```\n\n========================================\n\nComments:\n- but how do i do for development mode?\n- I've change remove the `src&#47;**&#47;*.entity.ts` from my `ormconfig.json` file but i still have this error in cli `Entity metadata for CaracteristiqueUser#photos was not found. Check if you specified a correct entity object and if it's connected in the connection options`\n- that's my package.json start scripts `\"scripts\": { \"start\": \"tsc-watch -r tsconfig-paths&#47;register src&#47;main.ts\", \"start:dev\": \"nodemon\", \"start:debug\": \"nest start --debug --watch\", \"start:prod\": \"node dist&#47;main\", },`\n- With your `nodemon`, are you also compiling the ts or are you using `ts-node`?\n- i use a nodemon.json file `{ \"watch\": [\"src\"], \"ext\": \"ts\", \"ignore\": [\"src&#47;**&#47;*.spec.ts\"], \"exec\": \"node --inspect=127.0.0.1:9223 -r ts-node&#47;register -- src&#47;main.ts\", \"env\": {} }`\n- Ah, so it is using `ts-node`. I would suggest trying to move towards `tsc-watch` and `tsc` in general as it will make configurations easier. Otherwise, you would need to change the `ormconfig.json` each time you want to move between dev and prod. It's super annoying, I know. The other option is to use `ormconfig.js` instead and use `__dirname` to dynamically change between `dist` and `src`","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":256,"estimatedTokens":2229}}981{"id":"stack-63334701","source":"stackoverflow","questionId":63334701,"title":"Is there way to use Nest JS with Sapper (Svelte)?","tags":["javascript","node.js","nestjs","svelte","sapper"],"text":"Title: Is there way to use Nest JS with Sapper (Svelte)?\nTags: javascript, node.js, nestjs, svelte, sapper\nSource: Stack Overflow\n\nQuestion:\nI've been looking for the past few days, but I haven't found a single sample code or article that discusses how to combine (*not separate them as API Service & Frontend Service*) Nest JS with Sapper (*Svelte*). Does anyone have any references in this regard?\n\n========================================\n\nComments:\n- How do you want to integrate them? You can build and deploy a NestJS API, and consume it from a separate Sapper app. Is that close to what you want?\n- Not. I want to combine the two things in one application or instance.\n- Marcio Koji Carvalho posted an Answer saying \"Nest.js Sapper working example Dirty but working example\"","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":196}}982{"id":"stack-52945342","source":"stackoverflow","questionId":52945342,"title":"MongooseError with uuid when using import instead of require()","tags":["node.js","typescript","mongoose","uuid","nestjs"],"text":"Title: MongooseError with uuid when using import instead of require()\nTags: node.js, typescript, mongoose, uuid, nestjs\nSource: Stack Overflow\n\nQuestion:\nI get the following error :\n\n```\nMongooseError: document must have an _id before saving\n```\n\nWhen I try to create an Object (Campagne) with `uuid` with my API using :\n\n```\nimport uuidv4 from 'uuid/v4';\n```\n\nIt works when I use :\n\n```\nconst uuidv4 = require('uuid/v4');\n```\n\nMy Campagne object is created correctly with its `uuid`.\n\nHere is the full code of my object's Schema :\n\n```\nimport * as mongoose from 'mongoose';\nimport uuidv4 from 'uuid/v4';\n\nexport const CampagneSchema = new mongoose.Schema({\n _id: { type: String, default: uuidv4 },\n dateDebut: Date,\n dateFin: Date,\n reduction: Number,\n});\n```\n\nTSLint tell me to use `import` instead of `require()` and underline it as an error in my IDE but it's definitely not working as shown above.\n\nCan someone explain me why is this happening please ?\n\nFor information, I use the NestJS node.js framework with Typescript.\n\nTo clarify : \n\n**I want to know why `import` is working for `mongoose` but not for `uuid` (`require` is working for `uuid`)**\n\n========================================\n\nTop Answer:\nRemove `_id: { type: String, default: uuidv4 },`\n\nMongoose will automatically generate `_id`\n\nAnd use `const ddd = require(...)`\n\nI believe ES6 modules not working in Node project normally\n\n========================================\n\nCode:\n```text\nMongooseError: document must have an _id before saving\n```\n\n```text\nimport uuidv4 from 'uuid/v4';\n```\n\n```text\nconst uuidv4 = require('uuid/v4');\n```\n\n```text\nimport * as mongoose from 'mongoose';\nimport uuidv4 from 'uuid/v4';\n\nexport const CampagneSchema = new mongoose.Schema({\n    _id: { type: String, default: uuidv4 },\n    dateDebut: Date,\n    dateFin: Date,\n    reduction: Number,\n});\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\nimport\n```\n\n```text\nrequire()\n```\n\n```text\nimport\n```\n\n```text\nmongoose\n```\n\n```text\nuuid\n```\n\n```text\nrequire\n```\n\n```text\nuuid\n```\n\n```text\nimport {v4 as uuid} from 'uuid';\n```\n\n```text\nnode-uuid\n```\n\n```text\nimport uuid from 'uuid/v4';\n```\n\n```text\nTypescript v3\n```\n\n```text\nNode v10.9.0\n```\n\n```text\nts-node\n```\n\n```text\nTypeError: v4_1.uuid is not a function\n```\n\n```text\nimport {v4 as uuid} from 'uuid';\n```\n\n```text\nuuid v3.3.2\n```\n\n```text\n_id: { type: String, default: uuidv4 },\n```\n\n```text\n_id\n```\n\n```text\nconst ddd = require(...)\n```\n\n========================================\n\nComments:\n- But I want to use uuid and not Mongoose id\n- `import` works for other cases than this one in my project (mongoose for example), why do I need to use `require()` for this specific case ?\n- @XavierFr I think that depends on library's modules structure. github.com/kelektiv/node-uuid#readme The library recommend CommonJS way\n- I see. I still don't understand why it doesn't work that way but they say to do it that way in CommonJS so I guess I'll just this. I keep the question open if anyone has answer to why exactly I can't use `import`.","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":178,"estimatedTokens":760}}983{"id":"stack-57155874","source":"stackoverflow","questionId":57155874,"title":"How to mock getMongoRepository in service nestjs","tags":["node.js","mongodb","typescript","nestjs","typeorm"],"text":"Title: How to mock getMongoRepository in service nestjs\nTags: node.js, mongodb, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI write unit test for my service in nestjs. In my function delete i use `getMongoRepository` to delete. But i stuck in write the unit test\n\nI've tried write the mock but it's not work\n\nmy service\n\n```\nasync delete(systemId: string): Promise {\n const systemRepository = getMongoRepository(Systems);\n return await systemRepository.deleteOne({ systemId });\n }\n```\n\nmy mock\n\n```\nimport { Mock } from './mock.type';\nimport { Repository, getMongoRepository } from 'typeorm';\n\n// @ts-ignore\nexport const mockRepositoryFactory: () => Mock> = jest.fn(\n () => ({\n save: jest.fn(Systems => Systems),\n delete: jest.fn(Systems => Systems),\n deleteOne: jest.fn(Systems => Systems),\n }),\n);\n```\n\nmy test\n\n```\nimport { ExternalSystemService } from '../external-system.service';\nimport { Systems } from '../entities/external-system.entity';\n\nmodule = await Test.createTestingModule({\n providers: [\n ExternalSystemService,\n {\n provide: getRepositoryToken(Systems),\n useFactory: mockRepositoryFactory,\n },\n ],\n }).compile();\n\n service = module.get(ExternalSystemService);\n mockRepository = module.get(getRepositoryToken(Systems));\n\n describe('delete', () => {\n it('should delete the system', async () => {\n mockRepository.delete.mockReturnValue(undefined);\n const deletedSystem = await service.delete(systemOne.systemId);\n\n expect(mockRepository.delete).toBeCalledWith({ systemId: systemOne.systemId });\n expect(deletedSystem).toBe(Object);\n });\n```\n\nI got this error\n\nExternalSystemService โ€บ delete โ€บ should not delete the system\n\n```\nConnectionNotFoundError: Connection \"default\" was not found.\n\n at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n at ConnectionManager.Object..ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n at Object.getMongoRepository (index.ts:300:35)\n at Object. (external-system/tests/external-system.service.spec.ts:176:33)\n at external-system/tests/external-system.service.spec.ts:7:71\n at Object..__awaiter (external-system/tests/external-system.service.spec.ts:3:12)\n at Object. (external-system/tests/external-system.service.spec.ts:175:51)\n```\n\n========================================\n\nCode:\n```js\nasync delete(systemId: string): Promise<DeleteWriteOpResultObject> {\n    const systemRepository = getMongoRepository(Systems);\n    return await systemRepository.deleteOne({ systemId });\n  }\n```\n\n```js\nimport { Mock } from './mock.type';\nimport { Repository, getMongoRepository } from 'typeorm';\n\n// @ts-ignore\nexport const mockRepositoryFactory: () => Mock<Repository<any>> = jest.fn(\n  () => ({\n    save: jest.fn(Systems => Systems),\n    delete: jest.fn(Systems => Systems),\n    deleteOne: jest.fn(Systems => Systems),\n  }),\n);\n```\n\n```js\nimport { ExternalSystemService } from '../external-system.service';\nimport { Systems } from '../entities/external-system.entity';\n\nmodule = await Test.createTestingModule({\n      providers: [\n        ExternalSystemService,\n        {\n          provide: getRepositoryToken(Systems),\n          useFactory: mockRepositoryFactory,\n        },\n      ],\n    }).compile();\n\n    service = module.get<ExternalSystemService>(ExternalSystemService);\n    mockRepository = module.get(getRepositoryToken(Systems));\n\n describe('delete', () => {\n    it('should delete the system', async () => {\n      mockRepository.delete.mockReturnValue(undefined);\n      const deletedSystem = await service.delete(systemOne.systemId);\n\n      expect(mockRepository.delete).toBeCalledWith({ systemId: systemOne.systemId });\n      expect(deletedSystem).toBe(Object);\n    });\n```\n\n```text\nConnectionNotFoundError: Connection \"default\" was not found.\n\n  at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n  at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n  at Object.getMongoRepository (index.ts:300:35)\n  at Object.<anonymous> (external-system/tests/external-system.service.spec.ts:176:33)\n  at external-system/tests/external-system.service.spec.ts:7:71\n  at Object.<anonymous>.__awaiter (external-system/tests/external-system.service.spec.ts:3:12)\n  at Object.<anonymous> (external-system/tests/external-system.service.spec.ts:175:51)\n```\n\n```text\ngetMongoRepository\n```\n\n```text\nconstructor(\n  @InjectRepository(Systems)\n  private readonly systemsRepository: MongoRepository<Systems>,\n) {}\n```\n\n```text\nasync delete(systemId: string): Promise<DeleteWriteOpResultObject> {\n  return this.systemsRepository.deleteOne({ systemId });\n}\n```\n\n========================================\n\nComments:\n- But Repository cannot use deleteOne\n- Use the type `MongoRepository` instead: github.com/typeorm/typeorm/blob/master/src/repository/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":164,"estimatedTokens":1199}}984{"id":"stack-76982359","source":"stackoverflow","questionId":76982359,"title":"How to replace deprecated getConnectionManager and getManager?","tags":["nestjs","typeorm"],"text":"Title: How to replace deprecated getConnectionManager and getManager?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS application utilizing TypeORM for database access.\n\nTypeORM has deprecated how `getConnection` and `getConnectionManager` can be used. I need direct access to it for dealing with transactions.\n\nHow to deal with this nowadays?\n\nThe answer at getConnection/getRepository typeorm is deprecated is not helpful and can't be applied on NestJS applications.\n\nMy `app.module.ts` looks like this:\n\n```\nconst connectionOptions: ConnectionOptions = {\n type: 'postgres',\n host: config.host,\n port: config.port,\n username: config.user || 'postgres',\n // ...\n}\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n cache: true,\n load: [configuration],\n }),\n\n TypeOrmModule.forRoot({\n ...connectionOptions,\n autoLoadEntities: true,\n }),\n```\n\nFor handling transactions, I found the following docs:\n\n```\nimport {getManager} from \"typeorm\";\nawait getManager().transaction(async transactionalEntityManager => {\n\n});\n```\n\nUnfortunately, `getManager` is deprecated.\n\nIn the TypeORM-Gitbook, I found the following examples:\n\n```\nawait myDataSource.transaction(async (transactionalEntityManager) => {\n // execute queries using transactionalEntityManager\n})\n```\n\nHowever, it is not clear to me how to achieve this global DataSource-instance and how to inject this one into `app.module.ts` initialization?\n\nIn the answer to the question I mentioned at the beginning, they suggest code like:\n\n```\nexport const appDataSource = new DataSource({\n // ... options\n});\n```\n\nIn the scope of a NestJS application, I can't find a suitable place to inject this.\n\n`package.json`:\n\n```\n\"dependencies\": {\n \"@golevelup/ts-jest\": \"^0.3.6\",\n \"@nestjs/axios\": \"^3.0.0\",\n \"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/config\": \"^2.3.1\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/jwt\": \"^10.0.3\",\n \"@nestjs/passport\": \"^9.0.3\",\n \"@nestjs/platform-express\": \"^9.0.0\",\n \"@nestjs/swagger\": \"^6.3.0\",\n \"@nestjs/typeorm\": \"^9.0.1\",\n \"typeorm\": \"^0.3.15\",\n // ...\n}\n```\n\n========================================\n\nCode:\n```text\nconst connectionOptions: ConnectionOptions = {\n  type: 'postgres',\n  host: config.host,\n  port: config.port,\n  username: config.user || 'postgres',\n   // ...\n}\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      isGlobal: true,\n      cache: true,\n      load: [configuration],\n    }),\n\n    TypeOrmModule.forRoot({\n      ...connectionOptions,\n      autoLoadEntities: true,\n    }),\n```\n\n```text\nimport {getManager} from \"typeorm\";\nawait getManager().transaction(async transactionalEntityManager => {\n\n});\n```\n\n```text\nawait myDataSource.transaction(async (transactionalEntityManager) => {\n    // execute queries using transactionalEntityManager\n})\n```\n\n```text\nexport const appDataSource = new DataSource({\n   // ... options\n});\n```\n\n```text\n\"dependencies\": {\n    \"@golevelup/ts-jest\": \"^0.3.6\",\n    \"@nestjs/axios\": \"^3.0.0\",\n    \"@nestjs/common\": \"^9.0.0\",\n    \"@nestjs/config\": \"^2.3.1\",\n    \"@nestjs/core\": \"^9.0.0\",\n    \"@nestjs/jwt\": \"^10.0.3\",\n    \"@nestjs/passport\": \"^9.0.3\",\n    \"@nestjs/platform-express\": \"^9.0.0\",\n    \"@nestjs/swagger\": \"^6.3.0\",\n    \"@nestjs/typeorm\": \"^9.0.1\",\n    \"typeorm\": \"^0.3.15\",\n    // ...\n}\n```\n\n```text\ngetConnection\n```\n\n```text\ngetConnectionManager\n```\n\n```text\napp.module.ts\n```\n\n```text\ngetManager\n```\n\n```text\napp.module.ts\n```\n\n```text\npackage.json\n```\n\n```text\nimport { DataSource, Repository } from 'typeorm';\n\n@Injectable()\nexport class MyFancyService {\n  constructor(\n    private dataSource: DataSource\n  ) {}\n```\n\n```text\nDataSource\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":185,"estimatedTokens":902}}985{"id":"stack-54517872","source":"stackoverflow","questionId":54517872,"title":"NestJS GraphQL DataSources","tags":["typescript","graphql","apollo-server","nestjs"],"text":"Title: NestJS GraphQL DataSources\nTags: typescript, graphql, apollo-server, nestjs\nSource: Stack Overflow\n\nQuestion:\n**WARNING THE CODE BELOW IS INCORRECT DATASOURCES NEED TO BE CREATED PER REQUEST.**\n\n**DO NOT USE THE CODE BELOW**\n\nIm attempting to use a `apollo-rest-datasource` with NestJS. The downside Im seeing is the DataSources do not participate in NestJS' DI system.\n\nI was able to work around this by having NestJS instantiate the singleton datasources and then using `GraphQLModule.forRootAsync` inject these instances into the `dataSources` property of Apollo Server.\n\n```\nGraphQLModule.forRootAsync({\n imports: [\n DataSourcesModule\n ],\n useFactory: (...args: DataSource[]) => {\n return {\n typePaths: ['./**/*.graphql'],\n context: ({req}: {req: Request}) => ({ token: req.headers.authorization }),\n playground: true,\n dataSources: () => {\n let dataInstances = {} as any;\n args.forEach(arg => {\n const dataSource = arg as any;\n dataInstances[dataSource.constructor.name] = arg;\n });\n return dataInstances;\n },\n };\n },\n inject: [...dataSources]\n```\n\nI now get DI working in my DataSource, and can use DI within the resolvers to include my DataSource instances (instead of accessing from the GraphQL context). While this works, it just feels wrong. \n\nIs there a better approach for NestJS' DI and Apollo GraphQL context?\n\n========================================\n\nTop Answer:\nI was able to solve this issue by using the `@Context` decorator on each of my resolvers methods in order to grab the data sources. The full answer with an example here.\n\n========================================\n\nCode:\n```text\nGraphQLModule.forRootAsync({\n      imports: [\n        DataSourcesModule\n      ],\n      useFactory: (...args: DataSource[]) => {\n        return {\n          typePaths: ['./**/*.graphql'],\n          context: ({req}: {req: Request}) => ({ token: req.headers.authorization }),\n          playground: true,\n          dataSources: () => {\n            let dataInstances = {} as any;\n            args.forEach(arg => {\n              const dataSource = arg as any;\n              dataInstances[dataSource.constructor.name] = arg;\n            });\n            return dataInstances;\n          },\n        };\n      },\n      inject: [...dataSources]\n```\n\n```text\napollo-rest-datasource\n```\n\n```text\nGraphQLModule.forRootAsync\n```\n\n```text\ndataSources\n```\n\n```js\nconst { RESTDataSource } = require('apollo-datasource-rest');\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nclass MoviesAPI extends RESTDataSource {\n  // Inject whatever Nest dependencies you want\n  constructor(private readonly someDependency: SomeDependency) {\n    super();\n    this.baseURL = 'https://movies-api.example.com/';\n  }\n\n  async getMovie(id) {\n    return this.get(`movies/${id}`);\n  }\n\n  async getMostViewedMovies(limit = 10) {\n    const data = await this.get('movies', {\n      per_page: limit,\n      order_by: 'most_viewed',\n    });\n    return data.results;\n  }\n}\n\n@Injectable()\nclass ResolverClass {\n   // Inject your datasources\n   constructor(private readonly moviesApi: MoviesAPI) { }\n}\n```\n\n```text\n@Injectable()\n```\n\n```text\n@Resolver\n```\n\n```text\nModulesContainer\n```\n\n```text\nMetadataScanner\n```\n\n```text\n@DataSource()\n```\n\n```text\n@Context\n```\n\n========================================\n\nComments:\n- Hello I am currently looking at using Nest with GraphQL, may I ask why you decided to use the apollo rest data source instead of the regular nest http client? Thank you for the help!\n- Apollo DataSources provide a caching mechanism that prevent duplicated http responses.\n- yes thats what Im doing, but Apollo Server needs the DataSources defined as a property of `datasources` to property instantiate them with other Apollo Server features.\n- I guess what Im getting at is what you have above works. And its what Im currently doing. It just feels weird to mix these two concepts. I guess thats OK?!\n- @cgatian I've updated the answer to give you some hints on how you might implement this in a more NestJS like way where your dataSources are automatically discovered\n- Good suggestion, I didn't know that existed.\n- It will work if you don't use the method `willSendRequest` in the DataSource class (e.g. to add the token into the request headers). The only way that I could achieve that was by passing the datasources dict into the `GraphQLModule`.\n- @JesseCarter - could you what your graphQL module config looks like in your working solution supporting DI into your RestDataSource?\n- Unfortunately, this method means that each data source takes on the default scope i.e. each is a singleton. This is not ideal since each data source instance now spans requests. Data sources are typically scoped per request. Using this method, Apollo will still execute these data sources per operation, unfortunately, however, the same data source instance is always reused since they are injected as a singletons :(\n- @cmd Could you please elaborate on why the data source should not be reused ? I know in the documentation it says you should scope data sources per operation but I am failing to understand the technicality behind it. Did you manage to get an explanation for it ?","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":152,"estimatedTokens":1291}}986{"id":"stack-73105792","source":"stackoverflow","questionId":73105792,"title":"NestJS/Typeorm ormconfig.json is not being used","tags":["nestjs","typeorm"],"text":"Title: NestJS/Typeorm ormconfig.json is not being used\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI was just using typeorm with NestJS as usual. But it installed version 8.1.4 instead of my previously used 8.0.3. With the newer version I couldn't get the ormconfig.json working. I then checked and installed 8.0.3 and it worked again.\nI have also tried with 9.0.0 and I couldn't get it to work their either.\nDoes somebody else has the same issue and maybe a temporary fix?\nThanks!\n\n========================================\n\nCode:\n```text\n@nestjs/typeorm@8.1.0\n```\n\n```text\ntypeorm@^.3.0\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- how exacly does this work? I tried creating a ormconfig.js but it gives the same error, and I'm using \"@nestjs/typeorm\": \"^9.0.1\"\n- As TypeORM's docs say you need to have a default export of a datasource, if this is to be used with the typeorm CLI. Otherwise, pass the config to `TypeormModule.forRoot&#47;forRootAsync()`","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":30,"estimatedTokens":252}}987{"id":"stack-59289023","source":"stackoverflow","questionId":59289023,"title":"In nestjs, is it possible to specify multiple handlers for the same route?","tags":["nestjs"],"text":"Title: In nestjs, is it possible to specify multiple handlers for the same route?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nIs it possible to specify multiple handler for the same route?\n\nAny HTTP GET request to the `/test` route should call the **get** handler unless the query string watch === '1', in which case it should call the watch handler instead.\n\n```\nimport { Controller, Get } from '@nestjs/common';\n\n@Controller('test')\nexport class TestController {\n @Get()\n get(){\n return 'get'\n }\n\n @Get('?watch=1')\n watch(){\n return 'get with watch param'\n }\n}\n```\n\nAs the framework does not seem to support this, I was hoping to be able to write a decorator to abstract this logic.\n\nie.\n\n```\nimport { Controller, Get } from '@nestjs/common';\nimport { Watch } from './watch.decorator';\n\n@Controller('test')\nexport class TestController {\n @Get()\n get(){\n return 'get'\n }\n\n @Watch()\n watch(){\n return 'get with watch param'\n }\n}\n```\n\nCan this be done? Can anyone point me to the right direction?\n\n========================================\n\nCode:\n```js\nimport { Controller, Get } from '@nestjs/common';\n\n@Controller('test')\nexport class TestController {\n  @Get()\n  get(){\n    return 'get'\n  }\n\n  @Get('?watch=1')\n  watch(){\n    return 'get with watch param'\n  }\n}\n```\n\n```js\nimport { Controller, Get } from '@nestjs/common';\nimport { Watch } from './watch.decorator';\n\n@Controller('test')\nexport class TestController {\n  @Get()\n  get(){\n    return 'get'\n  }\n\n  @Watch()\n  watch(){\n    return 'get with watch param'\n  }\n}\n```\n\n```text\n/test\n```\n\n```js\n@Controller('test')\nexport class TestController {\n    myService: MyService = new MyService();\n\n    @Get()\n    get(@Query('watch') watch: number) {\n        if (watch) {\n            return myService.doSomethingB(watch);\n        } else {\n            return myService.doSomethingA();\n        }\n    }\n}\n\nexport class MyService {\n    doSomethingA(): string {\n        return 'Do not watch me.'\n    }\n\n    doSomethingB(watch: number): string {\n        return 'Watch me for ' + watch + ' seconds.'\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":117,"estimatedTokens":513}}988{"id":"stack-57570837","source":"stackoverflow","questionId":57570837,"title":"How to delete nested entities in TypeORM and Nest.js","tags":["nestjs","typeorm"],"text":"Title: How to delete nested entities in TypeORM and Nest.js\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have one-to-many relation:\n\n```\nclass User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => Phone, phone => phone.user, {cascade: true})\n phones?: Phone[];\n}\n```\n\nAssume current data in database is following: user has two phone numbers:\n\n```\n{\n \"id\": 1,\n \"name\": \"Jhon\",\n \"phones\": [\n {\"id\": 1, \"phone\": \"123456\"},\n {\"id\": 2, \"phone\": \"567809\"}\n ]\n}\n```\n\nI build UI (web-interface) and from web-interface I want to have possibility to delete a phone number from user profile. So I do it and following POST request comes from UI: second phone number deleted\n\n```\n{\n \"id\": 1,\n \"name\": \"Jhon\",\n \"phones\": [\n {\"id\": 1, \"phone\": \"123456\"}\n ]\n}\n```\n\nHow to delete phone number id=2 from database?\nI use Nest CRUD module, as I understand from source code it just merges a new data from request with current data from database, so merging two phone numbers from database with the only phone number from request gives us array of tho phone numbers again and nothing deleted :frowning:\nI tried to do it manually and there are a lot of code!\n\n```\n@Override()\n async updateOne(\n @ParsedRequest() req: CrudRequest,\n @ParsedBody() dto: UpdateUserDto,\n @Param('id') id: number,\n ): Promise {\n\n // use standart Nest.js way to save new user data into database\n await this.service.updateOne(req, dto);\n\n // load fresh user data from database\n const user = await this.service.findOne(id);\n\n const phonesFromUi = dto.phones;\n const phonesToBeDeleted = [];\n // loop phone numbers from database - detect which to be deleted\n user.phones.forEach((phoneFromDb) => {\n const hasThisPhoneOnUi = phonesFromUi.find((phoneFromUi) => phoneFromUi.id === phoneFromDb.id);\n if (!hasThisPhoneOnUi) {\n // looks like this phone number was deleted on ui, so delete it from database too\n phonesToBeDeleted.push(phoneFromDb);\n }\n });\n // actually delete phone numbers from database\n await this.connection.getRepositoryFor(Phone).remove(phonesToBeDeleted);\n\n // reload fresh user data from database to get fresh list of phone numbers after delition some of them\n const user = await this.service.findOne(id);\n\n return user;\n }\n```\n\nIs there any way to do it via TypeORM build in functions or methods? How to delete some elements from nested array?\n\n========================================\n\nCode:\n```text\nclass User {\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @OneToMany(() => Phone, phone => phone.user, {cascade: true})\n    phones?: Phone[];\n}\n```\n\n```text\n{\n  \"id\": 1,\n  \"name\": \"Jhon\",\n  \"phones\": [\n    {\"id\": 1, \"phone\":  \"123456\"},\n    {\"id\": 2, \"phone\":  \"567809\"}\n  ]\n}\n```\n\n```text\n{\n  \"id\": 1,\n  \"name\": \"Jhon\",\n  \"phones\": [\n    {\"id\": 1, \"phone\":  \"123456\"}\n  ]\n}\n```\n\n```text\n@Override()\n  async updateOne(\n    @ParsedRequest() req: CrudRequest,\n    @ParsedBody() dto: UpdateUserDto,\n    @Param('id') id: number,\n  ): Promise<Shipment> {\n\n    // use standart Nest.js way to save new user data into database\n    await this.service.updateOne(req, dto);\n\n    // load fresh user data from database\n    const user = await this.service.findOne(id);\n\n    const phonesFromUi = dto.phones;\n    const phonesToBeDeleted = [];\n    // loop phone numbers from database - detect which to be deleted\n    user.phones.forEach((phoneFromDb) => {\n      const hasThisPhoneOnUi = phonesFromUi.find((phoneFromUi) => phoneFromUi.id === phoneFromDb.id);\n      if (!hasThisPhoneOnUi) {\n        // looks like this phone number was deleted on ui, so delete it from database too\n        phonesToBeDeleted.push(phoneFromDb);\n      }\n    });\n    // actually delete phone numbers from database\n    await this.connection.getRepositoryFor(Phone).remove(phonesToBeDeleted);\n\n    // reload fresh user data from database to get fresh list of phone numbers after delition some of them\n    const user = await this.service.findOne(id);\n\n    return user;\n  }\n```\n\n```text\nconst phones = await this.phoneRepository.find({userId:1});\nconst toDeletePhones = phones.filter((element)) => {\n  return updatePhones.indexOf(element) === -1;\n}\nthis.phoneRepository.remove(toDeletePhones);\n```\n\n========================================\n\nComments:\n- Thank you for response. I am actually do the same for now - manually filter array of phones and delete those are not in request from UI. So, at least now I know that there is no better way in TypeORM.\n- This would get even harder if your phone entity had a OneToMany relationship as well","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":169,"estimatedTokens":1139}}989{"id":"stack-77112317","source":"stackoverflow","questionId":77112317,"title":"Nest JS and Typescript with SWC is not compiling dist folder correctly","tags":["typescript","nestjs","swc"],"text":"Title: Nest JS and Typescript with SWC is not compiling dist folder correctly\nTags: typescript, nestjs, swc\nSource: Stack Overflow\n\nQuestion:\nHi all I'm getting this error. I have surf through all the internet but haven't found any useful solution and even the GitHub discussion was not even useful for me on this topic below are the some screenshots related to the same topic and the error I'm getting.\n\nhttps://i.sstatic.net/NTYjE.png\n\nhttps://i.sstatic.net/5E12J.png\n\nhttps://i.sstatic.net/xdZB4.png\n\nhttps://i.sstatic.net/yrsoo.png\n\nhttps://i.sstatic.net/2Aact.png\n\nhttps://i.sstatic.net/tXnXk.png\n\nI have tried verything using tspath and removing dist folder and removing package-lock.json node_modules, but nothing worked\n\n========================================\n\nTop Answer:\nI used to have the same issue on 1.3.95 but upgrading to 1.7.26 fixed it.\n\n========================================\n\nCode:\n```text\nnpm install -D @swc/core@1.3.78\n```\n\n```text\nnpm install -D @swc-node/register\n```\n\n```text\n\"start\": \"node -r '@swc-node/register' --watch --enable-source-maps src/main.ts\"\n```\n\n```text\n@swc-node/register\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.482Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":44,"estimatedTokens":281}}990{"id":"stack-72489975","source":"stackoverflow","questionId":72489975,"title":"NestJS Bull queues - Missing lock for job failed","tags":["typescript","redis","queue","nestjs","bull"],"text":"Title: NestJS Bull queues - Missing lock for job failed\nTags: typescript, redis, queue, nestjs, bull\nSource: Stack Overflow\n\nQuestion:\nI'm using Bull with NestJS to handle a jobs queue. In the process handler I would like to mark a job as failed instead of completed, but it seems - also reading the documentation - that the `Job#moveToFailed()` method is allowed only on waiting jobs.\n\nIn fact, it triggers an error saying \"Missing lock for job ${jobId} failed\".\nBut, calling the `Job#moveToFailed` with the `ignoreLock` parameter to true everything goes fine.\n\nWhat happens if I ignore the lock moving a job to failed? Is there some side effect? In my scenario, the queue jobs will be always consumed by the same `@Processor`.\n\nHere it is the piece of code I'm running for test purpose:\n\n```\n@Process()\nasync transcode(job: Job): Promise {\n const jobData = job.data as Record\n if (jobData == null) {\n await job.moveToFailed({ message: 'Hook marked as failed because of missing data' })\n return\n }\n\n // do other stuff for job execution..\n}\n```\n\n========================================\n\nCode:\n```text\n@Process()\nasync transcode(job: Job<unknown>): Promise<any> {\n  const jobData = job.data as Record<string, string | unknown>\n  if (jobData == null) {\n    await job.moveToFailed({ message: 'Hook marked as failed because of missing data' })\n    return\n  }\n\n  // do other stuff for job execution..\n}\n```\n\n```text\nJob#moveToFailed()\n```\n\n```text\nJob#moveToFailed\n```\n\n```text\nignoreLock\n```\n\n```text\n@Processor\n```\n\n```text\nawait job.moveToFailed({ message: 'Hook marked as failed because of missing data' }, false)\n```\n\n========================================\n\nComments:\n- set `ignoreLock` DOC\n- as I wrote @EmptyBrain, is there some side effect telling bull to ignore the lock?\n- Yes, I forgot to edit. We arrived at the same conclusion, it seems the only way to make it work properly.\n- Its throwing error like `Argument of type 'number' is not assignable to parameter of type 'boolean'.`\n- Use false in place of \"0\". The type looks like this: (method) Bull.Job.moveToFailed(errorInfo: { message: string; }, ignoreLock?: boolean): Promise\n- @RiteshKhatri you can pass `undefined` for the token param","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":551}}991{"id":"stack-65407405","source":"stackoverflow","questionId":65407405,"title":"How to tell TypeORM to use different logger (pino in this case)?","tags":["node.js","logging","nestjs","typeorm","pinojs"],"text":"Title: How to tell TypeORM to use different logger (pino in this case)?\nTags: node.js, logging, nestjs, typeorm, pinojs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS, TypeORM, pino and nestjs-pino.\n\nI need pino for my logs to be in JSON format, so that Google Cloud Logging can parse the logs.\n\nHowever, TypeORM logs are not in JSON format. They still somehow use their own logger.\n\nIs it possible to tell TypeORM to use the nestjs-pino logger instead of its own?\n\n========================================\n\nComments:\n- Dead links.....","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":135}}992{"id":"stack-71938557","source":"stackoverflow","questionId":71938557,"title":"How to import proto file in another proto file in NestJS","tags":["node.js","nestjs","protocol-buffers","proto","grpc-node"],"text":"Title: How to import proto file in another proto file in NestJS\nTags: node.js, nestjs, protocol-buffers, proto, grpc-node\nSource: Stack Overflow\n\nQuestion:\nI've come across the need to import one file into another, but I can't find a clear explanation of how to do it.\n\nSo, I have my index proto file using some message from common.proto. All proto files lie in the same directory.\n\nindex.proto:\n\n```\nsyntax = \"proto3\";\n\nimport \"common.proto\";\n\npackage index;\n```\n\ncommon.proto:\n\n```\nsyntax = \"proto3\";\n\npackage common;\n\nmessage Void {}\n```\n\nAnd I receive message: \" Cannot resolve import 'common.proto' \"\n\n========================================\n\nTop Answer:\n### Try loading all proto files from a directory instead, using `includeDirs`\n\nAn example :\n\n```\napp.connectMicroservice({\ntransport: Transport.GRPC,\noptions: {\n package: 'sample.user',\n protoPath: '/sample/user/user.proto',\n loader: {\n includeDirs: [join(__dirname, '..', 'protos')], // will load all proto files in the diectory 'protos'\n },\n},\n});\n```\n\n========================================\n\nCode:\n```text\nsyntax = \"proto3\";\n\nimport \"common.proto\";\n\npackage index;\n```\n\n```text\nsyntax = \"proto3\";\n\npackage common;\n\nmessage Void {}\n```\n\n```text\n--proto_path\n```\n\n```text\napp.connectMicroservice({\ntransport: Transport.GRPC,\noptions: {\n  package: 'sample.user',\n  protoPath: '/sample/user/user.proto',\n  loader: {\n    includeDirs: [join(__dirname, '..', 'protos')], // will load all proto files in the diectory 'protos'\n  },\n},\n});\n```\n\n```text\nincludeDirs\n```\n\n========================================\n\nComments:\n- @wh4y I think they use this flag under the hood, I use WebStorm as well and I knew I had to set it in the beginning. Happy Coding :)","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":95,"estimatedTokens":428}}993{"id":"stack-76978671","source":"stackoverflow","questionId":76978671,"title":"NestJS and Prisma, do we really need DTOs for validation when we could use Prisma Generated Type?","tags":["typescript","nestjs","prisma","dto","class-validator"],"text":"Title: NestJS and Prisma, do we really need DTOs for validation when we could use Prisma Generated Type?\nTags: typescript, nestjs, prisma, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI m building a NestJS project using Prisma ORM, and after some tutorial and check on the subject, I don't see (or seem to understand) the use of DTO here, when we could use the Prisma Generated Type\n\nIt's seems to be a duplication of what we already did in the Prisma Schema, and could lead to bad update later as we will have to update both the schema and the DTOs\n\nAfter some search on it I come to the solution to directly use the Prisma Generated Type (as UserCreateInput / UserGetPayload)\n\nhere is the code that I did :\n\nusers.interface.ts\n\n```\nimport { type Prisma } from \"@prisma-postgresql\";\n\n// select for query filtering\nexport const UsersSelect = {\n name: true,\n email: true,\n} satisfies Prisma.UsersSelect;\n// UsersGetPayload is autogenerated by prisma after migration\nexport type Users = Prisma.UsersGetPayload;\n```\n\nusers.service.ts\n\n```\nimport { Injectable } from \"@nestjs/common\";\n\n// prisma import\nimport { PrismaPostgresqlService } from \"../../prisma/services/prisma-postgresql.service\";\nimport { Users, UsersSelect } from \"../interfaces/user.interface\";\n\n@Injectable()\nexport class UserService {\n private prismaSQL;\n\n constructor(prismaSQL: PrismaPostgresqlService) {\n this.prismaSQL = prismaSQL;\n }\n\n async findAll(): Promise {\n return await this.prismaSQL.users.findMany({\n select: UsersSelect,\n });\n }\n}\n```\n\nwith this I can have my own type coming directly from prisma\n\nI don't know if it's indeed a good solution or not, maybe I m missing the point of DTOs here ?\n\nWhy would it be a good idea to still use DTOs in my case ? or is this a good solution ?\n\n========================================\n\nTop Answer:\nValentin, \n\nIMHO, DTOs are not always required. It depends on how you are organizing your app. If you are not interested in decoupling your code from the framework you are using, it sounds good to use the auto-generated types. As you said, it can bring more complexity than what you need. I would suggest starting that way, and as your app evolves it will show the necessity of creating DTOs or not.\n\n========================================\n\nCode:\n```js\nimport { type Prisma } from \"@prisma-postgresql\";\n\n// select for query filtering\nexport const UsersSelect = {\n    name: true,\n    email: true,\n} satisfies Prisma.UsersSelect;\n// UsersGetPayload is autogenerated by prisma after migration\nexport type Users = Prisma.UsersGetPayload<{ select: typeof UsersSelect }>;\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\n\n// prisma import\nimport { PrismaPostgresqlService } from \"../../prisma/services/prisma-postgresql.service\";\nimport { Users, UsersSelect } from \"../interfaces/user.interface\";\n\n@Injectable()\nexport class UserService {\n    private prismaSQL;\n\n    constructor(prismaSQL: PrismaPostgresqlService) {\n        this.prismaSQL = prismaSQL;\n    }\n\n    async findAll(): Promise<Users[]> {\n        return await this.prismaSQL.users.findMany({\n            select: UsersSelect,\n        });\n    }\n}\n```\n\n========================================\n\nComments:\n- That is the point of my question, I don't know why would I need it later, even if my app evolves, what are the need I could meet later ? As I said, everyone (even NestJS in their exemples) seems to be using DTOs at the start, so what I want to point is **Are we missing the power of prisma** ? Like is everyone using Dtos Cause they didn't find / look a way to directly use prisma to do it ? That is what I m trying to understand here, as you said, maybe later I will see the use of DTOs, but I want to find what could be this reason\n- scenario 1: You have a REST API that provides a GET for the user resource. The contract (data representation) that you have defined for the route has more information than you would have in a specific domain model. In the backend, you are gathering info from multiple models (user, address, payment, etc.) and then returning it to the client. In that case, I see the need for a DTO.\n- scenario 2: You have a REST API that provides POST, PATCH, and GET routes for user resource. For the POST DTO, you defined the contract with some fields being mandatory, such as name, email, and password. For the PATCH DTO you are not allowing changes on field email, then you will not have this field, and the name and password are optional. And, the GET DTO has more info than the POST and PATCH DTOs, for instance, it would contain the fields: id, name, email, password, createdAt, updatedAt. So, your GET DTO can be reused by the POST and PATCH to return the result to the client.\n- I hope that clarifies a bit for you :)\n- thanks for the example :) Taking everything you said, PRISMA type do handle and allow almost all the case EXCEPT one, the PUT/PATCH case With the generated type you can't specifically say what is not allowed or not to be updated, so you have to manually extract which data should be updated and the request will not be rejected if it's pass data that should not be allowed to be updated This do not affect documentation as we can specify allowed params with NestJS decorators And this should soon be covered by the Prisma team, as this is one of the most requested feature\n- github.com/prisma/prisma/issues/3401 So when this will be added to prisma, there should be a new generated type for only allowed property to be updated, and all the case should be covered That aside, when this will be added to PRISMA, all the case where DTOs could be used would be gone right ?\n- For your case case, yes. Although, as I said, you are being tight coupling to the framework. As you are using its auto-generated types all over your app. And, there is nothing wrong with going that way, it is just a matter of trade-offs that we always have to make when building software.\n- Yes, in the end if we think about the day we might want to change the framework we use it might be the best to go with DTO, also they are some tool that exist to update our DTO using the prisma schema\n- In the end it might be best to use DTOs, allowing swagger to work properly and decoupling the solution from the framework\n- the DTO generator that you've linked is a fork of a fork of a fork. Now, I don't know the details, but i figured that the original repo would be preferable to use: github.com/vegardit/prisma-generator-nestjs-dto\n- indeed, really weird I didn't see that sooner I will update my answer to this link","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":117,"estimatedTokens":1633}}994{"id":"stack-75454902","source":"stackoverflow","questionId":75454902,"title":"How to Use Heroku Background Workers with NestJS and Bull?","tags":["heroku","nestjs","web-worker","task-queue","bull"],"text":"Title: How to Use Heroku Background Workers with NestJS and Bull?\nTags: heroku, nestjs, web-worker, task-queue, bull\nSource: Stack Overflow\n\nQuestion:\nWhat is the recommended way of providing Heroku workers for heavy processes that I want running on my queue using NestJS?\n\nI have an HTTP server running on Heroku that executes certain time-consuming tasks (e.g. communicating with certain third-party APIs) that I want to be put in a Queue and have delegated to background workers.\n\nReading this example, it seems that I would create a processor file and instantiate the `Queue` object there and then define it's `process` function. That seems to allow scaling up, because each process would have the `Queue` object and define it's `process` therein. Spinning up more dynos would provide more workers.\n\nLooking over here, I see that I can declare the process file when I register the queue. There I do not need to instantiate the `Queue` object and define it's `process`, I can simply `export` a `default function`. Can I declare a worker process in my `Procfile` that points to one of these process files and scale them up? Will that work? Or am I missing something here?\n\nRight now, I don't have separate processes set up. I defined the `Processors` and the `Processes` using the given decorators within Nest's IoC container. I thought things would queue up nicely. What I've seen is that jobs come in fast and my server can't keep up with all the requests and jobs.\n\n========================================\n\nCode:\n```text\nQueue\n```\n\n```text\nprocess\n```\n\n```text\nQueue\n```\n\n```text\nprocess\n```\n\n```text\nQueue\n```\n\n```text\nprocess\n```\n\n```text\nexport\n```\n\n```text\ndefault function\n```\n\n```text\nProcfile\n```\n\n```text\nProcessors\n```\n\n```text\nProcesses\n```\n\n```text\n@Injectable()\nexport class SomeService {\n  constructor(@InjectQueue('my_queue') private readonly myQueue: Queue) {}\n\n  addToQueue(jobData: JobData) {\n    await this.myQueue.add(jobData);\n    \n    return 'Added to Queue';\n  }\n}\n```\n\n```text\nimport Queue from 'bull';\n\nconst myQueue = new Queue('my_queue', process.env.REDIS_URL);\n\nmyQueue.process(async (job: JobData) => {\n  await somePromise(job.data.id);\n  return 'success';\n});\n```\n\n```text\nconst myService = new SomeService();\n// myOtherService depends on myService. In Nest, it was automatically injected in the constructor. \nconst myOtherService = new SomeOtherService(myService);\n```\n\n```text\nQueue.add(job)\n```\n\n```text\nQueue.process(function)\n```\n\n```text\nmain.ts\n```\n\n```text\nQueue.process(function)\n```\n\n```text\nmy-queue.process.ts\n```\n\n```text\nProcfile\n```\n\n```text\nworker: node dist/path/to/my-queue.process.ts\n```\n\n```text\nworker.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":123,"estimatedTokens":667}}995{"id":"stack-71884254","source":"stackoverflow","questionId":71884254,"title":"How to use type (typescript type) in swagger @ApiProperty type","tags":["javascript","typescript","swagger","nestjs","nestjs-swagger"],"text":"Title: How to use type (typescript type) in swagger @ApiProperty type\nTags: javascript, typescript, swagger, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI'm facing a problem.\nI need to expose a 'type' in an @ApiProperty of swagger on my API.\nBut swagger don't accept it. I looked in many website to find solution but I did not find any.\n\nHere is the error I get:\n\nTS2693: 'testTest' only refers to a type, but is being used as a value\nhere.\n\n```\ntype testTest = 'A' | 'B';\n\n @ApiProperty({\n type: testTest,\n example: 'fr',\n})\ntest: testTest;\n```\n\nI can't use something else since the type I need to use is from an external library.\n\n========================================\n\nCode:\n```text\ntype testTest = 'A' | 'B';\n\n    @ApiProperty({\n  type: testTest,\n  example: 'fr',\n})\ntest: testTest;\n```\n\n```text\nconst testTest = ['A','B'];\n\n@ApiProperty({\n  type: String,\n  example: testTest[0],\n  enum: testTest\n})\ntest: testTest;\n```\n\n```text\ntype\n```\n\n```text\ntype\n```\n\n```text\ntype\n```\n\n```text\ntype testTest = 'A' | 'B';\n```\n\n========================================\n\nComments:\n- You can't. Swagger needs a *value*, the types are all erased in compilation.\n- Sure, you totally right. But: how can I convert a type to an array of values of the keys of the type ?\n- you can't. Also that type would be an `string`. So `type: String`. And you will need to set up some sort of validation to ensure that `test` is either `'A'` or `'B'`","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":360}}996{"id":"stack-72797278","source":"stackoverflow","questionId":72797278,"title":"Modify response with nestjs interceptor","tags":["node.js","nestjs","interceptor"],"text":"Title: Modify response with nestjs interceptor\nTags: node.js, nestjs, interceptor\nSource: Stack Overflow\n\nQuestion:\nI have Interceptor for modify icon path like this:\n\n```\n@Injectable()\nexport class GetProgramIconInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable | Promise> {\n return next.handle().pipe(\n map(data => {\n return {\n ...data,\n icon: generalFUnctions.getApplicationIcon(data.icon)\n };\n }),\n );\n }\n}\n```\n\nand when I use this in my find method, it works correctly and modifies the icon path.\n\n```\n@UseInterceptors(GetProgramIconInterceptor)\nasync find(id: string): Promise {\n const application = await this.repository.findById(id);\n if (!application) throw new ApplicationNotFoundException();\n return application;\n}\n```\n\nand when I use this Interceptor to the findAll method it doesn't work correctly and doesn't modify the path.\n\n```\n@UseInterceptors(GetProgramIconInterceptor)\nasync findAll(): Promise {\n return this.repository.find();\n}\n```\n\nI know the result of the findAll method is an array and I can create another Interceptor for it. Is there any way to handle it with one Interceptor\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class GetProgramIconInterceptor implements NestInterceptor {\n    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {\n        return next.handle().pipe(\n            map(data => {\n                return {\n                    ...data,\n                    icon: generalFUnctions.getApplicationIcon(data.icon)\n                };\n            }),\n        );\n    }\n}\n```\n\n```text\n@UseInterceptors(GetProgramIconInterceptor)\nasync find(id: string): Promise<Application> {\n    const application = await this.repository.findById(id);\n     if (!application) throw new ApplicationNotFoundException();\n     return application;\n}\n```\n\n```text\n@UseInterceptors(GetProgramIconInterceptor)\nasync findAll(): Promise<Application[]> {\n     return this.repository.find();\n}\n```\n\n```text\nmap((repositoryOrRespositories) => {\n  if (Array.isArray(repositoryOrRespositories)) {\n    return item.map((repository) => ({\n      ...repository,\n      icon: generalFUnctions.getApplicationIcon(repository.icon)\n    }));\n  } else {\n    return { ...repositoryOrRespositories, icon: generalFUnctions.getApplicationIcon(repositoryOrRespositories.icon) };\n  }\n})\n```\n\n```text\nfind\n```\n\n```text\nfindById\n```\n\n```text\nrepository\n```\n\n```text\nrepository[]\n```\n\n```text\niif\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":112,"estimatedTokens":633}}997{"id":"stack-70897778","source":"stackoverflow","questionId":70897778,"title":"NestJS blocking new requests after throwing error","tags":["javascript","node.js","typescript","error-handling","nestjs"],"text":"Title: NestJS blocking new requests after throwing error\nTags: javascript, node.js, typescript, error-handling, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've got a small testing application (a test lab) with an `AppControler` and an `AppService`, `AppController` has a `GET` endpoint and send requests payload to `AppService`, which has two async methods.\n\n**AppService**\n\n```\nasync requestTesting (payload): Promise { // This is what's being called from the controller\n \n if(payload) {\n await this.validateErrorHandling(payload)\n }\n\n console.log('TESTING', payload)\n\n// DO STUFF\n\n}\n\nasync validateErrorHandling(payload): Promise {\n console.log('DO STUFF')\n\n if(payload && payload.number > 2) { // This is true\n throw new Error()\n }\n\n}\n```\n\nWhen requestTesting calls validateErrorHandling, the second method is going to check that condition (if truthy) and shall throw an Error.\nI'm used to do this with an exception filter on real use cases, but in this very specific case, whenever I call my Controller's endpoint and that error is thrown on my `AppService`, the following is shown:\n\n```\nUnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"........\".\n```\n\nAnd I'm unable to make any other request through postman until I restart the app.\nPostman shows:\n\n```\nError: connect ECONNREFUSED 127.0.0.1:3000\n```\n\nNow, I'm aware that a try/catch should fix this, but I'm trying to understand why this is stopping my whole application instead of stopping the function execution only, as it never happened to me before, and if I try to throw it anywhere else, it just works.\n\nNow, both methods have a `Promise` return type, but if validateErrorHandling throws an error, everything should stop and that `console.log('TESTING', payload)` should not be executed (as if it were business logic).\nI'm afraid it's not just me being silly, but I might actually be missing something.\n\n========================================\n\nCode:\n```js\nasync requestTesting (payload): Promise<void> { // This is what's being called from the controller\n    \n  if(payload) {\n      await this.validateErrorHandling(payload)\n  }\n\n  console.log('TESTING', payload)\n\n// DO STUFF\n\n}\n\nasync validateErrorHandling(payload): Promise<void> {\n     console.log('DO STUFF')\n\n  if(payload && payload.number > 2) { // This is true\n     throw new Error()\n  }\n\n}\n```\n\n```text\nUnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"........\".\n```\n\n```text\nError: connect ECONNREFUSED 127.0.0.1:3000\n```\n\n```text\nAppControler\n```\n\n```text\nAppService\n```\n\n```text\nAppController\n```\n\n```text\nGET\n```\n\n```text\nAppService\n```\n\n```text\nAppService\n```\n\n```text\nPromise<void>\n```\n\n```text\nconsole.log('TESTING', payload)\n```\n\n```text\nthrow new UnprocessableEntityException({\n  errorCode: UpdateProductErrorStatusEnum.DeviceNotReported,\n  message: UpdateProductErrorMsgEnum.DeviceNotReported,\n});\n```\n\n========================================\n\nComments:\n- you problably forgot some `await`, leaving floating promises around. Check out all promises that are in-place when your controller's method get called\n- That's the part that's getting me, I omitted method names and other logic testing (only with console.log() inside of them), but everything is working just fine. Also, if I throw an error inside the controller, it won't stop the whole application, and altough that should just indicate that I am indeed missing something, I didn't find anything out of the ordinary\n- Can you show the controller function too please?\n- Thanks for your answer, but that did not answer my question. I'm used to handling errors on NestJS with a customized exception filter library that I made based of Nest global exception filter. NestJS is blocking (or stopping) the application after an error is thrown on that very specific case , and that's very weird. But thank you, anyway! Edit: Also, I don't agree with that errors being thrown to \"tell the front application that something went wrong\" only, it might be used for backend only application as well\n- Your exception filter (if it's the same thing that nestjs brings) will catch only HTTP exceptions. So, when you `throw Error()` you should catch it manually. And about your last sentence, yes throwing an error is used in the backend too. For example, you have a module that you publish on npm, then for example, if you do something wrong, the package throws an error (because they want to not let you go further if it's re) and you should handle it properly by catching it.\n- So, to sum up, either you throw an error for frontend or backend internal purposes, you should either throw HTTP based errors (for frontend case) or throw and catch it manually (for backend purposes)\n- Ah, I had to re-read you answer, I must have been tired and misinterpreted your answer, sorry. Anyway... What if I need to throw different errors based on business logic? I might create a custom filter that catches every kind of error (that's what the filter I mentioned does), and that would make my controller clean again, right? But if for some reason I don't want to catch errors on my controller?\n- Also, what do you mean by \"Throw in the service\" and \"Throw an Error and catch it on the controller\"? I am throwing it on the service.","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":135,"estimatedTokens":1384}}998{"id":"stack-61407959","source":"stackoverflow","questionId":61407959,"title":"Is there an elegant way using TypeORM to find one record in an array of OneToMany relation and assign it to another field in the entitiy?","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Is there an elegant way using TypeORM to find one record in an array of OneToMany relation and assign it to another field in the entitiy?\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a way to implement a function, using NestJS and TypeORM, that will find in OneToMany array a specific element and assign that value to another field in the object.\nAnd most important: implemented in a single place in the code.\n\nFor example:\n\nThe Entity `profile` have an array of `photos`, one of the photos is the profile picture. \nI would like to find that photo in the array and assign it to `profilePicture` if exist, on every select query.\nis there a way in typeORM to implement that in a single place in the code?\n\n```\n@Entity('profile')\nexport class Profile extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @OneToMany(type => Photo, photo => photo.profile)\n photos?: Photo[];\n\n profilePicture?: Photo;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity('profile')\nexport class Profile extends BaseEntity {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @OneToMany(type => Photo, photo => photo.profile)\n    photos?: Photo[];\n\n    profilePicture?: Photo;\n}\n```\n\n```text\nprofile\n```\n\n```text\nphotos\n```\n\n```text\nprofilePicture\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n.leftJoinAndMapOne(\"user.profilePhoto\", \"user.photos\", \"photo\", \"photo.isForProfile = TRUE\")\n.where(\"user.name = :name\", { name: \"Timber\" })\n.getOne();\n```\n\n```text\n@AfterLoad()\nprivate setProfile(): void {\n    this.photos.forEach((photo) => {\n        if (photo.isForProfile) {\n            this.photo = value;\n        }\n    });\n}\n```\n\n========================================\n\nComments:\n- I edited the question, I'm looking for a solution to implement in a single place in the code. So that the assignment will happen on automatically on every select query like TypeORM's `transformer`. I'll use leftJoinAndMapOne if there's no solution as I am looking for.","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":510}}999{"id":"stack-76604224","source":"stackoverflow","questionId":76604224,"title":"how to import from libs in NX","tags":["nestjs","microservices","nomachine-nx"],"text":"Title: how to import from libs in NX\nTags: nestjs, microservices, nomachine-nx\nSource: Stack Overflow\n\nQuestion:\nI have Microservice with **Nestjs** and **Nx**\n\nthis is project structure\n\n```\nproject\nโ”‚ \nโ”‚\nโ””โ”€โ”€โ”€apps\nโ”‚ โ”‚ gateway\nโ”‚ โ”‚ auth\nโ”‚ \nโ”‚ \nโ””โ”€โ”€โ”€libs\n โ””โ”€โ”€โ”€common\n```\n\nnow I want to import some module from `libs/common` in gateway\n\n```\nimport { RMQ_SERVICES } from '@app/common/constants/rmq.constant';\n```\n\nbut it doesn't work\n\n**Cannot find module '@app/common/constants/rmq.constant' or its corresponding type declarations.ts(2307)**\n\nI have also tried this\n\n```\nimport { RMQ_SERVICES } from 'libs/common/src/lib/constants/rmq.constant';\n```\n\nbut it doesn't worked .\n\n**Projects cannot be imported by a relative or absolute path, and must begin with a npm scopeeslint**\n\nso how can I do it ?\n\n========================================\n\nCode:\n```text\nproject\nโ”‚   \nโ”‚\nโ””โ”€โ”€โ”€apps\nโ”‚   โ”‚ gateway\nโ”‚   โ”‚ auth\nโ”‚   \nโ”‚   \nโ””โ”€โ”€โ”€libs\n    โ””โ”€โ”€โ”€common\n```\n\n```text\nimport { RMQ_SERVICES } from '@app/common/constants/rmq.constant';\n```\n\n```text\nimport { RMQ_SERVICES } from 'libs/common/src/lib/constants/rmq.constant';\n```\n\n```text\nlibs/common\n```\n\n```text\ntsconfig.base.json\n```\n\n```text\npaths\n```\n\n```text\nnx.json\n```\n\n```text\nnpmScope\n```\n\n```text\n@scope/\n```\n\n```text\n--importPath\n```\n\n```text\ntsconfig.base.json\n```\n\n```text\n@scope/server/kysely\n```\n\n```text\n@scope/shared/types\n```\n\n```text\ntsconfig.base.json\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Nx don't respect path imports if u use esbuild.","metadata":{"transformedAt":"2026-08-18T18:33:02.483Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":120,"estimatedTokens":383}}1000{"id":"stack-72098441","source":"stackoverflow","questionId":72098441,"title":"Test coverage: import statements not covered","tags":["typescript","unit-testing","jestjs","nestjs","sonarqube"],"text":"Title: Test coverage: import statements not covered\nTags: typescript, unit-testing, jestjs, nestjs, sonarqube\nSource: Stack Overflow\n\nQuestion:\nI'm writing tests with Jest for a Nest application in typescript. The problem is, I have uncovered import statements saying else path not taken\" and \"branch not covered\". The uncovered imports vary across classes. Sometimes it is underlined seemingly random in the middle of a line, see screenshot below. As a result, overall branch coverage is 47% only and one of the import lines is not covered.\n\nWhen generating SonarQube reports that use different reporter, the issue persists.\n\nhttps://i.sstatic.net/2dHmT.png\n\nSometimes it applies even to annotations.\n\nhttps://i.sstatic.net/5Woof.png\n\nI already tried:\n\n- To switch `sourceMap = true` as outlined here.\n\n- Removing transform and adding moduleDirectories to `package.json` as described here.\n\n- Moving Jest rootDir into project root.\n\nNothing helped. I'm totally stuck with this issue, particularly because it's a default setup used across many projects. It looks like something is of with one of the config files. Any idea what's wrong and ***how to fix those uncovered imports?***\n\nHere are some project configs:\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": false,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./src\",\n \"incremental\": false,\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true,\n \"noImplicitAny\": true,\n \"allowUnreachableCode\": false,\n \"strict\": true,\n \"alwaysStrict\": true,\n \"strictPropertyInitialization\": false,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true\n }\n}\n```\n\njest.config.ts\n\n```\n/** @format */\n\nmodule.exports = {\n moduleFileExtensions: ['js', 'json', 'ts'],\n testRegex: '.*\\\\.spec\\\\.ts$',\n transform: {\n '^.+\\\\.(t|j)s$': 'ts-jest',\n },\n collectCoverageFrom: [\n '**/*.(t|j)s',\n '!generated/openapi/model/*',\n '!types/*',\n '!generate-typings.ts',\n ],\n rootDir: './src',\n coverageDirectory: '../coverage',\n testEnvironment: 'node',\n reporters: ['default', 'jest-junit'],\n setupFilesAfterEnv: ['../test/jest.setup.redis-mock.ts'],\n};\n```\n\npackage.json\n\n```\n{\n \"name\": \"\",\n \"version\": \"0.0.0-local\",\n \"description\": \"\",\n \"author\": \"\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"postinstall\": \"npm run generate\",\n \"prebuild\": \"npm run clearDist\",\n \"clearDist\": \"rimraf ./dist\",\n \"generate\": \"rimraf ./src/generated && npm run generate:graphql && npm run generate:openapi\",\n \"generate:graphql\": \"mkdirp ./src/generated && ts-node ./src/generate-typings.ts\",\n \"generate:openapi\": \"mkdirp ./src/generated && openapi-generator-cli generate\",\n \"build\": \"nest build\",\n \"build:prod\": \"nest build --webpack\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"nest start\",\n \"start:dev\": \"cross-env GRAPHQL_PLAYGROUND=true cross-env NODE_ENV=development nest start --watch\",\n \"start:debug\": \"cross-env NODE_ENV=development nest start --debug --watch\",\n \"start:prod\": \"node dist/main\",\n \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\"\",\n \"lint:fix\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n \"test\": \"jest --runInBand\",\n \"test:ci\": \"jest --coverage --runInBand\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n \"test:sonar\": \"jest --coverage --runInBand --testResultsProcessor jest-sonar-reporter\"\n },\n \"dependencies\": {\n \"@apollo/gateway\": \"^0.50.1\",\n \"@azure/identity\": \"^2.0.4\",\n \"@azure/keyvault-secrets\": \"^4.4.0\",\n \"@nestjs/apollo\": \"^10.0.9\",\n \"@nestjs/axios\": \"^0.0.7\",\n \"@nestjs/common\": \"^8.4.4\",\n \"@nestjs/config\": \"^2.0.0\",\n \"@nestjs/core\": \"^8.4.4\",\n \"@nestjs/graphql\": \"^10.0.9\",\n \"@nestjs/passport\": \"^8.2.1\",\n \"@nestjs/platform-express\": \"^8.4.4\",\n \"@nestjs/schedule\": \"^1.1.0\",\n \"@nestjs/typeorm\": \"^8.0.3\",\n \"apollo-server-express\": \"^3.6.7\",\n \"applicationinsights\": \"^2.3.1\",\n \"axios\": \"^0.26.1\",\n \"cache-manager\": \"^3.6.1\",\n \"cache-manager-redis-store\": \"^2.0.0\",\n \"clone\": \"^2.1.2\",\n \"graphql\": \"^16.3.0\",\n \"graphql-fields-list\": \"^2.2.4\",\n \"mysql2\": \"^2.3.3\",\n \"openid-client\": \"^5.1.5\",\n \"redis\": \"^3.1.1\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rxjs\": \"^7.5.5\",\n \"ts-morph\": \"^14.0.0\",\n \"typeorm\": \"^0.2.34\"\n },\n \"jest-junit\": {\n \"outputDirectory\": \"./junit-reports\"\n },\n \"devDependencies\": {\n \"@nestjs/cli\": \"^8.2.5\",\n \"@nestjs/schematics\": \"^8.0.10\",\n \"@nestjs/testing\": \"^8.4.4\",\n \"@openapitools/openapi-generator-cli\": \"^2.4.26\",\n \"@types/cache-manager\": \"^3.4.3\",\n \"@types/cache-manager-redis-store\": \"^2.0.1\",\n \"@types/clone\": \"^2.1.1\",\n \"@types/cron\": \"^1.7.3\",\n \"@types/express\": \"^4.17.13\",\n \"@types/jest\": \"^27.4.1\",\n \"@types/node\": \"^17.0.25\",\n \"@types/redis\": \"^2.8.32\",\n \"@types/supertest\": \"^2.0.12\",\n \"@types/ws\": \"^8.5.3\",\n \"@typescript-eslint/eslint-plugin\": \"^5.20.0\",\n \"@typescript-eslint/parser\": \"^5.20.0\",\n \"cross-env\": \"^7.0.3\",\n \"eslint\": \"^8.13.0\",\n \"eslint-config-prettier\": \"^8.5.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"jest\": \"^27.5.1\",\n \"jest-junit\": \"^13.0.0\",\n \"jest-sonar-reporter\": \"^2.0.0\",\n \"mkdirp\": \"^1.0.4\",\n \"prettier\": \"^2.6.2\",\n \"redis-mock\": \"^0.56.3\",\n \"rimraf\": \"^3.0.2\",\n \"supertest\": \"^6.2.2\",\n \"ts-jest\": \"^27.1.4\",\n \"ts-loader\": \"^9.2.8\",\n \"ts-node\": \"^10.7.0\",\n \"tsconfig-paths\": \"^3.14.1\",\n \"typescript\": \"^4.6.3\",\n \"webpack\": \"^5.72.0\",\n \"webpack-cli\": \"^4.9.2\"\n },\n \"engines\": {\n \"npm\": \"^7\",\n \"node\": \"^14\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": false,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./src\",\n    \"incremental\": false,\n    \"resolveJsonModule\": true,\n    \"esModuleInterop\": true,\n    \"noImplicitAny\": true,\n    \"allowUnreachableCode\": false,\n    \"strict\": true,\n    \"alwaysStrict\": true,\n    \"strictPropertyInitialization\": false,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true\n  }\n}\n```\n\n```text\n/** @format */\n\nmodule.exports = {\n  moduleFileExtensions: ['js', 'json', 'ts'],\n  testRegex: '.*\\\\.spec\\\\.ts$',\n  transform: {\n    '^.+\\\\.(t|j)s$': 'ts-jest',\n  },\n  collectCoverageFrom: [\n    '**/*.(t|j)s',\n    '!generated/openapi/model/*',\n    '!types/*',\n    '!generate-typings.ts',\n  ],\n  rootDir: './src',\n  coverageDirectory: '../coverage',\n  testEnvironment: 'node',\n  reporters: ['default', 'jest-junit'],\n  setupFilesAfterEnv: ['../test/jest.setup.redis-mock.ts'],\n};\n```\n\n```text\n{\n  \"name\": \"\",\n  \"version\": \"0.0.0-local\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"postinstall\": \"npm run generate\",\n    \"prebuild\": \"npm run clearDist\",\n    \"clearDist\": \"rimraf ./dist\",\n    \"generate\": \"rimraf ./src/generated && npm run generate:graphql && npm run generate:openapi\",\n    \"generate:graphql\": \"mkdirp ./src/generated && ts-node ./src/generate-typings.ts\",\n    \"generate:openapi\": \"mkdirp ./src/generated && openapi-generator-cli generate\",\n    \"build\": \"nest build\",\n    \"build:prod\": \"nest build --webpack\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"cross-env GRAPHQL_PLAYGROUND=true cross-env NODE_ENV=development nest start --watch\",\n    \"start:debug\": \"cross-env NODE_ENV=development nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\"\",\n    \"lint:fix\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest --runInBand\",\n    \"test:ci\": \"jest --coverage --runInBand\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n    \"test:sonar\": \"jest --coverage --runInBand --testResultsProcessor jest-sonar-reporter\"\n  },\n  \"dependencies\": {\n    \"@apollo/gateway\": \"^0.50.1\",\n    \"@azure/identity\": \"^2.0.4\",\n    \"@azure/keyvault-secrets\": \"^4.4.0\",\n    \"@nestjs/apollo\": \"^10.0.9\",\n    \"@nestjs/axios\": \"^0.0.7\",\n    \"@nestjs/common\": \"^8.4.4\",\n    \"@nestjs/config\": \"^2.0.0\",\n    \"@nestjs/core\": \"^8.4.4\",\n    \"@nestjs/graphql\": \"^10.0.9\",\n    \"@nestjs/passport\": \"^8.2.1\",\n    \"@nestjs/platform-express\": \"^8.4.4\",\n    \"@nestjs/schedule\": \"^1.1.0\",\n    \"@nestjs/typeorm\": \"^8.0.3\",\n    \"apollo-server-express\": \"^3.6.7\",\n    \"applicationinsights\": \"^2.3.1\",\n    \"axios\": \"^0.26.1\",\n    \"cache-manager\": \"^3.6.1\",\n    \"cache-manager-redis-store\": \"^2.0.0\",\n    \"clone\": \"^2.1.2\",\n    \"graphql\": \"^16.3.0\",\n    \"graphql-fields-list\": \"^2.2.4\",\n    \"mysql2\": \"^2.3.3\",\n    \"openid-client\": \"^5.1.5\",\n    \"redis\": \"^3.1.1\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rxjs\": \"^7.5.5\",\n    \"ts-morph\": \"^14.0.0\",\n    \"typeorm\": \"^0.2.34\"\n  },\n  \"jest-junit\": {\n    \"outputDirectory\": \"./junit-reports\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^8.2.5\",\n    \"@nestjs/schematics\": \"^8.0.10\",\n    \"@nestjs/testing\": \"^8.4.4\",\n    \"@openapitools/openapi-generator-cli\": \"^2.4.26\",\n    \"@types/cache-manager\": \"^3.4.3\",\n    \"@types/cache-manager-redis-store\": \"^2.0.1\",\n    \"@types/clone\": \"^2.1.1\",\n    \"@types/cron\": \"^1.7.3\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"^27.4.1\",\n    \"@types/node\": \"^17.0.25\",\n    \"@types/redis\": \"^2.8.32\",\n    \"@types/supertest\": \"^2.0.12\",\n    \"@types/ws\": \"^8.5.3\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.20.0\",\n    \"@typescript-eslint/parser\": \"^5.20.0\",\n    \"cross-env\": \"^7.0.3\",\n    \"eslint\": \"^8.13.0\",\n    \"eslint-config-prettier\": \"^8.5.0\",\n    \"eslint-plugin-prettier\": \"^4.0.0\",\n    \"jest\": \"^27.5.1\",\n    \"jest-junit\": \"^13.0.0\",\n    \"jest-sonar-reporter\": \"^2.0.0\",\n    \"mkdirp\": \"^1.0.4\",\n    \"prettier\": \"^2.6.2\",\n    \"redis-mock\": \"^0.56.3\",\n    \"rimraf\": \"^3.0.2\",\n    \"supertest\": \"^6.2.2\",\n    \"ts-jest\": \"^27.1.4\",\n    \"ts-loader\": \"^9.2.8\",\n    \"ts-node\": \"^10.7.0\",\n    \"tsconfig-paths\": \"^3.14.1\",\n    \"typescript\": \"^4.6.3\",\n    \"webpack\": \"^5.72.0\",\n    \"webpack-cli\": \"^4.9.2\"\n  },\n  \"engines\": {\n    \"npm\": \"^7\",\n    \"node\": \"^14\"\n  }\n}\n```\n\n```text\nsourceMap = true\n```\n\n```text\npackage.json\n```\n\n```text\nsourceMap=true\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- You have `sourceMap: false` in the tsconfig.json. It looks like the errors are not properly aligned to the sources, because those errors don't relate to the highlighted lines.\n- In our case, we have multiple lcov.info files which we feed to SonarQube and it turns out that something started happening in our project which caused these independent coverage reports to no longer reconcile as they had before. It seems complicated but it may may be due to the version of SonarQube and even the `nyc` package in our case too but it still seems very unclear exactly. For the time being we've opted to run our coverage off of one of the lcov files generated for our end-to-end testing and to ignore the unit test coverage until we can upgrade SonarQube.\n- Out of curiosity, is it possible that SonarQube was upgraded in between your experimentation and tinkering? That would perhaps explain why it started working at least and may give some backing to this being an issue with SonarQube analysis of JavaScript and TypeScript with older versions.","metadata":{"transformedAt":"2026-08-18T18:33:02.569Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":376,"estimatedTokens":2916}}1001{"id":"stack-72682434","source":"stackoverflow","questionId":72682434,"title":"NestJS - How to implement RBAC with organization-scoped roles","tags":["nestjs","roles","multi-tenant","rbac","usergroups"],"text":"Title: NestJS - How to implement RBAC with organization-scoped roles\nTags: nestjs, roles, multi-tenant, rbac, usergroups\nSource: Stack Overflow\n\nQuestion:\nI am designing a REST backend in Nest.js that needs to allow `Users` to be a part of multiple `Organizations`. I want to use role-based access control, such that a user can have one or more named roles. Crucially, these roles need to be able to be either \"global\" (not dependent on any organization, ex. `SUPERUSER`), or \"scoped\" (specific to an organization, ex. `MANAGER`).\n\nI have decided on this basic database design, which links `Users` to `Organizations` using the `Roles` table in a many-one-many relationship:\n\nhttps://i.sstatic.net/LWQdH.png\n\nAs you can see, the `organizationId` field on a `Role` is optional, and if it is present, then the user is linked to that organization through the role. If it is not present, I assume this to be a \"global\" role. I find this to be an elegant database design, but I am having trouble implementing the guard logic for my endpoints.\n\nThe guard logic would go something like this:\n\n- Look up all the `Roles` from the database that match the current `userId`.\n\n- For global routes, check that at least one of the returned roles is in the list of required roles for the route.\n\n- For scoped routes, do the same, but also check that the `organizationId` of the role matches the organization ID associated with the operation (I'll elaborate below).\n\nConsider these two endpoints for `Jobs`. The first will retrieve all the jobs associated with a specified organization. The second will find a single job by its id:\n\n### Example route 1:\n\n### `GET /jobs?organizationId=XXXXX`\n\n```\n@Roles(Role.MANAGER, Role.EMPLOYEE)\n@UseGuards(JwtAuthGuard, RolesGuard)\n@Get()\ngetMyJobs(@Query() query: {organizationId: string}) {\n return this.jobsService.getJobs({\n organizationId: query.organizationId,\n })\n}\n```\n\n### Example route 2:\n\n### `GET /jobs/:jobId`\n\n```\n@Roles(Role.MANAGER, Role.EMPLOYEE)\n@UseGuards(JwtAuthGuard, RolesGuard)\n@Get(':jobId')\ngetJob(@Param('jobId') jobId: string) {\n return this.jobsService.getJob(jobId)\n}\n```\n\nIn the first example, I know the `organizationId` without doing any work because it is required as a query parameter. This id can be matched against the id specified in the `Role`. This is trivial to validate, and ensures that only users who belong to that organization can access the endpoint.\n\nIn the second example, the `organizationId` is not provided. I can easily query it from the database by looking up the `Job`, but that is work that should be done in the service/business logic. Additionally, guard logic executes before `getJob`. This is where I am stuck.\n\nThe only solution I can come up with is to pass the `organizationId` in every request, perhaps as a url parameter or HTTP header. Seems like there should be a better option than that. I'm sure this pattern is very common, but I don't know what it is called to do any research. Any help regarding this implementation would be greatly appreciated!\n\n========================================\n\nCode:\n```js\n@Roles(Role.MANAGER, Role.EMPLOYEE)\n@UseGuards(JwtAuthGuard, RolesGuard)\n@Get()\ngetMyJobs(@Query() query: {organizationId: string}) {\n  return this.jobsService.getJobs({\n    organizationId: query.organizationId,\n  })\n}\n```\n\n```js\n@Roles(Role.MANAGER, Role.EMPLOYEE)\n@UseGuards(JwtAuthGuard, RolesGuard)\n@Get(':jobId')\ngetJob(@Param('jobId') jobId: string) {\n  return this.jobsService.getJob(jobId)\n}\n```\n\n```text\nUsers\n```\n\n```text\nOrganizations\n```\n\n```text\nSUPERUSER\n```\n\n```text\nMANAGER\n```\n\n```text\nUsers\n```\n\n```text\nOrganizations\n```\n\n```text\nRoles\n```\n\n```text\norganizationId\n```\n\n```text\nRole\n```\n\n```text\nRoles\n```\n\n```text\nuserId\n```\n\n```text\norganizationId\n```\n\n```text\nJobs\n```\n\n```text\nGET /jobs?organizationId=XXXXX\n```\n\n```text\nGET /jobs/:jobId\n```\n\n```text\norganizationId\n```\n\n```text\nRole\n```\n\n```text\norganizationId\n```\n\n```text\nJob\n```\n\n```text\ngetJob\n```\n\n```text\norganizationId\n```\n\n```js\n@Roles(Role.MANAGER, Role.EMPLOYEE)\n@UseGuards(JwtAuthGuard, RolesGuard)\n@Get()\ngetMyJobs(@User() user) { // get a user from request\n  return this.jobsService.getJobs({\n    organizationIds: user.availableOrganizationIds, // <<- filter by organizations\n  })\n}\n```\n\n```text\nRolesGuard\n```\n\n```text\nuser.availableOrganizationIds = []\n```\n\n========================================\n\nComments:\n- That's a fantastic solution! How did I not think of it","metadata":{"transformedAt":"2026-08-18T18:33:02.569Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":187,"estimatedTokens":1112}}1002{"id":"stack-67205590","source":"stackoverflow","questionId":67205590,"title":"Why Nest.js claims to be \"progressive\"?","tags":["javascript","nestjs"],"text":"Title: Why Nest.js claims to be \"progressive\"?\nTags: javascript, nestjs\nSource: Stack Overflow\n\nQuestion:\nJust on the first page of Nest, they proudly claim :\n\nA **progressive** Node.js framework for building efficient, reliable and scalable server-side applications.\n\nThe only word I can't grasp is **progressive** and what that can means in the programming world.\n\nCan anyone explain the concept to me?\n\n========================================\n\nComments:\n- It just means \"modern\". Which in layman's terms simply means \"fancier than the competition\". I don't think it is important enough to be an answer so I'm just leaving it as a comment. PWA or progressive-web-apps in your tag actually means something completely different. It means a web page that is a normal web page but can progressively (in stages) turn off online features and work completely offline if the page cannot connect to the server - it also allows PWA pages to be installed as icons on IOS and Android so the webpage behaves like an app\n- I know this question is old, but I recently asked myself the same thing and hereโ€™s what I found. When NestJS calls itself progressive, itโ€™s referring to incremental adoption. What I mean is this: you can start with a lightweight setup using familiar Express or Fastify patterns, then gradually introduce more advanced features like CQRS, scaling your architecture over time without needing a full rewrite.","metadata":{"transformedAt":"2026-08-18T18:33:02.569Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":18,"estimatedTokens":355}}1003{"id":"stack-75899822","source":"stackoverflow","questionId":75899822,"title":"How can I implement a gRPC ServerWritableStream in nest.js?","tags":["typescript","nestjs","protocol-buffers","grpc","grpc-web"],"text":"Title: How can I implement a gRPC ServerWritableStream in nest.js?\nTags: typescript, nestjs, protocol-buffers, grpc, grpc-web\nSource: Stack Overflow\n\nQuestion:\nThe nest.js documentation doesn't mention anything regarding the case of a unidirectional ServerWritableStream. I want to receive a normal request and use call.write to pass to the client streaming messages. This works fine in plain TypeScript using the below but it doesn't work from within a nest.js gRPC controller. I am also using Envoy which works fine with the unary calls on nest.js as well as with the simple server.\n\n```\nfunction doOnAdd(call) {\n setInterval(() => {\n const myTodo = JSON.stringify({\n id: 'b779cb10-72c8-416f-9399-273eab8e3421',\n title: 'Fix the server streaming',\n completed: false,\n });\n console.log('Sending streaming data', myTodo);\n call.write({message: myTodo});\n }, 5000);\n\n call.on('end', () => {\n console.log('end');\n });\n\n setTimeout(() => {\n call.end();\n }, 30000);\n}\n```\n\nBut this nest.js code does not work (unary gRPC calls work fine in the same controller).\n\n```\n@GrpcMethod('TodoService', 'OnAdded')\n async onAdded(\n request: todo.OnAddedTodoRequest,\n metadata: Metadata,\n call: ServerWritableStream,\n ) {\n setInterval(() => {\n const myTodo = JSON.stringify({\n id: 'b779cb10-72c8-416f-9399-273eab8e3421',\n title: 'Fix the server streaming',\n completed: false,\n });\n console.log('Sending streaming data', myTodo);\n const message = new todo.ServerMessage({ message: myTodo });\n call.write(message);\n }, 5000);\n\n call.on('end', () => {\n console.log('end');\n });\n\n setTimeout(() => {\n call.end();\n }, 30000);\n }\n```\n\nFinally here is the simplified protobuf:\n\n```\nsyntax = \"proto3\";\n\npackage todo;\n\nservice TodoService {\n rpc OnAdded (OnAddedTodoRequest) returns (stream ServerMessage);\n}\n\nmessage OnAddedTodoRequest {}\n\nmessage ServerMessage {\n string message = 1;\n}\n```\n\n========================================\n\nCode:\n```text\nfunction doOnAdd(call) {\n  setInterval(() => {\n    const myTodo = JSON.stringify({\n      id: 'b779cb10-72c8-416f-9399-273eab8e3421',\n      title: 'Fix the server streaming',\n      completed: false,\n    });\n    console.log('Sending streaming data', myTodo);\n    call.write({message: myTodo});\n  }, 5000);\n\n  call.on('end', () => {\n    console.log('end');\n  });\n\n  setTimeout(() => {\n    call.end();\n  }, 30000);\n}\n```\n\n```text\n@GrpcMethod('TodoService', 'OnAdded')\n  async onAdded(\n    request: todo.OnAddedTodoRequest,\n    metadata: Metadata,\n    call: ServerWritableStream<todo.OnAddedTodoRequest, todo.ServerMessage>,\n  ) {\n    setInterval(() => {\n      const myTodo = JSON.stringify({\n        id: 'b779cb10-72c8-416f-9399-273eab8e3421',\n        title: 'Fix the server streaming',\n        completed: false,\n      });\n      console.log('Sending streaming data', myTodo);\n      const message = new todo.ServerMessage({ message: myTodo });\n      call.write(message);\n    }, 5000);\n\n    call.on('end', () => {\n      console.log('end');\n    });\n\n    setTimeout(() => {\n      call.end();\n    }, 30000);\n  }\n```\n\n```text\nsyntax = \"proto3\";\n\npackage todo;\n\nservice TodoService {\n  rpc OnAdded (OnAddedTodoRequest) returns (stream ServerMessage);\n}\n\nmessage OnAddedTodoRequest {}\n\nmessage ServerMessage {\n  string message = 1;\n}\n```\n\n```text\n@GrpcMethod('TodoService', 'OnAdded')\n  async onAdded(\n    request: todo.OnAddedTodoRequest,\n    metadata: Metadata,\n    call: ServerWritableStream<todo.OnAddedTodoRequest, todo.ServerMessage>,\n  ) {\n  await new Promise((resolve) => {\n    setInterval(() => {\n      const myTodo = JSON.stringify({\n        id: 'b779cb10-72c8-416f-9399-273eab8e3421',\n        title: 'Fix the server streaming',\n        completed: false,\n      });\n      console.log('Sending streaming data', myTodo);\n      const message = new todo.ServerMessage({ message: myTodo });\n      call.write(message);\n    }, 5000);\n\n    call.on('end', () => {\n      console.log('end');\n      resolve();\n    });\n\n    setTimeout(() => {\n      call.end();\n    }, 30000);\n  });\n}\n```\n\n========================================\n\nComments:\n- excellent case! but I still don't understand how to make a client that will work with the ServerWritableStream. when I call the OnAdded method, the returned observer immediately becomes completed without receiving any data. Did you manage to make a client to handle OnAdded stream response?\n- nice! but I still don't understand how to make a client that will work with the ServerWritableStream. when I call the OnAdded method, the returned observer immediately becomes completed without receiving any data. is there an any example of a client for a stream-from-server handling?\n- The promise above keeps it from completing before receiving 'end'. If you want to handle the received messages from the streaming just add inside the promise something like: call.on('data', function(data) { // Process data via e.g. a handler });","metadata":{"transformedAt":"2026-08-18T18:33:02.569Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":183,"estimatedTokens":1220}}1004{"id":"stack-77096984","source":"stackoverflow","questionId":77096984,"title":"Nest can't resolve dependencies of the AuthGuard (?, JwtService, ConfigService). the argument UserModel at index [0] is available in the BookModule","tags":["node.js","mongodb","authentication","jwt","nestjs"],"text":"Title: Nest can't resolve dependencies of the AuthGuard (?, JwtService, ConfigService). the argument UserModel at index [0] is available in the BookModule\nTags: node.js, mongodb, authentication, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\n**auth.guard.ts**\n\n```\nimport {\n CanActivate,\n ExecutionContext,\n Injectable,\n UnauthorizedException,\n} from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Request } from 'express';\nimport { Model } from 'mongoose';\nimport { User } from '../user/entities/user.entity';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n constructor(\n @InjectModel(User.name)\n private userModel: Model,\n private jwtService: JwtService,\n private readonly configService: ConfigService,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise {\n const request = context.switchToHttp().getRequest();\n const token = this.extractTokenFromHeader(request);\n if (!token) {\n throw new UnauthorizedException(\n 'You are not authorized to access this resource.',\n );\n }\n try {\n const payload = await this.jwtService.verifyAsync(token, {\n secret: this.configService.get('JWT_SECRET'),\n });\n console.log('payload ->>', payload);\n const user = await this.userModel.findById(payload.id);\n\n if (!user) {\n throw new UnauthorizedException('User not found.');\n }\n request['user'] = user;\n } catch {\n throw new UnauthorizedException(\n 'You are not authorized to access this resource.',\n );\n }\n return true;\n }\n\n private extractTokenFromHeader(request: Request): string | undefined {\n const [type, token] = request.headers.authorization?.split(' ') ?? [];\n return type === 'Bearer' ? token : undefined;\n }\n}\n```\n\n**auth.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { JwtModule, JwtService } from '@nestjs/jwt';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { UserSchema } from '../user/entities/user.entity';\n\n@Module({\n imports: [\n JwtModule.registerAsync({\n inject: [ConfigService],\n useFactory: (config: ConfigService) => {\n return {\n global: true,\n secret: config.get('JWT_SECRET'),\n signOptions: {\n expiresIn: config.get('JWT_EXPIRES'),\n },\n };\n },\n }),\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n ],\n controllers: [AuthController],\n providers: [AuthService, JwtService],\n exports: [AuthService, JwtService],\n})\nexport class AuthModule {}\n```\n\n**book.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { BookService } from './book.service';\nimport { BookController } from './book.controller';\nimport { BookSchema } from './schema/book.schema';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { AuthModule } from '../auth/auth.module'; \n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'Book', schema: BookSchema }]),\n AuthModule,\n ],\n controllers: [BookController],\n providers: [BookService],\n})\nexport class BookModule {}\n```\n\n**book.controller.ts**\n\n```\nimport {\n Body,\n Controller,\n Get,\n HttpStatus,\n Param,\n Post,\n Query,\n Req,\n Res,\n UseGuards,\n} from '@nestjs/common';\nimport { BookService } from './book.service';\nimport { CreateBookDto } from './dto/create-book.dto';\nimport { UpdateBookDto } from './dto/update-book.dto';\nimport { Book } from './schema/book.schema';\nimport { AuthGuard } from '../auth/auth.guard';\nimport { Request, Response } from 'express';\n\n@Controller({\n version: '1',\n path: 'books',\n})\nexport class BookController {\n constructor(private bookService: BookService) {}\n\n @Post()\n async createBook(\n @Body()\n book: CreateBookDto,\n ): Promise {\n return this.bookService.create(book);\n }\n\n @UseGuards(AuthGuard)\n @Get()\n async getAllBooks(\n @Req() req: Request,\n @Res() res: Response,\n @Query() query: any,\n ): Promise {\n console.log(req.user);\n\n const books = await this.bookService.findAll(query);\n return res.status(HttpStatus.OK).json({\n data: books,\n statusCode: 200,\n message: 'Books fetched successfully.',\n });\n }\n}\n```\n\nI am receiving\n\nNest can't resolve dependencies of the AuthGuard (?, JwtService,\nConfigService). Please make sure that the argument UserModel at index\n[0] is available in the BookModule context.\n\nthis error. i don't know what am i missing\n\n========================================\n\nCode:\n```text\nimport {\n  CanActivate,\n  ExecutionContext,\n  Injectable,\n  UnauthorizedException,\n} from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { JwtService } from '@nestjs/jwt';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Request } from 'express';\nimport { Model } from 'mongoose';\nimport { User } from '../user/entities/user.entity';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  constructor(\n    @InjectModel(User.name)\n    private userModel: Model<User>,\n    private jwtService: JwtService,\n    private readonly configService: ConfigService,\n  ) {}\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const token = this.extractTokenFromHeader(request);\n    if (!token) {\n      throw new UnauthorizedException(\n        'You are not authorized to access this resource.',\n      );\n    }\n    try {\n      const payload = await this.jwtService.verifyAsync(token, {\n        secret: this.configService.get<string>('JWT_SECRET'),\n      });\n      console.log('payload ->>', payload);\n      const user = await this.userModel.findById(payload.id);\n\n      if (!user) {\n        throw new UnauthorizedException('User not found.');\n      }\n      request['user'] = user;\n    } catch {\n      throw new UnauthorizedException(\n        'You are not authorized to access this resource.',\n      );\n    }\n    return true;\n  }\n\n  private extractTokenFromHeader(request: Request): string | undefined {\n    const [type, token] = request.headers.authorization?.split(' ') ?? [];\n    return type === 'Bearer' ? token : undefined;\n  }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { JwtModule, JwtService } from '@nestjs/jwt';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { AuthController } from './auth.controller';\nimport { AuthService } from './auth.service';\nimport { UserSchema } from '../user/entities/user.entity';\n\n@Module({\n  imports: [\n    JwtModule.registerAsync({\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) => {\n        return {\n          global: true,\n          secret: config.get<string>('JWT_SECRET'),\n          signOptions: {\n            expiresIn: config.get<string | number>('JWT_EXPIRES'),\n          },\n        };\n      },\n    }),\n    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n  ],\n  controllers: [AuthController],\n  providers: [AuthService, JwtService],\n  exports: [AuthService, JwtService],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { BookService } from './book.service';\nimport { BookController } from './book.controller';\nimport { BookSchema } from './schema/book.schema';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { AuthModule } from '../auth/auth.module';    \n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: 'Book', schema: BookSchema }]),\n    AuthModule,\n  ],\n  controllers: [BookController],\n  providers: [BookService],\n})\nexport class BookModule {}\n```\n\n```text\nimport {\n  Body,\n  Controller,\n  Get,\n  HttpStatus,\n  Param,\n  Post,\n  Query,\n  Req,\n  Res,\n  UseGuards,\n} from '@nestjs/common';\nimport { BookService } from './book.service';\nimport { CreateBookDto } from './dto/create-book.dto';\nimport { UpdateBookDto } from './dto/update-book.dto';\nimport { Book } from './schema/book.schema';\nimport { AuthGuard } from '../auth/auth.guard';\nimport { Request, Response } from 'express';\n\n@Controller({\n  version: '1',\n  path: 'books',\n})\nexport class BookController {\n  constructor(private bookService: BookService) {}\n\n  @Post()\n  async createBook(\n    @Body()\n    book: CreateBookDto,\n  ): Promise<Book> {\n    return this.bookService.create(book);\n  }\n\n  @UseGuards(AuthGuard)\n  @Get()\n  async getAllBooks(\n    @Req() req: Request,\n    @Res() res: Response,\n    @Query() query: any,\n  ): Promise<any> {\n    console.log(req.user);\n\n    const books = await this.bookService.findAll(query);\n    return res.status(HttpStatus.OK).json({\n      data: books,\n      statusCode: 200,\n      message: 'Books fetched successfully.',\n    });\n  }\n}\n```\n\n```text\nUserModel\n```\n\n```text\nBookModule\n```\n\n```text\nAuthModule\n```\n\n```text\nMongooseModule.forFeature([{ name: 'User', schema: UserSchema }])\n```\n\n```text\nMongooseModule\n```\n\n```text\nAuthModule\n```\n\n```text\nexports\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":373,"estimatedTokens":2209}}1005{"id":"stack-70500040","source":"stackoverflow","questionId":70500040,"title":"Nestjs HttpService error handling with AxiosRequestConfig's validateStatus function","tags":["node.js","typescript","nestjs","httpmodule","httpservice"],"text":"Title: Nestjs HttpService error handling with AxiosRequestConfig's validateStatus function\nTags: node.js, typescript, nestjs, httpmodule, httpservice\nSource: Stack Overflow\n\nQuestion:\nI need to handle http errors status code (such as 401, 500, etc) which can occur when consuming an external service using HttpService (HttpModule of Nestjs). Here is the implementation i am working on:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { HttpService } from '@nestjs/axios';\nimport { Logger } from '@nestjs/common';\nimport { AxiosRequestConfig } from 'axios';\nimport { catchError, firstValueFrom, map } from 'rxjs';\n\ntype Person = {\n name: string;\n lastName: string;\n};\n\n@Injectable()\nexport class PersonService {\n constructor(private httpService: HttpService) {}\n async findPerson(): Promise {\n const axiosConfig: AxiosRequestConfig = {\n method: 'get',\n url: 'https://service.dns/path/person',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${jwt}`,\n },\n validateStatus: function (status: number) {\n return status === 200;\n },\n };\n\n const personInstance: Person = await firstValueFrom(\n this.httpService.request(axiosConfig).pipe(\n catchError((e) => {\n Logger.error(e.response.data.errorMessage);\n throw new Error('internal communication error');\n }),\n map((res) => {\n return res.data;\n }),\n ),\n );\n return personInstance;\n }\n}\n```\n\nIn the code above, I just need the function `catchError` throws the custom error, but I am not able to make the function `validateStatus` to trigger the execution of `catchError`.\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { HttpService } from '@nestjs/axios';\nimport { Logger } from '@nestjs/common';\nimport { AxiosRequestConfig } from 'axios';\nimport { catchError, firstValueFrom, map } from 'rxjs';\n\ntype Person = {\n  name: string;\n  lastName: string;\n};\n\n@Injectable()\nexport class PersonService {\n  constructor(private httpService: HttpService) {}\n  async findPerson(): Promise<Person> {\n    const axiosConfig: AxiosRequestConfig = {\n      method: 'get',\n      url: 'https://service.dns/path/person',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${jwt}`,\n      },\n      validateStatus: function (status: number) {\n        return status === 200;\n      },\n    };\n\n    const personInstance: Person = await firstValueFrom(\n      this.httpService.request(axiosConfig).pipe(\n        catchError((e) => {\n          Logger.error(e.response.data.errorMessage);\n          throw new Error('internal communication error');\n        }),\n        map((res) => {\n          return res.data;\n        }),\n      ),\n    );\n    return personInstance;\n  }\n}\n```\n\n```text\ncatchError\n```\n\n```text\nvalidateStatus\n```\n\n```text\ncatchError\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { HttpService } from '@nestjs/axios';\nimport { Logger } from '@nestjs/common';\nimport { AxiosRequestConfig } from 'axios';\nimport { firstValueFrom } from 'rxjs';\n\ntype Person = {\n  name: string;\n  lastName: string;\n};\n\n@Injectable()\nexport class PersonService {\n  constructor(private httpService: HttpService) {}\n  async findPerson(): Promise<Person> {\n    const axiosConfig: AxiosRequestConfig = {\n      method: 'get',\n      url: 'https://service.dns/path/person',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer fake_jwt`,\n      },\n      validateStatus: function (status: number) {\n        return status === 200;\n      },\n    };\n\n    return firstValueFrom(this.httpService.request(axiosConfig))\n      .then((res) => res.data)\n      .catch((e) => {\n        Logger.error(e.errorMessage);\n        throw new Error('internal communication error');\n      });\n  }\n}\n```\n\n```text\nvalidateStatus\n```\n\n```text\nAxiosRequestConfig\n```\n\n```text\nPromise<AxiosResponse<any>>\n```\n\n```text\nObservable<AxiosResponse<any>\n```\n\n========================================\n\nComments:\n- this answer may help you. stackoverflow.com/questions/55601651/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":170,"estimatedTokens":1010}}1006{"id":"stack-71985215","source":"stackoverflow","questionId":71985215,"title":"How to pass a Date in url param and how to validate it with class-validator?","tags":["rest","nestjs","class-validator"],"text":"Title: How to pass a Date in url param and how to validate it with class-validator?\nTags: rest, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to validate a date param (with class-validator) in my Nest.js api; below is what I have:\n\n```\nclass DateValidate {\n @IsDate()\n date: Date;\n}\n```\n\n```\n@Get('day/:day')\n getDayMealsPlan(@Param('day') day: DateValidate): any {\n return day;\n }\n```\n\nI'm passing the date param in the URL like so:\n\n```\nlocalhost:3000/meals/day/2022-03-06T11:00:00.000Z\n```\n\nIt's throwing me a 400 error:\n\n```\n{\n \"statusCode\": 400,\n \"message\": [\n \"date must be a Date instance\"\n ],\n \"error\": \"Bad Request\"\n}\n```\n\nI have a 2 part question:\n\n- How to validate a date?\n\n- How would a date look in the param? Is this the right way to do it: 2022-03-06T11:00:00.000Z\n\n========================================\n\nTop Answer:\nI believe it should be:\n\n```\n@Get('day/:date') // <\ngetDayMealsPlan(@Param() o: DateValidate): any {\n return o.date\n}\n```\n\n========================================\n\nCode:\n```text\nclass DateValidate {\n  @IsDate()\n  date: Date;\n}\n```\n\n```text\n@Get('day/:day')\n  getDayMealsPlan(@Param('day') day: DateValidate): any {\n    return day;\n  }\n```\n\n```text\nlocalhost:3000/meals/day/2022-03-06T11:00:00.000Z\n```\n\n```text\n{\n    \"statusCode\": 400,\n    \"message\": [\n        \"date must be a Date instance\"\n    ],\n    \"error\": \"Bad Request\"\n}\n```\n\n```js\nclass DateValidate {\n  @IsDate()\n  @Type(() => Date)\n  day: Date;\n}\n```\n\n```js\n@Controller('something')\nexport class SomethingController {\n  @Get('day/:day')\n  getDayMealsPlan(@Param() params: DateValidate) {\n    console.log(params.day instanceof Date); // true\n    return params;\n  }\n}\n```\n\n```text\n2022-03-06T11:00:00.000Z\n```\n\n```text\nnot Date instance\n```\n\n```text\nType\n```\n\n```text\nclass-transformer\n```\n\n```js\n@Get('day/:date') // <\ngetDayMealsPlan(@Param() o: DateValidate): any {\n  return o.date\n}\n```\n\n========================================\n\nComments:\n- by using `@Param('day') day: DateValidate` you're telling that `day` is a object with `date` prop in it, but `req.params.day` isn't, that's why you're getting 400\n- So how should I be doing this so that it validates the Date properly. And how would I pass it in the url param\n- That gives me the same error unfortunately\n- Did you just repeat what comment above yours said?\n- I see, so when it comes in the url param, it's always a string and you'll have to change it to the type you want to validate. Thanks, your solution worked :)","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":138,"estimatedTokens":625}}1007{"id":"stack-66495537","source":"stackoverflow","questionId":66495537,"title":"NestJS e2e test mock Session decorator","tags":["node.js","typescript","session","nestjs"],"text":"Title: NestJS e2e test mock Session decorator\nTags: node.js, typescript, session, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to write an e2e test with supertest where my controller actually makes use of the `@Session()` decorator. I however don't want to have the full burden of initiating a session with db connection and so on so my app in the test does not actually initialize the session.\n\nI'd instead like to mock away the data provided by the Decorator in the first place and replace it with static data. I can't really find a solution as to how to realize this however.\n\nSample from controller:\n\n```\n@Get('/user/me')\npublic async getMe(@Session() session: Record) {\n if (!session?.user) {\n throw new InternalServerErrorException();\n }\n return session.user;\n}\n```\n\nWhat I'd ideally like the mock to look like:\n\n```\njest.mock(Session, jest.fn().mockImplementation(() => {\n return { user: { name: \"test user\" } };\n})\n```\n\nhowever this won't work.\n\nAccording to the official TypeScript documentation Parameter decorators can only be used to observe that a parameter has been set on a particular method. As this is not actually what's happening when using the `@Session()` decorator I tried having a look at the source code of how nestjs actually implements these decorators and I'm having at some trouble understanding it correctly.\n\nIf I'm not mistaking it seems like the decorator writes some metadata another decorator (probably `@Get()` in this case?) can make use of and extract the necessary data based on that.\n\nI'm a little confused as to how to test this properly so I'd be very thankful for some advice :)\n\n===========================================================================\n\nUpdate: I will now go ahead and instead of mocking the Session decorator itself mock the req.session while setting up my `app` in `beforeAll()` hook. Therefore I chose the following solution:\n\n```\napp.use((req, res, next) => {\n req.session = {\n user: {\n firstName: 'Max',\n lastName: 'Mustermann',\n },\n };\n next();\n});\n```\n\nI'll still be very happy in case someone knows a better solution.\n\n========================================\n\nCode:\n```text\n@Get('/user/me')\npublic async getMe(@Session() session: Record<string, unknown>) {\n  if (!session?.user) {\n    throw new InternalServerErrorException();\n  }\n  return session.user;\n}\n```\n\n```text\njest.mock(Session, jest.fn().mockImplementation(() => {\n  return { user: { name: \"test user\" } };\n})\n```\n\n```text\napp.use((req, res, next) => {\n    req.session = {\n      user: {\n        firstName: 'Max',\n        lastName: 'Mustermann',\n      },\n    };\n    next();\n});\n```\n\n```text\n@Session()\n```\n\n```text\n@Session()\n```\n\n```text\n@Get()\n```\n\n```text\napp\n```\n\n```text\nbeforeAll()\n```\n\n```js\n/**\n * Hook for overriding the testing module\n */\nexport type TestingModuleCreatePreHook = (\n  moduleBuilder: TestingModuleBuilder,\n) => TestingModuleBuilder;\n\n\n/**\n * Hook for adding items to nest application\n */\nexport type TestingAppCreatePreHook = (\n  app: NestExpressApplication,\n) => Promise<void>;\n\n/**\n * Sets basic e2e testing module of app\n */\nexport async function basicE2eSetup(\n  config: {\n    moduleBuilderHook?: TestingModuleCreatePreHook;\n    appInitHook?: TestingAppCreatePreHook;\n  } = {},\n): Promise<[NestExpressApplication, TestingModule]> {\n  let moduleBuilder: TestingModuleBuilder = Test.createTestingModule({\n    imports: [AppModule],\n  });\n\n  if (!!config.moduleBuilderHook) {\n    moduleBuilder = config.moduleBuilderHook(moduleBuilder);\n  }\n\n  const moduleFixture: TestingModule = await moduleBuilder.compile();\n  const app = moduleFixture.createNestApplication<NestExpressApplication>();  \n\n  if (config.appInitHook) {\n    await config.appInitHook(app);\n  }\n\n  return [await app.init(), moduleFixture];\n}\n```\n\n```js\ndescribe('AppController (e2e)', () => {\n  let app: INestApplication;\n\n  beforeEach(async () => {\n    [app] = await basicE2eSetup({\n      moduleBuilderHook: (moduleBuilder) => {\n        // your overrides go here\n        // Refer: https://docs.nestjs.com/fundamentals/testing#end-to-end-testing\n        // eg: moduleBuilder.overrideProvider(ProviderName).useValue(value)\n        return moduleBuilder;\n      },\n      appInitHook: async (app) => {\n        const result = await someAction();\n        // or get some service from app \n        // eg: const service = app.get<YourService>(YourService)\n        app.use((req, res, next) => {\n          // do something with request of response object\n          next();\n        })\n      } \n    });\n  });\n\n  it('/ (GET)', () => {\n    return request(app.getHttpServer())\n      .get('/')\n      .expect((res) => {\n        expect(res.text).toContain('Hi There');\n      });\n  });\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":183,"estimatedTokens":1175}}1008{"id":"stack-71938904","source":"stackoverflow","questionId":71938904,"title":"How to create multilevel nested queries in nestjs/graphql using @ResolveField?","tags":["node.js","graphql","nestjs","graphql-js"],"text":"Title: How to create multilevel nested queries in nestjs/graphql using @ResolveField?\nTags: node.js, graphql, nestjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\n### Hello. I can't figure out how to create multiple levels of nested queries with @ResolveFiled. I hope for your help. ๐Ÿ™\n\nWhat I'm doing and Context:\n\nI have a product. The product has a supplier. A vendor-specific product contains product variants. Variants contain options.\n\nI need to make a request in 4 levels:\n\n- Product\n\n- ProductHasProvider\n\n- Product Variants\n\n- Variant Options\n\nI use the \"Code First\" approach, created an ObjectType for each entity. Next, I create a \"Product\" resolver.\n\nCreating a second level \"ProductHasProvider\" with @ResolveField\n\nWhen adding a ResolveField (\"Providers\") - it appears inside the main resolver \"Product\" and resolves the Providers ObjectType. Okay, it works, I can make requests at the 2nd level correctly.\n\n```\n@ResolveField('Providers', () => [ProductHasProvider])\nasync getProductProviders(@Parent() product: Product) {\n const { id } = product;\n return await this.productListService.ProductsProviders({ id });\n}\n```\n\n- I want to make third level where ProductHasProvider has Variants. I decorate ProductHasProvider as the parent.\n\n```\n@ResolveField('variants', (type) => [Variant])\nasync getVariants(@Parent() productHasProvider: ProductHasProvider) {\n const { id } = productHasProvider;\n return await this.productListService.getVariants({ id });\n}\n```\n\nIn this case, this ResolveField defines the ObjectType for [Variants], but for some reason at the first level. That is, in Apollo studio, the field is displayed in \"Product\". I can't query Variants for ProductHasProvider.\n\n```\nquery Products {\n getProducts {\n Providers {\n id\n }\n variants {\n id\n options {\n id\n }\n }\n }\n}\n```\n\nExpected behavior:\n\nI add a new @ResolveField(() => [Variants]) with \"ProductHasProvider\" parent (Which is already @ResorveField for Product). And I can do 3rd and 4th level queries.\n\n```\nquery Products {\n getProducts {\n id\n Providers {\n id\n variants {\n id\n options {\n id\n }\n }\n }\n }\n}\n```\n\nPlease tell me what I'm doing wrong and how to achieve what I want. Thank you.๐Ÿ™\n\n========================================\n\nCode:\n```js\n@ResolveField('Providers', () => [ProductHasProvider])\nasync getProductProviders(@Parent() product: Product) {\n  const { id } = product;\n  return await this.productListService.ProductsProviders({ id });\n}\n```\n\n```js\n@ResolveField('variants', (type) => [Variant])\nasync getVariants(@Parent() productHasProvider: ProductHasProvider) {\n  const { id } = productHasProvider;\n  return await this.productListService.getVariants({ id });\n}\n```\n\n```text\nquery Products {\n  getProducts {\n    Providers {\n      id\n    }\n    variants {\n      id\n      options {\n        id\n      }\n    }\n  }\n}\n```\n\n```text\nquery Products {\n  getProducts {\n    id\n    Providers {\n      id\n      variants {\n        id\n        options {\n          id\n        }\n      }\n    }\n  }\n}\n```\n\n```text\n@Resolver('Product')\nexport class ProductsResolver {\n\n  @ResolveField('Providers', () => [ProductHasProvider])\n  async getProductProviders (@Parent() product: Product) {\n    const { id } = product;\n    return await this.productListService.ProductsProviders( { id });\n  }\n}\n```\n\n```text\n@Resolver('Provider')\nexport class ProvidersResolver {\n\n  @ResolveField('variants', () => [Variant])\n  async getProductProviders (@Parent() provider: ProductHasProvider) {\n    const { id } = provider;\n    return await this.variantsService.getVariantForProvider( { id });\n  }\n}\n```\n\n```text\n@ResolveField\n```\n\n```text\nResolver\n```\n\n```text\nResolver\n```\n\n```text\n@ResolveField\n```\n\n```text\n@ResolveField\n```\n\n```text\nResolver\n```\n\n```text\nResolver\n```\n\n========================================\n\nComments:\n- It just worked. Thanks a lo๐Ÿ™. I immediately knew that it was necessary to do this, but for some reason I convinced myself ๐Ÿคทโ€โ™‚๏ธ.\n- Just wanted to alert you to the n + 1 problem that can occur when configuring ResolverField. I the article at https://blog.logrocket.com/use-dataloader-nestjs.\n- \"return await\" is superfluous, u wrap promise inside promise","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":196,"estimatedTokens":1032}}1009{"id":"stack-72852781","source":"stackoverflow","questionId":72852781,"title":"NestJS Inject Factory provider into another Factory","tags":["typescript","nestjs"],"text":"Title: NestJS Inject Factory provider into another Factory\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have reviewed questions here, and they didn't help with my problem:\n\n- NestJS - Inject factory provider into another provider doesn't work\n\nI want to create an async provider that will fetch configs from remote repository, which I implemented like this:\n\n```\nimport { Injectable, Provider } from '@nestjs/common';\n@Injectable()\nexport class ApiConfigService {\n private config: any;\n\n public async init() {\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n this.config = {\n data: 3,\n };\n }\n}\n\nexport const API_CONFIG_FACTORY = 'API_CONFIG_FACTORY';\n\nconst createApiConfigFactory = () => {\n return {\n generate: async function () {\n const apiConfigService = new ApiConfigService();\n await apiConfigService.init();\n return apiConfigService;\n },\n };\n};\n\nexport const ApiConfigFactory: Provider = {\n provide: API_CONFIG_FACTORY,\n useFactory: createApiConfigFactory,\n};\n```\n\n**api-config.module.ts:**\n\n```\nimport { Module } from '@nestjs/common';\nimport { ApiConfigFactory } from './api-config.service';\n\n@Module({\n imports: [],\n providers: [ApiConfigFactory],\n exports: [ApiConfigFactory],\n})\nexport class ApiConfigModule {}\n```\n\nI also want to use that module in nestjs ThrottlerModule but when I try to do so:\n\n```\nimport { Module } from '@nestjs/common';\nimport { ThrottlerModule } from '@nestjs/throttler';\nimport { ApiConfigModule } from './api-config/api-config.module';\nimport { ApiConfigFactory } from './api-config/api-config.service';\n\n@Module({\n imports: [\n ApiConfigModule,\n ThrottlerModule.forRootAsync({\n imports: [ApiConfigModule],\n inject: [ApiConfigFactory],\n useFactory: (config: any) => {\n console.log('@config');\n console.log(config);\n\n return {\n ttl: config.get('throttle_api_ttl'),\n limit: config.get('throttle_api_limit'),\n };\n },\n }),\n ],\n})\nexport class AppModule {}\n```\n\nIt returns this error:\n\n```\nError: Nest can't resolve dependencies of the THROTTLER:MODULE_OPTIONS (?). Please make sure that the argument [object Object] at index [0] is available in the ThrottlerModule context.\n\nPotential solutions:\n- If [object Object] is a provider, is it part of the current ThrottlerModule?\n- If [object Object] is exported from a separate @Module, is that module imported within ThrottlerModule?\n @Module({\n imports: [ /* the Module containing [object Object] */ ]\n })\n```\n\nHow can I successfully implement async config provider that I would be able to inject into ThrottlerModule?\n\nThanks in advance for your time!\n\n========================================\n\nCode:\n```text\nimport { Injectable, Provider } from '@nestjs/common';\n@Injectable()\nexport class ApiConfigService {\n  private config: any;\n\n  public async init() {\n    await new Promise((resolve) => setTimeout(resolve, 500));\n\n    this.config = {\n      data: 3,\n    };\n  }\n}\n\nexport const API_CONFIG_FACTORY = 'API_CONFIG_FACTORY';\n\nconst createApiConfigFactory = () => {\n  return {\n    generate: async function () {\n      const apiConfigService = new ApiConfigService();\n      await apiConfigService.init();\n      return apiConfigService;\n    },\n  };\n};\n\nexport const ApiConfigFactory: Provider = {\n  provide: API_CONFIG_FACTORY,\n  useFactory: createApiConfigFactory,\n};\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ApiConfigFactory } from './api-config.service';\n\n@Module({\n  imports: [],\n  providers: [ApiConfigFactory],\n  exports: [ApiConfigFactory],\n})\nexport class ApiConfigModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ThrottlerModule } from '@nestjs/throttler';\nimport { ApiConfigModule } from './api-config/api-config.module';\nimport { ApiConfigFactory } from './api-config/api-config.service';\n\n@Module({\n  imports: [\n    ApiConfigModule,\n    ThrottlerModule.forRootAsync({\n      imports: [ApiConfigModule],\n      inject: [ApiConfigFactory],\n      useFactory: (config: any) => {\n        console.log('@config');\n        console.log(config);\n\n        return {\n          ttl: config.get('throttle_api_ttl'),\n          limit: config.get('throttle_api_limit'),\n        };\n      },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nError: Nest can't resolve dependencies of the THROTTLER:MODULE_OPTIONS (?). Please make sure that the argument [object Object] at index [0] is available in the ThrottlerModule context.\n\nPotential solutions:\n- If [object Object] is a provider, is it part of the current ThrottlerModule?\n- If [object Object] is exported from a separate @Module, is that module imported within ThrottlerModule?\n  @Module({\n    imports: [ /* the Module containing [object Object] */ ]\n  })\n```\n\n```js\nThrottlerModule.forRootAsync({\n  imports: [ApiConfigModule],\n  inject: [API_CONFIG_FACTORY],                // -> Provider token HERE\n  useFactory: (config: ApiConfigService) => {  // -> ApiConfigService HERE\n    return {\n      ttl: config.get('throttle_api_ttl'),\n      limit: config.get('throttle_api_limit'),\n    };\n  },\n}),\n```\n\n```js\n@Module({\n  imports: [],\n  providers: [\n    {\n      provide: ApiConfigService,\n      useFactory: async () => {\n        const apiConfigService = new ApiConfigService();\n        await apiConfigService.init();\n        return apiConfigService;\n      },\n    },\n  ],\n  exports: [ApiConfigService],\n})\nexport class ApiConfigModule {}\n```\n\n```js\nThrottlerModule.forRootAsync({\n  imports: [ApiConfigModule],\n  inject: [ApiConfigService],\n  useFactory: (config: ApiConfigService) => {\n    return {\n      ttl: config.get('throttle_api_ttl'),\n      limit: config.get('throttle_api_limit'),\n    };\n  },\n}),\n```\n\n```text\nApiConfigFactory\n```\n\n```text\nAPI_CONFIG_FACTORY\n```\n\n```text\nconfig\n```\n\n```text\napi-config.module.ts\n```\n\n```text\napp.module.ts\n```\n\n========================================\n\nComments:\n- I'm stuck on a similar issue... How can I instantiate `ApiConfigService` (to then call its `init()` method) in case it does inject 2 dependencies in the constructor?","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":258,"estimatedTokens":1493}}1010{"id":"stack-55626582","source":"stackoverflow","questionId":55626582,"title":"Can't use @Res() with FilesInterceptor()","tags":["javascript","node.js","typescript","multer","nestjs"],"text":"Title: Can't use @Res() with FilesInterceptor()\nTags: javascript, node.js, typescript, multer, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to upload a file using builtin multer and after then sending the response back to the user for success or failure. It was all going good until today, when I try to upload the Response wont come. after digging a bit I find out that when i use @res with @UploadedFile it does not execute the controller. I am new to nest.js.\n\nWorking.\n\n```\n@Post('uploads/avatar')\nasync uploadFile(@Req() req, @UploadedFile() avatar) {\n console.log(req.body);\n if (!req.body.user_id) {\n throw new Error('id params not found.');\n }\n try {\n const resultUpload = await this.userService.uploadUserImage(\n req.body.user_id,\n avatar, \n ); // returns the url for the uploaded image\n return resultUpload;\n } catch (error) {\n console.log(error);\n return error;\n }\n}\n```\n\nNot Working.\n\n```\n@Post('uploads/avatar')\nasync uploadFile(@Req() req, @UploadedFile() avatar, @Res() res) {\n console.log(req.body);\n if (!req.body.user_id) {\n throw new Error('id params not found.');\n }\n try {\n const resultUpload = await this.userService.uploadUserImage(\n req.body.user_id,\n avatar, \n ); // returns the url for the uploaded image\n return resultUpload;\n res.send(resultUpload);\n } catch (error) {\n console.log(error);\n res.send(error);\n }\n}\n```\n\n========================================\n\nTop Answer:\nlook, when you are using an interceptor, you are handling (with using `.handle()`) the stream of response (`observable`) not a whole package of it, **but** using express `@Res` actually is somehow getting around the whole flow of response streaming.\n\nthis is also explicitly mentioned in nestjs official documents:\n\nWe already know that handle() returns an Observable. The stream\ncontains the value returned from the route handler, and thus we can\neasily mutate it using RxJS's map() operator.\n\nWARNING\n\nThe response mapping feature doesn't work with the\nlibrary-specific response strategy (using the @Res() object directly\nis forbidden).\n\n========================================\n\nCode:\n```text\n@Post('uploads/avatar')\nasync uploadFile(@Req() req, @UploadedFile() avatar) {\n  console.log(req.body);\n  if (!req.body.user_id) {\n    throw new Error('id params not found.');\n  }\n  try {\n    const resultUpload = await this.userService.uploadUserImage(\n      req.body.user_id,\n      avatar, \n    ); // returns the url for the uploaded image\n    return resultUpload;\n  } catch (error) {\n    console.log(error);\n    return error;\n  }\n}\n```\n\n```text\n@Post('uploads/avatar')\nasync uploadFile(@Req() req, @UploadedFile() avatar, @Res() res) {\n  console.log(req.body);\n  if (!req.body.user_id) {\n    throw new Error('id params not found.');\n  }\n  try {\n    const resultUpload = await this.userService.uploadUserImage(\n      req.body.user_id,\n      avatar,      \n    ); // returns the url for the uploaded image\n    return resultUpload;\n   res.send(resultUpload);\n  } catch (error) {\n    console.log(error);\n    res.send(error);\n  }\n}\n```\n\n```text\n@Post('uploads/avatar')\nasync uploadFile(@Req() req, @UploadedFile() avatar) {\n  if (!req.body.user_id) {\n    // throw a 400\n    throw new BadRequestException('id params not found.');\n  }\n  try {\n    const resultUpload = await this.userService.uploadUserImage(\n      req.body.user_id,\n      avatar, \n    );\n    return resultUpload;\n  } catch (error) {\n    if (error.code === 'image_already_exists') {\n      // throw a 409\n      throw new ConflictException('image has already been uploaded');\n    } else {\n      // throw a 500\n      throw new InternalServerException();\n    }\n  }\n}\n```\n\n```text\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const UserId = createParamDecorator((data, req) => {\n  if (!req.body || !req.body.user_id) {\n    throw new BadRequestException('No user id given.')\n  }\n  return req.body.user_id;\n});\n```\n\n```text\n@Post('uploads/avatar')\nasync uploadFile(@UserId() userId, @UploadedFile() avatar) {\n```\n\n```text\n@Res\n```\n\n```text\n@Res\n```\n\n```text\nPromises\n```\n\n```text\nObservables\n```\n\n```text\nHttpException\n```\n\n```text\nNotFoundException\n```\n\n```text\n@Res\n```\n\n```text\nFilesInterceptor\n```\n\n```text\nmulter\n```\n\n```text\nuserId\n```\n\n```text\n.handle()\n```\n\n```text\nobservable\n```\n\n```text\n@Res\n```\n\n========================================\n\nComments:\n- I have doubts about this concept, but this clears them all. Thanks alot.\n- What are your doubts? One of the big advantages of nest is that you don't have to handle the response object directly but you can use the higher-level abstractions the framework offers instead.\n- I am developing an api. I used @Res in most of the controllers but when I tried it with @UploadedFile() I was not working. I had the doubt that it was because of multer that they implemented in the framework.\n- also how can I return a json object using automatic sending response? `{ status: \"OK\", mesage: \"Successful\"}`\n- Just return a javascript object, it will automatically be serialized to JSON.","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":214,"estimatedTokens":1252}}1011{"id":"stack-51493154","source":"stackoverflow","questionId":51493154,"title":"Cannot deploy nest.js project to Google Firebase Functions","tags":["javascript","firebase","google-cloud-functions","nestjs"],"text":"Title: Cannot deploy nest.js project to Google Firebase Functions\nTags: javascript, firebase, google-cloud-functions, nestjs\nSource: Stack Overflow\n\nQuestion:\nNestJs uses ES6, ES7 and ES8, but Firebase Functions is stuck at Node v.6.11.\n\nI tried to write a webpack config file w/ babel to transpile both my files and the node_modules to node v6.11 but I'm not able to complete the deploy due to a syntax error caused by an async function in the @nestjs/common/interceptors/file-fields.interceptor.js file.\n\n```\nโš  functions[api]: Deployment error.\nFunction load error: Code in file dist/index.js can't be loaded.\nIs there a syntax error in your code?\nDetailed stack trace: /user_code/node_modules/@nestjs/common/interceptors/file-fields.interceptor.js:10\n async intercept(context, call$) {\n ^^^^^^^^^\n\nSyntaxError: Unexpected identifier\n at createScript (vm.js:56:10)\n at Object.runInThisContext (vm.js:97:10)\n at Module._compile (module.js:549:28)\n at Object.Module._extensions..js (module.js:586:10)\n at Module.load (module.js:494:32)\n at tryModuleLoad (module.js:453:12)\n at Function.Module._load (module.js:445:3)\n at Module.require (module.js:504:17)\n at require (internal/module.js:20:19)\n at Object. (/user_code/node_modules/@nestjs/common/interceptors/index.js:6:10)\n```\n\nHere's my webpack.config.js file:\n\n```\n'use strict';\nconst nodeExternals = require('webpack-node-externals');\nmodule.exports = {\n entry: './src/server.ts',\n output: {\n filename: 'index.js',\n libraryTarget: 'this'\n },\n target: 'node',\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: [\n { \n loader: 'babel-loader',\n options: {\n presets: [\n [\n '@babel/preset-env',\n {\n \"targets\": {\n \"node\": \"6.11.1\"\n }\n },\n '@babel/stage-0'\n ]\n ],\n plugins: [require('@babel/plugin-transform-async-to-generator')]\n }\n }, \n {\n loader: 'ts-loader',\n options: {\n transpileOnly: true\n }\n }\n ]\n },\n {\n test: /\\.js$/,\n use: [\n { \n loader: 'babel-loader',\n options: {\n presets: [\n [\n '@babel/preset-env',\n {\n \"targets\": {\n \"node\": \"6.11.1\"\n }\n },\n '@babel/stage-0'\n ]\n ],\n plugins: [require('@babel/plugin-transform-async-to-generator')]\n }\n }\n ]\n }\n ]\n },\n resolve: {\n extensions: [ '.ts', '.tsx', '.js' ]\n },\n externals: [nodeExternals()]\n};\n```\n\nMy tsconfig.json:\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\"es6\", \"es2015.promise\"],\n \"module\": \"commonjs\",\n \"noImplicitAny\": false,\n \"outDir\": \"\",\n \"sourceMap\": true,\n \"removeComments\": true,\n \"noLib\": false,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowJs\": true,\n \"target\": \"es6\",\n \"typeRoots\": [\n \"node_modules/@types\"\n ]\n },\n \"include\": [\n \"src/**/*.ts\",\n \"spec/**/*.ts\"\n ],\n \"exclude\": [\n \"**/*.spec.ts\"\n ]\n}\n```\n\nWhat's wrong?\n\n========================================\n\nTop Answer:\nNode 6 won't run any code using the `async` keyword as it doesn't support async functions from ES2017.\n\nI'd recommend trying to use TypeScript for the transpilation of your code, using `es6` as a `target` in your `tsconfig.json`. It should transpile async functions. Please keep in mind that you might have to load specific polyfills depending on your needs. And you're probably aware of this detail but NestJS specifies Node 8.9+, as documented here:\n\n We the Node.js release schedule which recently moved to 8.x as an active LTS version. Therefore, Nest 5 supports >= 8.9.0 as the lowest version now. This shift gaves us sustainable performance boosts thanks to the es2017 target of the TypeScript compilation.\n\n========================================\n\nCode:\n```text\nโš   functions[api]: Deployment error.\nFunction load error: Code in file dist/index.js can't be loaded.\nIs there a syntax error in your code?\nDetailed stack trace: /user_code/node_modules/@nestjs/common/interceptors/file-fields.interceptor.js:10\n        async intercept(context, call$) {\n              ^^^^^^^^^\n\nSyntaxError: Unexpected identifier\n    at createScript (vm.js:56:10)\n    at Object.runInThisContext (vm.js:97:10)\n    at Module._compile (module.js:549:28)\n    at Object.Module._extensions..js (module.js:586:10)\n    at Module.load (module.js:494:32)\n    at tryModuleLoad (module.js:453:12)\n    at Function.Module._load (module.js:445:3)\n    at Module.require (module.js:504:17)\n    at require (internal/module.js:20:19)\n    at Object.<anonymous> (/user_code/node_modules/@nestjs/common/interceptors/index.js:6:10)\n```\n\n```text\n'use strict';\nconst nodeExternals = require('webpack-node-externals');\nmodule.exports = {\n    entry: './src/server.ts',\n    output: {\n        filename: 'index.js',\n        libraryTarget: 'this'\n    },\n    target: 'node',\n    module: {\n        rules: [\n            {\n                test: /\\.tsx?$/,\n                use: [\n                    { \n                        loader: 'babel-loader',\n                        options: {\n                            presets: [\n                                [\n                                    '@babel/preset-env',\n                                    {\n                                        \"targets\": {\n                                        \"node\": \"6.11.1\"\n                                        }\n                                    },\n                                    '@babel/stage-0'\n                                ]\n                            ],\n                            plugins: [require('@babel/plugin-transform-async-to-generator')]\n                        }\n                    }, \n                    {\n                        loader: 'ts-loader',\n                        options: {\n                            transpileOnly: true\n                        }\n                    }\n                ]\n            },\n            {\n                test: /\\.js$/,\n                use: [\n                    { \n                        loader: 'babel-loader',\n                        options: {\n                            presets: [\n                                [\n                                    '@babel/preset-env',\n                                    {\n                                        \"targets\": {\n                                        \"node\": \"6.11.1\"\n                                        }\n                                    },\n                                    '@babel/stage-0'\n                                ]\n                            ],\n                            plugins: [require('@babel/plugin-transform-async-to-generator')]\n                        }\n                    }\n                ]\n            }\n        ]\n    },\n    resolve: {\n        extensions: [ '.ts', '.tsx', '.js' ]\n    },\n    externals: [nodeExternals()]\n};\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"lib\": [\"es6\", \"es2015.promise\"],\n    \"module\": \"commonjs\",\n    \"noImplicitAny\": false,\n    \"outDir\": \"\",\n    \"sourceMap\": true,\n    \"removeComments\": true,\n    \"noLib\": false,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowJs\": true,\n    \"target\": \"es6\",\n    \"typeRoots\": [\n      \"node_modules/@types\"\n    ]\n  },\n  \"include\": [\n    \"src/**/*.ts\",\n    \"spec/**/*.ts\"\n  ],\n  \"exclude\": [\n    \"**/*.spec.ts\"\n  ]\n}\n```\n\n```text\nfirebase-functions version\n```\n\n```text\nfirebase-tools\n```\n\n```text\n{ โ€œnode\": โ€œ8โ€ }\n```\n\n```text\n/functions/package.json\n```\n\n```text\nasync\n```\n\n```text\nes6\n```\n\n```text\ntarget\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- I'm not sure what's wrong but can you try deploying to the Node 8 beta runtime and see if the issue persists? (change your babel and typescript config to target it)\n- It works on node 8. The problem is transpiling to node v6 :/ If you bootstrap a simple helloworld app using the latest version of nestjs and then try to deploy to Firebase cloud, you'll see the error on deploy.\n- I'm already using ts-loader (with es6 as the target) to transpile typescript files + babel 7 w/ preset-env that targets node v6.","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":305,"estimatedTokens":1955}}1012{"id":"stack-70963321","source":"stackoverflow","questionId":70963321,"title":"TypeORM composite foreign key","tags":["mysql","typescript","nestjs","typeorm"],"text":"Title: TypeORM composite foreign key\nTags: mysql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn a first class, the primary key is composite:\n\n```\n@Entity({\n name: 'ClassA',\n database: Constants.DATABASE_NAME,\n})\nexport class ClassA {\n @PrimaryColumn({\n name: 'Field1',\n type: 'varchar',\n length: 4,\n })\n field1: string;\n\n @PrimaryColumn({\n name: 'Field2',\n type: 'varchar',\n length: 2,\n })\n field2: string;\n\n @PrimaryColumn({\n name: 'Field3',\n type: 'integer',\n })\n field3: number;\n\n @OneToMany(() => ClassB, (classB) => classB.classA)\n classB: ClassB[];\n}\n```\n\nIn another class, the first class is used as a foreign key:\n\n```\n@Entity({\n name: 'ClassB',\n database: Constants.DATABASE_NAME,\n})\nexport class ClassB {\n\n ...\n\n @ManyToOne(() => ClassA, (classA) => classA.classB, {\n cascade: true,\n })\n @JoinColumn([\n { name: 'Field1', referencedColumnName: 'field1' },\n { name: 'Field2', referencedColumnName: 'field2' },\n { name: 'Field3', referencedColumnName: 'field3' },\n ])\n classA: ClassA;\n}\n```\n\nWhen I start NestJS using `nest start`, I get the error\n\n```\ncode: \"ER_FK_NO_INDEX_PARENT\"\nerrno: 1822\nsqlMessage: Failed to add the foreign key constraint. Missing index for constraint 'FK_1d19fe001872b5ee9ab545c18f8' in the referenced table 'ClassA'\nsqlState: \"HY000\n```\n\nI tried to alter the ClassA table and add indexes on each column of the primary key, and then an index of all columns of the primary key, but the error is still the same.\n\nIs this possible to manage this case with TypeORM?\n\nRelevant packages:\n\n- typeorm: `0.2.41`\n\n- @nestjs/core: `8.0.0`\n\n- @nestjs/typeorm: `8.0.3`\n\n- mysql: `2.18.1`\n\nDB: `MySQL v8.0` in a Docker container (`mysql:latest`)\n\nThank you.\n\n### Edit\n\nIt seems that the issue is that the table is created in more than one step with TypeORM. The table looks like this after the error message.\n\n```\nCREATE TABLE `ClassB` (\n `Date` datetime NOT NULL,\n `ClassAField1` varchar(4) NOT NULL,\n `ClassAField2` varchar(2) NOT NULL,\n `ClassAField3` int NOT NULL,\n PRIMARY KEY (`Date`,`ClassAField1`,`ClassAField2`,`ClassAField3`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\nThe error happens on the following query, where TypeORM tries to add the foreign key:\n\n```\nALTER TABLE `ClassB`\nADD CONSTRAINT `FK_479eaf779e0d5f0d0a83bb9e30d`\nFOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\nREFERENCES `LandPlots`(`Field1`,`Field2`,`Field3`) ON DELETE NO ACTION ON UPDATE NO ACTION\n```\n\nI made a few tests, and the following query works as intended:\n\n```\nCREATE TABLE `ClassB` (\n `Date` datetime NOT NULL,\n `ClassAField1` varchar(4) NOT NULL,\n `ClassAField2` varchar(2) NOT NULL,\n `ClassAField3` int NOT NULL,\n PRIMARY KEY (`Date`),\n KEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),\n CONSTRAINT `FK_e6b2926df2c758d8d8810e4345a`\n FOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\n REFERENCES `ClassA` (`Field1`, `Field2`, `Field3`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\nThe difference seems to be the line `KEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),`, which is missing from the generated SQL by TypeORM.\n\nFrom MySQL documentation, the `KEY` statement is synonymous to `INDEX`:\n\n```\nKEY | INDEX\n\nKEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.\n```\n\nSo I tried to add the `@Index` decorator to the column but it did not change anything. I added logging of all executed queries, and it seems that the `@Index` decorator is not executed, so, maybe the `@JoinColumn` decorator has priority over it? (Tried to sort decorators different ways just in case).\n\nThe only solution that I can think of with TypeORM would be to generate a hash or concatenation of all 3 primary keys, and make it the sole primary key. Two drawbacks: Data duplication and CPU usage when parsing entities before insertion.\n\nIf someone has a better suggestion I would like to hear it.\n\n### Edit 2 following questions from @RickJames\n\nUpdate statement:\n\n```\nUPDATE cb\nSET cb.SomeField = 'NewValue'\nFROM ClassB cb\nJOIN ClassA ca\nON cb.Field1 = ca.Field1\nAND cb.Field2 = ca.Field2\nAND cb.Field3 = ca.Field3\nWHERE ca.SomeOtherField LIKE '%partialvalue%'\nAND cb.otherPK = 1\n```\n\n========================================\n\nCode:\n```js\n@Entity({\n  name: 'ClassA',\n  database: Constants.DATABASE_NAME,\n})\nexport class ClassA {\n  @PrimaryColumn({\n    name: 'Field1',\n    type: 'varchar',\n    length: 4,\n  })\n  field1: string;\n\n  @PrimaryColumn({\n    name: 'Field2',\n    type: 'varchar',\n    length: 2,\n  })\n  field2: string;\n\n  @PrimaryColumn({\n    name: 'Field3',\n    type: 'integer',\n  })\n  field3: number;\n\n  @OneToMany(() => ClassB, (classB) => classB.classA)\n  classB: ClassB[];\n}\n```\n\n```js\n@Entity({\n  name: 'ClassB',\n  database: Constants.DATABASE_NAME,\n})\nexport class ClassB {\n\n  ...\n\n  @ManyToOne(() => ClassA, (classA) => classA.classB, {\n    cascade: true,\n  })\n  @JoinColumn([\n    { name: 'Field1', referencedColumnName: 'field1' },\n    { name: 'Field2', referencedColumnName: 'field2' },\n    { name: 'Field3', referencedColumnName: 'field3' },\n  ])\n  classA: ClassA;\n}\n```\n\n```text\ncode: \"ER_FK_NO_INDEX_PARENT\"\nerrno: 1822\nsqlMessage: Failed to add the foreign key constraint. Missing index for constraint 'FK_1d19fe001872b5ee9ab545c18f8' in the referenced table 'ClassA'\nsqlState: \"HY000\n```\n\n```sql\nCREATE TABLE `ClassB` (\n  `Date` datetime NOT NULL,\n  `ClassAField1` varchar(4) NOT NULL,\n  `ClassAField2` varchar(2) NOT NULL,\n  `ClassAField3` int NOT NULL,\n  PRIMARY KEY (`Date`,`ClassAField1`,`ClassAField2`,`ClassAField3`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\n```sql\nALTER TABLE `ClassB`\nADD CONSTRAINT `FK_479eaf779e0d5f0d0a83bb9e30d`\nFOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\nREFERENCES `LandPlots`(`Field1`,`Field2`,`Field3`) ON DELETE NO ACTION ON UPDATE NO ACTION\n```\n\n```sql\nCREATE TABLE `ClassB` (\n  `Date` datetime NOT NULL,\n  `ClassAField1` varchar(4) NOT NULL,\n  `ClassAField2` varchar(2) NOT NULL,\n  `ClassAField3` int NOT NULL,\n  PRIMARY KEY (`Date`),\n  KEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),\n  CONSTRAINT `FK_e6b2926df2c758d8d8810e4345a`\n  FOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\n  REFERENCES `ClassA` (`Field1`, `Field2`, `Field3`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\n```text\nKEY | INDEX\n\nKEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.\n```\n\n```sql\nUPDATE cb\nSET cb.SomeField = 'NewValue'\nFROM ClassB cb\nJOIN ClassA ca\nON cb.Field1 = ca.Field1\nAND cb.Field2 = ca.Field2\nAND cb.Field3 = ca.Field3\nWHERE ca.SomeOtherField LIKE '%partialvalue%'\nAND cb.otherPK = 1\n```\n\n```text\nnest start\n```\n\n```text\n0.2.41\n```\n\n```text\n8.0.0\n```\n\n```text\n8.0.3\n```\n\n```text\n2.18.1\n```\n\n```text\nMySQL v8.0\n```\n\n```text\nmysql:latest\n```\n\n```text\nKEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),\n```\n\n```text\nKEY\n```\n\n```text\nINDEX\n```\n\n```text\n@Index\n```\n\n```text\n@Index\n```\n\n```text\n@JoinColumn\n```\n\n```text\ncb:  INDEX(otherPK, Field1, Field2, Field3)\nca:  INDEX(Field1, Field2, Field3, SomeOtherField)\n```\n\n========================================\n\nComments:\n- Before helping with *how to* index, I would like to critique *what to* index. Please provide sample `SELECTs&#47;UPDATEs`/DELETEs` that you are hoping the add indexes for.\n- Hello @RickJames . The index ('KEY' in the 6th code snippet) on the composite foreign key because otherwise, from my tests, it finally works. But TypeORM does not seem to process both the primary key + \\@ManyToOne + \\@JoinColumn + \\@Index, it only processes the PK and tries afterward to alter the column into a composite FK, which does not work. I add an update statement but I'm not sure I understood your question well.\n- `` Too much of my time is spent trying to *work around* deficiencies in the products (ORMs, etc) that try to hide MySQL from the user. The users ends up having to understand *both* abstractions and write \"raw\" queries to get performance. ``\n- @RickJames I agree with you. For simple operations ORM are cool, and I wanted also to make the process cleaner by not manipulating SQL, but in the end a work that would have taken a few hours took days of my personal time.\n- Thank you for your help. It does not solve the TypeORM specific issue, but I think that in the end it's a TypeORM limit which cannot be solved using this ORM. I accept your answer because it'll be helpful optimizing queries on the database.","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":335,"estimatedTokens":2214}}1013{"id":"stack-71778848","source":"stackoverflow","questionId":71778848,"title":"Service injection in Guards and Circular Dependency","tags":["typescript","nestjs"],"text":"Title: Service injection in Guards and Circular Dependency\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm currently struggling with service injection in a guard.\n\nWell, the thing is I made a `JwtAuthGuard`, that needs both my `FirebaseService` and my `UserService`.\n\nSo I thought it'd be useful to create a `AuthGuardModule` so i only need to import my `AuthGuardModules` in the modules that have a `Controller`, to use my Guard.\n\nThe thing is that unfortunately, i need this guard for my `UserModule` too.\nSo that's natural that i get a `Circular Dependency Error` When i import my `AuthGuardModule` in my `UserModule`.\n\nThen, i tried all the things more or less related to `Circular Dependency Error` in Nest.js, but no can do.\n\nCan someone tell me if:\n\n- I am totally wrong thinking about making a module only for my guards ?\n\n- If I'm not, how can I fix my `Circular Dependency Error` ?\n\n- If I misunderstood that part, why isn't it right and what's the best way to do so ?\n\n### JwtAuthGuard\n\n```\n@Injectable()\nexport class JwtAuthGuard implements CanActivate {\n private readonly logger = new Logger(JwtAuthGuard.name)\n\n constructor(\n private readonly firebaseService: FirebaseService,\n private readonly userService: UserService\n ) { }\n\n async canActivate(context: ExecutionContext): Promise {\n const request = context.switchToHttp().getRequest();\n const token = request.headers['authorization'];\n\n if (!token) {\n throw new UnauthorizedException\n }\n\n try {\n const firebaseUser = await this.firebaseService.getUserByToken(token)\n request.user = await this.userService.getByEmail(firebaseUser.email)\n return true\n } catch (error) {\n this.logger.error(this.canActivate.name, error)\n throw new UnauthorizedException\n }\n }\n}\n```\n\n### AuthGuardModule\n\n```\n@Module({\n imports: [UserModule],\n providers: [FirebaseService, JwtAuthGuard],\n exports: [JwtAuthGuard]\n})\n\nexport class AuthGuardModule {}\n```\n\n### EDIT\n\nWell, jmcdo29 of the NestJS discord explained me that:\n\nYour `AuthGuardModule` should export the `UserModule` and the `FirebaseService`. Guards, when used in the `@UseGuards()` decorator, are used in the context of the current controller's module, instead of being looked at as an `Injectable` provider\n\nSo I did that way and it did solve my initial issue, but i have another circular dependency issue.\n\nFirst, let's resume resume the architecture i have:\n\n### AuthModule\n\n- It handles the routes for register, and the routes that send some emails like the password reset or the email verifying.\n\n- It needs the `UserModule` to create a user into my db when i call the register route\n\n```\n@Module({\n imports: [\n AuthGuardModule\n ],\n controllers: [AuthController],\n providers: [AuthService, EmailService, FirebaseService],\n})\n\nexport class AuthModule {}\n```\n\n### FileModule\n\n- It handles the file upload and deletion.\n\n```\n@Module({\n imports: [\n forwardRef(() => AuthGuardModule),\n BlobModule,\n MongooseModule.forFeature([{ name: File.name, schema: FileSchema }])\n ],\n controllers: [FileController],\n providers: [FileService],\n exports: [FileService],\n})\n\nexport class FileModule {}\n```\n\n### UserModule\n\n- It handles all the users routes.\n\n- It needs the `FileModule`, to check if the avatar exists when it's modified (i have only one route that updates all my users personal data)\n\n- It also needs the `AuthGuardModule` to use my `JwtAuthGuard`\n\n```\n@Module({\n imports: [\n forwardRef(() => AuthGuardModule),\n forwardRef(() => FileModule),\n MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])\n ],\n controllers: [UserController],\n providers: [UserService, FirebaseService],\n exports: [UserService, FileModule]\n })\n\n export class UserModule {}\n```\n\n### AuthGuardsModule\n\n- It contains my JWT check guard, and then i check if a user in my db is linked to the connected user\n\n- It needs the `UserModule` to get the user in my db\n\n```\n@Module({\n imports: [forwardRef(() => UserModule), FirebaseModule],\n providers: [JwtAuthGuard, RegisterAuthGuard],\n exports: [JwtAuthGuard, RegisterAuthGuard, FirebaseModule, UserModule]\n})\n\nexport class AuthGuardModule {}\n```\n\nI could use firebase to store my users avatars and do it front side, but i have to store it in Azure Blob Storage (it's imposed to my), so the FileModule handle all that thing\n\nSo, now, that i solved my AuthGuardsModule -> UserModule circular dependecy thanks to you guys, i have a new circular dependency issue: AuthGuardsModule -> UserModule -> FileModule\n\nI set a forwardRef of the AuthGuardsModule inside the FileModule but nest naturally said me that make sure that each side of a bidirectional relationships are decorated with \"forwardRef()\"\n\nSo i put a `forwardRef` to my `FileModule` import inside my `UserModule`, but same thing.\n\nAny idea ?\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class JwtAuthGuard implements CanActivate {\n  private readonly logger = new Logger(JwtAuthGuard.name)\n\n  constructor(\n    private readonly firebaseService: FirebaseService,\n    private readonly userService: UserService\n  ) { }\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const token = request.headers['authorization'];\n\n    if (!token) {\n      throw new UnauthorizedException\n    }\n\n    try {\n      const firebaseUser = await this.firebaseService.getUserByToken(token)\n      request.user = await this.userService.getByEmail(firebaseUser.email)\n      return true\n    } catch (error) {\n      this.logger.error(this.canActivate.name, error)\n      throw new UnauthorizedException\n    }\n  }\n}\n```\n\n```js\n@Module({\n    imports: [UserModule],\n    providers: [FirebaseService, JwtAuthGuard],\n    exports: [JwtAuthGuard]\n})\n\nexport class AuthGuardModule {}\n```\n\n```text\n@Module({\n  imports: [\n    AuthGuardModule\n  ],\n  controllers: [AuthController],\n  providers: [AuthService, EmailService, FirebaseService],\n})\n\nexport class AuthModule {}\n```\n\n```text\n@Module({\n    imports: [\n        forwardRef(() => AuthGuardModule),\n        BlobModule,\n        MongooseModule.forFeature([{ name: File.name, schema: FileSchema }])\n    ],\n    controllers: [FileController],\n    providers: [FileService],\n    exports: [FileService],\n})\n\nexport class FileModule {}\n```\n\n```text\n@Module({\n    imports: [\n      forwardRef(() => AuthGuardModule),\n      forwardRef(() => FileModule),\n      MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])\n    ],\n    controllers: [UserController],\n    providers: [UserService, FirebaseService],\n    exports: [UserService, FileModule]\n  })\n\n  export class UserModule {}\n```\n\n```text\n@Module({\n    imports: [forwardRef(() => UserModule), FirebaseModule],\n    providers: [JwtAuthGuard, RegisterAuthGuard],\n    exports: [JwtAuthGuard, RegisterAuthGuard, FirebaseModule, UserModule]\n})\n\nexport class AuthGuardModule {}\n```\n\n```text\nJwtAuthGuard\n```\n\n```text\nFirebaseService\n```\n\n```text\nUserService\n```\n\n```text\nAuthGuardModule\n```\n\n```text\nAuthGuardModules\n```\n\n```text\nController\n```\n\n```text\nUserModule\n```\n\n```text\nCircular Dependency Error\n```\n\n```text\nAuthGuardModule\n```\n\n```text\nUserModule\n```\n\n```text\nCircular Dependency Error\n```\n\n```text\nCircular Dependency Error\n```\n\n```text\nAuthGuardModule\n```\n\n```text\nUserModule\n```\n\n```text\nFirebaseService\n```\n\n```text\n@UseGuards()\n```\n\n```text\nInjectable\n```\n\n```text\nUserModule\n```\n\n```text\nFileModule\n```\n\n```text\nAuthGuardModule\n```\n\n```text\nJwtAuthGuard\n```\n\n```text\nUserModule\n```\n\n```text\nforwardRef\n```\n\n```text\nFileModule\n```\n\n```text\nUserModule\n```\n\n```js\n@Module({\n    imports: [forwardRef(() => UserModule), FirebaseModule],\n    providers: [...yourProviders],\n    exports: [...yourExportedInjectables]\n})\n\nexport class AuthModule {}\n```\n\n```js\n@Module({\n    imports: [...requiredImports],\n    providers: [FirebaseService],\n    exports: [FirebaseService]\n})\n\nexport class FirebaseModule {}\n```\n\n```js\n@Module({\n    imports: [forwardRef(() => AuthModule)],\n    providers: [...yourProviders],\n    exports: [...yourExportedInjectables]\n})\n\nexport class UserModule {}\n```\n\n```text\nforwardRef\n```\n\n```text\n@nestjs/common\n```\n\n```text\nJwtAuthGuard\n```\n\n```text\nAuthModule\n```\n\n```text\nAuthModule\n```\n\n```text\n/src/auth/guards/auth-guard.ts\n```\n\n```text\nFirebaseService\n```\n\n```text\nFirebaseModule\n```\n\n```text\nFirebaseModule\n```\n\n```text\nforwardRef\n```\n\n```text\nforwardRef\n```\n\n```text\nAuthModule\n```\n\n```text\nAuthModule\n```\n\n========================================\n\nComments:\n- Hey buddy, thanks for your awnser it helped me a lot ! I also had the aid of a someone of the nestJS discord, but i'm blocked by another circular dependency that's more tricky to me. I editted my inital post.","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":47,"totalLines":445,"estimatedTokens":2169}}1014{"id":"stack-66123056","source":"stackoverflow","questionId":66123056,"title":"Nestjs accepting also application/x-www-form-urlencoded","tags":["json","nestjs","x-www-form-urlencoded"],"text":"Title: Nestjs accepting also application/x-www-form-urlencoded\nTags: json, nestjs, x-www-form-urlencoded\nSource: Stack Overflow\n\nQuestion:\nWe have a service which is calling our nestjs microservice with header `Content-Type: application/x-www-form-urlencoded` which seems not to be parsed as expected.\n\nIf we start also from a clean nestjs project and put this pice of code in the **AppController**\n\n```\n@Post()\n async store(@Body() request: any) {\n console.log('request', request);\n }\n```\n\nIf we send data to the service with curl in this way:\n\n```\ncurl -d '{\"abc\": 123 }' -H 'Content-Type: application/x-www-form-urlencoded' -X POST http://localhost:3000\n```\n\nAt the end our console.log shows as that we don't have a valid json, the whole content of the body is puted in the first parameter of the request json, which is resulting in this\n\n```\nrequest { '{\"abc\": 123 }': '' }\n```\n\nAs you can see the content is not parsed right to the json, the documentation is not showing a lot of the parser, but googling this should work out of the bax\n\nCan someone help?\n\n========================================\n\nCode:\n```text\n@Post()\n  async store(@Body() request: any) {\n    console.log('request', request);\n  }\n```\n\n```text\ncurl -d '{\"abc\": 123 }' -H 'Content-Type: application/x-www-form-urlencoded' -X POST http://localhost:3000\n```\n\n```text\nrequest { '{\"abc\": 123 }': '' }\n```\n\n```text\nContent-Type: application/x-www-form-urlencoded\n```\n\n========================================\n\nComments:\n- we had to write it in the right way, which means -d 'abc=123', we thought tat putting the header will curl transform the data from json to url encoded ... which isn't so and also this probably would not make sense, if curl in background is doing something you probably also not would","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":58,"estimatedTokens":444}}1015{"id":"stack-60787515","source":"stackoverflow","questionId":60787515,"title":"NestJS REST API times out for long running request","tags":["node.js","rest","timeout","nestjs"],"text":"Title: NestJS REST API times out for long running request\nTags: node.js, rest, timeout, nestjs\nSource: Stack Overflow\n\nQuestion:\nAfter lengthy investigations the problems seems to be that the long running request times out and the endpoint is called again in NodeJS. There is no new network request from browser. I made a few tests and after 2 mins the endpoint is invoked again. I read that the default timeout for the http requests in NodeJS in 2mins.\n\nhttps://nodejs.org/docs/latest-v12.x/api/http.html#http_server_timeout\n\nI am using NestJS (with express), does anyone know how to increase this timeout value using NestJS framework ?\n\nHere is my initial question: Angular 9 http call with nestjs backend\n\n-Jani\n\n========================================\n\nTop Answer:\nYou can use some packages to apply a timeout as a middleware.\nhttps://www.npmjs.com/package/@nest-middlewares/connect-timeout\n\nThis package is just a wrapper of an express middleware, so be sure you use the express platform on your project.\n\n========================================\n\nCode:\n```text\nreq.setTimeout(300000); // 5 minutes\n```\n\n========================================\n\nComments:\n- I tried that and it does not work. My problem is that I need to increase the default server timeout (or request timeout) and that package does not modify that. See here: stackoverflow.com/questions/55364401/&hellip;. My answer fixes the issue per that specific request.","metadata":{"transformedAt":"2026-08-18T18:33:02.570Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":34,"estimatedTokens":359}}1016{"id":"stack-72080013","source":"stackoverflow","questionId":72080013,"title":"How to split jest e2e tests into multiple files without losing context?","tags":["testing","jestjs","nestjs","e2e-testing"],"text":"Title: How to split jest e2e tests into multiple files without losing context?\nTags: testing, jestjs, nestjs, e2e-testing\nSource: Stack Overflow\n\nQuestion:\nSo I've written plenty of e2e tests for my backend and this is becoming overwhelming as all of test methods are in one file.\n\nReason I have all of them in one file is that when my app is created, TypeORM creates in-memory database instance on which I do all of the tests - I need same database to be running across tests as I am doing cross-entities tests.\n\nThis part of code is crucial. It initializes app (which also initializes db under the hood):\n\n```\nlet app: INestApplication;\n\nbeforeAll(async () => {\n const moduleFixture = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n});\n```\n\nIs there a way to somehow transfer `beforeAll()`'s context so that it could be accessed from tests located in other files?\n\nMaybe somehow make `app` global?\n\n========================================\n\nCode:\n```text\nlet app: INestApplication;\n\nbeforeAll(async () => {\n  const moduleFixture = await Test.createTestingModule({\n    imports: [AppModule],\n  }).compile();\n\n  app = moduleFixture.createNestApplication();\n  await app.init();\n});\n```\n\n```text\nbeforeAll()\n```\n\n```text\napp\n```\n\n```text\nexport const e2eConfig: SqliteConnectionOptions = {\n  type: 'sqlite',\n  database: 'db.db',\n  entities: entities,\n  synchronize: true,\n};\n```\n\n```text\nsqlite\n```\n\n```text\nsqlite\n```\n\n```text\nmysql\n```\n\n========================================\n\nComments:\n- I'm trying something similar these days, but I've so far only managed to extract the inmemory database initialization code using Jest's `globalSetup` and `globalTeardown`. Note that no global context is shared that way, but at least I could start MongoDB and pass its URL in a temporary local file, so it can be used in the individual test suites. Did you have any more luck with sharing the actual application context?\n- Basically, I used jestjs.io/docs/27.x/mongodb and github.com/shelfio/jest-mongodb as my starting points, and then built my own global setup+teardown functions.\n- If you're using NodeJS 12+, check out this Jest runner: github.com/nicolo-ribaudo/jest-light-runner.","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":79,"estimatedTokens":566}}1017{"id":"stack-71041279","source":"stackoverflow","questionId":71041279,"title":"Reflector not injected to my custom guard in nestjs","tags":["node.js","nestjs"],"text":"Title: Reflector not injected to my custom guard in nestjs\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have created a guard in a separate module for checking feature flags as below\n\n```\n@Injectable()\nexport class FeatureFlagGuard implements CanActivate {\n constructor(\n private reflector: Reflector,\n private featureFlagService: FeatureFlagService\n ) {}\n\n async canActivate(context: ExecutionContext): Promise {\n const featureKey = this.reflector.get(\n FEATURE_FLAG_DECORATOR_KEY,\n context.getHandler()\n );\n\n if (!featureKey) {\n return true;\n }\n return await this.featureFlagService.isFeatureEnabled(featureKey);\n }\n}\n```\n\nand here is my decorator\n\n```\nimport { SetMetadata } from '@nestjs/common';\n\nexport const FEATURE_FLAG_DECORATOR_KEY = 'FEATURE_FLAG';\nexport const FeatureEnabled = (featureName: string) =>\n SetMetadata(FEATURE_FLAG_DECORATOR_KEY, featureName);\n```\n\nThen in appModule I provided the FeatureFlagGuard as below\n\n```\nproviders: [\n {\n provide: APP_GUARD,\n useClass: FeatureFlagGuard\n }\n ]\n```\n\nThen in my controller\n\n```\n@FeatureEnabled('FEATURE1')\n @Get('/check-feature-flag')\n checkFeatureFlag() {\n return {\n date: new Date().toISOString()\n };\n }\n```\n\nWhen I run the code I get this error, since the `reflector` is injected as null into my service\n\n```\n[error] [ExceptionsHandler] Cannot read properties of undefined (reading 'get')\n```\n\nNot sure what I missed\n\n========================================\n\nTop Answer:\nAs an addition, because I got here with a similar issue: Don't forget to make your guards request scoped, if your injecting request scoped services.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class FeatureFlagGuard implements CanActivate {\n    constructor(\n        private reflector: Reflector,\n        private featureFlagService: FeatureFlagService\n    ) {}\n\n    async canActivate(context: ExecutionContext): Promise<boolean> {\n        const featureKey = this.reflector.get<string>(\n            FEATURE_FLAG_DECORATOR_KEY,\n            context.getHandler()\n        );\n\n        if (!featureKey) {\n            return true;\n        }\n        return await this.featureFlagService.isFeatureEnabled(featureKey);\n    }\n}\n```\n\n```text\nimport { SetMetadata } from '@nestjs/common';\n\nexport const FEATURE_FLAG_DECORATOR_KEY = 'FEATURE_FLAG';\nexport const FeatureEnabled = (featureName: string) =>\n    SetMetadata(FEATURE_FLAG_DECORATOR_KEY, featureName);\n```\n\n```text\nproviders: [\n        {\n            provide: APP_GUARD,\n            useClass: FeatureFlagGuard\n        }\n    ]\n```\n\n```text\n@FeatureEnabled('FEATURE1')\n    @Get('/check-feature-flag')\n    checkFeatureFlag() {\n        return {\n            date: new Date().toISOString()\n        };\n    }\n```\n\n```text\n[error] [ExceptionsHandler] Cannot read properties of undefined (reading 'get')\n```\n\n```text\nreflector\n```\n\n```text\nFeatureFlagService\n```\n\n========================================\n\nComments:\n- If your `FeatureFlagService` `REQUEST` scoped?\n- @JayMcDoniel not sure, it should be like Role example on nestjs site\n- @JayMcDoniel feature flag service will downloads a json file and then reads the file and checks if the flag is true or false (which is not implemenetd yet)\n- @JayMcDoniel I removed featureFlagService from constructor and reflector get injected correctly\n- @JayMcDoniel `Reflector` can't be injected with `REQUEST` scoped service?\n- @AmrSalama That's not true. Enhancers and request scoped providers don't necessarily play well together","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":148,"estimatedTokens":873}}1018{"id":"stack-70110485","source":"stackoverflow","questionId":70110485,"title":"How to test Nestjs routes with @Query decorators and Validation Pipes?","tags":["jestjs","nestjs"],"text":"Title: How to test Nestjs routes with @Query decorators and Validation Pipes?\nTags: jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nImagine I have a Controller defined like so:\n\n```\nclass NewsEndpointQueryParameters {\n @IsNotEmpty()\n q: string;\n\n @IsNotEmpty()\n pageNumber: number;\n}\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get(['', 'ping'])\n ping(): PingEndpointResponse {\n return this.appService.ping();\n }\n\n @Get(['news'])\n getNews(\n @Query() queryParameters: NewsEndpointQueryParameters\n ): Observable {\n return this.appService.getNews(\n queryParameters.q,\n queryParameters.pageNumber\n );\n }\n}\n```\n\nI want to be able to test what happens in a request, if, for example, a query parameter is not provided.\n\nRight now this is my testing setup:\n\n```\ndescribe('AppController', () => {\n let app: TestingModule;\n let nestApp: INestApplication;\n let appService: AppService;\n\n beforeAll(async () => {\n app = await Test.createTestingModule({\n controllers: [AppController],\n providers: [AppService],\n imports: [HttpModule],\n }).compile();\n appService = app.get(AppService);\n nestApp = app.createNestApplication();\n await nestApp.init();\n return;\n });\n\n describe('/', () => {\n test('Return \"Pong!\"', async () => {\n const appServiceSpy = jest.spyOn(appService, 'ping');\n appServiceSpy.mockReturnValue({ message: 'Pong!' });\n const response = await supertest(nestApp.getHttpServer()).get('/');\n expect(response.body).toStrictEqual({\n message: 'Pong!',\n });\n return;\n });\n });\n\n describe('/ping', () => {\n test('Return \"Pong!\"', async () => {\n const appServiceSpy = jest.spyOn(appService, 'ping');\n appServiceSpy.mockReturnValue({ message: 'Pong!' });\n const response = await supertest(nestApp.getHttpServer()).get('/ping');\n expect(response.body).toStrictEqual({\n message: 'Pong!',\n });\n return;\n });\n });\n\n describe('/news', () => {\n describe('Correct query', () => {\n beforeEach(() => {\n const appServiceSpy = jest.spyOn(appService, 'getNews');\n appServiceSpy.mockReturnValue(\n new Observable((subscriber) => {\n subscriber.next({\n data: [{ url: 'test' }],\n message: 'test',\n status: 200,\n });\n subscriber.complete();\n })\n );\n return;\n });\n\n test('Returns with a custom body response.', async () => {\n const response = await supertest(nestApp.getHttpServer()).get(\n '/news?q=test&pageNumber=1'\n );\n expect(response.body).toStrictEqual({\n data: [{ url: 'test' }],\n message: 'test',\n status: 200,\n });\n return;\n });\n\n return;\n });\n\n describe('Incorrect query', () => {\n test(\"Returns an error if 'q' query parameter is missing.\", async () => {\n return;\n });\n\n test(\"Returns an error if 'pageNumber' query parameter is missing.\", async () => {\n return;\n });\n\n return;\n });\n\n return;\n });\n\n return;\n});\n```\n\nIf I do `nx serve` and then `curl 'localhost:3333/api/ping'`, I get:\n\n```\n{\"message\":\"Pong!\"}\n```\n\nAnd if I do `curl 'localhost:3333/api/news?q=test&pageNumber=1'` I get:\n\n```\n{\"data\":['lots of interesting news'],\"message\":\"News fetched successfully!\",\"status\":200}\n```\n\nFinally, if I do `curl 'localhost:3333/api/news?q=test'` I get:\n\n```\n{\"statusCode\":400,\"message\":[\"pageNumber should not be empty\"],\"error\":\"Bad Request\"}\n```\n\nHow can I replicate the last case? If I use `supertest`, there is no error returned like the above. I haven't found a way to mock the Controller's function too.\n\n========================================\n\nCode:\n```ts\nclass NewsEndpointQueryParameters {\n  @IsNotEmpty()\n  q: string;\n\n  @IsNotEmpty()\n  pageNumber: number;\n}\n\n@Controller()\nexport class AppController {\n  constructor(private readonly appService: AppService) {}\n\n  @Get(['', 'ping'])\n  ping(): PingEndpointResponse {\n    return this.appService.ping();\n  }\n\n  @Get(['news'])\n  getNews(\n    @Query() queryParameters: NewsEndpointQueryParameters\n  ): Observable<NewsEndpointResponse> {\n    return this.appService.getNews(\n      queryParameters.q,\n      queryParameters.pageNumber\n    );\n  }\n}\n```\n\n```ts\ndescribe('AppController', () => {\n  let app: TestingModule;\n  let nestApp: INestApplication;\n  let appService: AppService;\n\n  beforeAll(async () => {\n    app = await Test.createTestingModule({\n      controllers: [AppController],\n      providers: [AppService],\n      imports: [HttpModule],\n    }).compile();\n    appService = app.get<AppService>(AppService);\n    nestApp = app.createNestApplication();\n    await nestApp.init();\n    return;\n  });\n\n  describe('/', () => {\n    test('Return \"Pong!\"', async () => {\n      const appServiceSpy = jest.spyOn(appService, 'ping');\n      appServiceSpy.mockReturnValue({ message: 'Pong!' });\n      const response = await supertest(nestApp.getHttpServer()).get('/');\n      expect(response.body).toStrictEqual({\n        message: 'Pong!',\n      });\n      return;\n    });\n  });\n\n  describe('/ping', () => {\n    test('Return \"Pong!\"', async () => {\n      const appServiceSpy = jest.spyOn(appService, 'ping');\n      appServiceSpy.mockReturnValue({ message: 'Pong!' });\n      const response = await supertest(nestApp.getHttpServer()).get('/ping');\n      expect(response.body).toStrictEqual({\n        message: 'Pong!',\n      });\n      return;\n    });\n  });\n\n  describe('/news', () => {\n    describe('Correct query', () => {\n      beforeEach(() => {\n        const appServiceSpy = jest.spyOn(appService, 'getNews');\n        appServiceSpy.mockReturnValue(\n          new Observable<NewsEndpointResponse>((subscriber) => {\n            subscriber.next({\n              data: [{ url: 'test' }],\n              message: 'test',\n              status: 200,\n            });\n            subscriber.complete();\n          })\n        );\n        return;\n      });\n\n      test('Returns with a custom body response.', async () => {\n        const response = await supertest(nestApp.getHttpServer()).get(\n          '/news?q=test&pageNumber=1'\n        );\n        expect(response.body).toStrictEqual({\n          data: [{ url: 'test' }],\n          message: 'test',\n          status: 200,\n        });\n        return;\n      });\n\n      return;\n    });\n\n    describe('Incorrect query', () => {\n      test(\"Returns an error if 'q' query parameter is missing.\", async () => {\n        return;\n      });\n\n      test(\"Returns an error if 'pageNumber' query parameter is missing.\", async () => {\n        return;\n      });\n\n      return;\n    });\n\n    return;\n  });\n\n  return;\n});\n```\n\n```json\n{\"message\":\"Pong!\"}\n```\n\n```json\n{\"data\":['lots of interesting news'],\"message\":\"News fetched successfully!\",\"status\":200}\n```\n\n```json\n{\"statusCode\":400,\"message\":[\"pageNumber should not be empty\"],\"error\":\"Bad Request\"}\n```\n\n```text\nnx serve\n```\n\n```text\ncurl 'localhost:3333/api/ping'\n```\n\n```text\ncurl 'localhost:3333/api/news?q=test&pageNumber=1'\n```\n\n```text\ncurl 'localhost:3333/api/news?q=test'\n```\n\n```text\nsupertest\n```\n\n```js\nbeforeAll(async () => {\n  app = await Test.createTestingModule({\n    controllers: [AppController],\n    providers: [\n      AppService,\n      { provide: APP_PIPE, useValue: new ValidationPipe() },\n    ],\n    imports: [HttpModule, AppModule],\n  }).compile();\n  appService = app.get<AppService>(AppService);\n  nestApp = app.createNestApplication();\n  await nestApp.init();\n  return;\n});\n```\n\n```js\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, {\n    cors: environment.nestCors,\n  });\n  app.useGlobalPipes(new ValidationPipe());\n  const globalPrefix = 'api';\n  app.setGlobalPrefix(globalPrefix);\n  const port = process.env.PORT || 3333;\n  await app.listen(port, () => {\n    Logger.log('Listening at http://localhost:' + port + '/' + globalPrefix);\n  });\n}\n```\n\n```text\nbootstrap()\n```\n\n```text\nmain.ts\n```\n\n```text\nAppModule\n```\n\n```text\nnestApp.useGlobalPipes(new ValidationPipe())\n```\n\n```text\nawait nestApp.init()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":363,"estimatedTokens":1932}}1019{"id":"stack-66686818","source":"stackoverflow","questionId":66686818,"title":"Amazon AWS Amplify NestJs - host own frontend and backend","tags":["angular","amazon-web-services","nestjs"],"text":"Title: Amazon AWS Amplify NestJs - host own frontend and backend\nTags: angular, amazon-web-services, nestjs\nSource: Stack Overflow\n\nQuestion:\nThis is my first Question here.\nI develop a fullstack nestJS app with Angular and want to host it on aws now. After i read the manual, they just always talk about \"fullstack\" in combination with multiple frontends.\nThe Backend Environment from AWS doesnt help me anything, because i wrote my own backend.\n\nSo, can someone tell me, who i can deploy frontend and backend on aws and connect them with a rds ?\nFrontend works and i try something like that with the build file:\n\n```\nversion: 1\nfrontend:\n phases:\n preBuild:\n commands:\n - npm ci\n build:\n commands:\n - npm run build\n artifacts:\n baseDirectory: dist/apps/frontend-app\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\nbackend:\n phases:\n preBuild:\n commands:\n - npm ci\n build:\n commands:\n - npm run build-backend\n artifacts:\n baseDirectory: dist/apps/api\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n```\n\nThanks and stay healthy\n\n========================================\n\nCode:\n```text\nversion: 1\nfrontend:\n  phases:\n    preBuild:\n      commands:\n        - npm ci\n    build:\n      commands:\n        - npm run build\n  artifacts:\n    baseDirectory: dist/apps/frontend-app\n    files:\n      - '**/*'\n  cache:\n    paths:\n      - node_modules/**/*\nbackend:\n  phases:\n    preBuild:\n      commands:\n        - npm ci\n    build:\n      commands:\n        - npm run build-backend\n  artifacts:\n    baseDirectory: dist/apps/api\n    files:\n      - '**/*'\n  cache:\n    paths:\n      - node_modules/**/*\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":84,"estimatedTokens":401}}1020{"id":"stack-76592521","source":"stackoverflow","questionId":76592521,"title":"How to automatically update and get a relation column based on other relation","tags":["typescript","postgresql","rxjs","nestjs","typeorm"],"text":"Title: How to automatically update and get a relation column based on other relation\nTags: typescript, postgresql, rxjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect 3 relations - Photo, PhotoComment and PhotoRating. I want to let my users to have a possibility to rate a photo. These photos can have multiple comments by many users and multiple rates by many users (but only 1 rate per specific user). And I want to show that user rate on all comments that belongs to photos. However, I cannot make things work to show a rate inside comment and update it automatically whenever user change photo rate (uses `ratePhoto` method)\n\nWhen I call `ratePhoto` method I can see in PGAdmin that `photoRatingId` is not connected with `PhotoComment` and it's not updating rate there. However, `ratePhoto` method works fine and saves rate of `Photo` correctly\n\nI'm using NestJS, TypeORM, PostgreSQL and RxJS. I highly prefer to work on repository instead of queryBuilder\n\n`photos.service.ts`\n\n```\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable {\n return this.getPhoto(photoId).pipe(\n switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n map((photoRating: PhotoRating) => {\n if (!photoRating) {\n const newRating: PhotoRating = new PhotoRating();\n\n newRating.rate = ratePhotoDto.rate;\n newRating.user = user;\n newRating.photo = photo;\n\n return this.photoRatingRepository.save(newRating);\n }\n\n photoRating.rate = ratePhotoDto.rate;\n\n return this.photoRatingRepository.save(photoRating);\n }),\n )),\n );\n }\n```\n\n`photo.entity.ts`\n\n```\n@Entity()\nexport class Photo {\n //...\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)\n public photoComments: PhotoComment[];\n\n @OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)\n public photoRatings: PhotoRating[];\n}\n```\n\n`photo-comment.entity.ts`\n\n```\n@Entity()\nexport class PhotoComment {\n //...\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)\n @JoinColumn({ name: 'rate' })\n public photoRating: PhotoRating;\n}\n```\n\n`photo-rating.entity.ts`\n\n```\n@Entity()\n@Unique(['user', 'photo'])\nexport class PhotoRating {\n //...\n \n @Transform(({ value }) => +value)\n @Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })\n public rate: number;\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating, { cascade: true })\n public photoComment: PhotoComment;\n}\n```\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nIn my opinion, the problem is that you have not set the *photoComment*\n\nproperty on the photoRating entity. To do this, add the following code to the *ratePhoto method*\n\n```\nphotoRating.photoComment = photoComment;\n```\n\nThis will ensure that the *photoComment* property of the *photoRating* entity is set correctly.\n\n**The method should be as follows**\n\n```\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable {\n return this.getPhoto(photoId).pipe(\n switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n map((photoRating: PhotoRating) => {\n if (!photoRating) {\n const newRating: PhotoRating = new PhotoRating();\n newRating.rate = ratePhotoDto.rate;\n newRating.user = user;\n newRating.photo = photo;\n return this.photoRatingRepository.save(newRating);\n }\n photoRating.rate = ratePhotoDto.rate;\n photoRating.photoComment = photoComment;\n return this.photoRatingRepository.save(photoRating);\n }),\n )),\n );\n}\n```\n\n========================================\n\nCode:\n```text\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable<any> {\n        return this.getPhoto(photoId).pipe(\n            switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n                map((photoRating: PhotoRating) => {\n                    if (!photoRating) {\n                        const newRating: PhotoRating = new PhotoRating();\n\n                        newRating.rate = ratePhotoDto.rate;\n                        newRating.user = user;\n                        newRating.photo = photo;\n\n                        return this.photoRatingRepository.save(newRating);\n                    }\n\n                    photoRating.rate = ratePhotoDto.rate;\n\n                    return this.photoRatingRepository.save(photoRating);\n                }),\n            )),\n        );\n    }\n```\n\n```text\n@Entity()\nexport class Photo {\n    //...\n\n    @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)\n    public photoComments: PhotoComment[];\n\n    @OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)\n    public photoRatings: PhotoRating[];\n}\n```\n\n```text\n@Entity()\nexport class PhotoComment {\n    //...\n\n    @ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })\n    public photo: Photo;\n\n    @ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)\n    @JoinColumn({ name: 'rate' })\n    public photoRating: PhotoRating;\n}\n```\n\n```text\n@Entity()\n@Unique(['user', 'photo'])\nexport class PhotoRating {\n    //...\n    \n    @Transform(({ value }) => +value)\n    @Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })\n    public rate: number;\n\n    @ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })\n    public photo: Photo;\n\n    @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating, { cascade: true })\n    public photoComment: PhotoComment;\n}\n```\n\n```text\nratePhoto\n```\n\n```text\nratePhoto\n```\n\n```text\nphotoRatingId\n```\n\n```text\nPhotoComment\n```\n\n```text\nratePhoto\n```\n\n```text\nPhoto\n```\n\n```text\nphotos.service.ts\n```\n\n```text\nphoto.entity.ts\n```\n\n```text\nphoto-comment.entity.ts\n```\n\n```text\nphoto-rating.entity.ts\n```\n\n```text\npublic async ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Promise<void> {\n        await this.entityManager.transaction(async (entityManager: EntityManager) => {\n            const photo: Photo = await this.photoRepository.findOne({ where: { photo: { id: photoId } } });\n            const photoRating: PhotoRating = await this.photoRatingRepository.findOne({ where: { photo: { id: photo.id }, user: { id: user.id } } });\n    \n            if (!photoRating) {\n                const newRating: PhotoRating = await entityManager.save( // Saving new rate of photo\n                    PhotoRating, \n                    { ...ratePhotoDto, user, photo }\n                );\n    \n                await entityManager.update( // Fast update all comments that should be updated\n                    PhotoComment,\n                    { addedBy: { id: user.id }, photo: { id: photo.id } },\n                    { photoRating: newRating }\n                );\n    \n                return;\n            }\n    \n            await entityManager.save( // Saving rate of photo\n                PhotoRating, \n                { ...photoRating, ...ratePhotoDto }\n            );\n    \n            await entityManager.update( // Fast update all comments that should be updated\n                PhotoComment,\n                { addedBy: { id: user.id }, photo: { id: photo.id } },\n                { photoRating }\n            );\n        });\n    }\n```\n\n```text\n@Entity()\nexport class Photo { // No changes here\n    //...\n\n    @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)\n    public photoComments: PhotoComment[];\n\n    @OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)\n    public photoRatings: PhotoRating[];\n}\n```\n\n```text\n@Entity()\nexport class PhotoComment { // Deleted JoinColumn because I don't need that\n    //...\n\n    @ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })\n    public photo: Photo;\n\n    @ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)\n    public photoRating: PhotoRating;\n}\n```\n\n```text\n@Entity()\n@Unique(['user', 'photo'])\nexport class PhotoRating { // Deleted { cascade: true | from PhotoComment because I don't want it\n    //...\n    \n    @Transform(({ value }) => +value)\n    @Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })\n    public rate: number;\n\n    @ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })\n    public photo: Photo;\n\n    @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating)\n    public photoComment: PhotoComment;\n}\n```\n\n```text\n.update()\n```\n\n```text\ntransaction\n```\n\n```text\nRxJS\n```\n\n```text\nphotos.service.ts\n```\n\n```text\nphoto.entity.ts\n```\n\n```text\nphoto-comment.entity.ts\n```\n\n```text\nphoto-rating.entity.ts\n```\n\n```text\n.update()\n```\n\n```text\nphotoRating.photoComment = photoComment;\n```\n\n```text\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable<any> {\n  return this.getPhoto(photoId).pipe(\n    switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n      map((photoRating: PhotoRating) => {\n        if (!photoRating) {\n          const newRating: PhotoRating = new PhotoRating();\n          newRating.rate = ratePhotoDto.rate;\n          newRating.user = user;\n          newRating.photo = photo;\n          return this.photoRatingRepository.save(newRating);\n        }\n        photoRating.rate = ratePhotoDto.rate;\n        photoRating.photoComment = photoComment;\n        return this.photoRatingRepository.save(photoRating);\n      }),\n    )),\n  );\n}\n```\n\n========================================\n\nComments:\n- Why does `PhotoComment` entity has that `photoRating` property, and why does `PhotoRating` has that `photoComment`. Is it required to have a `photoRating` for a `photo` record or `photoComment` record?\n- I've set these entities with relations between themselves. Maybe I'm wrong, cause I'm still newbie in NestJS and TypeORM, however I think if I want to show a `rate` (which comes from `photoRating` in my comments (`PhotoComment` entity) and automatically adjust this rate on comments whenever user changes it (`ratePhoto` method on `Photo` entity), I have to set these relations. Correct me if I'm wrong\n- I don't have a `photoComment` data here. I need that rate to be visible for all comments of specific user so, maybe I'm wrong, but I don't think that getting all these comments here and manually setting rate to them every time user changes rate is a good approach\n- There are some indications that you may have used an AI tool (e.g., ChatGPT) to assist with this answer. If so, I'd encourage you to delete it since [posting of AI-generated content is not permitted on Stack Overflow].","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":381,"estimatedTokens":2781}}1021{"id":"stack-70343278","source":"stackoverflow","questionId":70343278,"title":"How do I generate a NestJS resource in an app within an Nx workspace using the nx cli?","tags":["visual-studio-code","nestjs","monorepo","nomachine-nx"],"text":"Title: How do I generate a NestJS resource in an app within an Nx workspace using the nx cli?\nTags: visual-studio-code, nestjs, monorepo, nomachine-nx\nSource: Stack Overflow\n\nQuestion:\nI want to generate a NestJS resource in my new nestjs app within an Nx workspace, similar to the way you would in a solo NextJS app using the nest generate cli command. Using the nx generate command I would expect to have to specify the app you want the resource added to, like:\n\n`nx generate @nestjs/schematics:resource **--app=haida-stories-api** --name=testresource`\n\nI tried the VS Nx Console but there are no options to specify the app target for the generate command. When I add a resource without tweaking any of the other options it just creates a new src directory in the root dir of the workspace and creates a resource unrelated to any app.\n\nThe --sourceRoot option in VS Nx Console allows me to manually enter the path to the source directory I want, but it doesn't automatically add the correct imports to the main app module.\n\nUsing the nx generate command on the command line rather than in Nx Console in VS, you can add the โ€œprojectโ€ argument:\n\n`nx g @nrwl/nest:resource project `\n\nThis command does generate the controller in the correct project src directory, but it doesnโ€™t edit the app module.ts file to add the file import statement and add the resource module to the imports array, making it a route in the app.\n\nIn a pure NestJS app, if I run the following nest cli command, it automatically edits the module file:\n\nnest generate controller test\n\nAm I missing some documentation on the Nx cli and how it works using the VS Nx Console?\n\n========================================\n\nTop Answer:\nYou can use\n\n**npm nx generate resource [name of resource]**\n\nto create new nest resource in nx workspace\n\n========================================\n\nCode:\n```text\nnx generate @nestjs/schematics:resource **--app=haida-stories-api** --name=testresource\n```\n\n```text\nnx g @nrwl/nest:resource <resource-name> project <app-name>\n```\n\n```text\nnx generate @nx/nest:resource [NAME] --directory projects/api/[NAME]\n```\n\n```text\nprojects/api\n```\n\n```text\n@nx/nest resource\n```\n\n```text\nnest g resource [name of resource]\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":60,"estimatedTokens":553}}1022{"id":"stack-63565951","source":"stackoverflow","questionId":63565951,"title":"How to convert this oracle query to typeorm?","tags":["oracle-database","typescript","nestjs","typeorm"],"text":"Title: How to convert this oracle query to typeorm?\nTags: oracle-database, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI was building an application in NestJS and I need to get the date from the Oracle, but I don't know how convert this query:\n\n```\nSELECT TO_CHAR\n (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"NOW\"\n FROM DUAL;\n```\n\nIn a TypeORM query.\n\nCan you help me?\n\n========================================\n\nCode:\n```text\nSELECT TO_CHAR\n    (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"NOW\"\n     FROM DUAL;\n```\n\n```text\nawait getManager().query(`SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"NOW\" FROM DUAL`);\n```\n\n========================================\n\nComments:\n- The date must come from database?","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":34,"estimatedTokens":178}}1023{"id":"stack-57408935","source":"stackoverflow","questionId":57408935,"title":"Not able to search through character varying[] array column","tags":["postgresql","nestjs","typeorm"],"text":"Title: Not able to search through character varying[] array column\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy postgres database table has a column location which is character `varying[]`. In my nestjs entity of the table I have following for the location column-\n\n```\n@Column(\"character varying\",{array:true})\n location: string[];\n```\n\nWhat I am trying to do is search the rows having passed parameter as locations.\nThis is the raw query which is giving me appropriate results-\n\n```\nselect * from blogs where language @> '{\"Spanish\",\"English\"}'\n```\n\nIn my nestjs service, how can I achieve the above query?\nI tried doing this-\n\n```\nreturn await this.blogsRepo.find({\n where: [\n {\n location: Any(body.locations)\n }\n ]\n})\n```\n\n`body.locations` is an array like this-\n\n```\nbody.locations = [\"Spanish\",\"English\"]\n```\n\nThe above typeorm solution gives me following error-\n\n 'could not find array type for data type character varying[]'\n\nWhat could be the possible solution for this? I will love a typeorm solution as I have kept raw query execution as my last option.\n\nThanks in advance,\n\n========================================\n\nTop Answer:\nYou could try this:\n\n```\nawait this.blogsRepo.find({\n where: `${body.locations} = ANY (location)`,\n});\n```\n\n========================================\n\nCode:\n```text\n@Column(\"character varying\",{array:true})\n    location: string[];\n```\n\n```text\nselect * from blogs where language @> '{\"Spanish\",\"English\"}'\n```\n\n```text\nreturn await this.blogsRepo.find({\n  where: [\n    {\n      location: Any(body.locations)\n    }\n  ]\n})\n```\n\n```text\nbody.locations = [\"Spanish\",\"English\"]\n```\n\n```text\nvarying[]\n```\n\n```text\nbody.locations\n```\n\n```text\n@>\n```\n\n```text\nRepository.query()\n```\n\n```text\nawait this.blogsRepo.find({\n  where: `${body.locations} = ANY (location)`,\n});\n```\n\n```text\nimport { Raw } from 'typeorm';\n```\n\n```text\n{value1, value2, value3}\n```\n\n```text\nconst searchKey = 'value3'\n\nsampleRepo.find({\n   where: {\n      columnName: Raw((alias) => ` '${searchKey}' = ANY (${alias})`),\n   }\n})\n```\n\n```text\n[{key1: 'value1', key2: 'value2'}, {key1: 'value21', key2: 'value22'}])\n```\n\n```text\nconst searchKey = 'value1'\n\nsampleRepo.find({\n   where: {\n      columnName: Raw((alias) => ` ${alias} @> '[{\"key1\": \"${searchKey}\"}]'`)\n   }\n})\n```\n\n```text\nRaw\n```\n\n```text\ncharacter varying\n```\n\n```text\njsonb\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":148,"estimatedTokens":593}}1024{"id":"stack-65956687","source":"stackoverflow","questionId":65956687,"title":"Cannot read property 'validateUser' of undefined ,NestJS using PassportJS","tags":["typescript","passport.js","nestjs"],"text":"Title: Cannot read property 'validateUser' of undefined ,NestJS using PassportJS\nTags: typescript, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI just want to implemented authentication by passportjs in NestJS.\nI got these lines of error when I send post request to \"localhost:3000/auth/login\".\n\n```\n[ExceptionsHandler] Cannot read property 'validateUser' of undefined\nTypeError: Cannot read property 'validateUser' of undefined\n```\n\nand These is my code :\n\nlocal.strategy.ts\n\n```\nimport { AuthService } from './auth.service';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Strategy } from 'passport-local';\nimport { UnauthorizedException } from '@nestjs/common';\n\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private authService: AuthService) {\n super();\n }\n async validate(username: string, password: string): Promise {\n console.log(username, password);\n const user = await this.authService.validateUser(username, password); auth.service.ts\n\n```\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AuthService {\n users = [{ id: 1, username: 'Peyman', password: 'password' }];\n async validateUser(username: string, password: string): Promise {\n console.log('Validate');\n const user = await this.users.find((x) => x.username === username);\n if (user && user.password === password) {\n return user;\n }\n return null;\n }\n}\n```\n\nauth.module.ts\n\n```\nimport { LocalStrategy } from './local.strategy';\nimport { Module } from '@nestjs/common';\nimport { PassportModule } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\n\n@Module({\n imports: [PassportModule],\n providers: [AuthService, LocalStrategy],\n exports: [PassportModule],\n})\nexport class AuthModule {}\n```\n\napp.module.ts\n\n```\nimport { Contact } from './contacts/contacts.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { ContactsModule } from './contacts/contacts.module';\nimport { AppController } from './app.controller';\nimport { AuthModule } from './auth/auth.module';\nimport { PassportModule } from '@nestjs/passport';\n\n@Module({\n imports: [\n ContactsModule,\n PassportModule,\n TypeOrmModule.forRoot({ entities: [Contact] }),\n AuthModule,\n ],\n controllers: [AppController],\n providers: [],\n})\nexport class AppModule {}\n```\n\napp.controller.ts\n\n```\nimport { Controller, Post, UseGuards, Request } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n @UseGuards(AuthGuard('local'))\n @Post('auth/login')\n public async login(@Request() req): Promise {\n return req.user;\n }\n}\n```\n\nI inject **authservice** by **dependency injection**, by got an error.\nHow can I fix this?\n\n========================================\n\nTop Answer:\nmanually removing the dist folder and restarting the server worked for me\n\n========================================\n\nCode:\n```text\n[ExceptionsHandler] Cannot read property 'validateUser' of undefined\nTypeError: Cannot read property 'validateUser' of undefined\n```\n\n```text\nimport { AuthService } from './auth.service';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Strategy } from 'passport-local';\nimport { UnauthorizedException } from '@nestjs/common';\n\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n  constructor(private authService: AuthService) {\n    super();\n  }\n  async validate(username: string, password: string): Promise<any> {\n    console.log(username, password);\n    const user = await this.authService.validateUser(username, password); <====This part\n    if (!user) {\n      return new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AuthService {\n  users = [{ id: 1, username: 'Peyman', password: 'password' }];\n  async validateUser(username: string, password: string): Promise<any> {\n    console.log('Validate');\n    const user = await this.users.find((x) => x.username === username);\n    if (user && user.password === password) {\n      return user;\n    }\n    return null;\n  }\n}\n```\n\n```text\nimport { LocalStrategy } from './local.strategy';\nimport { Module } from '@nestjs/common';\nimport { PassportModule } from '@nestjs/passport';\nimport { AuthService } from './auth.service';\n\n@Module({\n  imports: [PassportModule],\n  providers: [AuthService, LocalStrategy],\n  exports: [PassportModule],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Contact } from './contacts/contacts.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { ContactsModule } from './contacts/contacts.module';\nimport { AppController } from './app.controller';\nimport { AuthModule } from './auth/auth.module';\nimport { PassportModule } from '@nestjs/passport';\n\n@Module({\n  imports: [\n    ContactsModule,\n    PassportModule,\n    TypeOrmModule.forRoot({ entities: [Contact] }),\n    AuthModule,\n  ],\n  controllers: [AppController],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Controller, Post, UseGuards, Request } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n  @UseGuards(AuthGuard('local'))\n  @Post('auth/login')\n  public async login(@Request() req): Promise<any> {\n    return req.user;\n  }\n}\n```\n\n```text\n@Injectable()\n```\n\n```text\nLocalStrategy\n```\n\n========================================\n\nComments:\n- had this error, but forgot the @ before Injectable(), but wasn't getting an error message for syntax.\n- that's because calling just `Injectable()` isn't invalid. TS decorators factories are just functions. See typescriptlang.org/docs/handbook/decorators.html","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":221,"estimatedTokens":1429}}1025{"id":"stack-55108139","source":"stackoverflow","questionId":55108139,"title":"npm won't start:dev on NestJS application","tags":["npm","nodemon","nestjs"],"text":"Title: npm won't start:dev on NestJS application\nTags: npm, nodemon, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo I created a new `NestJS` application with the CLI. I got `nodemon` installed as a dependency and globally. My `package.json` looks like this:\n\n```\n\"scripts\": {\n\"build\": \"tsc -p tsconfig.build.json\",\n\"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n\"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n\"start:dev\": \"nodemon\",\n\"start:debug\": \"nodemon --config nodemon-debug.json\",\n```\n\nand my `nodemon.json` looks like this:\n\n```\n\"watch\": [\"src\"],\n\"ext\": \"ts\",\n\"ignore\": [\"src/**/*.spec.ts\"],\n\"exec\": \"ts-node -r tsconfig-paths/register src/main.ts\"\n```\n\nSo very basic setup. But if I try so start the dev server with: `npm start:dev`, I get this error message:\n\n```\nUsage: npm \n\nwhere is one of:\n\naccess, adduser, audit, bin, bugs, c, cache, ci, cit,\nclean-install, clean-install-test, completion, config,\ncreate, ddp, dedupe, deprecate, dist-tag, docs, doctor,\nedit, explore, get, help, help-search, hook, i, init,\ninstall, install-ci-test, install-test, it, link, list, ln,\nlogin, logout, ls, org, outdated, owner, pack, ping, prefix,\nprofile, prune, publish, rb, rebuild, repo, restart, root,\nrun, run-script, s, se, search, set, shrinkwrap, star,\nstars, start, stop, t, team, test, token, tst, un,\nuninstall, unpublish, unstar, up, update, v, version, view,\nwhoami\n\nSpecify configs in the ini-formatted file: /Users/XXXXX/.npmrc\nor on the command line via: npm --key value\nConfig info can be viewed via: npm help config\n\nnpm@6.6.0 /usr/local/lib/node_modules/npm\n\nDid you mean this?\n start\n```\n\nMy `npmrc` contains some credentials for my github repo from my job !\n\n========================================\n\nCode:\n```text\n\"scripts\": {\n\"build\": \"tsc -p tsconfig.build.json\",\n\"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n\"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n\"start:dev\": \"nodemon\",\n\"start:debug\": \"nodemon --config nodemon-debug.json\",\n```\n\n```text\n\"watch\": [\"src\"],\n\"ext\": \"ts\",\n\"ignore\": [\"src/**/*.spec.ts\"],\n\"exec\": \"ts-node -r tsconfig-paths/register src/main.ts\"\n```\n\n```text\nUsage: npm < command >\n\nwhere < command > is one of:\n\naccess, adduser, audit, bin, bugs, c, cache, ci, cit,\nclean-install, clean-install-test, completion, config,\ncreate, ddp, dedupe, deprecate, dist-tag, docs, doctor,\nedit, explore, get, help, help-search, hook, i, init,\ninstall, install-ci-test, install-test, it, link, list, ln,\nlogin, logout, ls, org, outdated, owner, pack, ping, prefix,\nprofile, prune, publish, rb, rebuild, repo, restart, root,\nrun, run-script, s, se, search, set, shrinkwrap, star,\nstars, start, stop, t, team, test, token, tst, un,\nuninstall, unpublish, unstar, up, update, v, version, view,\nwhoami\n\nSpecify configs in the ini-formatted file: /Users/XXXXX/.npmrc\nor on the command line via: npm <command> --key value\nConfig info can be viewed via: npm help config\n\nnpm@6.6.0 /usr/local/lib/node_modules/npm\n\nDid you mean this?\n    start\n```\n\n```text\nNestJS\n```\n\n```text\nnodemon\n```\n\n```text\npackage.json\n```\n\n```text\nnodemon.json\n```\n\n```text\nnpm start:dev\n```\n\n```text\nnpmrc\n```\n\n```text\nnpm run\n```\n\n```text\nnpm run start:dev\n```\n\n========================================\n\nComments:\n- Because I could not find myself anything related to this after searching a lot, I created this comment on a somewhat related post stackoverflow.com/a/59803280/588003 .\n- @Maxstgt Glad it worked for you. :-) Consider accepting the answer so that others know your problem is solved. Of course, feel free to leave the question open and wait for other answers. stackoverflow.com/help/someone-answers","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":139,"estimatedTokens":908}}1026{"id":"stack-76243514","source":"stackoverflow","questionId":76243514,"title":"NestJS: Option to make file in endpoint optional","tags":["express","nestjs"],"text":"Title: NestJS: Option to make file in endpoint optional\nTags: express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS to create REST API and I am trying to create an endpoint that will require certain body but also accept file that should be optional.\n\n```\n@UseGuards(JwtAuthGuard)\n@Post('create')\n@UseInterceptors(FileInterceptor('file', { }))\nasync createPost(@Req() req: any, @Body() createPostDto: CreatePostDto, @UploadedFile(new ParseFilePipeBuilder().addMaxSizeValidator({ maxSize: 2048 }).build({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY })) file: Express.Multer.File) {\n return await this.postsService.createPost(req.user, createPostDto, file);\n}\n```\n\nBut using this code makes the file required at all times as seen in this error response:\n\n```\n{\n \"statusCode\": 422,\n \"message\": \"File is required\",\n \"error\": \"Unprocessable Entity\"\n}\n```\n\nIs there a way to make the upload file optional?\n\n========================================\n\nTop Answer:\nJust found a perfect working solution for this this after searching the whole web.\njust add `fileIsRequired: false` to your code inside the build options:\n\n```\n.build({\n fileIsRequired: false,\n errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,\n }),\n```\n\nSo your updated code will be:\n\n```\nenter code here\n@UseGuards(JwtAuthGuard)\n@Post('create')\n@UseInterceptors(FileInterceptor('file', {}))\nasync createPost(\n@Req() req: any,\n@Body() createPostDto: CreatePostDto,\n@UploadedFile(\n new ParseFilePipeBuilder()\n .addMaxSizeValidator({ maxSize: 2048 })\n .build({\n fileIsRequired: false,\n errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,\n }),\n)\nfile: Express.Multer.File,\n) {\n return await this.postsService.createPost(req.user, createPostDto, file);\n}\n```\n\n========================================\n\nCode:\n```text\n@UseGuards(JwtAuthGuard)\n@Post('create')\n@UseInterceptors(FileInterceptor('file', { }))\nasync createPost(@Req() req: any, @Body() createPostDto: CreatePostDto, @UploadedFile(new ParseFilePipeBuilder().addMaxSizeValidator({ maxSize: 2048 }).build({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY })) file: Express.Multer.File) {\n        return await this.postsService.createPost(req.user, createPostDto, file);\n}\n```\n\n```json\n{\n    \"statusCode\": 422,\n    \"message\": \"File is required\",\n    \"error\": \"Unprocessable Entity\"\n}\n```\n\n```text\n@UseGuards(JwtAuthGuard)\n@Post('create')\n@UseInterceptors(FileInterceptor('file', { }))\nasync createPost(@Req() req: any, @Body() createPostDto: CreatePostDto, @UploadedFile(new ParseFilePipe({\n        validators: [\n            new MaxFileSizeValidator({ maxSize: parseInt(process.env.MAX_FILE_UPLOAD_SIZE) * 1000 })\n        ],\n        fileIsRequired: false\n    })) file?: Express.Multer.File) {\n        return await this.postsService.createPost(req.user, createPostDto, file);\n    }\n```\n\n```text\nfileIsRequired\n```\n\n```text\n.build({\n  fileIsRequired: false,\n  errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,\n }),\n```\n\n```text\nenter code here\n@UseGuards(JwtAuthGuard)\n@Post('create')\n@UseInterceptors(FileInterceptor('file', {}))\nasync createPost(\n@Req() req: any,\n@Body() createPostDto: CreatePostDto,\n@UploadedFile(\n  new ParseFilePipeBuilder()\n    .addMaxSizeValidator({ maxSize: 2048 })\n    .build({\n      fileIsRequired: false,\n      errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,\n    }),\n)\nfile: Express.Multer.File,\n) {\n return await this.postsService.createPost(req.user, createPostDto, file);\n}\n```\n\n```text\nfileIsRequired: false\n```\n\n========================================\n\nComments:\n- Should mention that this behavior is also possible even with ParseFilePipeBuilder - you can add 'fileIsRequired: false' to the build options.","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":140,"estimatedTokens":923}}1027{"id":"stack-64242423","source":"stackoverflow","questionId":64242423,"title":"Typeorm. use only the date part while querying via date and exclude the timestamp part","tags":["node.js","orm","nestjs","typeorm"],"text":"Title: Typeorm. use only the date part while querying via date and exclude the timestamp part\nTags: node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a use case where I have to retrieve a users record from the database via his date of birth.\nThe thing is that we have stored the date of birth of the user as datetime object which makes it very difficult to retrieve the users data, as we can not provide the exact date with timestamp.\n\nI tried looking for a functions support in typeorm using which I can just compare the provided date with only the date part of the birth date in database but did not find any reference anywhere.\n\n========================================\n\nTop Answer:\nDon't convert your column to a string. Here's how to do it with a date/datetime/timestamp.\n\n```\nimport { startOfDay, endOfDay } from 'date-fns';\nimport { Between, Equal } from \"typeorm\";\n//...\nlet findArgs = { \n where:{\n date: Between(startOfDay(webInputArgs.date).toISOString(), endOfDay(webInputArgs.date).toISOString()), \n userId: Equal(ctx.req.session.userId)\n }\n};\nreturn entity.find(findArgs) as any;\n```\n\n========================================\n\nCode:\n```text\ndate_of_birth::text LIKE '2011-01-%'\n```\n\n```text\nimport { startOfDay, endOfDay } from 'date-fns';\nimport { Between, Equal } from \"typeorm\";\n//...\nlet findArgs = { \n  where:{\n    date: Between(startOfDay(webInputArgs.date).toISOString(), endOfDay(webInputArgs.date).toISOString()), \n    userId: Equal(ctx.req.session.userId)\n  }\n};\nreturn entity.find(findArgs) as any;\n```\n\n```js\nconst usersBornToday = await getManager()\n    .createQueryBuilder(User, \"user\")\n    .where(`DATE_TRUNC('day', \"birthdatetime\") = :date`, {date: '2021-03-27'})\n    .getMany()\n```\n\n```text\nDATE_TRUNC()\n```\n\n```text\nlet date = '2022-01-25'; //yyyy-mm-dd, for Regex validation - /\\d{4}\\-\\d{2}\\-\\d{2}/\ndate = `${date}%`;\nqueryResult.where('CONVERT(date_of_birth, char) LIKE :date', { date });\n```\n\n```text\nMySQL\n```\n\n```text\nCONVERT\n```\n\n```text\nTodo:only show today stock list\n      const start = moment().startOf('day').toDate();\n      const end = moment().endOf('day').toDate();\n     \n      const query=getManger()\n        .createQueryBuilder(stocks, 'stocks')\n        .andWhere('stocks.createdAt BETWEEN :start AND :end', { start, end })\n```\n\n========================================\n\nComments:\n- The question is not clear, on one hand you're saying: \"I have to retrieve a users record from the database via his date of birth\" which implies you have the DOB, but then you say you don't. What are you trying exactly to do? fetch all users that were born on a specific date? what if two users were born on the same date?\n- @NirAlfasi We have DOB in database in datetime format but when we are querying it from front end, we are just sending the dd-mm-yy. So the query is not filtering the records out. Anyhow, I found the solution and added it as an answer down below.\n- This cannot be the solution to the problem (the way it's stated) since, as I mentioned above, there may be multiple customers with the same DOB.\n- I dont think this is a good solution. Converting your date to string only to query it with a LIKE operation prevents you from running any date function like between or greater/less than operations.\n- This is exactly what I needed, Thanks! Also if anyone is looking to make the date param dynamic from a javascript Date object, you can use `.where(`DATE_TRUNC('day', \"birthdatetime\") = :date`, {date: yourDateObject.toISOString().split('T')[0] })`\n- I applied same logic but not working, `WHERE CONVERT(`transactions`.`created_at`, char) LIKE '2023-05-01'`, I am using mysql, typeorm\n- You should add an explanation along code snippet to make it clearer.","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":93,"estimatedTokens":931}}1028{"id":"stack-60691983","source":"stackoverflow","questionId":60691983,"title":"@nestjs/jwt - Cannot read property 'challenge' of undefined","tags":["jwt","nestjs"],"text":"Title: @nestjs/jwt - Cannot read property 'challenge' of undefined\nTags: jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use `jwt` tokens in my `nestjs` app but when I run my project and call a controller with `@UseGuards(AuthGuard())` decorator, the app debug return the following error:\n\n```\nCannot read property 'challenge' of undefined\n```\n\n========================================\n\nTop Answer:\nyou have to import `PassportModule` as\n\n```\nimports: [\n TypeOrmModule.forFeature([UserRepository]),\n HttpModule,\n ConfigModule,\n PassportModule.register({ defaultStrategy: 'jwt' }),\n ],\n```\n\ninto **every** module where you want to use default strategy.\n\n========================================\n\nCode:\n```text\nCannot read property 'challenge' of undefined\n```\n\n```text\njwt\n```\n\n```text\nnestjs\n```\n\n```text\n@UseGuards(AuthGuard())\n```\n\n```text\n@UseGuards(AuthGuard())\n```\n\n```text\n@UseGuards(AuthGuard('jwt'))\n```\n\n```text\nimports: [\n    TypeOrmModule.forFeature([UserRepository]),\n    HttpModule,\n    ConfigModule,\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n  ],\n```\n\n```text\nPassportModule\n```\n\n========================================\n\nComments:\n- Hi, do I need to use PassportModule if I stop relying on jwt.strategy and started to use custom AuthGuard? In this AuthGuard I do the following: `const payload = await this.jwtService.verifyAsync(token, { secret: this.configService.get('jwt.secretKey', { infer: true }), });` and based on the response attach `user` to request. For some reason I still have the error from the topic, do I misunderstand something?","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":71,"estimatedTokens":394}}1029{"id":"stack-66086427","source":"stackoverflow","questionId":66086427,"title":"Docker container with nodejs app(NestJS) is not accessible from both other containers or host","tags":["node.js","docker","nginx","network-programming","nestjs"],"text":"Title: Docker container with nodejs app(NestJS) is not accessible from both other containers or host\nTags: node.js, docker, nginx, network-programming, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have an application, that consists of few docker containers: nginx, client, admin, backend and mongo.\n\nIn container \"backend\" is running NestJS application on port 5000. Container has exposed port 5000. But container is not responding to any requests and application inside of container doesn't receive them. I've even tried to expose port 5000 to my local machine so I could make request outside of docker-host but this way container doesn't respond as well. When I'm running this NestJS app locally on my machine everything works perfectly. I have nginx.conf to configure behavior nginx container. It should redirect certain requests to specific containers using proxy. This approach works fine for client and admin containers. Both hosting NextJS application and listening on specific port. I've used the same approach for \"backend\" container but even though nginx seems to make correct requests, it doesn't receive response or for some reason it makes requests to wrong address inside of docker-host\n\nDockerfile for my custom images:\n\n```\nFROM node:14.15.4 as client\nWORKDIR /usr/src/app\nCOPY /src/client/package*.json ./\nRUN npm install\nCOPY /src/client .\nEXPOSE 3000\nCMD [\"npm\", \"run\", \"dev\"]\n\nFROM node:14.15.4 as admin\nWORKDIR /usr/src/app\nCOPY /src/admin/package*.json ./\nRUN npm install\nCOPY /src/admin .\nEXPOSE 3001\nCMD [\"npm\", \"run\", \"dev\"]\n\nFROM node:14.15.4 as backend\nWORKDIR /usr/src/app\nCOPY /src/app/package*.json ./\nRUN npm install\nCOPY /src/app .\nEXPOSE 5000\nCMD [\"npm\", \"run\", \"start:dev\"]\n```\n\ndocker-compose.yml:\n\n```\nversion: '3'\nservices:\n nginx:\n image: nginx:${NGNIX_VERSION}\n depends_on:\n - client\n - admin\n links:\n - client:client\n - admin:admin\n - backend:backend\n restart: on-failure:30\n volumes:\n - ./deploy/shared/config/nginx/nginx.conf:/etc/nginx/conf.d/default.conf\n env_file:\n - .env\n networks:\n - default\n expose:\n - 80\n ports:\n - ${NGINX_BIND_PORT}:80\n mongo:\n image: mongo:${MONGO_VERSION}\n env_file:\n - .env\n networks:\n - default\n environment:\n MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME}\n MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}\n client:\n build:\n context: .\n target: client\n networks:\n - default\n volumes:\n - ./src/client:/usr/src/app\n admin:\n build:\n context: .\n target: admin\n networks:\n - default\n volumes:\n - ./src/admin:/usr/src/app\n backend:\n build:\n context: .\n target: backend\n networks:\n - default\n volumes:\n - ./src/app:/usr/src/app\n ports:\n - 5000:5000\n\nnetworks:\n default:\n driver: bridge\n```\n\nnginx.conf:\n\n```\nupstream docker-client {\n server client:3000;\n}\n\nupstream docker-admin {\n server admin:3001;\n}\n\nupstream docker-backend {\n server backend:5000;\n}\n\nserver {\n listen 80;\n server_name mr0bread.local;\n\n location / {\n proxy_pass http://docker-client;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_redirect off;\n proxy_read_timeout 600s;\n }\n\n location /admin {\n proxy_pass http://docker-admin;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_redirect off;\n proxy_read_timeout 600s;\n }\n\n location /backend {\n proxy_pass http://docker-backend;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_redirect off;\n proxy_read_timeout 600s;\n }\n}\n```\n\nHere is the link to repo: GitHub\n\n========================================\n\nTop Answer:\nWith Fastify, what worked for me was:\n\n```\napp.listen(3000, \"0.0.0.0\")\n```\n\n========================================\n\nCode:\n```text\nFROM node:14.15.4 as client\nWORKDIR /usr/src/app\nCOPY /src/client/package*.json ./\nRUN npm install\nCOPY /src/client .\nEXPOSE 3000\nCMD [\"npm\", \"run\", \"dev\"]\n\nFROM node:14.15.4 as admin\nWORKDIR /usr/src/app\nCOPY /src/admin/package*.json ./\nRUN npm install\nCOPY /src/admin .\nEXPOSE 3001\nCMD [\"npm\", \"run\", \"dev\"]\n\nFROM node:14.15.4 as backend\nWORKDIR /usr/src/app\nCOPY /src/app/package*.json ./\nRUN npm install\nCOPY /src/app .\nEXPOSE 5000\nCMD [\"npm\", \"run\", \"start:dev\"]\n```\n\n```text\nversion: '3'\nservices:\n  nginx:\n    image: nginx:${NGNIX_VERSION}\n    depends_on:\n      - client\n      - admin\n    links:\n      - client:client\n      - admin:admin\n      - backend:backend\n    restart: on-failure:30\n    volumes:\n      - ./deploy/shared/config/nginx/nginx.conf:/etc/nginx/conf.d/default.conf\n    env_file:\n      - .env\n    networks:\n      - default\n    expose:\n      - 80\n    ports:\n      - ${NGINX_BIND_PORT}:80\n  mongo:\n    image: mongo:${MONGO_VERSION}\n    env_file:\n      - .env\n    networks:\n      - default\n    environment:\n      MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME}\n      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}\n  client:\n    build:\n      context: .\n      target: client\n    networks:\n      - default\n    volumes:\n    - ./src/client:/usr/src/app\n  admin:\n    build:\n      context: .\n      target: admin\n    networks:\n      - default\n    volumes:\n    - ./src/admin:/usr/src/app\n  backend:\n    build:\n      context: .\n      target: backend\n    networks:\n      - default\n    volumes:\n    - ./src/app:/usr/src/app\n    ports:\n    - 5000:5000\n\nnetworks:\n  default:\n    driver: bridge\n```\n\n```text\nupstream docker-client {\n    server client:3000;\n}\n\nupstream docker-admin {\n    server admin:3001;\n}\n\nupstream docker-backend {\n    server backend:5000;\n}\n\nserver {\n    listen 80;\n    server_name mr0bread.local;\n\n    location / {\n        proxy_pass http://docker-client;\n        proxy_http_version 1.1;\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection \"upgrade\";\n        proxy_set_header Host $http_host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_redirect off;\n        proxy_read_timeout 600s;\n    }\n\n    location /admin {\n        proxy_pass http://docker-admin;\n        proxy_http_version 1.1;\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection \"upgrade\";\n        proxy_set_header Host $http_host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_redirect off;\n        proxy_read_timeout 600s;\n    }\n\n    location /backend {\n            proxy_pass http://docker-backend;\n            proxy_http_version 1.1;\n            proxy_set_header Upgrade $http_upgrade;\n            proxy_set_header Connection \"upgrade\";\n            proxy_set_header Host $http_host;\n            proxy_set_header X-Real-IP $remote_addr;\n            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n            proxy_redirect off;\n            proxy_read_timeout 600s;\n        }\n}\n```\n\n```text\napp.listen(\"localhost:3000\");\n```\n\n```text\napp.listen(\"0.0.0.0:3000\");\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nlocalhost\n```\n\n```text\napp.listen(3000, \"0.0.0.0\")\n```\n\n========================================\n\nComments:\n- Maybe your app binds on 127.0.0.1 (localhost)? To access a service inside a container, the service needs to listen on the correct network interface or just all available ones via 0.0.0.0. Could you check what your main file code looks like with a call to something like listen or serve?\n- @AndreasJ&#228;gle, thank you, specifying \"0.0.0.0\" as a host helped\n- Using Fastify too. This answer worked for me.","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":349,"estimatedTokens":1977}}1030{"id":"stack-51124374","source":"stackoverflow","questionId":51124374,"title":"Nest js cannot resolve dependencies. in Auth service","tags":["authentication","jwt","nestjs"],"text":"Title: Nest js cannot resolve dependencies. in Auth service\nTags: authentication, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\n**Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.**\n\n**Please find my project repository**\n\nNest-auth-test\n\n```\nError: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.\n at Injector.lookupComponentInExports (/home/arpit/Documents/aquaapp/node_modules/@nestjs/core/injector/injector.js:129:19)\n at \n at process._tickCallback (internal/process/next_tick.js:182:7)\n at Function.Module.runMain (internal/modules/cjs/loader.js:697:11)\n at Object. (/home/arpit/Documents/aquaapp/node_modules/ts-node/src/_bin.ts:177:12)\n at Module._compile (internal/modules/cjs/loader.js:654:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)\n at Module.load (internal/modules/cjs/loader.js:566:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:506:12)\n at Function.Module._load (internal/modules/cjs/loader.js:498:3)\n at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)\n at startup (internal/bootstrap/node.js:201:19)\n at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)\n 1: node::Abort() [/usr/bin/node]\n 2: 0x8d04d9 [/usr/bin/node]\n 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo const&)) [/usr/bin/node]\n 4: 0xb17d2c [/usr/bin/node]\n 5: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/bin/node]\n 6: 0x2176d1e042fd\nAborted (core dumped)\n```\n\n========================================\n\nCode:\n```text\nError: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.\n    at Injector.lookupComponentInExports (/home/arpit/Documents/aquaapp/node_modules/@nestjs/core/injector/injector.js:129:19)\n    at <anonymous>\n    at process._tickCallback (internal/process/next_tick.js:182:7)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:697:11)\n    at Object.<anonymous> (/home/arpit/Documents/aquaapp/node_modules/ts-node/src/_bin.ts:177:12)\n    at Module._compile (internal/modules/cjs/loader.js:654:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)\n    at Module.load (internal/modules/cjs/loader.js:566:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:498:3)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)\n    at startup (internal/bootstrap/node.js:201:19)\n    at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)\n 1: node::Abort() [/usr/bin/node]\n 2: 0x8d04d9 [/usr/bin/node]\n 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/usr/bin/node]\n 4: 0xb17d2c [/usr/bin/node]\n 5: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/bin/node]\n 6: 0x2176d1e042fd\nAborted (core dumped)\n```\n\n```text\n@Injectable()\nexport class SampleService {}\n\n@Module({\n  exports: [SampleService]\n})\nexport class ModuleA {}\n\n@Module({\n  imports: [ModuleA]\n})\nexport class ModuleB {}\n```\n\n========================================\n\nComments:\n- I have already exported. and Injected [services, controller].You can see my code available on gitlab. Thank you for helping me.\n- well as I can see in your auth.module you dont have imports: [UserModule].. you can check my project with nest and angular on github too github.com/bojidaryovchev/nest-angular\n- Thank you. ะ‘ะพะถะธะดะฐั€ ะ™ะพะฒั‡ะตะฒ for reply.. I have tried [imported usermodule] that. but i was getting same error.\n- in your `user.module.ts`, you do not `export` `UserService` and you do not `import` `UserModule` in `AuthModule`.\n- Thank you, @ChauTran and ะ‘ะพะถะธะดะฐั€ ะ™ะพะฒั‡ะตะฒ. for helping me. Now its workin fine.","metadata":{"transformedAt":"2026-08-18T18:33:02.571Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":85,"estimatedTokens":986}}1031{"id":"stack-67581642","source":"stackoverflow","questionId":67581642,"title":"How write schedulers using NestJS for multiple countries at 12:00AM(will be same in all timezone)?","tags":["node.js","express","nestjs","nestjs-config"],"text":"Title: How write schedulers using NestJS for multiple countries at 12:00AM(will be same in all timezone)?\nTags: node.js, express, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI have a scheduler that has to run on 12:00 AM of Indian time zone and 12:00 AM of Singapore timezone. I was able to write a cron job for Indian users, But how to trigger the same in Singapore at 12:00 AM?\n\n========================================\n\nTop Answer:\nI think easily use for example 9:30 PM (UTC+08:00(Singapore) - UTC+05:30(India)) AM instead of 12:00 AM\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class Service {\n  @Cron('* * 0 * * *', {\n    timeZone: 'Asia/Tehran', // use this website: https://momentjs.com/timezone/\n  })\n  async iran() {\n    this.yourFunction();\n  }\n\n  @Cron('* * 0 * * *', {\n    timeZone: 'Asia/Tokyo',\n  })\n  async japan() {\n    this.yourFunction();\n  }\n\n  async yourFunction() {\n    // write the schedule only one time\n  }\n}\n```\n\n========================================\n\nComments:\n- Yes, For that I need two separate schedulers with repeated code. In future, we will support multiple timezones. Then the solution is not feasible\n- whebn you are setting time to start, set two times, for India and singapour\n- but let me write the code and show you how.","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":44,"estimatedTokens":327}}1032{"id":"stack-67243790","source":"stackoverflow","questionId":67243790,"title":"VS code debugging of a NestJs dockerized apps inside a monorepo","tags":["node.js","debugging","visual-studio-code","nestjs"],"text":"Title: VS code debugging of a NestJs dockerized apps inside a monorepo\nTags: node.js, debugging, visual-studio-code, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have been trying to figure out for a while how I would go about setting up a attachment to node debugging processes that are exposed in my environment from multiple running nestjs apps within a mono-repo setup. (With VS code)\n\nhttps://github.com/bozvul993/nest-testing-mono-repo-debug\n\nIdeally i want the debugging sessions restarted on code changes [If this is possible], but more importantly working.\n\nI have provided a repository with my sample project.\nTo run the apps inside `/docker` folder\n`docker-compose -f dev.yml up`\nThis brings up the three apps in the monorepo. All apps exposed to the host machine their default node debugging ports...\n\nMy vs code launch configuration that i used to attempt this i included:\n\n```\n\"type\": \"node\",\n \"request\": \"attach\",\n \"name\": \"Debug App1\",\n \"address\": \"0.0.0.0\",\n \"port\": 9231,\n \"localRoot\": \"${workspaceFolder}/mono-repo\",\n \"remoteRoot\": \"/app/mono-repo\",\n \"trace\": true,\n \"restart\": true,\n \"sourceMaps\": true,\n \"skipFiles\": [\n \"/**\"\n ]\n }\n\nWith Web-storm this was easier to achieve somehow..\n```\n\n========================================\n\nCode:\n```text\n\"type\": \"node\",\n            \"request\": \"attach\",\n            \"name\": \"Debug App1\",\n            \"address\": \"0.0.0.0\",\n            \"port\": 9231,\n            \"localRoot\": \"${workspaceFolder}/mono-repo\",\n            \"remoteRoot\": \"/app/mono-repo\",\n            \"trace\": true,\n            \"restart\": true,\n            \"sourceMaps\": true,\n            \"skipFiles\": [\n                \"<node_internals>/**\"\n            ]\n        }\n\n\nWith Web-storm this was easier to achieve somehow..\n```\n\n```text\n/docker\n```\n\n```text\ndocker-compose -f dev.yml up\n```\n\n```text\nversion: '3.7'\nservices:\n  api:\n    container_name: api\n    build:\n      context: .\n      target: development\n    volumes:\n      - '.:/app'\n      - './node_modules:/app/node_modules'\n    command: yarn start:debug\n    ports:\n      - ${API_PORT}:${API_PORT}\n      - 9229:9229\n    networks:\n      - network\n  mongo_db:\n    ...\n    ...\n    ...\nnetworks: \n  network:\n    driver: bridge\n```\n\n```text\nFROM node:16-alpine as development\nARG NODE_ENV=development\nENV NODE_ENV=${NODE_ENV}\nWORKDIR /app\n\nCOPY package.json .\nCOPY yarn.lock .\n\nRUN yarn\n\nCOPY . .\n\nRUN yarn build\n\nFROM node:16-alpine as production\n...\n```\n\n```text\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"Debug: api\",\n      \"type\": \"node\",\n      \"request\": \"attach\",\n      \"restart\": true,\n      \"port\": 9229,\n      \"address\": \"0.0.0.0\",\n      \"localRoot\": \"${workspaceFolder}\",\n      \"remoteRoot\": \"/app\",\n      \"protocol\": \"inspector\",\n      \"skipFiles\": [\"<node_internals>/**\"]\n    }\n  ]\n}\n```\n\n```text\n\"start:debug\": \"nest start --debug 0.0.0.0:9229 --watch\",\n```\n\n```text\ndevelopment\n```\n\n```text\nDocker\n```\n\n```text\ndocker-compose.yaml\n```\n\n```text\nlaunch.json\n```\n\n```text\nstart:debug\n```\n\n```text\npackage.json\n```\n\n```text\ndocker compose up -d\n```\n\n========================================\n\nComments:\n- in command \"0.0.0.0:9229\" fixed my problem... tnx a lot\n- I have a similar setup but with a Nrwl NX monorepo. I have not been able to get debugging to work correctly with this setup. stackoverflow.com/questions/78962888/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":170,"estimatedTokens":834}}1033{"id":"stack-76308716","source":"stackoverflow","questionId":76308716,"title":"How to set up a RedisService using Redis from `ioredis`?","tags":["typescript","redis","jestjs","nestjs","ioredis"],"text":"Title: How to set up a RedisService using Redis from `ioredis`?\nTags: typescript, redis, jestjs, nestjs, ioredis\nSource: Stack Overflow\n\nQuestion:\nNestJs v9.0.0, ioredis v5.3.2, jest v29.5.0.\nI'm unable to properly set up my redis service to get it working in both, jest unit tests or starting the nest app. I have a service `RedisService` which imports Redis fromย 'ioredis'.\n\nGetting either issues when running the unit tests(jest) for the `RedisService`, or if I fix them then I get the below error when starting Nest:\n\n### Error #1\n\nWhen starting Nest or running the e2e:\n\n```\nNest can't resolve dependencies of the RedisService (?). Please make sure that the argument Redis at index [0] is available in the RedisModule context.\n\n Potential solutions:\n - Is RedisModule a valid NestJS module?\n - If Redis is a provider, is it part of the current RedisModule?\n - If Redis is exported from a separate @Module, is that module imported within RedisModule?\n @Module({\n imports: [ /* the Module containing Redis */ ]\n })\n```\n\nAbove error is reproduced when starting the app or running the e2e tests.\n\nThis is my `RedisService` with which the unit tests work fine, but when starting the app or running the e2e tests I get the Error #1:\n\n```\nimport { Injectable, OnModuleDestroy } from '@nestjs/common';\nimport Redis from 'ioredis';\n\n@Injectable()\nexport class RedisService implements OnModuleDestroy {\n constructor(private client: Redis) {} // {\n return await this.client.get(key);\n }\n}\n```\n\nI have tried different approaches, and this was the one the unit tests finally worked fine, but clearly not when running e2e tests or starting the app.\n\nHowever I can easily fix it by making my RedisService not to inject Redis from 'ioredis' into the constructor and instead instantiating it in onModuleInit lifecycle hook. BUT if I stop injecting it into the constructor, then its unit tests fail because the redisClient is an empty object instead of the mock I want it to be. Which leads to fix Error #1 but instead get Error #2 described below.\n\n### Error #2\n\nIn case of the tests failing, I get the following kind of errors:\n\n`TypeError: Cannot read properties of undefined (reading 'set')`\nand `TypeError: Cannot read properties of undefined (reading 'get')`\n\nThe unit tests instead fail BUT the e2e and app work successfully if I change the `redis.service.ts` to:\n\n```\nimport { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';\nimport Redis from 'ioredis';\n\n@Injectable()\nexport class RedisService implements OnModuleInit, OnModuleDestroy {\n private client: Redis; // no injection in the constructor\n\n async onModuleInit() {\n this.client = new Redis({\n host: process.env.REDIS_HOST,\n port: +process.env.REDIS_PORT,\n });\n }\n // ...\n}\n```\n\nThen the tests fail because the redisService is an empty object.\n\n### Context\n\nThese are the specs, `redis.service.spec.ts`:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport Redis from 'ioredis';\nimport * as redisMock from 'redis-mock';\nimport { RedisService } from './redis.service';\n\ndescribe('RedisService', () => {\n let service: RedisService;\n let redisClientMock: redisMock.RedisClient;\n\n beforeEach(async () => {\n redisClientMock = {\n set: jest.fn(),\n get: jest.fn(),\n };\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n RedisService,\n {\n provide: Redis,\n useValue: redisMock.createClient(),\n },\n ],\n }).compile();\n\n redisClientMock = module.get(Redis);\n service = module.get(RedisService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n describe('set', () => {\n it('should set a value in Redis with expiration date', async () => {\n const spy = jest.spyOn(redisClientMock, 'set');\n await service.set('my-key', 'my-value', 60);\n expect(spy).toHaveBeenCalledWith('my-key', 'my-value', 'EX', 60);\n });\n });\n\n describe('get', () => {\n it('should return null if the key does not exist', async () => {\n const spy = jest.spyOn(redisClientMock, 'get').mockReturnValue(undefined);\n const value = await service.get('nonexistent-key');\n expect(value).toBeUndefined();\n });\n it('should return the value if the key exists', async () => {\n jest.spyOn(redisClientMock, 'get').mockReturnValue('my-value');\n const value = await service.get('my-key');\n expect(value).toBe('my-value');\n });\n });\n});\n```\n\nHere is my\n`redis.module.ts`:\n\n```\nimport { Module } from '@nestjs/common';\nimport { RedisService } from './redis.service';\n\n@Module({\n providers: [RedisService],\n exports: [RedisService],\n})\nexport class RedisModule {}\n```\n\nRedisModule is in the imports array of the module where it is a dependency.\n\nI guess using ioredis we just have to avoid injecting it in the constructor, but then how can I fix `redis.service.spec.ts` so that it gets the redisClient on time? Should it be injected as a dependency in the constructor? In any case, how should Redis be implemented in Nest so that both, e2e and unit tests work smoothly?\n\n========================================\n\nCode:\n```text\nNest can't resolve dependencies of the RedisService (?). Please make sure that the argument Redis at index [0] is available in the RedisModule context.\n\n    Potential solutions:\n    - Is RedisModule a valid NestJS module?\n    - If Redis is a provider, is it part of the current RedisModule?\n    - If Redis is exported from a separate @Module, is that module imported within RedisModule?\n      @Module({\n        imports: [ /* the Module containing Redis */ ]\n      })\n```\n\n```text\nimport { Injectable, OnModuleDestroy } from '@nestjs/common';\nimport Redis from 'ioredis';\n\n@Injectable()\nexport class RedisService implements OnModuleDestroy {\n  constructor(private client: Redis) {} // <-- This is possibly the \"issue\". Unit tests work fine with this DI but app and e2e fail\n\n  async onModuleInit() {\n    this.client = new Redis({\n      host: process.env.REDIS_HOST,\n      port: +process.env.REDIS_PORT,\n    });\n  }\n\n  async onModuleDestroy() {\n    await this.client.quit();\n  }\n\n  async set(key: string, value: string, expirationSeconds: number) {\n    await this.client.set(key, value, 'EX', expirationSeconds);\n  }\n\n  async get(key: string): Promise<string | null> {\n    return await this.client.get(key);\n  }\n}\n```\n\n```text\nimport { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';\nimport Redis from 'ioredis';\n\n@Injectable()\nexport class RedisService implements OnModuleInit, OnModuleDestroy {\n  private client: Redis; // no injection in the constructor\n\n  async onModuleInit() {\n    this.client = new Redis({\n      host: process.env.REDIS_HOST,\n      port: +process.env.REDIS_PORT,\n    });\n  }\n  // ...\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport Redis from 'ioredis';\nimport * as redisMock from 'redis-mock';\nimport { RedisService } from './redis.service';\n\ndescribe('RedisService', () => {\n  let service: RedisService;\n  let redisClientMock: redisMock.RedisClient;\n\n  beforeEach(async () => {\n    redisClientMock = {\n      set: jest.fn(),\n      get: jest.fn(),\n    };\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        RedisService,\n        {\n          provide: Redis,\n          useValue: redisMock.createClient(),\n        },\n      ],\n    }).compile();\n\n    redisClientMock = module.get(Redis);\n    service = module.get<RedisService>(RedisService);\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n\n  describe('set', () => {\n    it('should set a value in Redis with expiration date', async () => {\n      const spy = jest.spyOn(redisClientMock, 'set');\n      await service.set('my-key', 'my-value', 60);\n      expect(spy).toHaveBeenCalledWith('my-key', 'my-value', 'EX', 60);\n    });\n  });\n\n  describe('get', () => {\n    it('should return null if the key does not exist', async () => {\n      const spy = jest.spyOn(redisClientMock, 'get').mockReturnValue(undefined);\n      const value = await service.get('nonexistent-key');\n      expect(value).toBeUndefined();\n    });\n    it('should return the value if the key exists', async () => {\n      jest.spyOn(redisClientMock, 'get').mockReturnValue('my-value');\n      const value = await service.get('my-key');\n      expect(value).toBe('my-value');\n    });\n  });\n});\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { RedisService } from './redis.service';\n\n@Module({\n  providers: [RedisService],\n  exports: [RedisService],\n})\nexport class RedisModule {}\n```\n\n```text\nRedisService\n```\n\n```text\nRedisService\n```\n\n```text\nRedisService\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'set')\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'get')\n```\n\n```text\nredis.service.ts\n```\n\n```text\nredis.service.spec.ts\n```\n\n```text\nredis.module.ts\n```\n\n```text\nredis.service.spec.ts\n```\n\n```text\nimport { Provider } from '@nestjs/common';\n    import Redis from 'ioredis';\n    \n    export type RedisClient = Redis;\n    \n    export const redisProvider: Provider = {\n      useFactory: (): RedisClient => {\n        return new Redis({\n          host: 'localhost',\n          port: 6379,\n        });\n      },\n      provide: 'REDIS_CLIENT',\n    };\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { redisProvider } from './redis.providers';\nimport { RedisService } from './redis.service';\n\n@Module({\n  providers: [redisProvider, RedisService],\n  exports: [RedisService],\n})\nexport class RedisModule {}\n```\n\n```text\nimport { Inject, Injectable } from '@nestjs/common';\nimport { RedisClient } from './redis.providers';\n\n@Injectable()\nexport class RedisService {\n  public constructor(\n    @Inject('REDIS_CLIENT')\n    private readonly client: RedisClient,\n  ) {}\n\n  async set(key: string, value: string, expirationSeconds: number) {\n    await this.client.set(key, value, 'EX', expirationSeconds);\n  }\n\n  async get(key: string): Promise<string | null> {\n    return await this.client.get(key);\n  }\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport Redis from 'ioredis';\nimport * as redisMock from 'redis-mock';\nimport { RedisService } from './redis.service';\n\ndescribe('RedisService', () => {\n  let service: RedisService;\n  let redisClientMock: redisMock.RedisClient;\n\n  beforeEach(async () => {\n    redisClientMock = {\n      set: jest.fn(),\n      get: jest.fn(),\n    };\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        RedisService,\n        {\n          provide: 'REDIS_CLIENT',\n          useValue: redisMock.createClient(),\n        },\n      ],\n    }).compile();\n\n    redisClientMock = module.get('REDIS_CLIENT');\n    service = module.get<RedisService>(RedisService);\n  });\n\n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n```\n\n```text\nNEST_DEBUG=true npm test\n```\n\n```text\nredis.provider.ts\n```\n\n```text\nredis.module.ts\n```\n\n```text\nredis.service.ts\n```\n\n```text\nredis.service.spec.ts\n```\n\n```text\nREDIS_CLIENT\n```\n\n```text\nioredis\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":429,"estimatedTokens":2739}}1034{"id":"stack-71891420","source":"stackoverflow","questionId":71891420,"title":"NestJS/TypeORM: Cannot set property metadata of # which has only a getter","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS/TypeORM: Cannot set property metadata of # which has only a getter\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI try to run my nestjstutorial app, the below error is showing. My backend is connected to a PostgreSQL db.\n\nTypeError: Cannot set property metadata of # which has only a getter\nat EntityManager.getCustomRepository (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\src\\entity-manager\\EntityManager.ts:1404:59)\nat DataSource.getCustomRepository (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\src\\data-source\\DataSource.ts:465:29)\nat InstanceWrapper.useFactory [as metatype] (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\typeorm\\dist\\typeorm.providers.js:13:35)\nat Injector.instantiateClass (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:333:55)\nat callback (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:48:41)\nat processTicksAndRejections (node:internal/process/task_queues:96:5)\nat Injector.resolveConstructorParams (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:122:24)\nat Injector.loadInstance (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:52:9)\nat Injector.loadProvider (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:74:9)\nat Injector.lookupComponentInImports (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:265:17)\n\nMy code looks like this:\n\n**app.module**\n\n```\nimport { Module } from '@nestjs/common';\n import { AppController } from './app.controller';\n import { AppService } from './app.service';\n import { UserController } from './user/user.controller';\n import { UserModule } from './user/user.module';\n import { UserService } from './user/user.services';\n import { QuizModule } from './modules/quiz/quiz.module';\n //import { QuizController } from './modules/quiz/quiz.controller';\n //import { QuizService } from './modules/quiz/quiz.services';\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { typeOrmConfig } from './config/typeorm.config';\n //import { QuizRepository } from './modules/quiz/quiz.repository';\n \n @Module({\n imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],\n controllers: [AppController],\n providers: [AppService],\n })\n export class AppModule {}\n```\n\n**quiz.controller**\n\n```\nimport {\n Body,\n Controller,\n Get,\n HttpCode,\n Post,\n UsePipes,\n ValidationPipe,\n } from '@nestjs/common';\n import { QuizService } from './quiz.services';\n import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n \n @Controller('quiz')\n export class QuizController {\n constructor(private readonly quizService: QuizService) {}\n \n @Get('/')\n getAllQuiz() {\n return this.quizService.getAllQuiz();\n }\n \n @Post('/create')\n @HttpCode(200)\n @UsePipes(ValidationPipe)\n async createQuiz(@Body() quizData: CreateQuizDto) {\n return await this.quizService.createNewQuiz(quizData);\n }\n }\n```\n\n**quiz.services**\n\n```\nimport { Injectable } from '@nestjs/common';\n import { InjectRepository } from '@nestjs/typeorm';\n import { QuizRepository } from './quiz.repository';\n import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n \n @Injectable()\n export class QuizService {\n constructor(\n @InjectRepository(QuizRepository) private quizRepository: QuizRepository,\n ) {}\n \n getAllQuiz() {\n return [1, 2, 'from service', 3];\n }\n async createNewQuiz(quiz: CreateQuizDto) {\n return await this.quizRepository.save(quiz);\n }\n }\n```\n\n**quiz.module**\n\n```\nimport { Module } from '@nestjs/common';\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { QuizController } from './quiz.controller';\n import { QuizService } from './quiz.services';\n import { QuizRepository } from './quiz.repository';\n \n @Module({\n controllers: [QuizController],\n imports: [TypeOrmModule.forFeature([QuizRepository])],\n providers: [QuizService],\n })\n export class QuizModule {}\n```\n\n**quiz.repository**\n\n```\nimport { EntityRepository, Repository } from 'typeorm';\n import { Quiz } from './quiz.entity';\n \n @EntityRepository(Quiz)\n export class QuizRepository extends Repository {\n // means Quiz module\n }\n```\n\n**typeorm.config**\n\n```\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\n export const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: '123456',\n database: 'quiz',\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n```\n\n**dto**\n\n```\nimport { isNotEmpty, IsNotEmpty, Length } from 'class-validator';\n\nexport class CreateQuizDto {\n @IsNotEmpty({ message: 'Title mandatory' })\n @Length(3, 255)\n title: string;\n\n @IsNotEmpty()\n @Length(3)\n description: string;\n}\n```\n\n**entity**\n\n```\nimport { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity('quizes')\nexport class Quiz extends BaseEntity {\n @PrimaryGeneratedColumn({\n comment: 'The quiz unique identifier',\n })\n id: number;\n\n @Column({\n type: 'varchar',\n })\n title: string;\n\n @Column({\n type: 'text',\n })\n description: string;\n\n @Column({\n type: 'varchar',\n })\n usernmae: string;\n\n @Column({\n type: 'date',\n })\n createddate: Date;\n\n @Column({\n type: 'boolean',\n default: 1,\n })\n isActive: boolean;\n}\n```\n\nSomebody know how can I fix this?\n\n========================================\n\nTop Answer:\nWhich version of **@nestjs/typeorm** and **typeorm** are you using? If you are using typeorm > 0.3 this is a known issue and using the required typeorm will solve the issue.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\n    import { AppController } from './app.controller';\n    import { AppService } from './app.service';\n    import { UserController } from './user/user.controller';\n    import { UserModule } from './user/user.module';\n    import { UserService } from './user/user.services';\n    import { QuizModule } from './modules/quiz/quiz.module';\n    //import { QuizController } from './modules/quiz/quiz.controller';\n    //import { QuizService } from './modules/quiz/quiz.services';\n    import { TypeOrmModule } from '@nestjs/typeorm';\n    import { typeOrmConfig } from './config/typeorm.config';\n    //import { QuizRepository } from './modules/quiz/quiz.repository';\n    \n    @Module({\n      imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],\n      controllers: [AppController],\n      providers: [AppService],\n    })\n    export class AppModule {}\n```\n\n```text\nimport {\n      Body,\n      Controller,\n      Get,\n      HttpCode,\n      Post,\n      UsePipes,\n      ValidationPipe,\n    } from '@nestjs/common';\n    import { QuizService } from './quiz.services';\n    import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n    \n    @Controller('quiz')\n    export class QuizController {\n      constructor(private readonly quizService: QuizService) {}\n    \n      @Get('/')\n      getAllQuiz() {\n        return this.quizService.getAllQuiz();\n      }\n    \n      @Post('/create')\n      @HttpCode(200)\n      @UsePipes(ValidationPipe)\n      async createQuiz(@Body() quizData: CreateQuizDto) {\n        return await this.quizService.createNewQuiz(quizData);\n      }\n    }\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\n    import { InjectRepository } from '@nestjs/typeorm';\n    import { QuizRepository } from './quiz.repository';\n    import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n    \n    @Injectable()\n    export class QuizService {\n      constructor(\n        @InjectRepository(QuizRepository) private quizRepository: QuizRepository,\n      ) {}\n    \n      getAllQuiz() {\n        return [1, 2, 'from service', 3];\n      }\n      async createNewQuiz(quiz: CreateQuizDto) {\n        return await this.quizRepository.save(quiz);\n      }\n    }\n```\n\n```text\nimport { Module } from '@nestjs/common';\n    import { TypeOrmModule } from '@nestjs/typeorm';\n    import { QuizController } from './quiz.controller';\n    import { QuizService } from './quiz.services';\n    import { QuizRepository } from './quiz.repository';\n    \n    @Module({\n      controllers: [QuizController],\n      imports: [TypeOrmModule.forFeature([QuizRepository])],\n      providers: [QuizService],\n    })\n    export class QuizModule {}\n```\n\n```text\nimport { EntityRepository, Repository } from 'typeorm';\n    import { Quiz } from './quiz.entity';\n    \n    @EntityRepository(Quiz)\n    export class QuizRepository extends Repository<Quiz> {\n      //<Quiz> means Quiz module\n    }\n```\n\n```text\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\n    export const typeOrmConfig: TypeOrmModuleOptions = {\n      type: 'postgres',\n      host: 'localhost',\n      port: 5432,\n      username: 'postgres',\n      password: '123456',\n      database: 'quiz',\n      entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n      synchronize: true,\n    };\n```\n\n```text\nimport { isNotEmpty, IsNotEmpty, Length } from 'class-validator';\n\nexport class CreateQuizDto {\n  @IsNotEmpty({ message: 'Title mandatory' })\n  @Length(3, 255)\n  title: string;\n\n  @IsNotEmpty()\n  @Length(3)\n  description: string;\n}\n```\n\n```text\nimport { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity('quizes')\nexport class Quiz extends BaseEntity {\n  @PrimaryGeneratedColumn({\n    comment: 'The quiz unique identifier',\n  })\n  id: number;\n\n  @Column({\n    type: 'varchar',\n  })\n  title: string;\n\n  @Column({\n    type: 'text',\n  })\n  description: string;\n\n  @Column({\n    type: 'varchar',\n  })\n  usernmae: string;\n\n  @Column({\n    type: 'date',\n  })\n  createddate: Date;\n\n  @Column({\n    type: 'boolean',\n    default: 1,\n  })\n  isActive: boolean;\n}\n```\n\n```js\nconstructor(\n    private quizRepository: QuizRepository,\n) {}\n```\n\n```text\nCustomRepository\n```\n\n```text\nInjectRepository\n```\n\n```text\nNestJS\n```\n\n```text\ntypeorm.config\n```\n\n```text\nQuiz\n```\n\n```text\nTypeORM\n```\n\n========================================\n\nComments:\n- Tried remove InjectRepository still error remains the same. Also edited the posted with typeorm.config\n- this solution worked for me as well, I also had exact problem.\n- It also solved other issues I was experiencing","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":415,"estimatedTokens":2577}}1035{"id":"stack-74262031","source":"stackoverflow","questionId":74262031,"title":"Managing Transactions in Sequelize on NestJS","tags":["node.js","typescript","sequelize.js","nestjs"],"text":"Title: Managing Transactions in Sequelize on NestJS\nTags: node.js, typescript, sequelize.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nIve integrated sequelize ORM in typescript. My database is connected successfully and even queries are working. Now i need to use transactions in my application but there's no clear documentation on how to make it work on nestjs.\n\nIve tried to integrate transactions through sequelize connection but it seems not to be working.\n\nin my app.module ive created the sequelize configuration for root\n\n```\n@Module({\n\nimports: [\n SequelizeModule.forRoot({\n dialect: 'mysql',\n host: 'localhost',\n port: 3306,\n username: Config.db_userName,\n // password: Config.db_password,\n database: \"myDbName\",\n autoLoadModels: true,\n models: []\n }),\n myModule],\n controllers: [AppController],\n providers: [AppService],\n```\n\nand in my service.ts file i have the following constructor trying to use this connection of sequelize\n\n```\n@InjectConnection()\nprivate sequelize: Sequelize,\n```\n\nafter that im trying to use this.sequelize.transaction its not giving me any error in code.. but after compiling. im receiving this error\n\n```\nthis.sequelize.transaction() is not a function\n```\n\n========================================\n\nTop Answer:\nI had an issue with:\n\n```\nprivate sequelize: Sequelize\n```\n\nAnd then I realized, I used wrong Sequelize import (from \"sequelize\"). This import worked for me.\n\n```\nimport { Sequelize } from \"sequelize-typescript\"\n```\n\nMaybe it will help someone :)\n\n========================================\n\nCode:\n```text\n@Module({\n\n\nimports: [\n    SequelizeModule.forRoot({\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: Config.db_userName,\n     // password: Config.db_password,\n      database: \"myDbName\",\n      autoLoadModels: true,\n      models: []\n    }),\n  myModule],\n  controllers: [AppController],\n  providers: [AppService],\n```\n\n```text\n@InjectConnection()\nprivate sequelize: Sequelize,\n```\n\n```text\nthis.sequelize.transaction() is not a function\n```\n\n```text\nprivate sequelize: Sequelize\n```\n\n```text\ninjectConnection()\n```\n\n```text\nprivate sequelize: Sequelize\n```\n\n```text\nimport { Sequelize } from \"sequelize-typescript\"\n```\n\n```text\ninitSequelizeCLS();\n```\n\n```text\n@Module({\n  imports: [\n    SequelizeModule.forRoot({\n      ...\n    }),\n    SequelizeTransactionalModule.register(), // << this\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n@Injectable()\nexport class AppService {\n  constructor(\n    @InjectModel(Something)\n    private readonly something: typeof Something,\n    private readonly anotherService: AnotherService,\n  ) {}\n\n  @Transactional()\n  async appMethod(): Promise<void> {\n    await this.something.create({ message: 'hello' });\n    await this.something.create({ message: 'world' });\n    await this.anotherService.method(); // will use the same transaction by default, customizable with propagation option\n  }\n}\n```\n\n========================================\n\nComments:\n- Did you check what is stored in `this.sequelize`?\n- Its Empty object","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":149,"estimatedTokens":774}}1036{"id":"stack-68690562","source":"stackoverflow","questionId":68690562,"title":"How to exclude a column from typeorm entity and could be optional to get the column using Find method","tags":["node.js","typescript","postgresql","nestjs","typeorm"],"text":"Title: How to exclude a column from typeorm entity and could be optional to get the column using Find method\nTags: node.js, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n@PrimaryGeneratedColumn()\nid: number;\n\n@Column()\nname: string;\n\n@Column()\npassword: string;\n}\n```\n\ni dont want password here because i want to return to client:\n\n```\nconst user = await User.find({where:{name:\"test\"}})\n```\n\nwhen i want to modify password i need password:\n\n```\nconst user = await User.findOne({where:{name:\"test\"}})\nuser.password=\"password\";\nawait user.save()\n```\n\nis there any solution with Find,FindAndCount or even FindOne methods?\n\n**How should i do?**\n\n========================================\n\nTop Answer:\nIf you don't want to apply `select: false` to column in entity, then other option is to selectively type columns in find method only which you need\n\n```\nthis.ManagementUnitRepository.find({\n select: [\"id\", \"name\"]\n});\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n@PrimaryGeneratedColumn()\nid: number;\n\n@Column()\nname: string;\n\n@Column()\npassword: string;\n}\n```\n\n```text\nconst user = await User.find({where:{name:\"test\"}})\n```\n\n```text\nconst user = await User.findOne({where:{name:\"test\"}})\nuser.password=\"password\";\nawait user.save()\n```\n\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  name: string;\n\n  @Column({select: false})\n  password: string;\n}\n```\n\n```text\n@Column\n```\n\n```text\nfind\n```\n\n```text\naddSelect\n```\n\n```text\nQueryBuilder\n```\n\n```text\nthis.ManagementUnitRepository.find({\n  select: [\"id\", \"name\"]\n});\n```\n\n```text\nselect: false\n```\n\n========================================\n\nComments:\n- thanks for your answer. is it possible to pass args of Find Method to `createQueryBuilder().where(args)` ? because i wrote some functionality for sorting and filtering dynamicly Find Method's Options. @rahul-sharma\n- `find` and `QueryBuillder`'s `where` accept arguments in different manners. Passing the json you wrote for `find` in `createQueryBuilder().where` won't be possible, I guess. You can always write any query that you wrote using `find` with `QueryBuilder`. You'll have to specify the filters in `where` and sort using `sort` method.\n- yes completely correct ,i finally remove the password field from returned array in Find() by using RXJS's map operator technically after get all the fields from database\n- Thank you for your solution @Awais Nasir","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":131,"estimatedTokens":679}}1037{"id":"stack-67069682","source":"stackoverflow","questionId":67069682,"title":"mongoose @prop() decorator type:Object in schema definition _ NestJS","tags":["mongoose","nestjs"],"text":"Title: mongoose @prop() decorator type:Object in schema definition _ NestJS\nTags: mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI recently moved to NestJs . I have some doubts for defining properties for mongoose schema .\n\nhow can I define object type inside schema :\n\nin express I defined such properties like this:\n\n```\nfoo:{\n type: Object\n },\n```\n\nnow here I cannot use Object type. I did use **any** keyword too.\n\n========================================\n\nCode:\n```text\nfoo:{\n        type: Object\n    },\n```\n\n```text\n@Prop({ type: Object })\n  foo: any;\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":32,"estimatedTokens":142}}1038{"id":"stack-69259893","source":"stackoverflow","questionId":69259893,"title":"no affect on CORS enabling with NESTJS","tags":["node.js","websocket","nestjs"],"text":"Title: no affect on CORS enabling with NESTJS\nTags: node.js, websocket, nestjs\nSource: Stack Overflow\n\nQuestion:\nI fail to enable the CORS for testing with the latest NestJS 8.0.6 and a fresh http + ws project. That said, I want to see the `Access-Control-Allow-Origin` in the servers response (so that the client would accept it). Here is my main.ts where I've tried 3 approches: 1) with options, 2) with a method, 3) with app.use. None of them works.\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { microserviceConfig} from \"./msKafkaConfig\";\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule, { cors: true}); // DOESN'T WORK\n app.enableCors(); // DOESN'T WORK\n\n app.connectMicroservice(microserviceConfig);\n await app.startAllMicroservices();\n\n \n // DOESN'T WORK\n app.use((req, res, next) => {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS,UPGRADE,CONNECT,TRACE');\n res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');\n next();\n });\n \n await app.listen(3000);\n\n}\nbootstrap();\n```\n\nPlease, do NOT give me a lesson on how dangerous CORS (XSForgery) is if we accept all domains. there is enough material about that. And I'm well aware of it. This is about NestJS not replying the `Access-Control-Allow-Origin` element in the header.\n\nThe browser console reports:\n\n```\nAccess to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Nm4kVQ1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\nIn the chrome header inspection I see:\n\n```\nRequest URL: http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Nm4kUZ-\nReferrer Policy: strict-origin-when-cross-origin\nConnection: keep-alive\nContent-Length: 97\nContent-Type: text/plain; charset=UTF-8\nDate: Mon, 20 Sep 2021 19:41:05 GMT\nKeep-Alive: timeout=5\nAccept: */*\nAccept-Encoding: gzip, deflate, br\nAccept-Language: en,de-DE;q=0.9,de;q=0.8,en-US;q=0.7,es;q=0.6\nCache-Control: no-cache\nConnection: keep-alive\nHost: localhost:3000\nOrigin: http://localhost:4200\nPragma: no-cache\nReferer: http://localhost:4200/\nsec-ch-ua: \"Google Chrome\";v=\"93\", \" Not;A Brand\";v=\"99\", \"Chromium\";v=\"93\"\nsec-ch-ua-mobile: ?0\nsec-ch-ua-platform: \"Windows\"\nSec-Fetch-Dest: empty\nSec-Fetch-Mode: cors\nSec-Fetch-Site: same-site\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36\nEIO: 4\ntransport: polling\nt: Nm4kUZ-\n```\n\nDoes the `Referrer Policy: strict-origin-when-cross-origin` have an influence?\n\n(btw, it works just fine with a simple express setup. So it cannot be my browser's fault.)\n\n========================================\n\nTop Answer:\nI deleted or changed **transports** argument in the array. It is from the frontend\n\n```\n//FRONTEND FILE\n socket = io(BE_URL, {\n withCredentials: true,\n query: {\n token,\n isUserNew,\n },\n transports: ['websocket', 'polling'], // USE ['polling', 'websocket'] OR DELETED IT\n autoConnect: false,\n });\n\n//BACKEND FILE\n@WebSocketGateway({\n cors: { credentials: true, methods: ['GET', 'POST'], origin: ['http://host1', 'http://host2']},\n transports: ['polling', 'websocket'],\n})\n```\n\nI read it - https://socket.io/docs/v3/client-initialization/#transports\n\nOne possible downside is that the validity of your CORS configuration will only be checked if the WebSocket connection fails to be established.\n\nI really hope this answer saves you some time.\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { microserviceConfig} from \"./msKafkaConfig\";\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, { cors: true}); // DOESN'T WORK\n  app.enableCors(); // DOESN'T WORK\n\n  app.connectMicroservice(microserviceConfig);\n  await app.startAllMicroservices();\n\n  \n  // DOESN'T WORK\n  app.use((req, res, next) => {\n    res.header('Access-Control-Allow-Origin', '*');\n    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS,UPGRADE,CONNECT,TRACE');\n    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');\n    next();\n  });\n  \n  await app.listen(3000);\n\n\n\n}\nbootstrap();\n```\n\n```text\nAccess to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Nm4kVQ1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n```\n\n```text\nRequest URL: http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Nm4kUZ-\nReferrer Policy: strict-origin-when-cross-origin\nConnection: keep-alive\nContent-Length: 97\nContent-Type: text/plain; charset=UTF-8\nDate: Mon, 20 Sep 2021 19:41:05 GMT\nKeep-Alive: timeout=5\nAccept: */*\nAccept-Encoding: gzip, deflate, br\nAccept-Language: en,de-DE;q=0.9,de;q=0.8,en-US;q=0.7,es;q=0.6\nCache-Control: no-cache\nConnection: keep-alive\nHost: localhost:3000\nOrigin: http://localhost:4200\nPragma: no-cache\nReferer: http://localhost:4200/\nsec-ch-ua: \"Google Chrome\";v=\"93\", \" Not;A Brand\";v=\"99\", \"Chromium\";v=\"93\"\nsec-ch-ua-mobile: ?0\nsec-ch-ua-platform: \"Windows\"\nSec-Fetch-Dest: empty\nSec-Fetch-Mode: cors\nSec-Fetch-Site: same-site\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36\nEIO: 4\ntransport: polling\nt: Nm4kUZ-\n```\n\n```text\nAccess-Control-Allow-Origin\n```\n\n```text\nAccess-Control-Allow-Origin\n```\n\n```text\nReferrer Policy: strict-origin-when-cross-origin\n```\n\n```js\n@WebsocketGateway({ cors: '*:*' })\nexport class FooGateway {}\n```\n\n```text\nenableCors\n```\n\n```text\n{ cors: true }\n```\n\n```text\nsocket.io\n```\n\n```text\n@WebsocketGateway()\n```\n\n```text\nhost:port\n```\n\n```text\nin main.ts\n\n    // import\n    import { NestExpressApplication } from '@nestjs/platform-express';\n\n    //in bootstrap() function\n    const app = await NestFactory.create<NestExpressApplication>(AppModule);\n    app.enableCors();\n    app.setGlobalPrefix('/api/v1')\n```\n\n```text\n//in your Gateway service \n\nimport { Socket, Server } from 'socket.io';\nimport {\n    OnGatewayConnection,\n    OnGatewayDisconnect,\n    OnGatewayInit,\n    SubscribeMessage,\n    WebSocketGateway,\n    WebSocketServer,\n} from \"@nestjs/websockets\";\n@WebSocketGateway(\n    {\n        path: \"/api/v1/ws\",\n        serveClient: false,\n        cors: {\n            origin: `*`\n        }\n    })\nexport class AppGateway\n    implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {\n    \n    private logger: Logger = new Logger(AppGateway.name);\n\n    ...\n    afterInit(server: Server) {\n        this.logger.log(`Init`);\n    }\n\n    handleDisconnect(client: Socket) {\n        this.logger.log(`handleDisconnect: ${client.id}`);\n        this.wss.socketsLeave(client.id);\n    }\n\n    handleConnection(client: Socket, ...args: any[]) {\n        this.wss.socketsJoin(client.id)\n        this.logger.log(`handleConnection: ${client.id}`);\n    }\n}\n```\n\n```text\n//in your client side \n\n this.socket = io(\"ws://localhost:3000\", \n       {\n        path: \"/api/v1/ws\",\n        reconnectionDelayMax: 10000,\n       }\n);\n```\n\n```text\n// package.json\n  \"dependencies\": { \n  \"@nestjs/platform-socket.io\": \"^8.0.6\",\n  \"@nestjs/platform-express\": \"^8.0.0\",\n  \"@nestjs/websockets\": \"^6.1.0\"\n},\n \"devDependencies\": {\n  \"@types/socket.io\": \"^3.0.2\",\n  \"@types/ws\": \"^7.4.7\"\n}\n```\n\n```text\n//FRONTEND FILE\n    socket = io(BE_URL, {\n      withCredentials: true,\n      query: {\n        token,\n        isUserNew,\n      },\n      transports: ['websocket', 'polling'], // USE ['polling', 'websocket'] OR DELETED IT\n      autoConnect: false,\n    });\n\n\n\n//BACKEND FILE\n@WebSocketGateway({\n  cors: { credentials: true, methods: ['GET', 'POST'], origin: ['http://host1', 'http://host2']},\n  transports: ['polling', 'websocket'],\n})\n```\n\n========================================\n\nComments:\n- Not to be insulting, but because a lot of people make this mistake, Have you inspected the response in your network console to determine what exactly the response is rather than stopping at the CORS error? what *exactly* is the cors error? How does websocket come into play here?\n- I just tested with `curl` and `{ cors: true }` and `app.enableCors()`. Both of these options resulted in having a response header `Access-Control-Allow-Origin: *`. Not sure what you're running into, but it doesn't seem to be the fault of the framework\n- @KevinB I don't think the websocket should have any affect. After all it's just an http upgrade - just pointing out.\n- @JayMcDoniel True. I've checked that too. (I've added CORS after I've added a Kafka Producer and Consumer. Maybe I messed up something there). Anyhow, thanks for confirming.\n- That URL looks like a Socket.IO connection URL. Do you have the CORS options enabled for the gateway? `@WebsocketGateway({ cors: '*:*' })`\n- @JayMcDoniel can your last reply as the answer so I can mark it. Jjjj... I totally missed the decorator's options - and thus the websocket own CORS settings. thanks heaps. Saved me hours.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- It helps me with cors problem.","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":319,"estimatedTokens":2372}}1039{"id":"stack-59866516","source":"stackoverflow","questionId":59866516,"title":"GraphQL endpoint return null object in Nest.js","tags":["graphql","nestjs","sequelize-typescript"],"text":"Title: GraphQL endpoint return null object in Nest.js\nTags: graphql, nestjs, sequelize-typescript\nSource: Stack Overflow\n\nQuestion:\nI'm using Nest.js and Sequelize-Typescript to build a GraphQL API.\n\nWhen I called delete and update mutations I got a null object, but the operation it is done. I need to put {nullable: true} because I got a error saying `Cannot return null for non-nullable field` . How I fix it? I need the endpoint to return the updated object to show the information on the front\n\nerror img\n\n*book.dto.ts*\n\n```\nimport { ObjectType, Field, Int, ID } from 'type-graphql';\n\n@ObjectType()\nexport class BookType {\n @Field(() => ID, {nullable: true})\n readonly id: number;\n @Field({nullable: true})\n readonly title: string;\n @Field({nullable: true})\n readonly author: string;\n}\n```\n\n*book.resolver.ts*\n\n```\nimport {Args, Mutation, Query, Resolver} from '@nestjs/graphql';\nimport { Book } from './model/book.entity';\nimport { BookType } from './dto/book.dto';\nimport { CreateBookInput } from './input/createBook.input';\nimport { UpdateBookInput } from './input/updateBook.input';\nimport { BookService } from './book.service';\n\n@Resolver('Book')\nexport class BookResolver {\n constructor(private readonly bookService: BookService) {}\n\n @Query(() => [BookType])\n async getAll(): Promise {\n return await this.bookService.findAll();\n }\n\n @Query(() => BookType)\n async getOne(@Args('id') id: number) {\n return await this.bookService.find(id);\n }\n\n @Mutation(() => BookType)\n async createItem(@Args('input') input: CreateBookInput): Promise {\n const book = new Book();\n book.author = input.author;\n book.title = input.title;\n return await this.bookService.create(book);\n }\n\n @Mutation(() => BookType)\n async updateItem(\n @Args('input') input: UpdateBookInput): Promise {\n return await this.bookService.update(input);\n }\n\n @Mutation(() => BookType)\n async deleteItem(@Args('id') id: number) {\n return await this.bookService.delete(id);\n }\n\n @Query(() => String)\n async hello() {\n return 'hello';\n }\n}\n```\n\n*book.service.ts*\n\n```\nimport {Inject, Injectable} from '@nestjs/common';\nimport {InjectRepository} from '@nestjs/typeorm';\nimport {Book} from './model/book.entity';\nimport {DeleteResult, InsertResult, Repository, UpdateResult} from 'typeorm';\n\n@Injectable()\nexport class BookService {\n constructor(@Inject('BOOKS_REPOSITORY') private readonly bookRepository: typeof Book) {}\n\n findAll(): Promise {\n return this.bookRepository.findAll();\n }\n\n find(id): Promise {\n return this.bookRepository.findOne({where: {id}});\n }\n\n create(data): Promise {\n return data.save();\n }\n\n update(data): Promise {\n return this.bookRepository.update(data, { where: {id: data.id} });\n }\n\n delete(id): Promise {\n return this.bookRepository.destroy({where: {id}});\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou can fix it setting option parameter in the resolver query\n\n```\n@Query(() => BookType, { nullable: true })\n```\n\n========================================\n\nCode:\n```text\nimport { ObjectType, Field, Int, ID } from 'type-graphql';\n\n@ObjectType()\nexport class BookType {\n    @Field(() => ID, {nullable: true})\n    readonly id: number;\n    @Field({nullable: true})\n    readonly title: string;\n    @Field({nullable: true})\n    readonly author: string;\n}\n```\n\n```text\nimport {Args, Mutation, Query, Resolver} from '@nestjs/graphql';\nimport { Book } from './model/book.entity';\nimport { BookType } from './dto/book.dto';\nimport { CreateBookInput } from './input/createBook.input';\nimport { UpdateBookInput } from './input/updateBook.input';\nimport { BookService } from './book.service';\n\n@Resolver('Book')\nexport class BookResolver {\n    constructor(private readonly bookService: BookService) {}\n\n    @Query(() => [BookType])\n    async getAll(): Promise<BookType[]> {\n        return await this.bookService.findAll();\n    }\n\n    @Query(() => BookType)\n    async getOne(@Args('id') id: number) {\n        return await this.bookService.find(id);\n    }\n\n    @Mutation(() => BookType)\n    async createItem(@Args('input') input: CreateBookInput): Promise<Book> {\n        const book = new Book();\n        book.author = input.author;\n        book.title = input.title;\n        return await this.bookService.create(book);\n    }\n\n    @Mutation(() => BookType)\n    async updateItem(\n        @Args('input') input: UpdateBookInput): Promise<[number, Book[]]> {\n        return await this.bookService.update(input);\n    }\n\n    @Mutation(() => BookType)\n    async deleteItem(@Args('id') id: number) {\n        return await this.bookService.delete(id);\n    }\n\n    @Query(() => String)\n    async hello() {\n        return 'hello';\n    }\n}\n```\n\n```text\nimport {Inject, Injectable} from '@nestjs/common';\nimport {InjectRepository} from '@nestjs/typeorm';\nimport {Book} from './model/book.entity';\nimport {DeleteResult, InsertResult, Repository, UpdateResult} from 'typeorm';\n\n@Injectable()\nexport class BookService {\n    constructor(@Inject('BOOKS_REPOSITORY') private readonly bookRepository: typeof Book) {}\n\n    findAll(): Promise<Book[]> {\n        return this.bookRepository.findAll<Book>();\n    }\n\n    find(id): Promise<Book> {\n       return this.bookRepository.findOne({where: {id}});\n    }\n\n    create(data): Promise<Book> {\n        return data.save();\n    }\n\n    update(data): Promise<[number, Book[]]> {\n        return this.bookRepository.update<Book>(data, { where: {id: data.id} });\n    }\n\n    delete(id): Promise<number> {\n        return this.bookRepository.destroy({where: {id}});\n    }\n}\n```\n\n```text\nCannot return null for non-nullable field\n```\n\n```text\n@Query(() => BookType, { nullable: true })\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":224,"estimatedTokens":1401}}1040{"id":"stack-74573177","source":"stackoverflow","questionId":74573177,"title":"In NestJs, I added Redis as cache manager, when I specify {ttl : 0} it throws a type error, it was working before","tags":["redis","nestjs"],"text":"Title: In NestJs, I added Redis as cache manager, when I specify {ttl : 0} it throws a type error, it was working before\nTags: redis, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using Redis as the cache manager in NestJs project. I was using a code like:\n\n```\nawait this.productCacheManager.set('products/time', data, { ttl: 60} )\n```\n\nWhen I delete the ttl argument or just put 60 there, it doesn't work and it immediately removes the record from redis, so I was using { ttl: 60} which was working until now.\nI do not know what happend but now it throws an error like:\n\nArgument of type '{ ttl: number; }' is not assignable to parameter of type 'number'.\n\nThe parameter I am typing is a number...\n\nTrying to make it work again like before.\n\n========================================\n\nTop Answer:\nmaybe this answer is too late. But if anyone experiences the same problem, you can try this method.\ni use these dependencies:\n\n\"cache-manager\": \"^5.2.3\", \"cache-manager-redis-store\": \"^3.0.1\",\n\n```\nawait this.cacheManager.set(\n key,\n value,\n {ttl: 1000} as any\n);\n```\n\n========================================\n\nCode:\n```text\nawait this.productCacheManager.set('products/time', data, { ttl: 60} )\n```\n\n```js\ncache.set(key, value, { ttl: 60 }) // in seconds\n```\n\n```js\ncache.set(key, value, 60000) // in milliseconds with v5!\n```\n\n```text\ncache-manager\n```\n\n```text\ncache-manager-redis-store\n```\n\n```text\ncache-manager\n```\n\n```text\ncache-manager-redis-store@^3\n```\n\n```text\ncache-manager@^5\n```\n\n```text\n{ ttl: 60}\n```\n\n```text\n60\n```\n\n```js\nawait this.cacheManager.set(key, value, { ttl: 60 }); // ttl 60 seconds\n```\n\n```js\nimport { CacheStore } from '@nestjs/cache-manager';\n```\n\n```text\nawait this.cacheManager.set(\n  key,\n  value,\n  {ttl: 1000} as any\n);\n```\n\n========================================\n\nComments:\n- It doesn't work, it gets deleted immediately no matter what number I give, even 0, that's why I switched to {ttl: 60}, and it worked this way, now it doesn't again...\n- See the answer I provided. I've made it work with a specific combination of versions.\n- Thank you oliver, will reflect this also on our stack\n- Thanks a lot. I use your recommended `CacheStore` for my CacheManager and it works\n- works for \"@nestjs/cache-manager\": \"^1.0.0\", \"cache-manager\": \"^5.2.1\", \"cache-manager-redis-store\": \"^3.0.1\",\n- nice... but ttl is mills `set: (key: string, value: unknown, ttl?: Milliseconds) => Promise;` I think there has a bug with `caching.d.ts`\n- `\"@nestjs&#47;cache-manager\": \"^2.2.2\", \"cache-manager\": \"^5.5.3\", \"cache-manager-redis-store\": \"^3.0.1\",` This works for me. Thank you.\n- It works for me too. Thank you Bro.","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":106,"estimatedTokens":660}}1041{"id":"stack-67855499","source":"stackoverflow","questionId":67855499,"title":"MongooseModule: Unable to connect to the database. On a dockerized Nestjs app with Mongo","tags":["mongodb","docker","mongoose","docker-compose","nestjs"],"text":"Title: MongooseModule: Unable to connect to the database. On a dockerized Nestjs app with Mongo\nTags: mongodb, docker, mongoose, docker-compose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to start a react-nestjs-mongo db application with docker-compose but for some reason it doesnt seems to work. `docker-compose --build` output shows something like this:\n\nserver | [Nest] 32 - 06/06/2021, 3:10:25 AM [MongooseModule] Unable to connect to the database. Retrying (7)... +33006ms\n\ndatabase | {\"t\":{\"$date\":\"2021-06-06T03:10:27.406+00:00\"},\"s\":\"I\",\n\"c\":\"STORAGE\", \"id\":22430,\n\n\"ctx\":\"WTCheckpointThread\",\"msg\":\"WiredTiger\nmessage\",\"attr\":{\"message\":\"[1622949027:406819][1:0x7f9ae2c3b700],\nWT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint\nsnapshot min: 7, snapshot max: 7 snapshot count: 0, oldest timestamp:\n(0, 0) , meta checkpoint timestamp: (0, 0)\"}}\n\nHere's my docker-compose:\n\n```\nversion: \"3.5\"\n\nservices: client:\n container_name: client\n build: ./client\n ports:\n - 3000:3000\n depends_on:\n - server\n\n server:\n container_name: server\n build: ./server\n ports:\n - 8000:8000\n depends_on:\n - mongodb\n links:\n - mongodb\n\n mongodb:\n container_name: database\n image: mongo\n restart: always\n ports:\n - \"27017:27017\"\n environment:\n MONGO_INITDB_ROOT_USERNAME: root\n MONGO_INITDB_ROOT_PASSWORD: example\n```\n\nAnd my app.modules.ts file looks like this:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({ \nimports: [\n MongooseModule.forRoot('mongodb://localhost:27017/nestjs', {\n useNewUrlParser: true,\n }), \n], \ncontrollers: [AppController], \nproviders: [AppService],\n }) \nclass AppModule {}\n```\n\nCan someone explain me why this isn't working?\n\n========================================\n\nTop Answer:\nI just faced the same issue!\n\nIn order to solve it you need to:\n\n- use container name instead of localhost (as manish also suggests)\n\n- provide username and password before host and port as explained in mongose doc: https://mongoosejs.com/docs/connections.html\n\n- inialize the database as explained in this question: Use MongoDB with docker-compose: create database and user\n\n========================================\n\nCode:\n```text\nversion: \"3.5\"\n\nservices:   client:\n    container_name: client\n    build: ./client\n    ports:\n      - 3000:3000\n    depends_on:\n      - server\n\n  server:\n    container_name: server\n    build: ./server\n    ports:\n      - 8000:8000\n    depends_on:\n      - mongodb\n    links:\n      - mongodb\n\n  mongodb:\n    container_name: database\n    image: mongo\n    restart: always\n    ports:\n      - \"27017:27017\"\n    environment:\n      MONGO_INITDB_ROOT_USERNAME: root\n      MONGO_INITDB_ROOT_PASSWORD: example\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({   \nimports: [\n    MongooseModule.forRoot('mongodb://localhost:27017/nestjs', {\n      useNewUrlParser: true,\n    }),   \n],   \ncontrollers: [AppController],   \nproviders: [AppService],\n })  \nclass AppModule {}\n```\n\n```text\ndocker-compose --build\n```\n\n========================================\n\nComments:\n- this solved this issue!","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":148,"estimatedTokens":835}}1042{"id":"stack-58632489","source":"stackoverflow","questionId":58632489,"title":"typeOrm unique row","tags":["nestjs","typeorm"],"text":"Title: typeOrm unique row\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a Entity using typeOrm on my NestJS, and it's not working as I expected.\n\nI have the following entity\n\n```\n@Entity('TableOne')\nexport class TableOneModel {\n @PrimaryGeneratedColumn()\n id: number\n\n @PrimaryColumn()\n tableTwoID: number\n\n @PrimaryColumn()\n tableThreeID: number\n\n @CreateDateColumn()\n createdAt?: Date\n}\n```\n\nThis code generate a migration that generates a table like the example below\n\n```\n+--------------+-------------+------+-----+----------------------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+-------------+------+-----+----------------------+-------+\n| id | int(11) | NO | | NULL | |\n| tableTwoID | int(11) | NO | | NULL | |\n| tableThreeID | int(11) | NO | | NULL | |\n| createdAt | datetime(6) | NO | | CURRENT_TIMESTAMP(6) | |\n+--------------+-------------+------+-----+----------------------+-------+\n```\n\nThat's ok, the problem is, that I want to the table only allow one row with `tableTwoID` and `tableThreeID`, what should I use in the Entity to generated the table as I expected it to be?\n\nExpected to not allow rows like the example below\n\n```\n+----+------------+--------------+----------------------------+\n| id | tableTwoID | tableThreeID | createdAt |\n+----+------------+--------------+----------------------------+\n| 1 | 1 | 1 | 2019-10-30 19:27:43.054844 |\n| 2 | 1 | 1 | 2019-10-30 19:27:43.819174 | <- should not allow the insert of this row\n+----+------------+--------------+----------------------------+\n```\n\n========================================\n\nTop Answer:\nThis is currently expected behavior from TypeORM. According to the documentation if you have multiple `@PrimaryColumn()` decorators you create a composite key. The combination of the composite key columns must be unique (in your above `'1' + '1' + '1' = '111'` vs `'2' + '1' + '1' = '211'`). If you are looking to make each column unique along with being a composite primary key, you should be able to do something like `@PrimaryColumn({ unique: true })`\n\n========================================\n\nCode:\n```js\n@Entity('TableOne')\nexport class TableOneModel {\n  @PrimaryGeneratedColumn()\n  id: number\n\n  @PrimaryColumn()\n  tableTwoID: number\n\n  @PrimaryColumn()\n  tableThreeID: number\n\n  @CreateDateColumn()\n  createdAt?: Date\n}\n```\n\n```text\n+--------------+-------------+------+-----+----------------------+-------+\n| Field        | Type        | Null | Key | Default              | Extra |\n+--------------+-------------+------+-----+----------------------+-------+\n| id           | int(11)     | NO   |     | NULL                 |       |\n| tableTwoID   | int(11)     | NO   |     | NULL                 |       |\n| tableThreeID | int(11)     | NO   |     | NULL                 |       |\n| createdAt    | datetime(6) | NO   |     | CURRENT_TIMESTAMP(6) |       |\n+--------------+-------------+------+-----+----------------------+-------+\n```\n\n```text\n+----+------------+--------------+----------------------------+\n| id | tableTwoID | tableThreeID | createdAt                  |\n+----+------------+--------------+----------------------------+\n|  1 |          1 |            1 | 2019-10-30 19:27:43.054844 |\n|  2 |          1 |            1 | 2019-10-30 19:27:43.819174 |    <- should not allow the insert of this row\n+----+------------+--------------+----------------------------+\n```\n\n```text\ntableTwoID\n```\n\n```text\ntableThreeID\n```\n\n```text\n@PrimaryColumn()\n```\n\n```text\n'1' + '1' + '1' = '111'\n```\n\n```text\n'2' + '1' + '1' = '211'\n```\n\n```text\n@PrimaryColumn({ unique: true })\n```\n\n========================================\n\nComments:\n- I got the message \"Error: Sqlite does not support AUTOINCREMENT on composite primary key\" when using multiple `@PrimaryColumn()` decorators with TypeORM and \"sqlite3\".\n- Thanks, this tip helped to solve my problem, I've used this like this `@Unique('uniqueTableTwoIDTableThreeID', ['tableTwoID', 'tableThreeID'])`\n- Annotating the entity class not the column will yield a composite key","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":127,"estimatedTokens":1015}}1043{"id":"stack-70531778","source":"stackoverflow","questionId":70531778,"title":"Get unsigned token for user from firebase auth emulator without frontend","tags":["firebase","firebase-authentication","nestjs","firebase-admin"],"text":"Title: Get unsigned token for user from firebase auth emulator without frontend\nTags: firebase, firebase-authentication, nestjs, firebase-admin\nSource: Stack Overflow\n\nQuestion:\nI am writing a custom backend (nestjs) in which I want to verify if the token from firebase auth is valid and retrieve user information too.\n\nI do not want to use the actual firebase auth so I ended up using firebase local emulator.\n\nNow I want to test my endpoint written in nestjs using postman wherein I send the unsigned token from postman for nestjs to verify from local emulator. But I couldn't find a way to create an unsigned token without creating a UI for the same, I really do not want to spend time in creating a react application to just `console.log` a token. Is there any better way to do this that I might be missing ??\n\nThanks for the help.\n\n========================================\n\nCode:\n```text\nconsole.log\n```\n\n```text\n{\n  \"email\": \"your-user@mail.com\",\n  \"password\": \"some-password\"   \n}\n```\n\n```text\n{\n    \"kind\": \"identitytoolkit#VerifyPasswordResponse\",\n    \"registered\": true,\n    \"localId\": \"yourUserId\",\n    \"email\": \"your-user@mail.com\",\n    \"idToken\": \"someIdToken\",\n    \"refreshToken\": \"someRefreshToken\",\n    \"expiresIn\": \"3600\"\n}\n```\n\n```text\n9099\n```\n\n```text\nPOST\n```\n\n```text\nidToken\n```\n\n```text\nhttp://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=any_key_you_want\n```\n\n```text\nfirebase\n```\n\n```text\nconnectAuthEmulator(auth, \"http://localhost:9099\");\n```\n\n========================================\n\nComments:\n- ( 1 ) the REST API Reference: firebase.google.com/docs/reference/rest/auth ( 2 ) the docs say you must also pass `\"returnSecureToken\": true`, but it seems to default to that if omitted ( 3 ) I initially got 404s and eventually discovered it was because my request code was URL-encoding the path (\"v1/accounts:signInWithPassword\" become \"v1/accounts%3AsignInWithPassword\") and the Emulator wasn't recognizing it - beware","metadata":{"transformedAt":"2026-08-18T18:33:02.572Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":67,"estimatedTokens":496}}1044{"id":"stack-66199633","source":"stackoverflow","questionId":66199633,"title":"How to access image from uploaded on nestjs server","tags":["node.js","angular","mongodb","express","nestjs"],"text":"Title: How to access image from uploaded on nestjs server\nTags: node.js, angular, mongodb, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a nestjs server and I have uploaded the images but when I try to access to those images they are a bunch of stuff that cant be interpreted as an image.(I also tried converting them to blob which then I converted to objectURL and then set it as src for img tag but that didnt work either).Upload code:\n\n```\n@Post('upload')\n @UseInterceptors(FileInterceptor('file',{\n storage: diskStorage({\n destination: './uploads',\n filename: editFileName,\n }),\n fileFilter: imageFileFilter,\n }))\n uploadFile(@UploadedFile() file){\n console.log(file);\n file.filename = file.originalname;\n const response = {\n originalname: file.originalname,\n filename: file.filename,\n }\n return response;\n }\n```\n\nThe above upload code perfectly saves the image as index-53a2.jpg in my uploads folder. Now trying to get the image using get req by:\n\n```\n@Get()\ndisplay(@Res() res){\n res.sendFile('index-53a2.jpg',{ root: './uploads' })\n}\n```\n\nlogging response for this it gives some string of unreadable(probably encoded) stuff.\n\ncode I used for testing:\n\n```\n\n \n \n \n $(function () {\n\n $('#abc').on('submit', function (e) {\n\n e.preventDefault();\n\n $.ajax({\n url: 'http:/localhost:3000/student/upload',\n method:'POST',\n data: new FormData(this),\n contentType: false,\n cache:false,\n processData:false,\n success: function (data) {\n console.log(data);\n // location.reload();\n }\n });\n\n });\n\n });\n\n function fun(){\n $.ajax({\n url: 'http://localhost:3000/student',\n success: function(data){\n console.log('s',data);\n let blob = new Blob([data]);\n var objectURL = URL.createObjectURL(blob);\n document.getElementById('img').src = objectURL;\n },\n error: function(data){\n console.log('e',data);\n }\n })\n }\n \n \n \n \n \n \n\n \n \n Button\n \n\n```\n\nAlso this html code is just for testing, my main purpose is to use this server so that I can take student image and data(contains basic details like name, phone, etc.) from angular and save it on mongoDB. Also I dont have any idea how to send my image from angular to nestjs and how to save it(and where to save it on MongoDB or Nestjs server and how)\n\nAny help would be greatly appreciated!!!\nThanks in advance.\n\n========================================\n\nTop Answer:\nI found solution to this. So what we have to do is basically append all our data in formData and send it in the request from angular.\n\n```\nlet formData = new FormData();\nformData.append('image',this.image);\n```\n\nNow this image attribute is taken from the function triggered by the onchange on the input tag that takes image as input.\n\n```\nonChange(event){\n this.image = event.target.files[0];\n}\n```\n\nNow we send it to backend from our service.\n\n```\nsendReq(formData){\n this.http.post('localhost:3000/your_route',formData);\n}\n```\n\nNow while accessing it from the Nestjs server we use FileInterceptor.\n\n```\nimport { Controller, Get, Post, Res, UploadedFile, UseInterceptors, Body } from '@nestjs/common';\nimport { FileInterceptor } from '@nestjs/platform-express';\nimport { editFileName, imageFileFilter } from './funcs';\nimport { diskStorage } from 'multer';\n\n@Post('your_route')\n@UseInterceptors(FileInterceptor('image',{\n storage: diskStorage({\n destination: './uploads',\n filename: editFileName,\n }),\n fileFilter: imageFileFilter,\n }))\n async func(@UploadedFile() file, @Body() body){\n try{\n body.image = file.filename;\n body.view = false;\n let res = await this.yourService.yourFunc(body);\n return {\n 'success': true,\n 'data': res\n }\n }\n catch(err){\n console.log(err);\n return {\n 'success': false,\n 'data': err\n }\n }\n }\n\nconst imageFileFilter = (req, file, callback) => {\n if (!file.originalname.match(/\\.(jpg|jpeg|png|gif)$/)) {\n return callback(new Error('Only image files are allowed!'), false);\n }\n callback(null, true);\n };\n\n const editFileName = (req, file, callback) => {\n const name = file.originalname.split('.')[0];\n const fileExtName = '.'+file.originalname.split('.')[1];\n const randomName = Array(4)\n .fill(null)\n .map(() => Math.round(Math.random() * 16).toString(16))\n .join('');\n callback(null, `${name}-${randomName}${fileExtName}`);\n };\n```\n\nSo this way we get a uploads folder in our root directory and image uploaded to our server gets saved here. To save the image the name I have user here is the name of the file being uploaded + '-' + a sequence of random char and int of length 4(Here you can have logic of your own).\n\n========================================\n\nCode:\n```text\n@Post('upload')\n    @UseInterceptors(FileInterceptor('file',{\n        storage: diskStorage({\n          destination: './uploads',\n          filename: editFileName,\n        }),\n        fileFilter: imageFileFilter,\n      }))\n    uploadFile(@UploadedFile() file){\n        console.log(file);\n        file.filename = file.originalname;\n        const response = {\n            originalname: file.originalname,\n            filename: file.filename,\n        }\n        return response;\n    }\n```\n\n```text\n@Get()\ndisplay(@Res() res){\n    res.sendFile('index-53a2.jpg',{ root: './uploads' })\n}\n```\n\n```text\n<html>\n  <head>\n    <script src=\"http://code.jquery.com/jquery-1.9.1.js\"></script>\n    <script>\n      $(function () {\n\n        $('#abc').on('submit', function (e) {\n\n          e.preventDefault();\n\n          $.ajax({\n            url: 'http:/localhost:3000/student/upload',\n            method:'POST',\n            data: new FormData(this),\n            contentType: false,\n            cache:false,\n            processData:false,\n            success: function (data) {\n              console.log(data);\n              // location.reload();\n            }\n          });\n\n        });\n\n      });\n\n      function fun(){\n        $.ajax({\n            url: 'http://localhost:3000/student',\n            success: function(data){\n                console.log('s',data);\n                let blob = new Blob([data]);\n                var objectURL = URL.createObjectURL(blob);\n                document.getElementById('img').src = objectURL;\n            },\n            error: function(data){\n                console.log('e',data);\n            }\n        })\n      }\n    </script>\n  </head>\n  <body>\n    <img alt=\"Image\" id=\"img\">\n    <form enctype= \"multipart/form-data\" id=\"abc\">\n      <input type=\"file\" name=\"file\" required accept=\"image/*\"><br>\n      <input name=\"submit\" type=\"submit\" value=\"Submit\">\n    </form>\n    <button onclick=\"fun()\">Button</button>\n  </body>\n</html>\n```\n\n```js\napp.useStaticAssets(join(__dirname, '..', 'public'), {\n    index: false,\n    prefix: '/public',\n});\n```\n\n```text\nmain.ts\n```\n\n```text\n.useStaticAssets\n```\n\n```text\napp\n```\n\n```text\nlet formData = new FormData();\nformData.append('image',this.image);\n```\n\n```text\nonChange(event){\n   this.image = event.target.files[0];\n}\n```\n\n```text\nsendReq(formData){\n   this.http.post('localhost:3000/your_route',formData);\n}\n```\n\n```text\nimport { Controller, Get, Post, Res, UploadedFile, UseInterceptors, Body } from '@nestjs/common';\nimport { FileInterceptor } from '@nestjs/platform-express';\nimport { editFileName, imageFileFilter } from './funcs';\nimport { diskStorage } from 'multer';\n\n\n\n@Post('your_route')\n@UseInterceptors(FileInterceptor('image',{\n        storage: diskStorage({\n          destination: './uploads',\n          filename: editFileName,\n        }),\n        fileFilter: imageFileFilter,\n      }))\n    async func(@UploadedFile() file, @Body() body){\n        try{\n            body.image = file.filename;\n            body.view = false;\n            let res = await this.yourService.yourFunc(body);\n            return {\n                'success': true,\n                'data': res\n            }\n        }\n        catch(err){\n            console.log(err);\n            return {\n                'success': false,\n                'data': err\n            }\n        }\n    }\n\nconst imageFileFilter = (req, file, callback) => {\n    if (!file.originalname.match(/\\.(jpg|jpeg|png|gif)$/)) {\n      return callback(new Error('Only image files are allowed!'), false);\n    }\n    callback(null, true);\n  };\n\n const editFileName = (req, file, callback) => {\n    const name = file.originalname.split('.')[0];\n    const fileExtName = '.'+file.originalname.split('.')[1];\n    const randomName = Array(4)\n      .fill(null)\n      .map(() => Math.round(Math.random() * 16).toString(16))\n      .join('');\n    callback(null, `${name}-${randomName}${fileExtName}`);\n  };\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":355,"estimatedTokens":2105}}1045{"id":"stack-57619668","source":"stackoverflow","questionId":57619668,"title":"NestJs - How Debug jest tests using typescript","tags":["node.js","typescript","jestjs","nestjs"],"text":"Title: NestJs - How Debug jest tests using typescript\nTags: node.js, typescript, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to debug my jest tests using typescript and Nestjs framework. I tried a lot of commands but none of them seem works. I have also tried this script provided by NestJs typescript starter but it doesn't work as well. \n\nHere's the command:\n\n\"`test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\"`\n\nEvery time after I run this command nothing happens, just this message appears in the console:\n\nhttps://i.sstatic.net/Z3u51.png \n\nAll of my tests are working fine without debug mode.\n\nI've found some blog posts/tutorials telling how we can debug jest tests using typescript and ts-jest but none of them worked for me :(\n\nMy questions are: \n\n- Do I need to do any extra setting on vscode **launch.json**?\nWhy nothing happens when I run the command test:debug? (Nothing happens after *Debugger listening on ws://127.0.0.1:9229/5f1fa5dd-6450-488b-8e4d-cc9ff3003804*\nFor help, see: https://nodejs.org/en/docs/inspector\n\n========================================\n\nTop Answer:\nThere are many ways of debugging jest tests, vscode launch.json is one of them, you can also work with Google Chrome's inspector (chrome://inspect) in the moment you run the web socket it will appear on the devices list and then you add your folder in the chrome inspector. Here you have the Official Jest Documentation\n\n========================================\n\nCode:\n```text\ntest:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\"\n```\n\n```text\nauto attach\n```\n\n```text\n--inspect-brk\n```\n\n```text\n--inspect\n```\n\n```text\nabout:inspect\n```\n\n========================================\n\nComments:\n- Thanks. The only thing missing was the auto attach.","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":57,"estimatedTokens":469}}1046{"id":"stack-62279826","source":"stackoverflow","questionId":62279826,"title":"Caching return value from a service method","tags":["node.js","typescript","caching","service","nestjs"],"text":"Title: Caching return value from a service method\nTags: node.js, typescript, caching, service, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using nestjs and have just installed the `cache-manager` module and are trying to cache a response from a service call.\n\nI register the cache module in a sample module (sample.module.ts):\n\n```\nimport { CacheInterceptor, CacheModule, Module } from '@nestjs/common';\nimport { SampleService } from './sample.service';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport * as redisStore from 'cache-manager-redis-store';\n\n@Module({\n imports: [\n CacheModule.register({\n ttl: 10,\n store: redisStore,\n host: 'localhost',\n port: 6379,\n }),\n ],\n providers: [\n SampleService,\n {\n provide: APP_INTERCEPTOR,\n useClass: CacheInterceptor,\n }\n ],\n exports: [SampleService],\n})\nexport class SampleModule {}\n```\n\nThen in my service (sample.service.ts):\n\n```\n@Injectable()\nexport class SampleService {\n @UseInterceptors(CacheInterceptor)\n @CacheKey('findAll')\n async findAll() {\n // Make external API call\n }\n}\n```\n\nLooking at redis I can see that nothing is cached for the service method call. If I use the same approach with a controller, then everything works fine and I can see the cached entry in my redis database. I am thinking that there is no way out of the box to cache individual service method calls in nestjs.\n\nReading the `documentation` it seems that I am only able to use this approach for controllers, microservices and websockets, but not ordinary services?\n\n========================================\n\nCode:\n```text\nimport { CacheInterceptor, CacheModule, Module } from '@nestjs/common';\nimport { SampleService } from './sample.service';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport * as redisStore from 'cache-manager-redis-store';\n\n\n@Module({\n  imports: [\n    CacheModule.register({\n      ttl: 10,\n      store: redisStore,\n      host: 'localhost',\n      port: 6379,\n    }),\n ],\n providers: [\n   SampleService,\n   {\n     provide: APP_INTERCEPTOR,\n     useClass: CacheInterceptor,\n   }\n ],\n exports: [SampleService],\n})\nexport class SampleModule {}\n```\n\n```text\n@Injectable()\nexport class SampleService {\n  @UseInterceptors(CacheInterceptor)\n  @CacheKey('findAll')\n  async findAll() {\n    // Make external API call\n  }\n}\n```\n\n```text\ncache-manager\n```\n\n```text\ndocumentation\n```\n\n```text\nexport class SampleService {\n\n  constructor(@Inject(CACHE_MANAGER) protected readonly cacheManager) {}  \n\n  findAll() {\n    const value = await this.cacheManager.get(key)\n    if (value) {\n      return value\n    }\n\n    const respone = // ...\n    this.cacheManager.set(key, response, ttl)\n    return response\n  }\n```\n\n```text\nCacheInterceptor\n```\n\n```text\nInterceptors\n```\n\n```text\nControllers\n```\n\n```text\ncacheManager\n```\n\n========================================\n\nComments:\n- I ended up writing a small decorator that can be used to handle caching for services: npmjs.com/package/@cyclonecode/service-cache\n- Yes I also figured out this is the way, I had problems with my method running multiple times before the cache was actually set though, but this was not really a problem related to caching.","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":141,"estimatedTokens":785}}1047{"id":"stack-75385386","source":"stackoverflow","questionId":75385386,"title":"Property 'cookies' does not exist on type 'Request'","tags":["typescript","express","nestjs"],"text":"Title: Property 'cookies' does not exist on type 'Request'\nTags: typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to read cookie in a nestjs controller.\n\ni am following the docs at https://docs.nestjs.com/techniques/cookies#use-with-express-default\n\nHere's my code\n\n```\nimport { Controller, Get, Render, Req } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n\n @Get()\n @Render('home')\n getHello(@Req() req: Request) {\n return { text: req.cookies['id'] };\n }\n}\n```\n\nthe problem is that type `Request` from express does not have `cookies`. So i get this error.\n\n```\nsrc/app.controller.ts:11:24 - error TS2339: Property 'cookies' does not exist on type 'Request'.\n\n11 return { text: req.cookies['id'] };\n ~~~~~~~\n```\n\nThe code actually works if i remove type `Request` from `req`. But thhen i lost type-safety.\n\n========================================\n\nCode:\n```js\nimport { Controller, Get, Render, Req } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n\n  @Get()\n  @Render('home')\n  getHello(@Req() req: Request) {\n    return { text: req.cookies['id'] };\n  }\n}\n```\n\n```bash\nsrc/app.controller.ts:11:24 - error TS2339: Property 'cookies' does not exist on type 'Request'.\n\n11     return { text: req.cookies['id'] };\n                          ~~~~~~~\n```\n\n```text\nRequest\n```\n\n```text\ncookies\n```\n\n```text\nRequest\n```\n\n```text\nreq\n```\n\n```text\nRequest\n```\n\n```text\nexpress\n```\n\n```text\n@types/express\n```\n\n========================================\n\nComments:\n- if you followed nestjs docs then I assume you installed cookie parser with its types and used it as global middleware in your app right, if so I think the problem is with the Request type I don't see where you import it in your code you should import it from express","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":92,"estimatedTokens":446}}1048{"id":"stack-70907698","source":"stackoverflow","questionId":70907698,"title":"how to send the exception/error for nestjs websocket of adapter @nestjs/platform-ws","tags":["javascript","angular","websocket","rxjs","nestjs"],"text":"Title: how to send the exception/error for nestjs websocket of adapter @nestjs/platform-ws\nTags: javascript, angular, websocket, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to send the exception using nestjs websocket based on conditions, tried using\n\n**throw new WsException('Invalid data');**\n\nbut not sending any exception\n\nHere is the sample code\n\n```\nimport WebSocket from 'ws';\nimport {\n SubscribeMessage,\n WebSocketGateway,\n WsException,\n} from '@nestjs/websockets';\n\n@WebSocketGateway({ path: '/api' })\nexport class MainGateway {\n @SubscribeMessage('message')\n handleMessage(client: WebSocket, payload: any) {\n if (payload.id === 4) {\n throw new WsException('Invalid Data');\n }\n client.send(JSON.stringify({ id: payload.id }));\n }\n}\n```\n\nand I'm creating the connection using angular here is the code snippet\n\n```\nexport class WsComponent implements OnInit {\n public value!: number;\n public subject$ = webSocket('ws://localhost:3000/api');\n\n ngOnInit(): void {\n const event = { event: 'message', data: { id: 4 } };\n\n this.subject$.subscribe({\n next: (v: any) => (this.value = v.id),\n error: (e) => console.error(e),\n complete: () => console.info('complete'),\n });\n\n this.subject$.next(event);\n }\n}\n```\n\nPlease help me to solve the issue\n\n========================================\n\nTop Answer:\nit's working but needs more testing. If you find a bug, please report it.\n\n```\nimport { ArgumentsHost, Catch } from '@nestjs/common';\nimport { BaseWsExceptionFilter } from '@nestjs/websockets';\nimport { PacketType } from 'socket.io-parser';\n@Catch()\nexport class AllExceptionsSocketFilter extends BaseWsExceptionFilter {\n catch(exception: any, host: ArgumentsHost) {\n const client = host.switchToWs().getClient();\n client.packet({\n type: PacketType.ACK,\n data: [{ error: exception?.message }],\n id: client.nsp._ids++,\n });\n }\n}\n```\n\nUse:\n\n```\n@WebSocketGateway()\n@UseFilters(new AllExceptionsSocketFilter())\nexport class ContatoGateway {\n ...\n```\n\n**EDIT: New method, working and tested:**\n\n```\nimport { ArgumentsHost, Catch } from '@nestjs/common';\nimport { BaseWsExceptionFilter } from '@nestjs/websockets';\n\n@Catch()\nexport class AllExceptionsSocketFilter extends BaseWsExceptionFilter {\n catch(exception: any, host: ArgumentsHost) {\n const args = host.getArgs();\n // event ack callback\n if ('function' === typeof args[args.length - 1]) {\n const ACKCallback = args.pop();\n ACKCallback({ error: exception.message, exception });\n }\n}\n```\n\n}\n\n========================================\n\nCode:\n```text\nimport WebSocket from 'ws';\nimport {\n  SubscribeMessage,\n  WebSocketGateway,\n  WsException,\n} from '@nestjs/websockets';\n\n@WebSocketGateway({ path: '/api' })\nexport class MainGateway {\n  @SubscribeMessage('message')\n  handleMessage(client: WebSocket, payload: any) {\n    if (payload.id === 4) {\n      throw new WsException('Invalid Data');\n    }\n    client.send(JSON.stringify({ id: payload.id }));\n  }\n}\n```\n\n```text\nexport class WsComponent implements OnInit {\n  public value!: number;\n  public subject$ = webSocket('ws://localhost:3000/api');\n\n  ngOnInit(): void {\n    const event = { event: 'message', data: { id: 4 } };\n\n    this.subject$.subscribe({\n      next: (v: any) => (this.value = v.id),\n      error: (e) => console.error(e),\n      complete: () => console.info('complete'),\n    });\n\n    this.subject$.next(event);\n  }\n}\n```\n\n```js\nimport { ArgumentsHost, Catch, HttpException } from \"@nestjs/common\";\nimport { BaseWsExceptionFilter, WsException } from \"@nestjs/websockets\";\n\n@Catch(WsException, HttpException)\nexport class WebsocketExceptionsFilter extends BaseWsExceptionFilter {\n  catch(exception: WsException | HttpException, host: ArgumentsHost) {\n    const client = host.switchToWs().getClient() as WebSocket;\n    const data = host.switchToWs().getData();\n    const error = exception instanceof WsException ? exception.getError() : exception.getResponse();\n    const details = error instanceof Object ? { ...error } : { message: error };\n    client.send(JSON.stringify({\n      event: \"error\",\n      data: {\n        id: (client as any).id,\n        rid: data.rid,\n        ...details\n      }\n    }));\n  }\n}\n```\n\n```js\n@WebSocketGateway()\n@UseFilters(WebsocketExceptionsFilter)\n@UsePipes(new ValidationPipe({ transform: true }))\nexport class FeedGateway implements OnGatewayConnection, OnGatewayDisconnect {\n}\n```\n\n```json\n{\"event\":\"error\",\"data\":{\"id\":\"7a784ce568767a1016090c6a\",\"rid\":\"connect\",\"statusCode\":400,\"message\":[\"language must be a valid enum value\"],\"error\":\"Bad Request\"}}\n```\n\n```text\nextends BaseWsExceptionFilter\n```\n\n```text\nimport { ArgumentsHost, Catch } from '@nestjs/common';\nimport { BaseWsExceptionFilter } from '@nestjs/websockets';\nimport { PacketType } from 'socket.io-parser';\n@Catch()\nexport class AllExceptionsSocketFilter extends BaseWsExceptionFilter {\n   catch(exception: any, host: ArgumentsHost) {\n      const client = host.switchToWs().getClient();\n      client.packet({\n          type: PacketType.ACK,\n          data: [{ error: exception?.message }],\n          id: client.nsp._ids++,\n      });\n   }\n}\n```\n\n```text\n@WebSocketGateway()\n@UseFilters(new AllExceptionsSocketFilter())\nexport class ContatoGateway {\n   ...\n```\n\n```text\nimport { ArgumentsHost, Catch } from '@nestjs/common';\nimport { BaseWsExceptionFilter } from '@nestjs/websockets';\n\n@Catch()\nexport class AllExceptionsSocketFilter extends BaseWsExceptionFilter {\n  catch(exception: any, host: ArgumentsHost) {\n  const args = host.getArgs();\n  // event ack callback\n  if ('function' === typeof args[args.length - 1]) {\n    const ACKCallback = args.pop();\n    ACKCallback({ error: exception.message, exception });\n  }\n}\n```\n\n```text\n... in WsException filter\nconst args = host.getArgs();\n\n        // Find possible acknowledgement callback from the end of arguments\n        const ackCallback = this.findAckCallback(args);\n\n        if (ackCallback !== null) {\n            console.log(\"acknowledgement callback exists\");\n            ackCallback(wsEventErrorResponse);\n        } else {\n            console.log(\"acknowledgement callback does not exist\");\n            client.emit(\"globalError\", wsEventErrorResponse);\n        }\n    }\n\n    /**\n     * Finds the acknowledgement callback from the end of the arguments.\n     * @param args The arguments passed to the event handler.\n     * @returns The acknowledgement callback if it exists, otherwise null.\n     */\n    private findAckCallback(args: unknown[]): Function | null {\n        if (Array.isArray(args) && args.length >= 1) {\n            for (let i = args.length - 1; i >= Math.max(0, args.length - 3); i--) {\n                const arg = args[i];\n                if (typeof arg === \"function\") {\n                    return arg;\n                }\n            }\n        }\n        return null;\n    }\n```\n\n```js\nimport { ArgumentsHost, Catch, HttpException } from '@nestjs/common';\nimport { WsException } from '@nestjs/websockets';\n\n@Catch(WsException)\nexport class WsExceptionFilter {\n  // Or any other exception.\n  catch(exception: WsException, host: ArgumentsHost) {\n    const client = host.switchToWs().getClient();\n    client.emit('my-log-error-event', exception);\n  }\n}\n```\n\n```js\n@WebSocketGateway()\n@UseFilters(new WsExceptionFilter())\nexport class ConnectionGateway {}\n```\n\n```text\nclient.emit\n```\n\n```text\nclient.send\n```\n\n========================================\n\nComments:\n- for me, the function is the second to last argument. the last argument is the event name. don't know if this is a version issue or just something that might be inconsistent, but regardless, it would be worth it to create a more robust way of finding the acknowledgement.","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":294,"estimatedTokens":1907}}1049{"id":"stack-73581933","source":"stackoverflow","questionId":73581933,"title":"TypeORM \"OR\" \"AND \"operator combination","tags":["typescript","graphql","nestjs","typeorm"],"text":"Title: TypeORM \"OR\" \"AND \"operator combination\nTags: typescript, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm not sure how to use the OR condition in typeOrm where clause, could not find solution so far.\n\nI have a db call as follows\n\n\r\n\r\n\n```\ndb.getRepository(MyModel).find({\nwhere:{\n type : \"new\",\n status: \"A\"\n region: \"central\"\n zip_code: \"4831\"\n }\n })\n```\n\n\r\n\r\n\r\n\nI need to modify the above call same as to below SQL query\n\n```\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```\n\n========================================\n\nTop Answer:\nYou can use the createQueryBuilder of typeorm. You can check the use of bracket here. You can use orWhere wherever you need to use the OR condition. By your query, you can use the below code:\n\n```\ncreateQueryBuilder(\"MyModel\")\n .where(\"MyModel.type = :type\", { type: \"new\" })\n .andWhere(\"MyModel.status = :status\", { status: \"A\" })\n .andWhere(\n new Brackets((qb) => {\n qb.where(\"MyModel.region = :region\", {\n region: \"central\",\n }).orWhere(\"MyModel.zip_code = :zip\", { zip: \"4831\" });\n })\n );\n```\n\nThis will result in the SQL query:\n\n```\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```\n\n========================================\n\nCode:\n```html\ndb.getRepository(MyModel).find({\nwhere:{\n  type : \"new\",\n  status: \"A\"\n  region: \"central\"\n  zip_code: \"4831\"\n  }\n  })\n```\n\n```text\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```\n\n```js\ndb.getRepository(MyModel).find({\n  where: [\n    {\n      type : \"new\",\n      status: \"A\",\n      region: \"central\"\n    },\n    {\n      type : \"new\",\n      status: \"A\",\n      zip_code: \"4831\"\n    },\n  ]\n})\n```\n\n```sql\nselect * from model \n  where \n    (type=\"new\" and status=\"A\" and region=\"central\")\n  OR  \n    (type=\"new\" and status=\"A\" and zip_code=\"4831\")\n```\n\n```text\nwhere\n```\n\n```text\nOR\n```\n\n```text\ncreateQueryBuilder(\"MyModel\")\n  .where(\"MyModel.type = :type\", { type: \"new\" })\n  .andWhere(\"MyModel.status = :status\", { status: \"A\" })\n  .andWhere(\n    new Brackets((qb) => {\n      qb.where(\"MyModel.region = :region\", {\n        region: \"central\",\n      }).orWhere(\"MyModel.zip_code = :zip\", { zip: \"4831\" });\n    })\n  );\n```\n\n```text\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":124,"estimatedTokens":594}}1050{"id":"stack-64459543","source":"stackoverflow","questionId":64459543,"title":"Nestjs and Class Validator - at least one field should not be empty","tags":["nestjs","class-validator"],"text":"Title: Nestjs and Class Validator - at least one field should not be empty\nTags: nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI have NestJS API, which has a PATCH endpoint for modifying a resource. I use the `class-validator` library for validating the payload. In the DTO, all fields are set to optional with the `@IsOptional()`decorator. Because of that, if I send an empty payload, the validation goes through and then the update operation errors.\n\nI am wondering if there is a simple way to have all fields set to optional as I do and at the same time make sure that at least one of them is not empty, so the object is not empty.\n\nThanks!\n\n========================================\n\nCode:\n```text\nclass-validator\n```\n\n```text\n@IsOptional()\n```\n\n```text\nInjectable()\nexport class ValidatePayloadExistsPipe implements PipeTransform {\n  transform(payload: any): any {\n    if (!Object.keys(payload).length) {\n      throw new BadRequestException('Payload should not be empty');\n    }\n\n    return payload;\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":34,"estimatedTokens":257}}1051{"id":"stack-77923120","source":"stackoverflow","questionId":77923120,"title":"How to fix @Body() is undefined in NestJS","tags":["typescript","nestjs"],"text":"Title: How to fix @Body() is undefined in NestJS\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy @Body() in my NestJS App seems always to be undefined. I dont use any middleware right now, so I am quite confused how this can happen. Here is my setup:\n\nController:\n\n```\nimport { Body, Controller, HttpCode, HttpStatus, Post, Req } from \"@nestjs/common\";\nimport { AuthService } from './auth.service';\n\n@Controller('api/auth')\nexport class AuthController {\n constructor(private authService: AuthService) {}\n\n @HttpCode(HttpStatus.OK)\n @Post('login')\n signIn(@Body() signInDto: Record) {\n return this.authService.signIn(signInDto.username, signInDto.password);\n }\n}\n```\n\nHere the signInDto is always undefined. Also if I pass the @Req() to the function, it is also undefined..\n\nmain.ts:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\nimport { tenancyMiddleware } from './modules/tenancy/tenancy.middleware';\nimport { DataSource, getConnection, getManager } from 'typeorm';\nimport { getTenantConnection } from './modules/tenancy/tenancy.utils';\nimport { SnakeNamingStrategy } from './snake-naming.strategy';\nimport { join } from 'path';\nimport { appDataSource } from './datasource.app';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n // config\n const configService = app.get(ConfigService);\n const port = configService.get('port');\n app.enableCors();\n\n // Multitenancy\n //app.use(tenancyMiddleware);\n await appDataSource.initialize();\n await appDataSource.runMigrations();\n const schemas = await appDataSource.query(\n 'select schema_name as name from information_schema.schemata;',\n );\n\n for (let i = 0; i Postman Headers:\n\n```\n{\n \"accept\": \"application/json\",\n \"content-type\": \"application/json\",\n \"user-agent\": \"PostmanRuntime/7.36.1\",\n \"cache-control\": \"no-cache\",\n\n \"host\": \"localhost:3000\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"connection\": \"keep-alive\",\n \"content-length\": \"28\"\n}\n```\n\nAll I found from other questions was to add the content-type header, but it did not fix it. Any hints why my body is always undefined?\n\n========================================\n\nCode:\n```text\nimport { Body, Controller, HttpCode, HttpStatus, Post, Req } from \"@nestjs/common\";\nimport { AuthService } from './auth.service';\n\n@Controller('api/auth')\nexport class AuthController {\n  constructor(private authService: AuthService) {}\n\n  @HttpCode(HttpStatus.OK)\n  @Post('login')\n  signIn(@Body() signInDto: Record<string, any>) {\n    return this.authService.signIn(signInDto.username, signInDto.password);\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ConfigService } from '@nestjs/config';\nimport { tenancyMiddleware } from './modules/tenancy/tenancy.middleware';\nimport { DataSource, getConnection, getManager } from 'typeorm';\nimport { getTenantConnection } from './modules/tenancy/tenancy.utils';\nimport { SnakeNamingStrategy } from './snake-naming.strategy';\nimport { join } from 'path';\nimport { appDataSource } from './datasource.app';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  // config\n  const configService = app.get(ConfigService);\n  const port = configService.get<number>('port');\n  app.enableCors();\n\n  // Multitenancy\n  //app.use(tenancyMiddleware);\n  await appDataSource.initialize();\n  await appDataSource.runMigrations();\n  const schemas = await appDataSource.query(\n    'select schema_name as name from information_schema.schemata;',\n  );\n\n  for (let i = 0; i < schemas.length; i += 1) {\n    const { name: schema } = schemas[i];\n\n    if (schema.startsWith('tenant_')) {\n      const tenantId = schema.replace('tenant_', '');\n      const connection = await getTenantConnection(tenantId);\n      await connection.runMigrations();\n      await connection.close();\n    }\n  }\n\n  await app.listen(port);\n}\nbootstrap();\n```\n\n```text\n{\n  \"accept\": \"application/json\",\n  \"content-type\": \"application/json\",\n  \"user-agent\": \"PostmanRuntime/7.36.1\",\n  \"cache-control\": \"no-cache\",\n\n  \"host\": \"localhost:3000\",\n  \"accept-encoding\": \"gzip, deflate, br\",\n  \"connection\": \"keep-alive\",\n  \"content-length\": \"28\"\n}\n```\n\n```text\nreflect-metadata\n```\n\n```text\ntypeorm\n```\n\n```text\n0.3.19\n```\n\n```text\n0.3.20\n```\n\n========================================\n\nComments:\n- Are you using typeorm, and if so what version of it do you have installed?\n- Thank you, the hint with typeorm fixed it!","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":169,"estimatedTokens":1130}}1052{"id":"stack-54027807","source":"stackoverflow","questionId":54027807,"title":"Is there a way to set default value to missing/optional JSON attribute?","tags":["node.js","json","typescript","nestjs"],"text":"Title: Is there a way to set default value to missing/optional JSON attribute?\nTags: node.js, json, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use NodeJs/NestJs to build a RESTful service. I created some object to match with the request JSON. In these objects there are some optional attributes, but I would like to set default values to them if the client does not send them via JSON.\n\nWhat is the best way to achieve the goal?\n\nThis is my DTO to match with JSON.\n\n```\nimport { IsDefined, IsNumber, Min } from 'class-validator';\nimport { ApiModelProperty, ApiModelPropertyOptional } from '@nestjs/swagger';\n\nexport class RequestDto {\n @IsDefined()\n @IsNumber()\n @Min(0)\n @ApiModelProperty({description: 'The current age.'})\n public CurrentAge: number;\n\n @ApiModelPropertyOptional({description: 'The existing saving amount.'})\n public ExistingSavingAmount: number = 0;\n}\n```\n\nThis is my NestJs controller\n\n```\nimport { Controller, Post, Body, Param } from '@nestjs/common';\nimport { RequestDto } from './Dto/Request.Dto';\nimport { ApiResponse, ApiOperation } from '@nestjs/swagger';\n\n@Controller('mycontroller')\nexport class MyController {\n @Post('MyEndPoint')\n @ApiOperation({ title: 'Do something' })\n @ApiResponse({ status: 201, description: 'Something is done' })\n public doSomething(@Body() request: RequestDto) {\n // do more jobs\n }\n}\n```\n\nI launch the service, and post following JSON to my end point\n\n```\n{\n \"CurrentAge\": 40,\n}\n```\n\nIn my controller I see `ExistingSavingAmount` is blank in stead of having value of 0. But if I instantiate the `RequestDto` directly I could see the value of `ExistingSavingAmount` is 0.\n\n========================================\n\nTop Answer:\nOK, without code samples from the OP, the fidelity of this response may need improvement. That said, the \"nest-y\" way to do this is through a TransformPipe. \n\nThe canonical example they give is for the ParseIntPipe:\n\n```\nimport { Injectable, BadRequestException} from '@nestjs/common';\n\n@Injectable()\nexport class ParseIntPipe {\n transform(value, metadata) {\n const val = parseInt(value, 10);\n if (isNaN(val)) {\n throw new BadRequestException('Validation failed');\n }\n return val;\n }\n}\n```\n\nWithout knowing what your defaults look like, I'm going to assume it's something like a product, and you want to default some things and put some things as an empty string:\n\n```\nimport { Injectable, BadRequestException} from '@nestjs/common';\n\n// we will assume you have your own validation for the non-optional bits\nconst optionalDefaults = {\n description: '',\n category: 'Miscelleneous'\n}\n\n@Injectable()\nexport class ProductDefaultsPipe {\n transform(value, metadata) {\n const val = Object.assign(optionalDefaults, value);\n return val;\n }\n}\n```\n\nNow, that said you might be using something that provides schemas and model definitions (like Joi or Mongoose). If you are, then I'd recommend setting all the defaults and validations in that schema and then applying the schema in your TransformPipe rather than writing much custom code at all. For example, if you have a ProductSchema, this would work for you:\n\n```\n@Injectable()\nexport class ProductDefaultsPipe {\n async transform(value, metadata) {\n const val = new Product(value);\n const isValid = await val.validate();\n if (!isValid) {\n throw new BadRequestException('Validation failed');\n }\n return val;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { IsDefined, IsNumber, Min } from 'class-validator';\nimport { ApiModelProperty, ApiModelPropertyOptional } from '@nestjs/swagger';\n\nexport class RequestDto {\n    @IsDefined()\n    @IsNumber()\n    @Min(0)\n    @ApiModelProperty({description: 'The current age.'})\n    public CurrentAge: number;\n\n    @ApiModelPropertyOptional({description: 'The existing saving amount.'})\n    public ExistingSavingAmount: number = 0;\n}\n```\n\n```text\nimport { Controller, Post, Body, Param } from '@nestjs/common';\nimport { RequestDto } from './Dto/Request.Dto';\nimport { ApiResponse, ApiOperation } from '@nestjs/swagger';\n\n@Controller('mycontroller')\nexport class MyController {\n    @Post('MyEndPoint')\n    @ApiOperation({ title: 'Do something' })\n    @ApiResponse({ status: 201, description: 'Something is done' })\n    public doSomething(@Body() request: RequestDto) {\n        // do more jobs\n    }\n}\n```\n\n```text\n{\n    \"CurrentAge\": 40,\n}\n```\n\n```text\nExistingSavingAmount\n```\n\n```text\nRequestDto\n```\n\n```text\nExistingSavingAmount\n```\n\n```text\n@UsePipes(new ValidationPipe({ transform: true }))\n@Post('MyEndPoint')\npublic doSomething(@Body() request: RequestDto) {\n```\n\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(ApplicationModule);\n  app.useGlobalPipes(new ValidationPipe({ transform: true }));\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nRequestDto\n```\n\n```text\nclassTransformer.plainToClass()\n```\n\n```text\nValidationPipe\n```\n\n```text\n{ transform: true }\n```\n\n```text\nRequestDto\n```\n\n```text\nimport { Injectable, BadRequestException} from '@nestjs/common';\n\n@Injectable()\nexport class ParseIntPipe {\n  transform(value, metadata) {\n    const val = parseInt(value, 10);\n    if (isNaN(val)) {\n      throw new BadRequestException('Validation failed');\n    }\n    return val;\n  }\n}\n```\n\n```text\nimport { Injectable, BadRequestException} from '@nestjs/common';\n\n// we will assume you have your own validation for the non-optional bits\nconst optionalDefaults = {\n   description: '',\n   category: 'Miscelleneous'\n}\n\n@Injectable()\nexport class ProductDefaultsPipe {\n  transform(value, metadata) {\n    const val = Object.assign(optionalDefaults, value);\n    return val;\n  }\n}\n```\n\n```text\n@Injectable()\nexport class ProductDefaultsPipe {\n  async transform(value, metadata) {\n    const val = new Product(value);\n    const isValid = await val.validate();\n    if (!isValid) {\n       throw new BadRequestException('Validation failed');\n    }\n    return val;\n  }\n}\n```\n\n========================================\n\nComments:\n- Can you show one of your existing endpoints as an example, perhaps even with sample JSON to show us what you mean?\n- @Paul I have updated my post with code sample.\n- Thanks a lot for your input. Further question, without using `classTransformer.plainToClass()` or `@UsePipes(new ValidationPipe({ transform: true }))`, the DTO class is not instantiated, then where it is from? Since I come from C# background, the object is deserialized from JSON in this case, therefore it is instantiated by the serializer. JavaScript/TypeScript is very different in this case?\n- Without the class transformer it will not be deserialized from JSON but instead stay a plain Javascript object. Since this happens during run time, there are no type checks. In fact, you won't have a RequestDto object during run time instead you'll have a plain object that (hopefully, no one checked) complies with the interface of your RequestDto.","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":255,"estimatedTokens":1716}}1053{"id":"stack-59672817","source":"stackoverflow","questionId":59672817,"title":"configService.get('key') fails on type cast and joi on validation","tags":["typescript","nestjs","joi"],"text":"Title: configService.get('key') fails on type cast and joi on validation\nTags: typescript, nestjs, joi\nSource: Stack Overflow\n\nQuestion:\nI created a custom configuration file for my NestJs REST API. This is a simple example for the port the application is listening on.\n\nI have a .env file with the content\n\n```\nSERVER_PORT = 3000\n```\n\nAn example for my configuration file\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport * as Joi from '@hapi/joi';\n\n@Injectable()\nexport class ServerConfigService {\n constructor(private readonly configService: ConfigService) {\n const { error } = Joi.object({\n port: Joi.number()\n .port()\n .required(),\n }).validate({ port: this.port });\n\n if (error) { // no error thrown\n throw error;\n }\n\n console.log(typeof this.port); // type is string but should be number\n }\n\n public get port(): number {\n return this.configService.get('SERVER_PORT');\n }\n}\n```\n\nI would expect the ports type to be `number` but it's still a `string`. So two things come to my mind:\n\n- I call `this.configService.get('key')` as shown here with a generic type. Why does it still return a string? I would expect a type cast.\n\n- I use joi for the validation as described here. I would expect joi throwing an error.\n\nThe port variable might be a bad example because Nest is able to deal with a port of type string. But other parts expect numbers and throw errors if a config variable should be a number but is of type string.\n\nDid I miss something?\n\n========================================\n\nTop Answer:\nAs written above this is highly misleading and should be changed. There's no reason why the returned value should be explicitly casted if the generic indicates a concrete type.\n\nWhat I don't get is why there is no type casting exception on:\n\nconst myNumber:number = this.configService.get('PROPERTY_PATH');\n\nEven if ConfigService effectively returns a string, how can it be assigned as-is to a number? In fact myNumber will effectively be a string even though it is explicitly defined as number. This is a Typescript issue just as much.\n\n========================================\n\nCode:\n```text\nSERVER_PORT = 3000\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport * as Joi from '@hapi/joi';\n\n@Injectable()\nexport class ServerConfigService {\n  constructor(private readonly configService: ConfigService) {\n    const { error } = Joi.object({\n      port: Joi.number()\n        .port()\n        .required(),\n    }).validate({ port: this.port });\n\n    if (error) { // no error thrown\n      throw error;\n    }\n\n    console.log(typeof this.port); // type is string but should be number\n  }\n\n  public get port(): number {\n    return this.configService.get<number>('SERVER_PORT');\n  }\n}\n```\n\n```text\nnumber\n```\n\n```text\nstring\n```\n\n```text\nthis.configService.get<T>('key')\n```\n\n```text\npublic get port(): number {\n  return +this.configService.get('SERVER_PORT');\n}\n```\n\n```text\nConfigService\n```\n\n```text\ndotenv\n```\n\n```text\n{convert: true}\n```\n\n```text\nJoi.number()\n```\n\n```text\nnumber\n```\n\n========================================\n\nComments:\n- Is that `get()` method actually generic? Looking at the source, it's not. Even if it was generic, It's probably actually a string and I doubt the implementation would be able to perform that conversion, generic parameters are not usable at runtime and would not be able to do anything with that.\n- Thanks for your response. The linked NestJsx repository is not an official one I think? And why would I provide a type then =? Further why does Joi validate successfully .. At least this one should throw an error ...\n- Yeah, sorry, I realized that the more I dug in. I can't find the source for that `ConfigService` class. &#175;_(ใƒ„)_/&#175;\n- But, the second part of my comment still stands, all you can really tell the compiler there is that the the return value should be treated as a number, but it doesn't necessarily mean that it will be a number.\n- Ok found it, it definitely doesn't perform any conversions, it simply gets the value. The runtime type will be however it is read, which is probably all strings. You'll need to convert yourself.\n- Hmm I think the docs are confusing then...\n- but why does joi pass the validation?\n- yes, you are right. Thanks for the example. But why does joi throw no error?\n- I'm not familiar with nestjs or joi so I can't tell you for sure. But if I were to venture a guess, joi is smart enough to know that a string representation of a number is valid. If you set a server port that is not a number (before doing this conversion), it would likely fail.","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":147,"estimatedTokens":1163}}1054{"id":"stack-54425219","source":"stackoverflow","questionId":54425219,"title":"Modify or save data in request object in fastify","tags":["javascript","node.js","typescript","express","nestjs"],"text":"Title: Modify or save data in request object in fastify\nTags: javascript, node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use nestjs to build a REST API.\n\nI have a middleware which loads data from redis cache and should save it in the request object to access it in the controller function.\n\nIf i use express as engine it works, but with fastify it doesn't work. The data is undefined in the controller function.\n\nThe code looks like:\n\n```\nfunction mymiddleware(req, res, next) => {\n req.data = {...};\n next();\n};\n```\n\n========================================\n\nCode:\n```text\nfunction mymiddleware(req, res, next) => {\n    req.data = {...};\n    next();\n};\n```\n\n```text\nconst fastify = require('fastify')({ logger: true })\n\nfastify.use(function (req, res, next) {\n  console.log('middy')\n  req.data = { hello: 'world' }\n  next();\n})\n\nfastify.get('/', (req, res) => {\n  res.send(`hello ${req.raw.data.hello}`)\n})\n\nfastify.listen(3000)\n```\n\n```text\nreq\n```\n\n```text\n.use\n```\n\n```text\n.raw\n```\n\n========================================\n\nComments:\n- Probably not what you wanted to hear but I'm able to reproduce this issue in a brand new scaffolded Nest app with the most basic possible middleware. There seems to be a bunch of issues currently open with the Fastify adapter so I'm wondering if it might not be production ready at this point. I'd open an issue on Github for this as it seems like show stopping functionality to me\n- How do you register that middleware?\n- I registering the middleware how it is described in the nestjs docs.\n- @Jesse can you post a link to your issue?","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":65,"estimatedTokens":401}}1055{"id":"stack-76921431","source":"stackoverflow","questionId":76921431,"title":"TypeOrm-Postgres-NestJs @Column('decimal') is returning string","tags":["typescript","postgresql","nestjs","typeorm","nestjs-typeorm"],"text":"Title: TypeOrm-Postgres-NestJs @Column('decimal') is returning string\nTags: typescript, postgresql, nestjs, typeorm, nestjs-typeorm\nSource: Stack Overflow\n\nQuestion:\nI have some columns with type decimal. I am using query builder for aggregation. The only problem is after aggregating the result the fields that have decimal values are returning as string after executing the query.\n\nI want to set it globally across my project to consider decimal numbers in entity as decimal numbers only while executing queries and not string.\n\nI have tried using transformer with @Column() but it is not working.\n\n```\n@Column('decimal', {\n transformer: {\n to(value) {\n return value;\n },\n from(value) {\n return parseFloat(value);\n },\n },\n })\n price: number;\n```\n\nbut even if it works I don't want to write same thing for all columns.\nI want to make this setting globally.\n\n========================================\n\nCode:\n```text\n@Column('decimal', {\n    transformer: {\n      to(value) {\n        return value;\n      },\n      from(value) {\n        return parseFloat(value);\n      },\n    },\n  })\n  price: number;\n```\n\n```text\n// transformer\nexport class DecimalColumnTransformer {\n    to(data: number): number {\n        return data;\n    }\n    from(data: string): number {\n        return parseFloat(data);\n    }\n}\n```\n\n```text\n// entity\n@Column('decimal', {\n    precision: 5,\n    scale: 2,\n    transformer: new DecimalColumnTransformer(),\n})\nprice: number;\n```\n\n```text\nnumber\n```\n\n```text\nstring\n```\n\n```text\nmysql\n```\n\n```text\nsupportBigNumbers: false\n```\n\n```text\nnode-mysql\n```\n\n```text\nprecision\n```\n\n```text\nscale\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":94,"estimatedTokens":402}}1056{"id":"stack-54098773","source":"stackoverflow","questionId":54098773,"title":"NestJs: multiple views directory","tags":["node.js","typescript","express","nestjs"],"text":"Title: NestJs: multiple views directory\nTags: node.js, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am developing an MVC app using nestJs framework, and I used the hbs template-engine.\n\nAccording to the documentation I have to use this configuration to make nestjs able to serve views: \n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(ApplicationModule);\n\n app.useStaticAssets(join(__dirname, '..', 'public'));\n app.setBaseViewsDir(join(__dirname, '..', 'views'));\n app.setViewEngine('hbs');\n\n await app.listen(3000);\n}\n```\n\nThis configuration assumes that all views are located in one directory (views) but what if every module has its own views?\n\n========================================\n\nTop Answer:\nI'm assuming you have an app structure similar to this:\n\n```\nsrc\n main.ts\n /users\n users.controller.ts\n /views\n my-view.hbs\n /books\n books.controller.ts\n /views\n my-view.hbs\n```\n\nThen you can set the base view dir to `src`: \n\n```\napp.setBaseViewsDir(__dirname);\n```\n\nAnd reference the view with its relative path in your controllers:\n\n```\n@Controller('users')\nexport class UsersController {\n\n @Render('users/views/my-view')\n ^^^^^^^^^^^^^^^^^^^\n @Get()\n async getMyView() {\n```\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(ApplicationModule);\n\n  app.useStaticAssets(join(__dirname, '..', 'public'));\n  app.setBaseViewsDir(join(__dirname, '..', 'views'));\n  app.setViewEngine('hbs');\n\n  await app.listen(3000);\n}\n```\n\n```text\napp.setBaseViewsDir([\n  join(__dirname, '..', 'users/views'), \n  join(__dirname, '..', 'books/views'),\n]);\n```\n\n```text\napp.setBaseViewsDir([\n    join(__dirname, '..', 'users/views'), \n    join(__dirname, '..', 'books/views'),\n  ] as any);\n```\n\n```text\nas any\n```\n\n```text\nsrc\n  main.ts\n  /users\n       users.controller.ts\n       /views\n         my-view.hbs\n  /books\n       books.controller.ts\n       /views\n         my-view.hbs\n```\n\n```text\napp.setBaseViewsDir(__dirname);\n```\n\n```text\n@Controller('users')\nexport class UsersController {\n\n  @Render('users/views/my-view')\n           ^^^^^^^^^^^^^^^^^^^\n  @Get()\n  async getMyView() {\n```\n\n```text\nsrc\n```\n\n========================================\n\nComments:\n- Thanks! it works. but by this method all the \"src\" folder will be exposed as public right ? is this safe ?\n- I think it only gets exposed when you set `useStaticAssets` (which you don't have to). Views should only be accessible when you explicitly expose them via `@Render`.\n- @maroodb not a solution for you?\n- But it does not expose any files publicly unless you explicitly reference them in `@Render`. And even if you have your views directory next to your src directory, you can access views in the src directory by using relative paths: `..&#47;src&#47;my-view`, but again only with `@Render`. So there's no difference.\n- @maroodb I've added a better option to my answer. :-)\n- this makes sense!\n- Oh, what happened? Ran into a problem?\n- Sorry, it was a undesired click :p\n- The correct typings are available from version v5.7.0\n- iam not able to achieve this, Failed to lookup view\n- @SaurabhYadav This too general to be answered. Please open a new question and include the relevant code snippets. Also, see the other answer above, maybe this will work for you.\n- in main.ts I have set app.setBaseViewsDir(__dirname); all thing are same as you have mentioned in answer. I have also created a git repo for this github.com/saurabhkhoshya/nestjs-mvc-handlebar\n- it be great if you have any sample for this github.com/nestjs/nest/issues/1513\n- You can even create the render path from `__dirname` to avoid coupling controller with the path of the feature folder. A basic example would be: `@Render(__dirname + '&#47;views&#47;my-view')`","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":140,"estimatedTokens":951}}1057{"id":"stack-55942795","source":"stackoverflow","questionId":55942795,"title":"Call my NestJs microservice with nodeJS app","tags":["node.js","microservices","nestjs"],"text":"Title: Call my NestJs microservice with nodeJS app\nTags: node.js, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nI think I can say I'm a bit of a noob with microservices. So, which is why I wanted to play with it. I used NestJs, because it looked easy\n\nFirst I created a new app with `nest new myservice`\nThen I copied from the microservice docs the example `main.ts` and controller.ts into the project:\n\n`main.ts`:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { Transport } from '@nestjs/microservices';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(AppModule, {\n transport: Transport.TCP,\n options: { host: 'localhost', port: 3005 },\n });\n app.listen(() => console.log('Microservice is listening'));\n}\nbootstrap();\n```\n\n`app.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n imports: [],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {\n```\n\n`controoler.ts`\n\n```\nimport { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n @MessagePattern({ cmd: 'sum' })\n accumulate(data: number[]): number {\n return (data || []).reduce((a, b) => a + b);\n }\n}\n```\n\nNow when I start it, all looks well:\n\n```\nโœ— yarn start\nyarn run v1.13.0\n$ ts-node -r tsconfig-paths/register src/main.ts\n[Nest] 45783 - 05/01/2019, 11:08 PM [NestFactory] Starting Nest application...\n[Nest] 45783 - 05/01/2019, 11:08 PM [InstanceLoader] AppModule dependencies initialized +17ms\n[Nest] 45783 - 05/01/2019, 11:08 PM [NestMicroservice] Nest \nmicroservice successfully started \nMicroservice is listening\n```\n\nSo, if anything is wrong here, please let me know! But know I would like to write a small test nodejs app that can call/communicate with this microservice. Any suggestion where to start with that. Can I use axios for example or should I use something else. Any help would be appreciated!\n\n========================================\n\nTop Answer:\nI tried to communicate express app with nodejs microservice following the last post (Aleksandr Yatsenko) and works OK only if you install on your express app:\n\n- @nestjs/microservices\n\n- @nestjs/commons\n\n- @nestjs/core\n\n- rxjs\n\nHere is the code:\n\n\r\n\r\n\n```\nconst express = require('express')\nconst app = express()\nconst port = 3002\nconst { ClientTCP } = require('@nestjs/microservices');\nconst { lastValueFrom } = require('rxjs');\n\n(async () => {\n const client = new ClientTCP({\n host: 'localhost',\n port: 3001,\n });\n\n await client.connect();\n\n app.get('/', async (req, res) => {\n const pattern = { cmd: 'sum' };\n const data = JSON.parse(req.query.data)\n\n const result = await lastValueFrom(client.send(pattern, data))\n\n res.json({ result })\n })\n\n app.listen(port, () => {\n console.log(`Example app listening at http://localhost:${port}`)\n })\n\n})();\n```\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { Transport } from '@nestjs/microservices';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n    const app = await NestFactory.createMicroservice(AppModule, {\n        transport: Transport.TCP,\n        options: { host: 'localhost', port: 3005 },\n    });\n    app.listen(() => console.log('Microservice is listening'));\n}\nbootstrap();\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\n@Module({\n    imports: [],\n    controllers: [AppController],\n    providers: [AppService],\n})\nexport class AppModule {\n```\n\n```text\nimport { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\n\n@Controller()\nexport class AppController {\n    @MessagePattern({ cmd: 'sum' })\n    accumulate(data: number[]): number {\n        return (data || []).reduce((a, b) => a + b);\n    }\n}\n```\n\n```text\nโœ— yarn start\nyarn run v1.13.0\n$ ts-node -r tsconfig-paths/register src/main.ts\n[Nest] 45783   - 05/01/2019, 11:08 PM   [NestFactory] Starting Nest application...\n[Nest] 45783   - 05/01/2019, 11:08 PM   [InstanceLoader] AppModule dependencies initialized +17ms\n[Nest] 45783   - 05/01/2019, 11:08 PM   [NestMicroservice] Nest \nmicroservice successfully started \nMicroservice is listening\n```\n\n```text\nnest new myservice\n```\n\n```text\nmain.ts\n```\n\n```text\nmain.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\ncontrooler.ts\n```\n\n```text\nimport { ClientTCP } from '@nestjs/microservices';\n\n(async () => {\n    const client = new ClientTCP({\n        host: 'localhost',\n        port: 3005,\n    });\n\n    await client.connect();\n\n    const pattern = { cmd: 'sum' };\n    const data = [2, 3, 4, 5];\n\n    const result = await client.send(pattern, data).toPromise();\n    console.log(result);\n})();\n```\n\n```js\nconst express = require('express')\nconst app = express()\nconst port = 3002\nconst { ClientTCP } = require('@nestjs/microservices');\nconst { lastValueFrom } = require('rxjs');\n\n(async () => {\n    const client = new ClientTCP({\n        host: 'localhost',\n        port: 3001,\n    });\n\n    await client.connect();\n\n    app.get('/', async (req, res) => {\n        const pattern = { cmd: 'sum' };\n        const data = JSON.parse(req.query.data)\n\n        const result = await lastValueFrom(client.send(pattern, data))\n\n        res.json({ result })\n    })\n\n    app.listen(port, () => {\n        console.log(`Example app listening at http://localhost:${port}`)\n    })\n\n})();\n```\n\n========================================\n\nComments:\n- I don't understand, what isn't working? Asking for critiques should be done on Code Review, Stack Overflow is for code that doesn't work. If you're just asking for suggestions on what you should code, that too is off-topic because it is too broad.\n- How to call the same from an angular application or any front end framework ?\n- is it always necesssary to have a nestjs client application to contact nest js microservice aplication ?\n- Yes. Directly calling an Backend via TCP from an Angular application seems not possible. You have to use WebSocket or HTTP always as \"bridge\".","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":253,"estimatedTokens":1557}}1058{"id":"stack-61954447","source":"stackoverflow","questionId":61954447,"title":"How to get the exception error as Object in Nestjs Validation?","tags":["javascript","node.js","nestjs","class-validator"],"text":"Title: How to get the exception error as Object in Nestjs Validation?\nTags: javascript, node.js, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nBy default, when validation fails the response came out like \n\n```\n{\n statusCode: 400,\n message: [ 'Provide a url.', 'test must be a string' ],\n error: 'Bad Request'\n}\n```\n\nHow can I get the value of messages as:\n\n```\n{\n statusCode: 400,\n message: {\n \"url\": 'Provide a url.',\n \"test\": 'test must be a string'\n },\n error: 'Bad Request'\n}\n```\n\n========================================\n\nCode:\n```text\n{\n    statusCode: 400,\n    message: [ 'Provide a url.', 'test must be a string' ],\n    error: 'Bad Request'\n}\n```\n\n```text\n{\n    statusCode: 400,\n    message: {\n        \"url\": 'Provide a url.',\n        \"test\": 'test must be a string'\n    },\n    error: 'Bad Request'\n}\n```\n\n```js\nexceptionFactory: (errors) => {\n  const errorMessages = {};\n  errors.forEach(error => {\n    errorMessages[error.property]= Object.values(error.contraints).join('. ').trim();\n  });\n  return new BadRequestException(errorMessages);\n}\n```\n\n```text\nValidationPipe\n```\n\n```text\nexceptionFacotry\n```\n\n========================================\n\nComments:\n- I think it should '=' not ':'\n- `exceptonFactory` is a property of the`options` **object** passed to the `ValidationPipe`, so `:` is correct here\n- in typescript it's '=' instead of ':'\n- You're right, was thinking it was a raw object, not an assignment.\n- It will not return nested error message.\n- Typo in the answer: `error.contraints` should be `error.constraints`","metadata":{"transformedAt":"2026-08-18T18:33:02.573Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":77,"estimatedTokens":387}}1059{"id":"stack-59343683","source":"stackoverflow","questionId":59343683,"title":"Add Property to Express Request Object","tags":["javascript","typescript","express","nestjs"],"text":"Title: Add Property to Express Request Object\nTags: javascript, typescript, express, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a property \"forwardingUrl\" to the Express request object.\n\nI tried declaration merging by creating a file ./typing.d.ts:\n\n```\ndeclare namespace Express {\n export interface Request {\n forwardingUrl: string;\n }\n}\n```\n\nin the editor I can use the property and access it but when I compile I get the following error:\n\n```\nProperty 'forwardingUrl' does not exist on type 'Request'.\n```\n\nWhat am I missing?\n\nEDIT\n\nThe code where I get the error:\n\n```\nimport { Middleware, Request } from '@tsed/common';\nimport { Request as ExpressRequest } from 'express';\n@Middleware()\nexport class Wso2ForwardingUrlParser {\n async use(@Request() request: ExpressRequest) {\n if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {\n request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;\n } else {\n request.forwardingUrl = '';\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nI ran into this same issue and solved it by adding `//@ts-ignore` just above the lines where the error is being thrown:\n\n```\nimport { Middleware, Request } from '@tsed/common';\nimport { Request as ExpressRequest } from 'express';\n\n@Middleware()\nexport class Wso2ForwardingUrlParser {\n async use(@Request() request: ExpressRequest) {\n if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {\n\n //@ts-ignore\n request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;\n\n } else {\n\n //@ts-ignore\n request.forwardingUrl = '';\n }\n }\n}\n```\n\nI would also recommend using a param decorator to get this value later in the code. Since you've already added this extra \"forwardingUrl\" property to the request instance via your middleware, create a param decorator like so:\n\n```\n// ./ForwardingUrlDecorator.ts\n\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const ForwardingUrl = createParamDecorator((_data: any, req: any) => {\n return req.forwardingUrl;\n});\n```\n\nThen in your controller you can grab that value without having to reference the entire express instance as a parameter in your methods:\n\n```\nimport { Controller } from '@nestjs/common';\nimport { ForwardingUrl } from './ForwardingUrlDecorator';\n\n@Controller()\nexport class YourController {\n\n @Get()\n public async getTheThing(@ForwardingUrl() forwardingUrl: string) {\n //...\n }\n}\n```\n\n========================================\n\nCode:\n```text\ndeclare namespace Express {\n  export interface Request {\n    forwardingUrl: string;\n  }\n}\n```\n\n```text\nProperty 'forwardingUrl' does not exist on type 'Request<ParamsDictionary>'.\n```\n\n```text\nimport { Middleware, Request } from '@tsed/common';\nimport { Request as ExpressRequest } from 'express';\n@Middleware()\nexport class Wso2ForwardingUrlParser {\n    async use(@Request() request: ExpressRequest) {\n        if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {\n            request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;\n        }   else {\n            request.forwardingUrl = '';\n        }\n    }\n}\n```\n\n```text\nimport {Request} from \"@tsed/common\";\n\nexport interface RequestModel extends Request {\n    forwardingUrl: string\n}\n```\n\n```text\nimport { Middleware, Request } from '@tsed/common';\nimport { Request as ExpressRequest } from 'express';\n@Middleware()\nexport class Wso2ForwardingUrlParser {\n    async use(@Request() request: RequestModel) {\n        if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {\n            request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;\n        }   else {\n            request.forwardingUrl = '';\n        }\n    }\n}\n```\n\n```text\nimport { Middleware, Request } from '@tsed/common';\nimport { Request as ExpressRequest } from 'express';\n\n@Middleware()\nexport class Wso2ForwardingUrlParser {\n    async use(@Request() request: ExpressRequest) {\n        if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {\n\n            //@ts-ignore\n            request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;\n\n        }   else {\n\n            //@ts-ignore\n            request.forwardingUrl = '';\n        }\n    }\n}\n```\n\n```text\n// ./ForwardingUrlDecorator.ts\n\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const ForwardingUrl = createParamDecorator((_data: any, req: any) => {\n    return req.forwardingUrl;\n});\n```\n\n```text\nimport { Controller } from '@nestjs/common';\nimport { ForwardingUrl } from './ForwardingUrlDecorator';\n\n@Controller()\nexport class YourController {\n\n    @Get()\n    public async getTheThing(@ForwardingUrl() forwardingUrl: string) {\n        //...\n    }\n}\n```\n\n```text\n//@ts-ignore\n```\n\n```text\nexport {};\n\nexport type _Foo = Foo;\n\ndeclare global {\n  namespace Express {\n    interface Request {\n      foo: _Foo;\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- Request already exists developer.mozilla.org/en-US/docs/Web/API/Request and this is Request but your is Express.Request.\n- Also @types/express npmjs.com/package/@types/express exists.\n- Request extends Request so shouldn't it work?\n- @Zydnar I need to add a property to express.request\n- But `export interface Request {` does not have any \"extends\". Can you include the code where you get the Error, also show the imports.\n- @Zydnar added the code\n- you can either do `async use((@Request() request) as ExpressRequest) {` because I thnk typescript is reading incorrectly decorator or try to extend parameters inside <> like this: github.com/DefinitelyTyped/DefinitelyTyped/blob/&hellip;\n- I was just getting and setting the properties but love your suggestion of using the decorator this way.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":225,"estimatedTokens":1496}}1060{"id":"stack-61440798","source":"stackoverflow","questionId":61440798,"title":"define DTO for ApiParam and ApiQuery","tags":["swagger","nestjs"],"text":"Title: define DTO for ApiParam and ApiQuery\nTags: swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using the nestjs swagger module and want to create my API documentation. For endpoints relying on the request body I can assign a DTO class to the docs like\n\n```\n@ApiBody({ type: CreateUserDTO })\n```\n\nSome endpoints also rely on the request params or queries. For params I would do something like\n\n```\n@ApiParam({ type: GetUserByIdDTO })\n```\n\n(I know this is a bad example because there is no need for a DTO for a user id but let's assume you want to validate your params with a DTO class using class-validator)\n\nbut I'm getting this error\n\n Argument of type '{ type: typeof GetUserByIdDTO; }' is not assignable\n to parameter of type 'ApiParamOptions'. Property 'name' is missing\n in type '{ type: typeof GetUserByIdDTO; }' but required in type\n 'ApiParamMetadata'.\n\nFor queries I would do something like\n\n```\n@ApiQuery({ type: GetUsersDTO })\n```\n\nand get this error\n\n Argument of type '{ type: typeof GetUsersDTO; }' is not assignable to\n parameter of type 'ApiQueryOptions'. Property 'name' is missing in\n type '{ type: typeof GetUsersDTO; }' but required in type\n 'ApiQueryMetadata'.\n\nSo the `APIBody` decorator seems to work fine but how can I fix my `APIParam` and `APIQuery` decorators?\n\n========================================\n\nCode:\n```text\n@ApiBody({ type: CreateUserDTO })\n```\n\n```text\n@ApiParam({ type: GetUserByIdDTO })\n```\n\n```text\n@ApiQuery({ type: GetUsersDTO })\n```\n\n```text\nAPIBody\n```\n\n```text\nAPIParam\n```\n\n```text\nAPIQuery\n```\n\n```text\nasync findElements(@Query() query: ElementsQueryDto) {\n  // ...\n}\n```\n\n```text\n@ApiQuery\n```\n\n```text\n@ApiParam\n```\n\n```text\n@Query('pageSize')\n```\n\n```text\n@Param('id')\n```\n\n========================================\n\nComments:\n- I documented my dto fields with the `ApiProperty` decorator. And yes, this seems to be enough. So you say there is no need for the `ApiQuery` or `ApiParam` decoratior because this code is fine `public getUsers(@Query() getUsersDTO: GetUsersDTO): Promise { &#47;* ... *&#47; }` because the swagger module will document the fields from the dto on its own?\n- Exactly, this is swagger nestjs module default behaviour and ApiQuery or ApiParam is intended as a fallback / shortand for simpler scenarios where you donโ€™t need a Dto.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":95,"estimatedTokens":579}}1061{"id":"stack-75177775","source":"stackoverflow","questionId":75177775,"title":"NestJS not handling error from thrown from service in controller","tags":["nestjs"],"text":"Title: NestJS not handling error from thrown from service in controller\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a simple setup where I'm calling a service method from the controller like so:\n\n```\n// companies.controller.ts\n\n@Controller(\"company\")\nexport class CompaniesController {\n constructor(private companiesService: CompaniesService) {}\n\n @Post(\"/:id/upload\")\n @UseInterceptors(FilesInterceptor(\"file\"))\n uploadFiles(\n @Param(\"id\") id: string,\n @UploadedFiles() files: Array,\n ) {\n // throw new HttpException(\"Company not found\", HttpStatus.NOT_ACCEPTABLE);\n // console.log(files);\n try {\n this.companiesService.uploadFiles(id, files);\n console.log(\"didn't get error\");\n } catch (error) {\n console.log(\"got error\");\n throw new HttpException(\"forbidden\", HttpStatus.FORBIDDEN);\n }\n }\n}\n\n// companies.service.ts\n\n@Injectable()\nexport class CompaniesService {\n constructor(\n private prisma: PrismaService,\n private s3Service: S3Service,\n private filesService: FilesService,\n ) {}\n\n async uploadFiles(id: Company[\"id\"], files: Array) {\n const company = false // for testing\n\n if (!company) {\n console.log(\"Company not found\");\n throw new Error();\n }\n}\n```\n\nI'm running this by using `nest start --watch`.\n\nWhen I call this endpoint, My app quits and I get the following logged to my console:\n\n```\ndidn't get error\nCompany not found\n\n/src/companies/companies.service.ts:54\n throw new Error();\n ^\nError: \n at CompaniesService.uploadFiles (/src/companies/companies.service.ts:54:13)\n```\n\nHow come I can't catch the error I'm throwing in my controller? It's clearly not `catch`ing because it's logging `company not found`. Exception Filtering is supposed to be built in by default so I'm not sure why this isn't producing a `500`?\n\n========================================\n\nCode:\n```js\n// companies.controller.ts\n\n@Controller(\"company\")\nexport class CompaniesController {\n  constructor(private companiesService: CompaniesService) {}\n\n  @Post(\"/:id/upload\")\n  @UseInterceptors(FilesInterceptor(\"file\"))\n  uploadFiles(\n    @Param(\"id\") id: string,\n    @UploadedFiles() files: Array<Express.Multer.File>,\n  ) {\n    // throw new HttpException(\"Company not found\", HttpStatus.NOT_ACCEPTABLE);\n    // console.log(files);\n    try {\n      this.companiesService.uploadFiles(id, files);\n      console.log(\"didn't get error\");\n    } catch (error) {\n      console.log(\"got error\");\n      throw new HttpException(\"forbidden\", HttpStatus.FORBIDDEN);\n    }\n  }\n}\n\n// companies.service.ts\n\n@Injectable()\nexport class CompaniesService {\n  constructor(\n    private prisma: PrismaService,\n    private s3Service: S3Service,\n    private filesService: FilesService,\n  ) {}\n\n  async uploadFiles(id: Company[\"id\"], files: Array<Express.Multer.File>) {\n    const company = false // for testing\n\n    if (!company) {\n      console.log(\"Company not found\");\n      throw new Error();\n    }\n}\n```\n\n```text\ndidn't get error\nCompany not found\n\n/src/companies/companies.service.ts:54\n      throw new Error();\n            ^\nError: \n    at CompaniesService.uploadFiles (/src/companies/companies.service.ts:54:13)\n```\n\n```text\nnest start --watch\n```\n\n```text\ncatch\n```\n\n```text\ncompany not found\n```\n\n```text\n500\n```\n\n```text\nawait\n```\n\n```text\nthis.companiesService.uploadFiles(id, files);\n```\n\n```text\nasync\n```\n\n```text\nuploadFiles\n```\n\n```text\nawait\n```\n\n```text\nthis.companiesService.uploadFiles\n```\n\n========================================\n\nComments:\n- Yes, that was it! I knew it had to be something silly I was missing. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":172,"estimatedTokens":879}}1062{"id":"stack-64010514","source":"stackoverflow","questionId":64010514,"title":"Can't send a request using grpcurl","tags":["grpc","nestjs","grpcurl"],"text":"Title: Can't send a request using grpcurl\nTags: grpc, nestjs, grpcurl\nSource: Stack Overflow\n\nQuestion:\nI have a server using NestJs+gRPC, I storage data in PostgreSQL, there is no problems in getting data and so on. I can't send grpcurl request :((\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.connectMicroservice(grpcClientOptions);\n\n await app.startAllMicroservicesAsync();\n await app.listen(3000);\n console.log(`Application is running on: ${await app.getUrl()}`);\n}\n(async () => await bootstrap())();\n\nexport const grpcClientOptions: ClientOptions = {\n transport: Transport.GRPC,\n options: {\n url: '0.0.0.0:5000',\n package: 'user',\n protoPath: join(__dirname,'user/user.proto'),\n loader: {\n keepCase: true,\n longs: Number,\n defaults: false,\n arrays: true,\n objects: true,\n },\n },\n};\n```\n\nProto file looks like\n\n```\nsyntax = \"proto3\";\n\npackage user;\n\nservice UserService {\n rpc FindOne (UserById) returns (User) {}\n}\n\nmessage UserById {\n string id = 1;\n}\n\nmessage User {\n int32 id = 1;\n string name = 2;\n string password = 3;\n string email = 4;\n string createdAt = 5;\n string updatedAt = 6;\n}\n```\n\nAnd user controller\n\n```\n@Get(':id')\n getById(@Param('id') id: string): Observable {\n console.log(id);\n return this.userService.findOne({ id : +id });\n }\n\n @GrpcMethod('UserService','FindOne')\n async findOne(data: UserById): Promise {\n const { id } = data;\n console.log(id);\n return this.userModel.findOne({\n where: {\n id : id\n },\n });\n }\n```\n\nIt works correctly when I sending request from browser, but I can't make it using grpcurl.\nenter image description here\n\nThanks in forward!\n\n========================================\n\nTop Answer:\nGrpcurl on winodws differes from Linux/Mac.\nOn winodws, no need to enclose a json message single quote.\nE.g.\n\n```\ngrpcurl.exe --plaintext -d {\\\"message\\\":\\\"How\\u0020are\\u0020you\\\"} localhost:9090 GreetingService.greeting\n```\n\nNote: We need to escape whitespace using \\u0020 and escape double quotes with a back slash'`\\`'.\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.connectMicroservice<MicroserviceOptions>(grpcClientOptions);\n\n  await app.startAllMicroservicesAsync();\n  await app.listen(3000);\n  console.log(`Application is running on: ${await app.getUrl()}`);\n}\n(async () => await bootstrap())();\n\nexport const grpcClientOptions: ClientOptions = {\n  transport: Transport.GRPC,\n  options: {\n    url: '0.0.0.0:5000',\n    package: 'user',\n    protoPath: join(__dirname,'user/user.proto'),\n    loader: {\n      keepCase: true,\n      longs: Number,\n      defaults: false,\n      arrays: true,\n      objects: true,\n    },\n  },\n};\n```\n\n```text\nsyntax = \"proto3\";\n\npackage user;\n\nservice UserService {\n  rpc FindOne (UserById) returns (User) {}\n}\n\nmessage UserById {\n  string id = 1;\n}\n\nmessage User {\n  int32 id = 1;\n  string name = 2;\n  string password = 3;\n  string email = 4;\n  string createdAt = 5;\n  string updatedAt = 6;\n}\n```\n\n```text\n@Get(':id')\n  getById(@Param('id') id: string): Observable<User> {\n    console.log(id);\n    return this.userService.findOne({ id : +id });\n  }\n\n  @GrpcMethod('UserService','FindOne')\n  async findOne(data: UserById): Promise<User> {\n    const { id } = data;\n    console.log(id);\n    return this.userModel.findOne({\n      where: {\n        id : id\n      },\n    });\n  }\n```\n\n```text\n/\n```\n\n```text\nsrc/user\n```\n\n```text\n\\\n```\n\n```text\n-d '{\\\"id\\\": 1}'\n```\n\n```text\ngrpcurl.exe --plaintext -d {\\\"message\\\":\\\"How\\u0020are\\u0020you\\\"} localhost:9090  GreetingService.greeting\n```\n\n```text\n\\\n```\n\n========================================\n\nComments:\n- Please copy-paste text into questions rather than include images. The commands looks well-formed and, for me in a Linux shell, I get (as expected) a connection refused (as I've no server on localhost:5000). I suspect (!) the issue is that you're on Windows but using a forward-slash between `src&#47;user` whereas on Windows (!?) file path separators should be a back-slash?\n- The url `0.0.0.0:5000` doesn't look right for a client. What if you use `localhost:5000` instead?\n- @DazWilkin Thanks a lot!!!! Now I can send requests, but now I got another problem: I can't pass my id:1 param. In terminal I have grpcurl -d \"{\"id\":1}\" -plaintext -import-path src\\user -proto user.proto localhost:5000 user.UserService.FindOne Error invoking method \"user.UserService.FindOne\": error getting request data: invalid character 'i' looking for beginning of object key string. May be u can help? I'm using Windows\n- You're welcome! Glad it worked. Please try `-d \"{\\\"id\\\":1}\"`\n- @DazWilkin grpcurl -d '{\\\"id\\\":1}' -plaintext -import-path src\\user -proto user.proto localhost:5000 user.UserService.FindOne Error invoking method \"user.UserService.FindOne\": error getting request data: invalid character '\\'' looking for beginning of value . It doens't work, but thank u anyway))\n- OK, please see the link and try `-d '{\\\"id\\\": 1}'` learn.microsoft.com/en-us/aspnet/core/grpc/&hellip;\n- @DazWilkin thanks, can u pls put your comment as answer and I'll accept it\n- The space character should also be removed, to make the command works correctly on Windows.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":207,"estimatedTokens":1301}}1063{"id":"stack-70796428","source":"stackoverflow","questionId":70796428,"title":"how to use RabbitMQ and REST-API in Nest App?","tags":["javascript","rabbitmq","microservices","nestjs"],"text":"Title: how to use RabbitMQ and REST-API in Nest App?\nTags: javascript, rabbitmq, microservices, nestjs\nSource: Stack Overflow\n\nQuestion:\nGood Day!\n\nI'm trying to implement `2 microservices that communicate with each other through a message broker`. `But one of them should accept Http requests via REST-Api`. Unfortunately, I don't understand how to make the microservice listen to both the message queue and incoming HTTP requests. Perhaps I donโ€™t understand something in the paradigm of communication through a message broker, but how then to receive requests from the client and forward them to the microservice architecture?\n\n*Main.ts*\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport {Transport, MicroserviceOptions} from '@nestjs/microservices'\n\nasync function bootstrap() {\n const app = await NestFactory.createMicroservice(AppModule, {\n transport: Transport.RMQ,\n options: {\n urls: ['amqp://rabbitmq:5672'],\n queue: 'hello_world',\n queueOptions: {\n durable: false\n },\n },\n });\n await app.listen();\n}\nbootstrap();\n```\n\nAs you can see, now the application is not listening on port 3000 as in the standard approach. What should be done?\n\n========================================\n\nCode:\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport {Transport, MicroserviceOptions} from '@nestjs/microservices'\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n    transport: Transport.RMQ,\n    options: {\n      urls: ['amqp://rabbitmq:5672'],\n      queue: 'hello_world',\n      queueOptions: {\n        durable: false\n      },\n    },\n  });\n  await app.listen();\n}\nbootstrap();\n```\n\n```text\n2 microservices that communicate with each other through a message broker\n```\n\n```text\nBut one of them should accept Http requests via REST-Api\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport {Transport, MicroserviceOptions} from '@nestjs/microservices'\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const microservice = app.connectMicroservice({\n    transport: Transport.RMQ,\n    options: {\n      urls: ['amqp://rabbitmq:5672'],\n      queue: 'hello_world',\n      queueOptions: {\n        durable: false\n      },\n    },\n  });\n\n  await app.startAllMicroservices();\n  await app.listen(3000);\n}\nbootstrap();\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":612}}1064{"id":"stack-58296297","source":"stackoverflow","questionId":58296297,"title":"Can you configure the NestJS cache TTL per-endpoint?","tags":["javascript","node.js","caching","nestjs"],"text":"Title: Can you configure the NestJS cache TTL per-endpoint?\nTags: javascript, node.js, caching, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm currently using the NestJS caching mechanism as described in the docs: https://docs.nestjs.com/techniques/caching\n\nUsing this I can customise the caching of an entire module with the following:\n\n```\nCacheModule.register({\n ttl: 5, // seconds\n max: 10, // maximum number of items in cache\n});\n```\n\nHowever, there are certain **endpoints** that I want to cache for a longer period of time than the rest. (e.g. Long running operations that don't change as often as the others)\n\nSomething similar was described here: https://github.com/nestjs/nest/issues/695 but looks like it was closed without truly solving the whole problem.\n\nI'm imagining something like:\n\n```\n@Cache({ ttl: 600 })\n@Get()\nfindAll(): string[] {\n return service.longRunningOperation();\n}\n```\n\nAny thoughts?\n\n========================================\n\nTop Answer:\nControl ttl cache by decorator isn't support yet. There's a feature request in github to include this in a future version.\n\nBut, you can use a more verbose approach to deal with it. Inject the cache-manager object into your controllers constructors and use the 'wrap' function on each desired route:\n\n```\nconstructor(\n @Inject(CACHE_MANAGER) private cacheManager\n) {}\n\n@Get()\nasync get(): Promise {\n const customers = await this.cacheManager.wrap(\n '/customers',\n function() {\n return service.longRunningOperation()\n },\n { ttl: 600 }\n )\n return customers\n}\n```\n\n========================================\n\nCode:\n```text\nCacheModule.register({\n  ttl: 5, // seconds\n  max: 10, // maximum number of items in cache\n});\n```\n\n```text\n@Cache({ ttl: 600 })\n@Get()\nfindAll(): string[] {\n  return service.longRunningOperation();\n}\n```\n\n```text\n@Get()\n@CacheTTL(100) \n@UseInterceptors(CacheInterceptor)\nfindAll(): string[] {\n  return service.longRunningOperation();\n}\n```\n\n```text\n'@nestjs/common'\n```\n\n```js\nconstructor(\n  @Inject(CACHE_MANAGER) private cacheManager\n) {}\n\n@Get()\nasync get(): Promise<any> {\n  const customers = await this.cacheManager.wrap(\n    '/customers',\n    function() {\n      return service.longRunningOperation()\n    },\n    { ttl: 600 }\n  )\n  return customers\n}\n```\n\n```text\nimport {memoizeAsync} from 'utils-decorators';\n\nclass Controller {\n\n\n @Get('endpointA')\n @memoizeAsync(60 * 60 * 1000 * 12)\n endpointA() {\n }\n\n @Get('endpointB')\n @memoizeAsync(60 * 60 * 1000 * 24)\n endpointB() {\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":123,"estimatedTokens":619}}1065{"id":"stack-67311637","source":"stackoverflow","questionId":67311637,"title":"Why jwtService is undefined?","tags":["typescript","jwt","nestjs"],"text":"Title: Why jwtService is undefined?\nTags: typescript, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nJwtAuthGuard where I verify token from headers:\n\n```\nimport { JwtService } from '@nestjs/jwt';\nimport {\n CanActivate,\n ExecutionContext,\n UnauthorizedException\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\nexport class JwtAuthGuard implements CanActivate {\n constructor(private jwtService: JwtService) {}\n\n canActivate(\n context: ExecutionContext\n ): boolean | Promise | Observable {\n const req = context.switchToHttp().getRequest();\n\n try {\n const authHeader = req.headers.authorization;\n const token = authHeader.split(' ')[1];\n\n const user = this.jwtService.verify(token);\n\n req.user = user;\n return true;\n } catch (error) {\n console.log(error);\n throw new UnauthorizedException();\n }\n }\n}\n```\n\nMy controller:\n\n```\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { JwtAuthGuard } from 'src/auth/jwt-auth.guard';\n \n @Controller('api/messages')\n export class MessagesController {\n @UseGuards(JwtAuthGuard)\n @Get()\n getAllUserMessages() {\n return \"it's work\";\n }\n }\n```\n\nAuthModule where I registered JWT:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UsersModule } from 'src/users/users.module';\nimport { JwtModule } from '@nestjs/jwt';\nimport { ConfigService } from '@nestjs/config';\n\n@Module({\n providers: [AuthService],\n controllers: [AuthController],\n imports: [\n UsersModule,\n JwtModule.registerAsync({\n useFactory: async (configService: ConfigService) => ({\n secret: configService.get('AUTH_KEY'),\n signOptions: {\n expiresIn: '12h'\n }\n }),\n inject: [ConfigService]\n })\n ],\n exports: [JwtModule, AuthService]\n})\nexport class AuthModule {}\n```\n\nWhen I go to route `/api/messages` with token, I get error:\n\n```\nTypeError: Cannot read property 'verify' of undefined\nat JwtAuthGuard.canActivate (/Users/alexander/Projects/nest/paska/dist/auth/jwt-auth.guard.js:18:42)\n```\n\n========================================\n\nCode:\n```text\nimport { JwtService } from '@nestjs/jwt';\nimport {\n  CanActivate,\n  ExecutionContext,\n  UnauthorizedException\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\nexport class JwtAuthGuard implements CanActivate {\n  constructor(private jwtService: JwtService) {}\n\n  canActivate(\n    context: ExecutionContext\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    const req = context.switchToHttp().getRequest();\n\n    try {\n      const authHeader = req.headers.authorization;\n      const token = authHeader.split(' ')[1];\n\n      const user = this.jwtService.verify(token);\n\n      req.user = user;\n      return true;\n    } catch (error) {\n      console.log(error);\n      throw new UnauthorizedException();\n    }\n  }\n}\n```\n\n```text\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { JwtAuthGuard } from 'src/auth/jwt-auth.guard';\n    \n @Controller('api/messages')\n export class MessagesController {\n  @UseGuards(JwtAuthGuard)\n  @Get()\n   getAllUserMessages() {\n     return \"it's work\";\n     }\n  }\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UsersModule } from 'src/users/users.module';\nimport { JwtModule } from '@nestjs/jwt';\nimport { ConfigService } from '@nestjs/config';\n\n@Module({\n  providers: [AuthService],\n  controllers: [AuthController],\n  imports: [\n    UsersModule,\n    JwtModule.registerAsync({\n      useFactory: async (configService: ConfigService) => ({\n        secret: configService.get('AUTH_KEY'),\n        signOptions: {\n          expiresIn: '12h'\n        }\n      }),\n      inject: [ConfigService]\n    })\n  ],\n  exports: [JwtModule, AuthService]\n})\nexport class AuthModule {}\n```\n\n```text\nTypeError: Cannot read property 'verify' of undefined\nat JwtAuthGuard.canActivate (/Users/alexander/Projects/nest/paska/dist/auth/jwt-auth.guard.js:18:42)\n```\n\n```text\n/api/messages\n```\n\n```text\n@Injectable()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":183,"estimatedTokens":1010}}1066{"id":"stack-66879023","source":"stackoverflow","questionId":66879023,"title":"Dependency hell in NestJS/TS","tags":["javascript","typescript","nestjs"],"text":"Title: Dependency hell in NestJS/TS\nTags: javascript, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI build `NestJS` projecct with many modules and recently I got lost in them a bit, My last thing which I'm doing was added `QueueService` to my `ProjectService` and `ProjectModule`, but after launch whole app, the compiler throw me this:\n\n```\nError: Nest can't resolve dependencies of the QueueService (UtilsService, UserService, Connection, ?). Please make sure that the argument Object at index [3] is available in the ProjectModule context.\n```\n\nThe argument at the index[3] at `QueueService` is `ProjectService`, so why they want from me to import `ProjectModule/ProjectService` into my `ProjectModule`? :P\n\nhere is my all code:\n\n```\n@Injectable()\nexport class ProjectService {\n constructor(\n private conn: Connection,\n private utilsService: UtilsService,\n private userService: UserService,\n private notificationService: NotificationsService,\n private queueService: QueueService \n ) { }\n```\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt'})\n ],\n providers: [ProjectService, UtilsService, UserService, NotificationsService, QueueService ],\n controllers: [ProjectController],\n exports: [ProjectService]\n})\nexport class ProjectModule {}\n```\n\n```\n@Injectable()\nexport class QueueService {\n constructor(\n readonly conn: Connection,\n readonly utilsService: UtilsService,\n readonly userService: UserService,\n readonly projectService: ProjectService\n ){}\n}\n```\n\n```\n@Module({\n imports: [\n AuthModule,\n PassportModule.register({ defaultStrategy: 'jwt'})],\n providers: [QueueService , UtilsService, UserService, NotificationsService, ProjectService],\n controllers: [QueueController ],\n exports: [PassportModule]\n})\nexport class QueueModule {}\n```\n\nAppModule\n\n```\n@Module({\n imports: [\n ...,\n TypeOrmModule.forRootAsync({\n useClass: TypeOrmConfigService\n }),\n PassportModule.register({ defaultStrategy: 'jwt'}),\n JwtModule.register({\n secret: 'secretKey'\n }),\n ScheduleModule.forRoot(),\n ...,\n ...,\n QueueModule,\n ...,\n ...,\n ProjectModule,\n ...,\n ...,\n ...\n ],\n controllers: [..., ..., ..., ..., ...],\n providers: [ ..., ..., ..., ..., ...,ProjectService, ..., ..., QueueService],\n})\nexport class AppModule {}\n```\n\nthanks for any help, I stuck here for 3-4h and I do not know what can I do more :(\n\n////////////////////////////////////\n\n========================================\n\nCode:\n```text\nError: Nest can't resolve dependencies of the QueueService (UtilsService, UserService, Connection, ?). Please make sure that the argument Object at index [3] is available in the ProjectModule context.\n```\n\n```text\n@Injectable()\nexport class ProjectService {\n    constructor(\n        private conn: Connection,\n        private utilsService: UtilsService,\n        private userService: UserService,\n        private notificationService: NotificationsService,\n        private queueService: QueueService \n    ) { }\n```\n\n```text\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt'})\n  ],\n  providers: [ProjectService, UtilsService, UserService, NotificationsService, QueueService ],\n  controllers: [ProjectController],\n  exports: [ProjectService]\n})\nexport class ProjectModule {}\n```\n\n```text\n@Injectable()\nexport class QueueService {\n    constructor(\n        readonly conn: Connection,\n        readonly utilsService: UtilsService,\n        readonly userService: UserService,\n        readonly projectService: ProjectService\n    ){}\n}\n```\n\n```text\n@Module({\n  imports: [\n    AuthModule,\n    PassportModule.register({ defaultStrategy: 'jwt'})],\n  providers: [QueueService , UtilsService, UserService, NotificationsService, ProjectService],\n  controllers: [QueueController ],\n  exports: [PassportModule]\n})\nexport class QueueModule {}\n```\n\n```text\n@Module({\n  imports: [\n    ...,\n    TypeOrmModule.forRootAsync({\n      useClass: TypeOrmConfigService\n    }),\n    PassportModule.register({ defaultStrategy: 'jwt'}),\n    JwtModule.register({\n        secret: 'secretKey'\n    }),\n    ScheduleModule.forRoot(),\n    ...,\n    ...,\n    QueueModule,\n    ...,\n    ...,\n    ProjectModule,\n    ...,\n    ...,\n    ...\n  ],\n  controllers: [..., ..., ..., ..., ...],\n  providers: [ ..., ..., ..., ..., ...,ProjectService, ..., ..., QueueService],\n})\nexport class AppModule {}\n```\n\n```text\nNestJS\n```\n\n```text\nQueueService\n```\n\n```text\nProjectService\n```\n\n```text\nProjectModule\n```\n\n```text\nQueueService\n```\n\n```text\nProjectService\n```\n\n```text\nProjectModule/ProjectService\n```\n\n```text\nProjectModule\n```\n\n```js\n@Injectable()\nexport class QueueService {\n    constructor(\n        readonly conn: Connection,\n        readonly utilsService: UtilsService,\n        readonly userService: UserService,\n        @Inject(forwardRef(() => ProjectService))\n        readonly projectService: ProjectService\n    ){}\n}\n```\n\n```js\n@Injectable()\nexport class ProjectService {\n    constructor(\n        private conn: Connection,\n        private utilsService: UtilsService,\n        private userService: UserService,\n        private notificationService: NotificationsService,\n        @Inject(forwardref(() => QueueService))\n        private queueService: QueueService \n    ) { }\n```\n\n```js\n@Module({\n  imports: [\n    AuthModule,\n    forwardRef(() => ProjectModule),\n    PassportModule.register({ defaultStrategy: 'jwt'})],\n  providers: [QueueService , UtilsService, UserService, NotificationsService],\n  controllers: [QueueController ],\n  exports: [PassportModule, QueueService]\n})\nexport class QueueModule {}\n```\n\n```js\n@Module({\n  imports: [\n    forwardref(() => QueueModule),\n    PassportModule.register({ defaultStrategy: 'jwt'})\n  ],\n  providers: [ProjectService, UtilsService, UserService, NotificationsService ],\n  controllers: [ProjectController],\n  exports: [ProjectService]\n})\nexport class ProjectModule {}\n```\n\n```text\nQueueService\n```\n\n```text\nProjectService\n```\n\n```text\nforwardRef\n```\n\n```text\nprovider\n```\n\n```text\nProjectModule\n```\n\n```text\nQueueModule\n```\n\n```text\nforwardRef\n```\n\n```text\nUtilsModule\n```\n\n```text\nNotificationsModule\n```\n\n```text\nUserModule\n```\n\n========================================\n\nComments:\n- looks like you need to import the `ProjectModule` into `QueueModule`. Did you tried this? (just put `ProjectModule` in `imports` array)","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":308,"estimatedTokens":1566}}1067{"id":"stack-69545580","source":"stackoverflow","questionId":69545580,"title":"MongoDB and class-validator unique validation - NESTJS","tags":["javascript","typescript","mongoose","nestjs","class-validator"],"text":"Title: MongoDB and class-validator unique validation - NESTJS\nTags: javascript, typescript, mongoose, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\n### TL;DR\n\nI am trying to run mongoose query in my validator\n\nHello, I am trying to make a custom decorator which throws an error if a value for that field already exists. I am trying to use the mongoose model inside the class that validates the route. Unlike in resolver/controller, `@InjectModel()` does not work in validator class. My validator is like this\n\n```\nimport { getModelToken, InjectModel } from \"@nestjs/mongoose\";\nimport {\n ValidationArguments,\n ValidatorConstraint,\n ValidatorConstraintInterface,\n} from \"class-validator\";\nimport { Model } from \"mongoose\";\nimport { User } from \"../schema/user.schema\";\n\n@ValidatorConstraint({ name: \"IsUniqueUser\", async: true })\nexport class UniqueValidator implements ValidatorConstraintInterface {\n constructor(\n @InjectModel(User.name)\n private readonly userModel: Model,\n ) {}\n\n async validate(value: any, args: ValidationArguments) {\n const filter = {};\n\n console.log(this.userModel);\n console.log(getModelToken(User.name));\n filter[args.property] = value;\n const count = await this.userModel.count(filter);\n return !count;\n }\n\n defaultMessage(args: ValidationArguments) {\n return \"$(value) is already taken\";\n }\n}\n```\n\nand my DTO that uses the above decorator is\n\n```\n@InputType({})\nexport class UserCreateDTO {\n @IsString()\n name: string;\n\n @IsUniqueUser({\n message: \"Phone number is already taken\",\n })\n @Field(() => String)\n phone: string;\n}\n```\n\nThe console says\n`cannot read value count of undefined` implying that `userModel` is undefined.\n\n### InShort\n\nI want to run the query in my validator. How can I do so?\n\n========================================\n\nCode:\n```text\nimport { getModelToken, InjectModel } from \"@nestjs/mongoose\";\nimport {\n  ValidationArguments,\n  ValidatorConstraint,\n  ValidatorConstraintInterface,\n} from \"class-validator\";\nimport { Model } from \"mongoose\";\nimport { User } from \"../schema/user.schema\";\n\n@ValidatorConstraint({ name: \"IsUniqueUser\", async: true })\nexport class UniqueValidator implements ValidatorConstraintInterface {\n  constructor(\n    @InjectModel(User.name)\n    private readonly userModel: Model<User>,\n  ) {}\n\n  async validate(value: any, args: ValidationArguments) {\n    const filter = {};\n\n    console.log(this.userModel);\n    console.log(getModelToken(User.name));\n    filter[args.property] = value;\n    const count = await this.userModel.count(filter);\n    return !count;\n  }\n\n  defaultMessage(args: ValidationArguments) {\n    return \"$(value) is already taken\";\n  }\n}\n```\n\n```js\n@InputType({})\nexport class UserCreateDTO {\n  @IsString()\n  name: string;\n\n  @IsUniqueUser({\n    message: \"Phone number is already taken\",\n  })\n  @Field(() => String)\n  phone: string;\n}\n```\n\n```text\n@InjectModel()\n```\n\n```text\ncannot read value count of undefined\n```\n\n```text\nuserModel\n```\n\n```text\nimport { useContainer } from 'class-validator';\nuseContainer(app.select(AppModule), {fallbackOnErrors: true});\n```\n\n```text\n...\nproviders: [UniqueValidator],  \n...\n```\n\n```text\n@Validate(UniqueValidator, ['email'], {\n    message: 'emailAlreadyExists',\n  })\n```\n\n```text\nmain.ts\n```\n\n```text\nUniqueValidator\n```\n\n```text\n@Injectable()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":157,"estimatedTokens":822}}1068{"id":"stack-64337152","source":"stackoverflow","questionId":64337152,"title":"TypeORM make COUNT query on table which maps two tables together","tags":["mysql","database","nestjs","typeorm"],"text":"Title: TypeORM make COUNT query on table which maps two tables together\nTags: mysql, database, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities `Model` and `Video` where `Video` basically store information about videos and `Model` store information about model. Because each video can have multiple models and each model can have multiple video entities looks like this:\n\n### How my entites and tables looks like:\n\n```\n// Video Entity\n@Entity()\nexport class Video {\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n name: string;\n\n @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n description: string;\n\n @ManyToMany((type) => Model)\n @JoinTable()\n models: Model[];\n}\n\n// Model Entity\n@Entity()\nexport class Model {\n\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column()\n name: string;\n\n @Column()\n code: string;\n}\n```\n\nBecause there is relation `@ManyToMany` between model and video TypeORM also created one extra table for connecting this two. Table name is `video_models_model` and it looks like this:\n\n```\n+-----------+---------+\n| videoId | modelId |\n+===========+=========+\n| 1 | 107 |\n+-----------+---------+\n| 2 | 142 |\n+-----------+---------+\n| 3 | 91 |\n+-----------+---------+\n```\n\n### What I need:\n\nBased on modelId I need to find out `COUNT()` of videos.\nIn regular query language it would be something like:\n\n```\nSELECT model.*, COUNT(model_videos.videoId) as totalVideos FROM model as model\nLEFT JOIN `video_models_model` `model_videos` ON `model_videos`.`modelId`=`model`.`id` \nWHERE model.id = 1;\n```\n\n### What I tried:\n\nThis is how regular query would looks like:\n\n```\nthis.modelRepository\n .createQueryBuilder('model') \n .where('model.id = :id', { id: id }) \n .getOne();\n```\n\nso what I did was added to `Model` entity\n\n```\n@ManyToMany(type => Video)\n @JoinTable()\n videos: Video[];\n```\n\nand after that I tried\n\n```\nthis.modelRepository\n .createQueryBuilder('model')\n .leftJoin('model.videos', 'videos')\n .select('COUNT(videos)', 'totalVideos') \n .where('model.id = :id', { id: id }) \n .getOne();\n```\n\nBut it didn't work for me at all pluis it created one additional table named `model_videos_video` with `modelId` and `videoId` columns. So basically duplicate `video_models_model` table.\n\nIs there any way how to make that easy query with TypeORM?\n\n========================================\n\nCode:\n```text\n// Video Entity\n@Entity()\nexport class Video {\n  @PrimaryGeneratedColumn()\n  id?: number; \n\n  @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n  name: string;\n\n  @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n  description: string;\n\n  @ManyToMany((type) => Model)\n  @JoinTable()\n  models: Model[];\n}\n\n\n// Model Entity\n@Entity()\nexport class Model {\n\n  @PrimaryGeneratedColumn()\n  id?: number; \n\n  @Column()\n  name: string;\n\n  @Column()\n  code: string;\n}\n```\n\n```text\n+-----------+---------+\n| videoId   | modelId |\n+===========+=========+\n| 1         | 107     |\n+-----------+---------+\n| 2         | 142     |\n+-----------+---------+\n| 3         | 91      |\n+-----------+---------+\n```\n\n```text\nSELECT model.*, COUNT(model_videos.videoId) as totalVideos FROM model as model\nLEFT JOIN `video_models_model` `model_videos` ON `model_videos`.`modelId`=`model`.`id` \nWHERE model.id = 1;\n```\n\n```text\nthis.modelRepository\n  .createQueryBuilder('model')  \n  .where('model.id = :id', { id: id })        \n  .getOne();\n```\n\n```text\n@ManyToMany(type => Video)\n  @JoinTable()\n  videos: Video[];\n```\n\n```text\nthis.modelRepository\n  .createQueryBuilder('model')\n  .leftJoin('model.videos', 'videos')\n  .select('COUNT(videos)', 'totalVideos')  \n  .where('model.id = :id', { id: id })        \n  .getOne();\n```\n\n```text\nModel\n```\n\n```text\nVideo\n```\n\n```text\nVideo\n```\n\n```text\nModel\n```\n\n```text\n@ManyToMany\n```\n\n```text\nvideo_models_model\n```\n\n```text\nCOUNT()\n```\n\n```text\nModel\n```\n\n```text\nmodel_videos_video\n```\n\n```text\nmodelId\n```\n\n```text\nvideoId\n```\n\n```text\nvideo_models_model\n```\n\n```text\n@Entity()\nexport class Video {\n  @PrimaryGeneratedColumn()\n  id?: number; \n\n  @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n  name: string;\n\n  @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n  description: string;\n\n  @ManyToMany(type => Model, model => model.videos)\n  @JoinTable()\n  models: Model[];\n}\n```\n\n```text\n@Entity()\nexport class Model {\n\n  @PrimaryGeneratedColumn()\n  id?: number; \n\n  @Column()\n  name: string;\n\n  @Column()\n  code: string;\n\n  @ManyToMany(type => Video, video => video.models)\n  videos: Video[];\n}\n```\n\n```text\nthis.modelRepository\n  .createQueryBuilder('model')\n  .loadRelationCountAndMap('model.videoCount', 'model.videos')\n  .where('model.id = :id', { id: id })        \n  .getOne();\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":269,"estimatedTokens":1208}}1069{"id":"stack-69026231","source":"stackoverflow","questionId":69026231,"title":"NestJS: Type 'NestFastifyApplication' does not satisfy the constraint 'INestApplication'","tags":["node.js","typescript","nestjs","dependency-management","fastify"],"text":"Title: NestJS: Type 'NestFastifyApplication' does not satisfy the constraint 'INestApplication'\nTags: node.js, typescript, nestjs, dependency-management, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm building a back-end application with NestJS and I'm trying to use fastify instead of express as the underlying framework. I'm following the documentation (available here) to use fastify, however I got the following type issue:\n\n```\nType 'NestFastifyApplication' does not satisfy the constraint 'INestApplication'.\n\nType 'NestFastifyApplication' is missing the following properties from type\n'INestApplication': use, enableCors, enableVersioning, listenAsync, and 22 more\n```\n\nHere the code:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport {\n FastifyAdapter,\n NestFastifyApplication,\n} from '@nestjs/platform-fastify';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(\n AppModule,\n new FastifyAdapter(),\n );\n await app.listen(3001);\n}\nbootstrap();\n```\n\n========================================\n\nTop Answer:\nPS: If you have the following issue :\n\n```\nType 'NestFastifyApplication' does not satisfy the constraint 'INestApplication'.\n```\n\nPerhaps there is a compatibility versions issue of both @nestjs/platform-\nfastify and NestJS core packages, so run\n\n```\nyarn upgrade-interactive --latest\n```\n\nto update the dependencies to their last stable versions.\n\nThe ref : https://dev.to/ouelle/basic-crud-operations-with-nestjs-typescript-fastify-mongodb-1f1k\n\n========================================\n\nCode:\n```text\nType 'NestFastifyApplication' does not satisfy the constraint 'INestApplication'.\n\nType 'NestFastifyApplication' is missing the following properties from type\n'INestApplication': use, enableCors, enableVersioning, listenAsync, and 22 more\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport {\n  FastifyAdapter,\n  NestFastifyApplication,\n} from '@nestjs/platform-fastify';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter(),\n  );\n  await app.listen(3001);\n}\nbootstrap();\n```\n\n```text\nyarn remove @nestjs/platform-fastify\nyarn add @nestjs/platform-fastify\n```\n\n```text\n@nestjs/platform-fastify\n```\n\n```text\n@nestjs/common\n```\n\n```text\n@nestjs/core\n```\n\n```text\n@nestjs/platform-fastify or @nestjs/platform-express\n```\n\n```text\nType 'NestFastifyApplication<RawServerDefault>' does not satisfy the constraint 'INestApplication'.\n```\n\n```text\nyarn upgrade-interactive --latest\n```\n\n========================================\n\nComments:\n- @ErangaHeshan I know, but Stackoverflow requires me to wait 2 days\n- this doesn't solve my issue.\n- @Sisir do you have every package correctly installed?\n- Yeah, I ended up using express.\n- I had the same issue try `npm i`\n- Finally found a solution here : github.com/nestjs/nest/issues/4036#issuecomment-585790276 Basically ensure that `@nestjs&#47;common`, `@nestjs&#47;core`, and `@nestjs&#47;platform-{express&#47;fastify}` versions in package.json match\n- @JEFF has the solution that worked for me\n- @JEFF gave the right solution. This answer should be update.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":122,"estimatedTokens":803}}1070{"id":"stack-71470050","source":"stackoverflow","questionId":71470050,"title":"mongoose model.save() return TypeError: callback is not a function","tags":["node.js","typescript","mongodb","mongoose","nestjs"],"text":"Title: mongoose model.save() return TypeError: callback is not a function\nTags: node.js, typescript, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn my nestjs project I'm using mongoose and getting `TypeError: callback is not a function` while I'm trying to model.save().\n\n```\n\"@nestjs/common\": \"^8.0.0\",\n\"@nestjs/config\": \"^1.2.0\",\n\"@nestjs/core\": \"^8.0.0\",\n\"@nestjs/mongoose\": \"^9.0.2\",\n\"mongoose\": \"^6.2.6\",\n```\n\nIn my `tags.service.ts` for storing data I have this function:\n\n```\nasync create(createTagDto: CreateTagDto): Promise {\n return await new this.tagModel(createTagDto).save();\n}\n```\n\nAccording to Mongoose documentation by saving a document this should return a Promise.\n\nIn my `tags.controller.ts` I define endpoint by calling service function above by:\n\n```\n@Post()\nasync create(@Body() createTagDto: CreateTagDto) {\n return await this.tagsService.create(createTagDto);\n}\n```\n\nTrying to post data to the endpoint, the new document is created in the database but the server return `Internal server error` with status code 500. The only description in the console is above mentioned `TypeError: callback is not a function` somewhere in `node_modules/mongoose/lib/statemachine.js:137:14`.\n\nDoes anyone experienced such an issue?\n\n========================================\n\nTop Answer:\nTry changing this:\n\n```\nreturn await new this.tagModel(createTagDto).save();\n```\n\nto this\n\n```\nconst tag = await new this.tagModel.create(createTagDto);\nreturn tag.save();\n```\n\n========================================\n\nCode:\n```text\n\"@nestjs/common\": \"^8.0.0\",\n\"@nestjs/config\": \"^1.2.0\",\n\"@nestjs/core\": \"^8.0.0\",\n\"@nestjs/mongoose\": \"^9.0.2\",\n\"mongoose\": \"^6.2.6\",\n```\n\n```text\nasync create(createTagDto: CreateTagDto): Promise<Tag> {\n   return await new this.tagModel(createTagDto).save();\n}\n```\n\n```text\n@Post()\nasync create(@Body() createTagDto: CreateTagDto) {\n    return await this.tagsService.create(createTagDto);\n}\n```\n\n```text\nTypeError: callback is not a function\n```\n\n```text\ntags.service.ts\n```\n\n```text\ntags.controller.ts\n```\n\n```text\nInternal server error\n```\n\n```text\nTypeError: callback is not a function\n```\n\n```text\nnode_modules/mongoose/lib/statemachine.js:137:14\n```\n\n```text\napp.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))\n```\n\n```text\nreturn await new this.tagModel(createTagDto).save();\n```\n\n```text\nconst tag = await new this.tagModel.create(createTagDto);\nreturn tag.save();\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor(Res))\n@Post() {\n  return \"test\"\n}\n```\n\n```text\nMongooseClassSerializerInterceptor\n```\n\n========================================\n\nComments:\n- What does the `tagModel` method look like? The `new` on `new this.tagModel(createTagDto)` makes me wonder if it doesn't return a document, but instead something else with a `save` method (which then calls Mongoose's `save` but in a different way).\n- `tagModel` is imported Model from mongoose `import { Model } from 'mongoose';` and injected in a service constructor as such `constructor(@InjectModel(Tag.name) private tagModel: Model) {}`\n- It seems that the line `app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))` in the project `main.ts` file cause this error. I will explore more the reasons and answer the question with more detailed description.\n- Unfortunately the same result `TypeError: callback is not a function` in `node_modules&#47;mongoose&#47;lib&#47;statemachine.js:137:14`. Would it be a bug in mongoose statemachine.js? It seems that the callback is declared as an array and trying to use it as an function... `let states = [...arguments]; const callback = states.pop();` ... `return callback(path, i, paths);`\n- Could you some more details of how your custom interceptor properly serialized the mongo document to get around this issue?\n- As itโ€™s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":135,"estimatedTokens":1017}}1071{"id":"stack-67044809","source":"stackoverflow","questionId":67044809,"title":"Nestjs: Correct schema for array of subdocuments in mongoose (without default _id or redefine ObjectId)","tags":["node.js","mongodb","typescript","mongoose","nestjs"],"text":"Title: Nestjs: Correct schema for array of subdocuments in mongoose (without default _id or redefine ObjectId)\nTags: node.js, mongodb, typescript, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am working with Nest.js and trying to create a Schema with decorators which contain array of sub-document field.\n\nI don't have any troubles, with importing/export the Schema and converting it to a model, until:\n\nhttps://i.sstatic.net/rAou2.png\n\nI receive the following error in my `service` file.\n\nAfter hours of googling, I discover that the real reason is behind the `array` sub-document fields, and only with them. *As soon, as I remove the `members` field. the schema & model will be fine.* And have to do nothing with the solution described in following, or any other answers relevant with `extends Mongoose.Document`. (*If you have already done it*)\n\nMost of cases, that I found, are relevant with sub-documents, but not array sub-document. And I'd like to ask:\n\n### How to correctly create a field with an array of subdocuments in Nestjs via mongoose / Typescript with using of decorators?\n\nAnd unseed this error:\n\n```\nS2344: Type 'Guild' does not satisfy the constraint 'Document'. ย ย \n The types returned by 'delete(...).$where(...).cast(...)' are incompatible between these types.\n Type 'UpdateQuery' is not assignable to type 'UpdateQuery>'.\n Type 'UpdateQuery' is not assignable to type '_UpdateQuery>>>'.\nTypes of property '$pull' are incompatible.\n Type 'PullOperator>>' has no properties in common with type 'PullOperator>>>'.\n```\n\nMy Schema is:\n\n```\nimport { Document, Schema as MongooseSchema } from 'mongoose';\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\nclass GuildMember {\n @Prop({ type: String, required: true, lowercase: true })\n _id: string;\n\n @Prop({ required: true })\n id: number;\n\n @Prop({ required: true })\n rank: number;\n}\n\n@Schema({ timestamps: true })\nexport class Guild extends Document {\n @Prop({ type: String, required: true, lowercase: true })\n _id: string;\n\n @Prop({ type: MongooseSchema.Types.Array})\n members: GuildMember[]\n}\n\nexport const GuildsSchema = SchemaFactory.createForClass(Guild);\n```\n\n### What have I done.\n\nVarious ways including:\n\n- Cover sub-document `Class` with `@Schema()` decorator and adding `extends Document`\n\n- Adding `type:` to field `@Prop()` decorator:\n\n```\n@Prop({ type: [GuildMember] })\n members: GuildMember[]\n```\n\nor vice-versa. It's `ok` for primitives, but not for `Class` embedded documents.\n\n- adding `@Prop({ ref: () => GuildMember })`\n\nAnd following the official NestJs docs:\n\n```\n@Prop({ type: [{ type: MongooseSchema.Types.Array, ref: GuildMember }] })\n members: GuildMember[]\n```\n\nIt still doesn't help. I thought, that it could be relevant, not just with `mongoose.Document`, but also another type, which is: `mongoose.DocumentArray`\n\n### Updated:\n\nAccording to current progress. It seems that problem is relevant with the `field: type` value of default mongoose, not the `@Prop` decorator itself. So even if I write something like that:\n\n```\n@Prop()\n members: Types.Array\n```\n\nit still gives an error. Type is imported from: `import { Document, Schema as MongooseSchema, Types } from 'mongoose';`\n\n========================================\n\nTop Answer:\nYour `members` prop is not a simple array. It is a collection of sub docs and should be declared as `[SchemaTypes.ObjectId]` which will implement sub documents with `_id` field via default mongo `ObjectID` value:\n\n```\n@Prop({ type: [SchemaTypes.ObjectId], ref: 'GuildMember'})\nmembers: GuildMember[]\n```\n\n========================================\n\nCode:\n```text\nS2344: Type 'Guild' does not satisfy the constraint 'Document<any, {}>'. ย ย \n  The types returned by 'delete(...).$where(...).cast(...)' are incompatible between these types.\n   Type 'UpdateQuery<Guild>' is not assignable to type 'UpdateQuery<Document<any, {}>>'.\n     Type 'UpdateQuery<Guild>' is not assignable to type '_UpdateQuery<_AllowStringsForIds<LeanDocument<Document<any, {}>>>>'.\nTypes of property '$pull' are incompatible.\n  Type 'PullOperator<_AllowStringsForIds<LeanDocument<Guild>>>' has no properties in common with type 'PullOperator<_AllowStringsForIds<LeanDocument<Document<any, {}>>>>'.\n```\n\n```text\nimport { Document, Schema as MongooseSchema } from 'mongoose';\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\nclass GuildMember {\n  @Prop({ type: String, required: true, lowercase: true })\n  _id: string;\n\n  @Prop({ required: true })\n  id: number;\n\n  @Prop({ required: true })\n  rank: number;\n}\n\n@Schema({ timestamps: true })\nexport class Guild extends Document {\n  @Prop({ type: String, required: true, lowercase: true })\n  _id: string;\n\n  @Prop({ type: MongooseSchema.Types.Array})\n  members: GuildMember[]\n}\n\nexport const GuildsSchema = SchemaFactory.createForClass(Guild);\n```\n\n```text\n@Prop({ type: [GuildMember] })\n  members: GuildMember[]\n```\n\n```text\n@Prop({ type: [{ type: MongooseSchema.Types.Array, ref: GuildMember }] })\n  members: GuildMember[]\n```\n\n```text\n@Prop()\n  members: Types.Array<GuildMember>\n```\n\n```text\nservice\n```\n\n```text\narray\n```\n\n```text\nmembers\n```\n\n```text\nextends Mongoose.Document\n```\n\n```text\nClass\n```\n\n```text\n@Schema()\n```\n\n```text\nextends Document\n```\n\n```text\ntype:\n```\n\n```text\n@Prop()\n```\n\n```text\nok\n```\n\n```text\nClass\n```\n\n```text\n@Prop({ ref: () => GuildMember })\n```\n\n```text\nmongoose.Document\n```\n\n```text\nmongoose.DocumentArray\n```\n\n```text\nfield: type\n```\n\n```text\n@Prop\n```\n\n```text\nimport { Document, Schema as MongooseSchema, Types } from 'mongoose';\n```\n\n```text\nimport { Document, Schema as MongooseSchema, Types } from \"mongoose\";\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\n\n@Schema()\nclass Pet extends Document  {\n  @Prop({ type: Number })\n  _id: number;\n\n  @Prop({ type: String })\n  name: string;\n}\n\nexport const PetsSchema = SchemaFactory.createForClass(Pet);\n```\n\n```text\n@Prop({ type: [PetsSchema] })\n  pets: Types.Array<Pet>;\n```\n\n```text\n@Prop({ _id: false, type: [PetsSchema] })\n  pets: Types.Array<Pet>;\n```\n\n```text\nObjectId\n```\n\n```text\n@Prop\n```\n\n```text\n_id\n```\n\n```text\n@Prop({ type: [SchemaTypes.ObjectId], ref: 'GuildMember'})\nmembers: GuildMember[]\n```\n\n```text\nmembers\n```\n\n```text\n[SchemaTypes.ObjectId]\n```\n\n```text\n_id\n```\n\n```text\nObjectID\n```\n\n========================================\n\nComments:\n- Okey, I have also found an answer for this question (should post it in couple of hours), but what I do want to use `SchemaTypes.ObjectId` for `_id` field for my `array of objects&#47;docs`? Is there any option, like: `_id: false` ?\n- I dont get your question, sorry. Could be you be more specific ?\n- I mean that, as far as I know, an array of documents can use *build-in _id field with generated Object_id values by mongo itself*. In my case, I generate the `_id` field for subdocuments by myself and don't want to generate it by mongo. So my question is: **How with this solution achieve non generated, but manual determination of `_id` for sub-documents?**\n- I don't know if there is a way to do that within mongoose. Maybe use some 3rd party lib like `class-transformer` ? see some use-cases in nestjs doc: docs.nestjs.com/techniques/serialization\n- Hmm, I haven't seen this before. It deserves to take a look.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":295,"estimatedTokens":1815}}1072{"id":"stack-61214198","source":"stackoverflow","questionId":61214198,"title":"TypeOrm query builder","tags":["nestjs","typeorm"],"text":"Title: TypeOrm query builder\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI can't figure out how to write the following MySql statement using TypeOrm Query Builder\n\n SELECT reg.id FROM farm.reg WHERE grpId = 'ABC';\n\nthis select is returning just the id's but my query builder is returning the entire objects.\n\nIn this moment I have this function in my NestJs service but I need to use 'map' and I don't want to..\n\n```\nasync getGrupIds(entity: string, grpId: string) {\n\n console.log(entity, grpId);\n const ids = await getRepository(reg)\n .createQueryBuilder(entity)\n .where('reg.grpId = :grpId', {grpId: grpId})\n .getMany();\n console.log(ids);\n return ids.map(o => o.id);\n\n }\n```\n\nThank you\n\n========================================\n\nCode:\n```text\nasync getGrupIds(entity: string, grpId: string) {\n\n        console.log(entity, grpId);\n        const ids = await getRepository(reg)\n        .createQueryBuilder(entity)\n        .where('reg.grpId = :grpId', {grpId: grpId})\n        .getMany();\n        console.log(ids);\n        return ids.map(o => o.id);\n\n    }\n```\n\n```text\n//I suppose you have a *grpId* variable in your function \n\nconst ids = await getRepository(Reg)\n    .createQueryBuilder('reg')\n    .select('reg.grpId', 'id')\n    .where('reg.grpId = :grpId', { grpId } )\n    .getRawMany();\n    console.log(ids);\n    return ids    \n}\n```\n\n========================================\n\nComments:\n- async getGroupIds(entity: string, grpId: string) { const ids = await getRepository(reg) .createQueryBuilder(entity) .select('reg.id') .where('reg.grpId = :grpId', {grpId: grpId}) .getRawMany(); console.log(ids); // return ids.map(o => o.id); return ids } works like a charm, many thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":423}}1073{"id":"stack-55323943","source":"stackoverflow","questionId":55323943,"title":"NestJS: Using forRoot / forChild in custom module - race condition?","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: NestJS: Using forRoot / forChild in custom module - race condition?\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nRepo is available here to highlight the issue.\n\nI am having a problem with a race condition. I have created a `ConfigModule` - this has a `forRoot` and a `forChild`.\n\nThe `forRoot` sets up the loading of the `.env` file and the `forChild` uses it in another module.\n\nThe problem is that `forChild` is called before `forRoot`. The `ConfigService` would be injected with missing config because `forRoot` hasn't executed first.\n\n```\n> AppModule > ConfigModule.forRoot InstanceModule >\n> ConfigModule.forChild\n```\n\nI placed some simple `console.log` commands that output this\n\n```\nI am in Config Module FOR CHILD\nI am in Config Module FOR ROOT\n```\n\nAs you can see the `forChild` is being executed first, I tried using `forwardRef` and that didn't work.\n\nIf you let the application run you will see\n\n```\n[2019-03-24T11:49:33.602] [ERROR] ConfigService - There are missing mandatory configuration: Missing PORT\n[2019-03-24T11:49:33.602] [FATAL] ConfigService - Missing mandatory configuration, cannot continue!, exiting\n```\n\nThis is because I check that some `process.env` are available which are loaded in via `dotenv`. Of course, because the `forRoot` isn't executed first then the `forChild` returns its own new instance of the `ConfigService`.\n\n`ConfigService` validates the availability of the environment variables.\n\nSo, basically, the `forChild` is executing and returning its own `ConfigService` before `forRoot`.\n\nTO make it work, if you comment out the `InstanceModule` inside the `AppModule` then it will automatically start listening and returns the port number from an environment variable.\n\nOf course, because `InstanceModule` uses the `forChild` - there is a race condition.\n\n========================================\n\nCode:\n```text\n> AppModule > ConfigModule.forRoot InstanceModule >\n> ConfigModule.forChild\n```\n\n```text\nI am in Config Module  FOR CHILD\nI am in Config Module  FOR ROOT\n```\n\n```text\n[2019-03-24T11:49:33.602] [ERROR] ConfigService - There are missing mandatory configuration: Missing PORT\n[2019-03-24T11:49:33.602] [FATAL] ConfigService - Missing mandatory configuration, cannot continue!, exiting\n```\n\n```text\nConfigModule\n```\n\n```text\nforRoot\n```\n\n```text\nforChild\n```\n\n```text\nforRoot\n```\n\n```text\n.env\n```\n\n```text\nforChild\n```\n\n```text\nforChild\n```\n\n```text\nforRoot\n```\n\n```text\nConfigService\n```\n\n```text\nforRoot\n```\n\n```text\nconsole.log\n```\n\n```text\nforChild\n```\n\n```text\nforwardRef\n```\n\n```text\nprocess.env\n```\n\n```text\ndotenv\n```\n\n```text\nforRoot\n```\n\n```text\nforChild\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\nforChild\n```\n\n```text\nConfigService\n```\n\n```text\nforRoot\n```\n\n```text\nInstanceModule\n```\n\n```text\nAppModule\n```\n\n```text\nInstanceModule\n```\n\n```text\nforChild\n```\n\n```text\nforRoot\n```\n\n```text\nforChild\n```\n\n```text\nConfigModule\n```\n\n```text\nConfigService\n```\n\n```text\n.env\n```\n\n```text\nnestjs/typeorm\n```\n\n```text\nTypeOrmCoreModule\n```\n\n```text\nTypeOrmModule.forRoot\n```\n\n```text\nTypeOrmModule.forChild\n```\n\n```text\n@Global\n```\n\n```text\nforChild\n```\n\n```text\nConfigModule\n```\n\n```text\nforChild()\n```\n\n```text\nConfigService\n```\n\n```text\nAppModule\n```\n\n```text\nonModuleInit\n```\n\n========================================\n\nComments:\n- Can you post the link to your repo?\n- Sorry my bad, I forgot to paste it :-) Updated it now.\n- Great explanation, I tested it and it works. And Thanks for explaining the forRoot and forChild - its now much more clearer.","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":45,"totalLines":236,"estimatedTokens":894}}1074{"id":"stack-55953780","source":"stackoverflow","questionId":55953780,"title":"NestJS With supertest doesn't compile with 'Cannot invoke an expression whose type lacks a call signature'","tags":["typescript","nestjs"],"text":"Title: NestJS With supertest doesn't compile with 'Cannot invoke an expression whose type lacks a call signature'\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen trying to run e2e tests from the NestJS examples, my test does not compile with 'Cannot invoke an expression whose type lacks a call signature' for the line\n\n```\nrequest(app.getHttpServer())\n```\n\nCode is from the NestJS testing examples.\n\nIt might have to do with my tsconfig?\n\n```\nimport * as request from \"supertest\";\nimport { Test } from \"@nestjs/testing\";\nimport { INestApplication } from \"@nestjs/common\";\n\ndescribe(\"App\", () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const module = await Test.createTestingModule({\n imports: []\n }).compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n it(`/GET`, () => {\n return request(app.getHttpServer())\n .get(\"/\")\n .expect(200);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\n========================================\n\nTop Answer:\nYou must import the module.\n\n```\nimport * as request from \"supertest\";\nimport { Test } from \"@nestjs/testing\";\nimport { INestApplication } from \"@nestjs/common\";\nimport { AppModule } from '../src/app.module';\n\ndescribe(\"App\", () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const module = await Test.createTestingModule({\n imports: [AppModule] // {\n return request(app.getHttpServer())\n .get(\"/\")\n .expect(200);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\n========================================\n\nCode:\n```text\nrequest(app.getHttpServer())\n```\n\n```text\nimport * as request from \"supertest\";\nimport { Test } from \"@nestjs/testing\";\nimport { INestApplication } from \"@nestjs/common\";\n\ndescribe(\"App\", () => {\n  let app: INestApplication;\n\n  beforeAll(async () => {\n    const module = await Test.createTestingModule({\n      imports: []\n    }).compile();\n\n    app = module.createNestApplication();\n    await app.init();\n  });\n\n  it(`/GET`, () => {\n    return request(app.getHttpServer())\n      .get(\"/\")\n      .expect(200);\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n```\n\n```text\nimport request from \"supertest\";\n```\n\n```text\nimport * as request from \"supertest\";\nimport { Test } from \"@nestjs/testing\";\nimport { INestApplication } from \"@nestjs/common\";\nimport { AppModule } from '../src/app.module';\n\ndescribe(\"App\", () => {\n  let app: INestApplication;\n\n  beforeAll(async () => {\n    const module = await Test.createTestingModule({\n      imports: [AppModule] // <- this\n    }).compile();\n\n    app = module.createNestApplication();\n    await app.init();\n  });\n\n  it(`/GET`, () => {\n    return request(app.getHttpServer())\n      .get(\"/\")\n      .expect(200);\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n```\n\n========================================\n\nComments:\n- This fixed it: import request from \"supertest\";","metadata":{"transformedAt":"2026-08-18T18:33:02.574Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":146,"estimatedTokens":724}}1075{"id":"stack-56721356","source":"stackoverflow","questionId":56721356,"title":"Set \"basedir\" option for Pug in NestJS","tags":["node.js","pug","nestjs"],"text":"Title: Set \"basedir\" option for Pug in NestJS\nTags: node.js, pug, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use `pug` layouts in `NestJS`, however when extending a layout from an absolute path, `pug` requires the `basedir` option to be set.\n\nIn ExpressJS you would use `app.locals.basedir = ...`, what would be the equivalent in NestJS?\n\n```\nconst server = await NestFactory.create(AppModule);\nserver.setViewEngine('pug');\nserver.setBaseViewsDir(join(__dirname, 'templates', 'views'));\nawait server.listen(config.server.port);\n```\n\nUsing `extends /layouts/index` in a view would throw the following; `the \"basedir\" option is required to use includes and extends with \"absolute\" paths`.\n\nI'm not looking to use relative paths, since this quickly becomes very messy. E.g. `extends ../../../layouts/index`\n\n========================================\n\nTop Answer:\nFrom what I can tell, you can achieve the same functionality as `/layouts/index` with just using `layout/index` so long as `layout` is a folder in your `templates/views` directory. \n\nI've set up a git repo as a working example so you can test it out yourself and see if I need to go in more depth about anything.\n\n**EDIT** 6/27/2019:\n\nThank you, I misunderstood your initial question.\n\nWith creating and express based application, you can send an `express server` to the `NestFactory` to use that server instance instead of having Nest create a plain instance for you. From here you can set up the `express server` as you normally would and get the desired functionality. I've modified the git repo to be able to test the scenario better and believe this is what you are looking for.\n\nMy `main.ts`\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { NestExpressApplication, ExpressAdapter } from '@nestjs/platform-express';\nimport * as express from 'express';\nimport { AppModule } from './app.module';\nimport { join } from 'path';\n\nasync function bootstrap() {\n // Creating and setting up the express instanced server\n const server = express();\n server.locals.basedir = join(__dirname, '..', 'views');\n // Using the express server instance in the nest factory\n const app = await NestFactory.create(AppModule, new ExpressAdapter(server));\n app.useStaticAssets(join(__dirname, '..', 'public'));\n app.setBaseViewsDir(join(__dirname, '..', 'views'));\n app.setViewEngine('pug');\n await app.listen(3000);\n}\nbootstrap();\n```\n\nOverall the folder set up is like so\n\n```\nsrc\n|-app.controller.ts\n|-app.module.ts\n|-app.service.ts\n|-main.ts\nviews\n|-hello\n |-home.pug\n|-message\n |-message.pug\n|-templates\n |-layout.pug\n```\n\nAnd the beginning of my `home.pug` and `message.pug` files is `extends /templates/layout`\n\n========================================\n\nCode:\n```text\nconst server = await NestFactory.create<NestExpressApplication>(AppModule);\nserver.setViewEngine('pug');\nserver.setBaseViewsDir(join(__dirname, 'templates', 'views'));\nawait server.listen(config.server.port);\n```\n\n```text\npug\n```\n\n```text\nNestJS\n```\n\n```text\npug\n```\n\n```text\nbasedir\n```\n\n```text\napp.locals.basedir = ...\n```\n\n```text\nextends /layouts/index\n```\n\n```text\nthe \"basedir\" option is required to use includes and extends with \"absolute\" paths\n```\n\n```text\nextends ../../../layouts/index\n```\n\n```text\nconst express = server.getHttpAdapter().getInstance();\nexpress.locals.basedir = join(__dirname, 'templates');\n```\n\n```text\ngetHttpAdapter().getInstance()\n```\n\n```text\nbasedir\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { NestExpressApplication, ExpressAdapter } from '@nestjs/platform-express';\nimport * as express from 'express';\nimport { AppModule } from './app.module';\nimport { join } from 'path';\n\nasync function bootstrap() {\n  // Creating and setting up the express instanced server\n  const server = express();\n  server.locals.basedir = join(__dirname, '..', 'views');\n  // Using the express server instance in the nest factory\n  const app = await NestFactory.create<NestExpressApplication>(AppModule, new ExpressAdapter(server));\n  app.useStaticAssets(join(__dirname, '..', 'public'));\n  app.setBaseViewsDir(join(__dirname, '..', 'views'));\n  app.setViewEngine('pug');\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nsrc\n|-app.controller.ts\n|-app.module.ts\n|-app.service.ts\n|-main.ts\nviews\n|-hello\n  |-home.pug\n|-message\n  |-message.pug\n|-templates\n  |-layout.pug\n```\n\n```text\n/layouts/index\n```\n\n```text\nlayout/index\n```\n\n```text\nlayout\n```\n\n```text\ntemplates/views\n```\n\n```text\nexpress server\n```\n\n```text\nNestFactory\n```\n\n```text\nexpress server\n```\n\n```text\nmain.ts\n```\n\n```text\nhome.pug\n```\n\n```text\nmessage.pug\n```\n\n```text\nextends /templates/layout\n```\n\n========================================\n\nComments:\n- Thanks for your answer, but like I indicated in the question, Iโ€™m not looking to use relative paths.\n- You're right! I totally misinterpreted that. See the edit for an updated answer.\n- Saw your edit a bit late, but you're right, however Nest will create it's own Express instance that you can access with `getHttpAdapter().getInstance()`, from there you're able to set the `locals.basedir`.\n- Both are viable options. Nest will create its own instance if one is not already passed to it. I saw Kamil respond to your GitHub issue with the `getHttpAdatper().getInstance()`. I think that overall is a better approach, but it is nice to know both work.","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":217,"estimatedTokens":1335}}1076{"id":"stack-61733060","source":"stackoverflow","questionId":61733060,"title":"Unit testing NestJS controller with injection","tags":["typescript","unit-testing","testing","dependency-injection","nestjs"],"text":"Title: Unit testing NestJS controller with injection\nTags: typescript, unit-testing, testing, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI need to make an unit test for a controller who use injection with NestJS.\n\nI don't know how to mock and spy this service (MyEmitter).\nI need to declare it in test.controller.spec.ts inside beforeEach() but how ?\n\n**test.controller.ts**\n\n```\nimport {\n Controller,\n Body,\n Post,\n} from '@nestjs/common';\nimport {\n WebhookDto,\n} from './dto/webhook.dto';\nimport { MyEmitter } from './test.events';\nimport { InjectEventEmitter } from 'nest-emitter';\n\n@Controller()\nexport class TestController {\n constructor(\n @InjectEventEmitter() private readonly myEmitter: MyEmitter,\n ) {}\n\n @Post('webhook')\n public async postWebhook(\n @Body() webhookDto: WebhookDto,\n ): Promise {\n ...\n this.myEmitter.emit('webhook', webhookDto);\n }\n}\n```\n\n**test.controller.spec.ts**\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TestController } from './test.controller';\nimport EventEmitter = require('events');\nimport { EVENT_EMITTER_TOKEN } from 'nest-emitter';\nimport { MyEmitter } from './test.events';\n\ndescribe('Test Controller', () => {\n let testController: TestController;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [],\n providers: [\n {\n provide: EVENT_EMITTER_TOKEN,\n useValue: {\n emit: jest.fn(),\n },\n },\n ],\n controllers: [TestController],\n }).compile();\n\n testController = module.get(TetsController);\n });\n\n describe('postWebhook', () => {\n it('should send the event', async () => {\n const myEmitterSpy = jest.spyOn(myEmitter, 'emit');\n const result = await testController.postWebhook({...});\n expect(myEmitterSpy).toBeCalledTimes(1);\n });\n });\n});\n```\n\nThank you really much for your help.\n\n========================================\n\nTop Answer:\nRather than injecting every dependencies (which should be tested separately), it is better to use jest.spyOn because controller has a service dependency or dependencies which might have other dependencies.\n\nWe should mock the method that will be called in the current test.\n\nHere is the sample controller test.\n\n```\nimport { SampleController } from './sample.controller';\nimport { SampleService } from './sample.service';\n\ndescribe('SampleController', () => {\n let sampleController: SampleController;\n let sampleService: SampleService;\n\n beforeEach(() => {\n // SampleService depends on a repository class\n // Passing null becasue SampleService will be mocked\n // So it does not need any dependencies.\n sampleService = new SampleService(null);\n // SampleController has one dependency SampleService\n sampleController = new SampleController(sampleService);\n });\n\n it('should be defined', async () => {\n expect(sampleController).toBeDefined();\n });\n\n describe('findAll', () => {\n it('should return array of samples', async () => {\n // Response of findAllByQuery Method\n // findAllByQUeryParams is a method of SampleService class.\n // I want the method to return an array containing 'test' value'.\n const expectedResult = ['test'];\n\n // Creating the mock method\n // The method structure is the same as the actual method structure.\n const findAllByQueryParamsMock = async (query: any) => expectedResult;\n\n // I am telling jest to spy on the findAllByQueryParams method\n // and run the mock method when the findAllByQueryParams method is called in the controller.\n jest\n .spyOn(sampleService, 'findAllByQueryParams')\n .mockImplementation(findAllByQueryParamsMock);\n\n const actualResult = await sampleController.findAll({});\n\n expect(actualResult).toBe(expectedResult);\n });\n });\n});\n```\n\n========================================\n\nCode:\n```text\nimport {\n  Controller,\n  Body,\n  Post,\n} from '@nestjs/common';\nimport {\n  WebhookDto,\n} from './dto/webhook.dto';\nimport { MyEmitter } from './test.events';\nimport { InjectEventEmitter } from 'nest-emitter';\n\n@Controller()\nexport class TestController {\n  constructor(\n    @InjectEventEmitter() private readonly myEmitter: MyEmitter,\n  ) {}\n\n  @Post('webhook')\n  public async postWebhook(\n    @Body() webhookDto: WebhookDto,\n  ): Promise<void> {\n    ...\n    this.myEmitter.emit('webhook', webhookDto);\n  }\n}\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TestController } from './test.controller';\nimport EventEmitter = require('events');\nimport { EVENT_EMITTER_TOKEN } from 'nest-emitter';\nimport { MyEmitter } from './test.events';\n\ndescribe('Test Controller', () => {\n  let testController: TestController;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports: [],\n      providers: [\n        {\n          provide: EVENT_EMITTER_TOKEN,\n          useValue: {\n            emit: jest.fn(),\n          },\n        },\n      ],\n      controllers: [TestController],\n    }).compile();\n\n    testController = module.get<TestController>(TetsController);\n  });\n\n  describe('postWebhook', () => {\n    it('should send the event', async () => {\n      const myEmitterSpy = jest.spyOn(myEmitter, 'emit');\n      const result = await testController.postWebhook({...});\n      expect(myEmitterSpy).toBeCalledTimes(1);\n    });\n  });\n});\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TestController } from './test.controller';\nimport EventEmitter = require('events');\nimport { EVENT_EMITTER_TOKEN } from 'nest-emitter';\nimport { MyEmitter } from './test.events';\n\ndescribe('Test Controller', () => {\n  let testController: TestController;\n  let myEmitter: MyEmitter;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports: [],\n      providers: [\n        {\n          provide: EVENT_EMITTER_TOKEN,\n          useValue: {\n            emit: jest.fn(),\n          },\n        },\n      ],\n      controllers: [TestController],\n    }).compile();\n\n    testController = module.get<TestController>(TetsController);\n    myEmitter = module.get<MyEmitter>(EVENT_EMITTER_TOKEN);\n  });\n\n  describe('postWebhook', () => {\n    it('should send the event', async () => {\n      const myEmitterSpy = jest.spyOn(myEmitter, 'emit'); // you can also add on mockResponse type functions here like mockReturnValue and mockResolvedValue\n      const result = await testController.postWebhook({...});\n      expect(myEmitterSpy).toBeCalledTimes(1);\n    });\n  });\n});\n```\n\n```text\nmodule.get()\n```\n\n```text\nEVENT_EMITTER_TOKEN\n```\n\n```text\ndescribe\n```\n\n```text\nlet testController: TestController\n```\n\n```text\nimport { SampleController } from './sample.controller';\nimport { SampleService } from './sample.service';\n\ndescribe('SampleController', () => {\n  let sampleController: SampleController;\n  let sampleService: SampleService;\n\n  beforeEach(() => {\n    // SampleService depends on a repository class\n    // Passing null becasue SampleService will be mocked\n    // So it does not need any dependencies.\n    sampleService = new SampleService(null);\n    // SampleController has one dependency SampleService\n    sampleController = new SampleController(sampleService);\n  });\n\n  it('should be defined', async () => {\n    expect(sampleController).toBeDefined();\n  });\n\n  describe('findAll', () => {\n    it('should return array of samples', async () => {\n      // Response of findAllByQuery Method\n      // findAllByQUeryParams is a method of SampleService class.\n      // I want the method to return an array containing 'test' value'.\n      const expectedResult = ['test'];\n\n      // Creating the mock method\n      // The method structure is the same as the actual method structure.\n      const findAllByQueryParamsMock = async (query: any) => expectedResult;\n\n      // I am telling jest to spy on the findAllByQueryParams method\n      // and run the mock method when the findAllByQueryParams method is called in the controller.\n      jest\n        .spyOn(sampleService, 'findAllByQueryParams')\n        .mockImplementation(findAllByQueryParamsMock);\n\n      const actualResult = await sampleController.findAll({});\n\n      expect(actualResult).toBe(expectedResult);\n    });\n  });\n});\n```\n\n========================================\n\nComments:\n- Thank you very much !! Your solution works well. So simple finally :)\n- If you're looking for more examples, I've got an entire repository that you can look at\n- Thank you for the link and for this repository. It will be helpfull !","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":311,"estimatedTokens":2096}}1077{"id":"stack-58983404","source":"stackoverflow","questionId":58983404,"title":"Retrieve data from RxJS observable in HttpModule","tags":["rxjs","axios","observable","nestjs"],"text":"Title: Retrieve data from RxJS observable in HttpModule\nTags: rxjs, axios, observable, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am failing to understand how to `map` the data properties out of `HttpService` in my NestJS application. To my understanding, this `Observable` just wraps `axios`. Here's some example code:\n\n```\ninterface Todo {\n task: string,\n completed: false\n}\n\nimport {\n Injectable,\n HttpService,\n Logger,\n NotFoundException,\n} from '@nestjs/common'\nimport { map } from 'rxjs/operators\n\nasync getTodo(todoUrl: string): Todo {\n const resp = this.httpService\n .get('https://example.com/todo_json')\n .pipe(map(response => response.data)) // map task/completed properties?\n return resp\n}\n```\n\n`resp` in this case seems to be of type `Observable`. How do I retrieve just the data properties I want using `map` on this request to return my `Todo` interface?\n\n========================================\n\nTop Answer:\nLooking at your code:\n\n```\nimport { map } from 'rxjs/operators' \n\nasync getTodo(todoUrl: string): Todo {\n const resp = this.httpService\n .get('https://example.com/todo_json')\n .pipe(map(response => response.data)) // map task/completed properties?\n return resp\n}\n```\n\n`getTodo` returns an Observable, not the response. So your return value should be `Observable`.\n\nThe code should look more like this:\n\n```\ngetTodo(): Observable {\n return this.http.get('https://example.com/todo_json')\n .pipe(\n map(response => response.data),\n catchError(this.handleError)\n );\n }\n```\n\nEDIT: You can't just return the data from this method because it is asynchronous. It does not have the data yet. The method returns an Observable ... which is basically a contract saying that it will (at some later time) return the data for you.\n\n========================================\n\nCode:\n```text\ninterface Todo {\n   task: string,\n   completed: false\n}\n\nimport {\n  Injectable,\n  HttpService,\n  Logger,\n  NotFoundException,\n} from '@nestjs/common'\nimport { map } from 'rxjs/operators\n\nasync getTodo(todoUrl: string): Todo {\n   const resp = this.httpService\n      .get('https://example.com/todo_json')\n      .pipe(map(response => response.data)) // map task/completed properties?\n   return resp\n}\n```\n\n```text\nmap\n```\n\n```text\nHttpService\n```\n\n```text\nObservable\n```\n\n```text\naxios\n```\n\n```text\nresp\n```\n\n```text\nObservable\n```\n\n```text\nmap\n```\n\n```text\nTodo\n```\n\n```js\n@Injectable()\nexport class TodoService {\n\n  constructor(private readonly http: HttpService) {}\n\n  getTodos(todoUrl: string): Observable<Todo> {\n    return this.http.get(todoUrl).pipe(\n      map(resp => resp.data),\n    );\n  }\n\n}\n```\n\n```js\n@Injectable()\nexport class TodoService {\n\n  constructor(private readonly http: HttpService) {}\n\n  getTodos(todoUrl: string): Todo {\n    const myTodo = await this.http.get(todoUrl).pipe(\n      map(resp => resp.data),\n    ).toPromise();\n    return myTodo;\n  }\n\n}\n```\n\n```js\n@Injectable()\nexport class TodoService {\n\n  constructor(private readonly http: HttpService) {}\n\n  getTodos(todoUrl: string): Todo {\n    const myTodo = await lastValueFrom(this.http.get(todoUrl).pipe(\n      map(resp => resp.data),\n    ));\n    return myTodo;\n  }\n\n}\n```\n\n```text\nthis.todoSerivce.getTodos(todoUrl)\n```\n\n```text\n.toPromise()\n```\n\n```text\n.toPromise()\n```\n\n```text\nRxJS@^7\n```\n\n```text\ntoPromise()\n```\n\n```text\nv8\n```\n\n```text\nlastValueFrom\n```\n\n```text\nimport { map } from 'rxjs/operators' \n\nasync getTodo(todoUrl: string): Todo {\n   const resp = this.httpService\n      .get('https://example.com/todo_json')\n      .pipe(map(response => response.data)) // map task/completed properties?\n   return resp\n}\n```\n\n```text\ngetTodo(): Observable<Todo> {\n    return this.http.get<Todo>('https://example.com/todo_json')\n      .pipe(\n        map(response => response.data),\n        catchError(this.handleError)\n      );\n  }\n```\n\n```text\ngetTodo\n```\n\n```text\nObservable<Todo>\n```\n\n```text\nasync getTodo(todoUrl: string): Todo {\n   const resp = this.httpService\n      .get('https://example.com/todo_json')\n      .pipe(map(response => response.data)) // map task/completed properties?\n   return resp.toPromise();\n}\n```\n\n```text\nasync getTodo(todoUrl: string): Todo {\n    const resp = await this.httpService\n      .get('https://example.com/todo_json')\n      .toPromise();\n    return resp.data;\n}\n```\n\n========================================\n\nComments:\n- You have to subscribe to the Observable.\n- I understand it returns an Observable. Maybe I need to make my question more clear - I just want to return a Todo, based on my interface specified in the question. I do not wish to return an Observable. I want to retrieve that data from the Observable and return that instead as the method interface suggests.\n- how do you import `map`?\n- I updated the example above ... but it looks like someone else already answered your query in the prior answer.\n- Where in the NestJS documentation does it suggest that the framework subscribes to Observables for you? Also, is there a way to return just the `Todo` with the properties I want without the Observable?\n- It talks about it in the asynchronicity section of the controller. Like I said though, if you just want to return the `Todo` interface without returning the observable, tack on a `.toPromise()` and await the observable, setting it to some constant (you can still do the `map` and `pipe` operations). Then you can just `return myTodo;`. I'll make an update to show further\n- This is great. Mind if I ask how to use map to just retrieve the properties I want from `resp`? in this case, task and completed?\n- That kinda depends on what is completely sent back by the api, and without that information it's hard to say how to map things down. But, `map` is just a function so you could expand it out to take on a fuller form and do whatever transformations you need\n- how do you import `map`?\n- @jim `import { map } from 'rxjs&#47;operators'`","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":255,"estimatedTokens":1468}}1078{"id":"stack-55226176","source":"stackoverflow","questionId":55226176,"title":"How can I define mutations or queries without any parameters in graphql?","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: How can I define mutations or queries without any parameters in graphql?\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a problem with graphql:\n\n```\ntype Mutation {\n clearEsLog(): string\n clearRabbit(): string\n}\n```\n\nI use Nestjs and when I run the app the error is:\n\n UnhandledPromiseRejectionWarning: Syntax Error: Expected Name, found )\n\n========================================\n\nCode:\n```text\ntype Mutation {\n    clearEsLog(): string\n    clearRabbit(): string\n}\n```\n\n```text\ntype Mutation {\n    clearEsLog: string\n    clearRabbit: string\n}\n```\n\n```text\n()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":38,"estimatedTokens":155}}1079{"id":"stack-55091698","source":"stackoverflow","questionId":55091698,"title":"NestJs + Passport - JWTStrategy never being called with RS256 tokens","tags":["javascript","jwt","passport.js","nestjs","passport-jwt"],"text":"Title: NestJs + Passport - JWTStrategy never being called with RS256 tokens\nTags: javascript, jwt, passport.js, nestjs, passport-jwt\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement RS256 JWT tokens in nestjs backend. I followed the example provided in nestjs documentation. \n\nIn my module I register the `JwtModule` with my private key:\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.key`),\n signOptions: {\n expiresIn: 3600,\n },\n }),\n ],\n controllers: [AuthController],\n providers: [AuthService, JwtStrategy, HttpStrategy],\n})\nexport class AuthModule {}\n```\n\nI'm able to call auth/token endpoint and get the token but when I try to access guarded endpoint I always get 401. \n\nBelow you can find my custom `JwtStrategy`:\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: extractKey(`${process.cwd()}/keys/jwt.public.key`),\n });\n }\n\n async validate(payload: JwtPayload) {\n console.log('JwtStrategy');\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\nAnd guarded endpoint:\n\n```\n@Controller('auth')\nexport class AuthController {\n constructor(private readonly authService: AuthService) {}\n\n @Get('token')\n async createToken(): Promise {\n return await this.authService.createToken();\n }\n\n @Get('data')\n @UseGuards(AuthGuard())\n findAll() {\n console.log('Guarded endpoint');\n // This route is restricted by AuthGuard\n // JWT strategy\n }\n}\n```\n\nI assume that when I call the auth/data I should see in the console at least the \"JwtStrategy\" string that I log in the validate method. Unfortunately it never shows up. Why the validate method is never called?\n\nPlease find the codesandbox below\n\nhttps://codesandbox.io/s/8n1ojrmp8?fontsize=14\n\n========================================\n\nTop Answer:\nNot sure if it works but you can try this\n\n```\n@UseGuards(AuthGuard('jwt'))\n```\n\nabove your protected route.\n\n========================================\n\nCode:\n```text\n@Module({\n    imports: [\n       PassportModule.register({ defaultStrategy: 'jwt' }),\n       JwtModule.register({\n         secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.key`),\n         signOptions: {\n            expiresIn: 3600,\n         },\n       }),\n    ],\n    controllers: [AuthController],\n    providers: [AuthService, JwtStrategy, HttpStrategy],\n})\nexport class AuthModule {}\n```\n\n```text\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n   constructor(private readonly authService: AuthService) {\n      super({\n          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n          secretOrKey: extractKey(`${process.cwd()}/keys/jwt.public.key`),\n      });\n   }\n\n   async validate(payload: JwtPayload) {\n       console.log('JwtStrategy');\n       const user = await this.authService.validateUser(payload);\n       if (!user) {\n           throw new UnauthorizedException();\n       }\n       return user;\n   }\n}\n```\n\n```text\n@Controller('auth')\nexport class AuthController {\n   constructor(private readonly authService: AuthService) {}\n\n   @Get('token')\n   async createToken(): Promise<any> {\n      return await this.authService.createToken();\n   }\n\n   @Get('data')\n   @UseGuards(AuthGuard())\n   findAll() {\n      console.log('Guarded endpoint');\n      // This route is restricted by AuthGuard\n      // JWT strategy\n   }\n}\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtStrategy\n```\n\n```text\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(private readonly authService: AuthService) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: publicKey,\n      algorithms: ['RS256'],\n      ^^^^^^^^^^^^^^^^^^^^^^\n    });\n```\n\n```text\nJwtModule.register({\n  secretOrPrivateKey: privateKey,\n  signOptions: {\n    expiresIn: 3600,\n    algorithm: 'RS256',\n    ^^^^^^^^^^^^^^^^^^^\n  },\n}),\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtStrategy\n```\n\n```text\n@UseGuards(AuthGuard('jwt'))\n```\n\n========================================\n\nComments:\n- The example in your codesandbox also works for me. But it implements regular HS256 tokens. As I wrote in my question problem is with RS256 tokens - so signed with RSA certificate.\n- Please have a look at my code sandbox - I've added a link in my question.\n- Sorry, my previous answer was incorrect. See my edit\n- Besides providing the algorith name in JwtModule and JwtStrategy I would only add that crucial is to have also keys in proper format. Private and public keys must be both in RSA format. Mine public key was provided in SSH2 format and thats why it was not working.","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":200,"estimatedTokens":1216}}1080{"id":"stack-75782271","source":"stackoverflow","questionId":75782271,"title":"How to validate nested array of multiple types using class-validator?","tags":["javascript","typescript","validation","nestjs","class-validator"],"text":"Title: How to validate nested array of multiple types using class-validator?\nTags: javascript, typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI use nestjs with class-validator, and I have the following case:\n\n- Two classes with same field name that has different types:\n\n```\nclass A {\n @IsDefined()\n field: number;\n}\n\nclass B {\n @IsDefined()\n field: string;\n}\n```\n\n- Third class that has array of elements from types A or B, my problem is how to validate each array member against its own class:\n\n```\nclass C {\n @ValidateNested({ each: true })\n @Type(I_DON'T_KNOW_WHAT_TO_DO_HERE)\n array: (A | B)[];\n}\n```\n\nHow can I validate the array?\n\nThanks ahead!\n\n========================================\n\nCode:\n```text\nclass A {\n  @IsDefined()\n  field: number;\n}\n\nclass B {\n  @IsDefined()\n  field: string;\n}\n```\n\n```text\nclass C {\n  @ValidateNested({ each: true })\n  @Type(I_DON'T_KNOW_WHAT_TO_DO_HERE)\n  array: (A | B)[];\n}\n```\n\n```js\nimport { Type } from 'class-transformer';\nimport { IsDefined, IsEnum, IsNumber, IsString, ValidateNested } from 'class-validator';\n\nenum VersionEnum {\n  VERSION_1 = 'v1',\n  VERSION_2 = 'v2',\n}\n\nclass Discriminator {\n  @IsEnum(VersionEnum)\n  version: VersionEnum;\n}\n\nclass A extends Discriminator {\n  @IsDefined()\n  @IsNumber()\n  field: number;\n}\n\nclass B extends Discriminator {\n  @IsDefined()\n  @IsString()\n  field: string;\n}\n\nexport class C {\n  @ValidateNested({ each: true })\n  @Type(() => Discriminator, {\n    discriminator: {\n      property: 'version',\n      subTypes: [\n        { value: A, name: VersionEnum.VERSION_1 },\n        { value: B, name: VersionEnum.VERSION_2 },\n      ],\n    },\n    keepDiscriminatorProperty: true,\n  })\n  array: (A | B)[];\n}\n```\n\n```js\n@Controller()\nexport class AppController {\n  @Post()\n  public example(\n    @Body(new ValidationPipe({ transform: true }))\n    body: C,\n  ) {\n    return body;\n  }\n}\n```\n\n```bash\ncurl --location 'localhost:3000/' \\\n--header 'Content-Type: application/json' \\\n--data '{\n  \"array\": [\n    {\n      \"version\": \"v1\",\n      \"field\": 1\n    },\n    {\n      \"version\": \"v2\",\n      \"field\": \"2\"\n    }\n  ]\n}'\n```\n\n```text\n{\n  \"version\": \"v2\",\n- \"field\": \"2\"\n+ \"field\": 2\n}\n```\n\n```bash\n{\n  \"statusCode\": 400,\n  \"message\": [\n    \"array.1.field must be a string\"\n  ],\n  \"error\": \"Bad Request\"\n}\n```\n\n```text\n\"version\"\n```\n\n```text\nfield\n```\n\n```text\nnumber\n```\n\n```text\nversion\n```\n\n```text\nfield\n```\n\n```text\nstring\n```\n\n```text\ndiscriminator\n```\n\n```text\nsubTypes.[].value\n```\n\n```text\nsubTypes.[].name\n```\n\n```text\ndiscriminator\n```\n\n```text\nsubTypes.[].name\n```\n\n```text\nversion\n```\n\n========================================\n\nComments:\n- Hi, thanks for the answer! Isn't the discriminator solution a little bit messy? The need for changing the original object just for the validator does not seem much of a clean code\n- You can also look for one property which exists in one object and not in the other and verify if the value is undefined or is another value. I think that the options of \"@Type\" should be improved and have some open issues to do it.\n- Agreed about the last sentence. I checked the link you gave in the answer and it really seems like the discriminator is the only appropriate solution. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":202,"estimatedTokens":808}}1081{"id":"stack-77064210","source":"stackoverflow","questionId":77064210,"title":"How to pass a NodeJS parameter to NestJS to extend the stack trace","tags":["node.js","nestjs"],"text":"Title: How to pass a NodeJS parameter to NestJS to extend the stack trace\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nI must pass the node parameter `--stack_trace_limit=200` to NestJS to show an extended trace. I want to continue using nest-cli for development reasons. It seems that NestJS does not proxify NodeJS parameters to NodeJS.\n\nRegards.\n\n========================================\n\nTop Answer:\nanother way is by using the `--exec` option from Nest's CLI:\n\n```\nnest start --exec \"node --stack_trace_limit=200\"\n```\n\n========================================\n\nCode:\n```text\n--stack_trace_limit=200\n```\n\n```bash\nNODE_OPTIONS=\"--stack_trace_limit=200\" nest start\n```\n\n```text\nNODE_OPTIONS\n```\n\n```text\nnest start --exec \"node --stack_trace_limit=200\"\n```\n\n```text\n--exec\n```\n\n========================================\n\nComments:\n- It's `--stack-trace-limit`, not `--stack_trace_limit`. If you are trying something and it doesn't work, check if it works with the first variant; maybe, that's the real answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":45,"estimatedTokens":256}}1082{"id":"stack-75057430","source":"stackoverflow","questionId":75057430,"title":"How to list properties of a Nestjs DTO class?","tags":["javascript","nestjs","prisma"],"text":"Title: How to list properties of a Nestjs DTO class?\nTags: javascript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI have following Nestjs DTO class:\n\n```\n// create-job-offer.dto.ts\nimport { IsOptional, IsNumber } from 'class-validator';\n\nexport class CreateJobOfferDto {\n @IsNumber()\n @IsOptional()\n mentorId: number;\n\n @IsNumber()\n @IsOptional()\n companyId: number;\n}\n```\n\nI want to obtain the list of class properties: `['mentorId', 'companyId']`.\n\nI tried so far in a controller without success following methods:\n\n```\nObject.getOwnPropertyNames(new CreateJobOfferDto());\nObject.getOwnPropertyNames(CreateJobOfferDto);\n\nObject.getOwnPropertySymbols(new CreateJobOfferDto());\nObject.getOwnPropertySymbols(CreateJobOfferDto);\n\nObject.getOwnPropertyDescriptors(CreateJobOfferDto);\nObject.getOwnPropertyDescriptors(new CreateJobOfferDto());\n\nObject.getPrototypeOf(CreateJobOfferDto);\nObject.getPrototypeOf(new CreateJobOfferDto());\n```\n\nIf I add a method, or vars in a constructor, I can get them, but not the properties.\n\nThe reason why I want to achieve this is, I am using Prisma and React, and in my React app I want to receive the list of class properties so that I can generate a model form dynamically.\n\n========================================\n\nTop Answer:\nAs well as the custom solution Mostafa proposes, you can use the `@Expose` decorator combined with the `plainToInstance` function from the `class-transformer` library.\n\n```\nimport { Expose } from 'class-transformer';\n\nexport class UserDto {\n @Expose()\n @IsNotEmpty()\n firstName: string;\n\n @Expose()\n @IsEmail()\n @IsOptional()\n public readonly email: string;\n}\n```\n\nAnd to get the keys:\n\n```\nimport { plainToInstance } from 'class-transformer';\nimport { UserDto } from './userDto';\n\nconst userDtoInstance = plainToInstance(UserDto, {});\n\nconsole.log(Object.keys(userDtoInstance));\n```\n\n========================================\n\nCode:\n```text\n// create-job-offer.dto.ts\nimport { IsOptional, IsNumber } from 'class-validator';\n\nexport class CreateJobOfferDto {\n  @IsNumber()\n  @IsOptional()\n  mentorId: number;\n\n  @IsNumber()\n  @IsOptional()\n  companyId: number;\n}\n```\n\n```text\nObject.getOwnPropertyNames(new CreateJobOfferDto());\nObject.getOwnPropertyNames(CreateJobOfferDto);\n\nObject.getOwnPropertySymbols(new CreateJobOfferDto());\nObject.getOwnPropertySymbols(CreateJobOfferDto);\n\nObject.getOwnPropertyDescriptors(CreateJobOfferDto);\nObject.getOwnPropertyDescriptors(new CreateJobOfferDto());\n\nObject.getPrototypeOf(CreateJobOfferDto);\nObject.getPrototypeOf(new CreateJobOfferDto());\n```\n\n```text\n['mentorId', 'companyId']\n```\n\n```ts\n// typescript\nclass A {\n    private readonly property1: string;\n    public readonly property2: boolean;\n}\n```\n\n```js\n// javascript\n\"use strict\";\nclass A {}\n```\n\n```js\nconst properties = Symbol('properties');\n\n// This decorator will be called for each property, and it stores the property name in an object.\nexport const Property = () => {\n  return (obj: any, propertyName: string) => {\n    (obj[properties] || (obj[properties] = [])).push(propertyName);\n  };\n};\n\n// This is a function to retrieve the list of properties for a class\nexport function getProperties(obj: any): [] {\n  return obj.prototype[properties];\n}\n```\n\n```ts\nimport { getProperties } from './decorators/property.decorator';\n\nexport class UserDto {\n  @Property()\n  @IsNotEmpty()\n  firstName: string;\n\n  @Property()\n  @IsEmail()\n  @IsOptional()\n  public readonly email: string;\n}\n```\n\n```ts\nimport { UserDto } from './dtos/user.dto';\n\ngetProperties(UserDto); // [ 'firstName', 'email' ]\n```\n\n```ts\nimport { keys } from 'ts-transformer-keys';\n\ninterface Props {\n  id: string;\n  name: string;\n  age: number;\n}\nconst keysOfProps = keys<Props>();\n\nconsole.log(keysOfProps); // ['id', 'name', 'age']\n```\n\n```text\ngetProperties\n```\n\n```text\nimport { Expose } from 'class-transformer';\n\nexport class UserDto {\n  @Expose()\n  @IsNotEmpty()\n  firstName: string;\n\n  @Expose()\n  @IsEmail()\n  @IsOptional()\n  public readonly email: string;\n}\n```\n\n```text\nimport { plainToInstance } from 'class-transformer';\nimport { UserDto } from './userDto';\n\nconst userDtoInstance = plainToInstance(UserDto, {});\n\nconsole.log(Object.keys(userDtoInstance));\n```\n\n```text\n@Expose\n```\n\n```text\nplainToInstance\n```\n\n```text\nclass-transformer\n```\n\n========================================\n\nComments:\n- great answer, thanks a lot. I'm surprise that when compiling TS to JS, it just deletes the keys, I'd would expect to initialise them as null or sth.","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":219,"estimatedTokens":1123}}1083{"id":"stack-53544876","source":"stackoverflow","questionId":53544876,"title":"How to integrate Neo4j database, NestJS framework and GraphQL?","tags":["neo4j","cypher","graphql","nestjs","resolver"],"text":"Title: How to integrate Neo4j database, NestJS framework and GraphQL?\nTags: neo4j, cypher, graphql, nestjs, resolver\nSource: Stack Overflow\n\nQuestion:\nI'm trying to integrate my REST API (NestJS) with new Neo4j database with GraphQL queries. Anybody succeed? Thanks in advance\n\nEDIT 1: (I added my code)\n\n```\nimport { Resolver } from \"@nestjs/graphql\";\nimport { Query, forwardRef, Inject, Logger } from \"@nestjs/common\";\nimport { Neo4jService } from \"src/shared/neo4j/neoj4.service\";\nimport { GraphModelService } from \"./models/model.service\";\nimport { Movie } from \"src/graphql.schema\";\n\n@Resolver('Movie')\n export class GraphService {\n constructor(private readonly _neo4jService: Neo4jService) {}\n\n @Query()\n async getMovie() {\n console.log(\"hello\");\n return neo4jgraphql(/*i don't know how get the query and params*/);\n }\n}\n```\n\n========================================\n\nTop Answer:\nI have not worked on GraphQL, but I know there is an npm package(Neo4j-graphql-js) to translate GraphQL queries into Cypher queries. It makes it easier to use GraphQL and Neo4j together.\n\nAlso, check GRANDstack it is a full-stack development integration for building Graph-based applications.\n\nI suggest you to visit Neo4j Community.\n\n========================================\n\nCode:\n```text\nimport { Resolver } from \"@nestjs/graphql\";\nimport { Query, forwardRef, Inject, Logger } from \"@nestjs/common\";\nimport { Neo4jService } from \"src/shared/neo4j/neoj4.service\";\nimport { GraphModelService } from \"./models/model.service\";\nimport { Movie } from \"src/graphql.schema\";\n\n@Resolver('Movie')\n    export class GraphService {\n    constructor(private readonly _neo4jService: Neo4jService) {}\n\n    @Query()\n    async getMovie() {\n        console.log(\"hello\");\n        return neo4jgraphql(/*i don't know how get the query and params*/);\n    }\n}\n```\n\n```text\n@Injectable()\nexport class Neo4JGraphQLInterceptor implements NestInterceptor {\n  intercept(\n    context: ExecutionContext,\n    next: CallHandler<any>,\n  ): Observable<any> | Promise<Observable<any>> {\n    const ctx = GqlExecutionContext.create(context);\n    return neo4jgraphql(\n      ctx.getRoot(),\n      ctx.getArgs(),\n      ctx.getContext(),\n      ctx.getInfo(),\n    );\n  }\n}\n```\n\n```text\n@Resolver('Movie')\n@UseInterceptors(Neo4JGraphQLInterceptor)\nexport class MovieResolver {}\n```\n\n```text\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      typePaths: ['./**/*.gql'],\n      transformSchema: augmentSchema,\n      context: {\n        driver: neo4j.driver(\n          'bolt://neo:7687',\n          neo4j.auth.basic('neo4j', 'password1234'),\n        ),\n      },\n    }),\n  ],\n  controllers: [...],\n  providers: [..., MovieResolver, Neo4JGraphQLInterceptor],\n})\n```\n\n```text\nNestInterceptor\n```\n\n```text\nResolver\n```\n\n```text\nGraphQLModule\n```\n\n```text\ntransformSchema: augmentSchema\n```\n\n```text\n**appmodule.ts**\n....\nimport { makeExecutableSchema } from 'graphql-tools';\nimport { v1 as neo4j } from 'neo4j-driver';\nimport { augmentTypeDefs, augmentSchema  } from 'neo4j-graphql-js';\nimport { Neo4jService } from './neo4j/neo4j.service';\nimport { MyModule } from './my/my.module';\nimport { MyResolver } from './my/my.resolver';\nimport { MyService } from './my/my.service';\n....\nimport { typeDefs } from './generate-schema';  // SDL type file\n...\nconst driver =  neo4j.driver('bolt://localhost:3000', neo4j.auth.basic('neo4j', 'neo4j'))\n\nconst schema = makeExecutableSchema({\n  typeDefs: augmentTypeDefs(typeDefs),\n });\nconst augmentedSchema = augmentSchema(schema);   // Now we have an augmented schema\n\n@Module({\n  imports: [\n    MyModule,\n\n    GraphQLModule.forRoot({\n      schema: augmentedSchema,       \n      context: {\n      driver,\n       },\n     }),\n    ],\n  controllers: [],\n\n  providers: [ Neo4jService,\n               myResolver,\n             ],\n})\nexport class AppModule {}\n\n**myResolver.ts**\n\nimport { Args, Mutation, Query, Resolver  } from '@nestjs/graphql';\n\nimport { MyService } from './my.service';\n\n@Resolver('My')\nexport class MyResolver {\n\n    constructor(\n        private readonly myService: MyService) {}\n\n      @Query()\n      async getData(object, params, ctx, resolveInfo) {\n       return await this.myService.getData(object, params, ctx, resolveInfo);\n      }\n\n     *//Notice I am just passing the graphql params, etc to the myService*\n\n}\n\n**myService.ts**\n\nimport { Injectable } from '@nestjs/common';\nimport { Neo4jService } from '../neo4j/neo4j.service';\n\n@Injectable()\nexport class MyService {\n\n    constructor(private neo4jService: Neo4jService) {}\n\n    async getData(object, params, ctx, resolveInfo) {\n        return await this.neo4jService.getData(object, params, ctx, resolveInfo);\n   }\n\n     *// Again I am just passing the graphql params, etc to the neo4jService*\n }\n**neo4jService.ts**\nimport { Injectable } from '@nestjs/common';\nimport { neo4jgraphql } from 'neo4j-graphql-js';\n\n\n@Injectable()\nexport class Neo4jService {\n\n        getData(object, params, ctx, resolveInfo) {\n              return neo4jgraphql(object, params, ctx, resolveInfo);\n            }\n     .....\n     ......\n}\n```\n\n========================================\n\nComments:\n- Maybe try showing us something you've attempted\n- @Gonzalo De Benito Cassad&#243; See if this may help. medium.com/@faaizhussain/nestjs-graphql-neo4j-1e3e6e552a80\n- Check out DRIVINE.ORG. I haven't added GraphQL support yet, however I think that you will like it otherwise.\n- I'm reading all the documentation of this framework and I can't find the solution to my answer... Thank you! :)\n- @GonzaloDeBenitoCassad&#243; you didn't check accept this answer ..should I assume it didn't work for you?...did you find a better solution?\n- I changed the framework time ago, I think this is the better solution\n- @Christian Lutz .....can you clarify your use of the augmentSchema here?...I take it you have 'augmentSchema = makeAugmentedSchema(typeDefs) somewhere in your code...since you are not using 'definitions' I assume you are using 'definitionsFactory.generate' to generate the schema.ts file...I am getting an error 'unkown relation' when I do that.....it's rejecting the @ relation directives in the SDL file how did you compute 'augmentSchema'?\n- @MichaelE The `augmentSchema` function is the one from *neo4j-graphql-js* grandstack.io/docs/&hellip;. To make the `@relation` work I added `directive @relation(name: String, direction: String) on FIELD_DEFINITION` to my SDL file. Unfortunately I did not have the opportunity to work with graphql and nest since I posted this answer. So maybe things improved since then.\n- @ChristianLutz actually a new variable was introduced 'augmentTypeDefs' which now requires `const schema = makeExecutableSchema({ typeDefs: augmentTypeDefs(typeDefs), });` in order to get @relation and the neo4j directives working\n- @ChristianLutz I just got back to the question and I have a followup question for you. You indicated that you used GRANDStack to create the augmentedSchema...my question is...did you create a duplicated SDL type files to do this? typePaths: ['./**/*.gql'] would have created an inmemory schema for nest... so I would love to see the code used to create the augmentedSchema....if you don't mind ...thanks\n- With decorators it's pretty easy to read and implement! Thank you\n- thank you but its missing the most challenging issue: the custom directive from neo4j like @relationship","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":225,"estimatedTokens":1840}}1084{"id":"stack-77908004","source":"stackoverflow","questionId":77908004,"title":"Validate keycloak token","tags":["jwt","nestjs","keycloak"],"text":"Title: Validate keycloak token\nTags: jwt, nestjs, keycloak\nSource: Stack Overflow\n\nQuestion:\nIn a keycloak context I am using Insomnia to get a token and send a post request to my nestjs app. I use this function to validate the token\n\n```\nasync validateToken(token: string): Promise {\n try {\n // Make a request to the Keycloak token endpoint to validate the token\n // Decode the token to extract its claims\n const decodedToken: CustomJwtPayload = jwtDecode(token);\n console.log(Date());\n console.log(decodedToken);\n\n // Validate the token signature (verify it with Keycloak public key)\n const publicKeyResponse = await axios.get(\n `${process.env.KEYCLOAK_BASE_URL}/protocol/openid-connect/certs`,\n );\n\n const publicKey = publicKeyResponse.data.keys[0].x5c[0];\n // Verify the token signature with the public key\n const verifiedToken = jwt.verify(token, publicKey, {\n algorithms: ['RS256'],\n });\n\n console.log(verifiedToken);\n\n if (!verifiedToken) {\n return false;\n }\n\n // Check token expiry\n const currentTime = Math.floor(Date.now() / 1000);\n if (decodedToken.exp && decodedToken.exp Yet I am having this error\n`Error validating token: JsonWebTokenError: invalid token` it's not verbose enough and I can not get my mind around it.\n\nDoes anyone have any idea how to get through ?\n\n**EDIT:** now that both my db and keycloak are running on the same Docker, here is my app structure\n\n```\nmy-nestjs-project/\nโ”‚\nโ”œโ”€โ”€ src/\nโ”‚ โ”œโ”€โ”€ auth/\nโ”‚ โ”œโ”€โ”€ catApi/\nโ”‚ โ”‚ โ”œโ”€โ”€ catApi.controller.spec.ts \nโ”‚ โ”‚ โ”œโ”€โ”€ catApi.controller.ts\nโ”‚ โ”‚ โ”œโ”€โ”€ catApi.module.ts\nโ”‚ โ”‚ โ”œโ”€โ”€ catApi.service.spec.ts\nโ”‚ โ”‚ โ””โ”€โ”€ catApi.service.ts\nโ”‚ โ”œโ”€โ”€ job/\nโ”‚ โ”‚ โ”œโ”€โ”€ dto\nโ”‚ โ”‚ โ”œโ”€โ”€ job.controller.ts\nโ”‚ โ”‚ โ”œโ”€โ”€ job.module.ts\nโ”‚ โ”‚ โ””โ”€โ”€ job.service.ts\nโ”‚ โ”œโ”€โ”€ keycloak/\nโ”‚ โ”‚ โ”œโ”€โ”€ keycloak.guard.spec.ts # ??? nothing is happening here\nโ”‚ โ”‚ โ”œโ”€โ”€ keycloak.guard.ts # guarding routes in the backend\nโ”‚ โ”‚ โ”œโ”€โ”€ keycloak.module.ts\nโ”‚ โ”‚ โ””โ”€โ”€ keycloak.service.ts # Keycloak logic to discover keycloak issuer conf, validatetoken\nโ”‚ โ”œโ”€โ”€ prisma\nโ”‚ โ”œโ”€โ”€ webapp\nโ”‚ โ”‚ โ”œโ”€โ”€ dto\nโ”‚ โ”‚ โ”œโ”€โ”€ job.controller.ts \nโ”‚ โ”‚ โ”œโ”€โ”€ job.module.ts\nโ”‚ โ”‚ โ””โ”€โ”€ job.service.ts\nโ”‚ โ”‚\nโ”‚ โ””โ”€โ”€ ... # Other pages (e.g., app.module.ts, main.ts, etc.)\nโ”‚\nโ”œโ”€โ”€ node_modules/ # Node modules (not manually edited)\nโ”‚\nโ”œโ”€โ”€ .env.local # Environment variables (e.g., Keycloak URL, client ID)\nโ”‚\nโ”œโ”€โ”€ styles/ # Global styles, CSS modules, etc.\nโ”‚\nโ”œโ”€โ”€ docker-compose.yml # Keycloak Docker Compose File\nโ”‚\nโ”œโ”€โ”€ package.json # Project metadata and dependencies\nโ”‚\nโ””โ”€โ”€ ...\n```\n\nJob and Webapp are both business logic and have db tables, they will be the protected routes when I succeed. I am using catApi to hit catfacts and get some fun and quirky content with Insomnia, this route is currently protected\n\n```\n@Get('facts/cats')\n @UseGuards(KeycloakAuthGuard)\n getCatFacts() {\n this.apiService.getCatFactsWithAxiosLib();\n }\n```\n\nI get my token via : https://i.sstatic.net/D71tD.png\n\nand ask for cat fact like this https://i.sstatic.net/oPxxN.png\n\nand that's when it runs through my function above and send me back the error\n\n========================================\n\nCode:\n```js\nasync validateToken(token: string): Promise<boolean> {\n    try {\n      // Make a request to the Keycloak token endpoint to validate the token\n      // Decode the token to extract its claims\n      const decodedToken: CustomJwtPayload = jwtDecode(token);\n      console.log(Date());\n      console.log(decodedToken);\n\n      // Validate the token signature (verify it with Keycloak public key)\n      const publicKeyResponse = await axios.get<PublicKeyResponse>(\n        `${process.env.KEYCLOAK_BASE_URL}/protocol/openid-connect/certs`,\n      );\n\n      const publicKey = publicKeyResponse.data.keys[0].x5c[0];\n      // Verify the token signature with the public key\n      const verifiedToken = jwt.verify(token, publicKey, {\n        algorithms: ['RS256'],\n      });\n\n      console.log(verifiedToken);\n\n      if (!verifiedToken) {\n        return false;\n      }\n\n      // Check token expiry\n      const currentTime = Math.floor(Date.now() / 1000);\n      if (decodedToken.exp && decodedToken.exp < currentTime) {\n        return false; // Token expired\n      }\n      // Verify token issuer\n      if (decodedToken.notes.iss !== `${process.env.KEYCLOAK_BASE_URL}`) {\n        return false; // Invalid issuer\n      }\n\n      // Check token audience\n      if (decodedToken.aud !== process.env.KEYCLOAK_CLIENT_ID) {\n        return false; // Invalid audience\n      }\n\n      // Token is valid\n      return true;\n    } catch (error) {\n      console.error('Error validating token:', error);\n      return false;\n    }\n  }\n}\n```\n\n```text\nmy-nestjs-project/\nโ”‚\nโ”œโ”€โ”€ src/\nโ”‚   โ”œโ”€โ”€ auth/\nโ”‚   โ”œโ”€โ”€ catApi/\nโ”‚   โ”‚   โ”œโ”€โ”€ catApi.controller.spec.ts  \nโ”‚   โ”‚   โ”œโ”€โ”€ catApi.controller.ts\nโ”‚   โ”‚   โ”œโ”€โ”€ catApi.module.ts\nโ”‚   โ”‚   โ”œโ”€โ”€ catApi.service.spec.ts\nโ”‚   โ”‚   โ””โ”€โ”€ catApi.service.ts\nโ”‚   โ”œโ”€โ”€ job/\nโ”‚   โ”‚   โ”œโ”€โ”€ dto\nโ”‚   โ”‚   โ”œโ”€โ”€ job.controller.ts\nโ”‚   โ”‚   โ”œโ”€โ”€ job.module.ts\nโ”‚   โ”‚   โ””โ”€โ”€ job.service.ts\nโ”‚   โ”œโ”€โ”€ keycloak/\nโ”‚   โ”‚   โ”œโ”€โ”€ keycloak.guard.spec.ts # ??? nothing is happening here\nโ”‚   โ”‚   โ”œโ”€โ”€ keycloak.guard.ts      # guarding routes in the backend\nโ”‚   โ”‚   โ”œโ”€โ”€ keycloak.module.ts\nโ”‚   โ”‚   โ””โ”€โ”€ keycloak.service.ts    # Keycloak logic to discover keycloak issuer conf, validatetoken\nโ”‚   โ”œโ”€โ”€ prisma\nโ”‚   โ”œโ”€โ”€ webapp\nโ”‚   โ”‚   โ”œโ”€โ”€ dto\nโ”‚   โ”‚   โ”œโ”€โ”€ job.controller.ts \nโ”‚   โ”‚   โ”œโ”€โ”€ job.module.ts\nโ”‚   โ”‚   โ””โ”€โ”€ job.service.ts\nโ”‚   โ”‚\nโ”‚   โ””โ”€โ”€ ...                  # Other pages (e.g., app.module.ts, main.ts, etc.)\nโ”‚\nโ”œโ”€โ”€ node_modules/            # Node modules (not manually edited)\nโ”‚\nโ”œโ”€โ”€ .env.local               # Environment variables (e.g., Keycloak URL, client ID)\nโ”‚\nโ”œโ”€โ”€ styles/                  # Global styles, CSS modules, etc.\nโ”‚\nโ”œโ”€โ”€ docker-compose.yml       # Keycloak Docker Compose File\nโ”‚\nโ”œโ”€โ”€ package.json             # Project metadata and dependencies\nโ”‚\nโ””โ”€โ”€ ...\n```\n\n```js\n@Get('facts/cats')\n  @UseGuards(KeycloakAuthGuard)\n  getCatFacts() {\n    this.apiService.getCatFactsWithAxiosLib();\n  }\n```\n\n```text\nError validating token: JsonWebTokenError: invalid token\n```\n\n```yaml\nversion: '3.7'\n\nservices:\n  postgres:\n    image: postgres\n    volumes:\n      - postgres_data:/var/lib/postgresql/data\n    environment:\n      POSTGRES_DB: keycloak\n      POSTGRES_USER: keycloak\n      POSTGRES_PASSWORD: password\n\n  keycloak:\n    image: quay.io/keycloak/keycloak:latest  # Update to the latest Keycloak image\n    command: start-dev\n    environment:\n      KC_DB: postgres\n      KC_DB_URL: jdbc:postgresql://postgres/keycloak\n      KC_DB_USERNAME: keycloak\n      KC_DB_PASSWORD: password\n      KC_HTTP_ENABLED: true  # Enable HTTP if you're not using HTTPS\n      KC_HEALTH_ENABLED: true\n      KEYCLOAK_ADMIN: admin\n      KEYCLOAK_ADMIN_PASSWORD: admin\n    ports:\n      - 8080:8080\n    restart: always\n    depends_on:\n      - postgres\n\nvolumes:\n  postgres_data:\n    driver: local\n```\n\n```bash\ndocker compose up\n```\n\n```text\nhttp://localhost:8080/\n```\n\n```text\nPOST http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/token\n```\n\n```text\nclient_id : admin-cli\nusername  : admin\npassword  : 1234\ngrant_type : password\n```\n\n```js\nimport {Body, Controller, Post} from '@nestjs/common';\nimport {KeycloakService} from '../keycloak/keycloak.service';\n\n@Controller('auth')\nexport class AuthController {\n  constructor(private keycloakService: KeycloakService) {}\n\n  @Post('validateToken')\n  async validateToken(@Body() body) {\n    const {token} = body;\n    return await this.keycloakService.validateToken(token);\n  }\n}\n```\n\n```js\nimport {Module} from '@nestjs/common';\n\nimport {KeycloakModule} from '../keycloak/keycloak.module';\n\nimport {AuthController} from './auth.controller';\nimport {AuthService} from './auth.service';\n\n@Module({\n  imports: [KeycloakModule],\n  providers: [AuthService],\n  controllers: [AuthController]\n})\nexport class AuthModule {\n}\n```\n\n```js\nimport {HttpModule} from '@nestjs/axios';\nimport {Module} from '@nestjs/common';\n\nimport {KeycloakModule} from '../keycloak/keycloak.module';\n\nimport {CatApiController} from './catApi.controller';\nimport {CatApiService} from './catApi.service';\n\n@Module({\n  imports: [\n    KeycloakModule,\n    HttpModule,\n  ],\n  controllers: [CatApiController],\n  providers: [CatApiService],\n})\nexport class CatApiModule {\n}\n```\n\n```js\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { CatApiService } from './catApi.service';\nimport { KeycloakAuthGuard } from '../keycloak/keycloak.guard';\n\n@Controller('facts')\nexport class CatApiController {\n  constructor(private catApiService: CatApiService) {}\n\n  @Get('cats')\n  @UseGuards(KeycloakAuthGuard)\n  async getCatFacts() {\n    return this.catApiService.getCatFactsWithAxiosLib();\n  }\n}\n```\n\n```js\nimport {HttpService} from '@nestjs/axios';\nimport {Injectable} from '@nestjs/common';\nimport {AxiosResponse} from 'axios';\nimport {Observable} from 'rxjs';\nimport {map} from 'rxjs/operators';\n\n@Injectable()\nexport class CatApiService {\n  constructor(private httpService: HttpService) {}\n\n  async getCatFactsWithAxiosLib(): Promise<any> {\n    try {\n      // Replace 'external-api-url' with the actual API URL\n      const response: Observable<AxiosResponse<any>> =\n          this.httpService.get('https://catfact.ninja/breeds?limit=1');\n      return response\n          .pipe(map((axiosResponse) => {\n            return {\n              data: axiosResponse.data,\n              status: axiosResponse.status,\n            };\n          }))\n          .toPromise();\n    } catch (error) {\n      // Handle error (e.g., log it, format it, etc.)\n      console.error('Error fetching cat facts:', error);\n      throw new Error('Failed to fetch cat facts');\n    }\n  }\n}\n```\n\n```js\nimport {CanActivate, ExecutionContext, Injectable} from '@nestjs/common';\nimport {Observable} from 'rxjs';\n\nimport {KeycloakService} from './keycloak.service';\n\n@Injectable()\nexport class KeycloakAuthGuard implements CanActivate {\n  constructor(private keycloakService: KeycloakService) {}\n\n  canActivate(\n      context: ExecutionContext,\n      ): boolean|Promise<boolean>|Observable<boolean> {\n    const request = context.switchToHttp().getRequest();\n    const token = this.keycloakService.extractToken(request);\n\n    if (!token) {\n      // Handle the case where the token is not provided\n      return false;\n    }\n\n    return this.keycloakService.validateToken(token);\n  }\n}\n```\n\n```js\nimport { HttpModule } from '@nestjs/axios';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\n\nimport { KeycloakService } from './keycloak.service';\n\n@Module({\n  imports: [HttpModule, ConfigModule],\n  providers: [KeycloakService],\n  exports: [KeycloakService],\n})\nexport class KeycloakModule {\n}\n```\n\n```js\nimport {HttpService} from '@nestjs/axios';\nimport {Injectable} from '@nestjs/common';\nimport axios from 'axios';\nimport * as jwt from 'jsonwebtoken';\n\n@Injectable()\nexport class KeycloakService {\n  constructor(private httpService: HttpService) {}\n\n  extractToken(request: any): string|null {\n    const authHeader = request.headers.authorization;\n    if (authHeader) {\n      return authHeader.split(' ')[1];  // Assumes Bearer token format\n    }\n    return null;\n  }\n\n  async validateToken(token: string): Promise<boolean> {\n    const keycloakUrl = 'http://localhost:8080';\n    const realm = 'my-nestjs-app';\n    const clientId = 'admin-cli';\n\n    try {\n      if (!token) {\n        console.error('Token not provided');\n        return false;\n      }\n      const decodedToken = jwt.decode(token, {complete: true});\n\n      const publicKeyResponse = await axios.get(\n          `${keycloakUrl}/realms/${realm}/protocol/openid-connect/certs`);\n      const signingKey = publicKeyResponse.data.keys.find(\n          key => key.use === 'sig' && key.alg === 'RS256');\n\n      if (!signingKey) {\n        return false;  // Signing key not found\n      }\n\n      const pemStart = '-----BEGIN CERTIFICATE-----\\n';\n      const pemEnd = '\\n-----END CERTIFICATE-----';\n      const pem = pemStart + signingKey.x5c[0] + pemEnd;\n\n      if (decodedToken.payload.iss !== `${keycloakUrl}/realms/${realm}`) {\n        return false;  // Invalid issuer\n      }\n\n      if (decodedToken.payload.azp !== clientId) {\n        return false;  // Invalid audience\n      }\n\n      const currentTime = Math.floor(Date.now() / 1000);\n      if (decodedToken.payload.exp < currentTime) {\n        return false;  // Token expired\n      }\n\n      jwt.verify(token, pem, {algorithms: ['RS256']});\n      return true;\n    } catch (error) {\n      console.error('Error validating token:', error);\n      return false;  // Error in validating token\n    }\n  }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { AuthModule } from './auth/auth.module';\nimport { CatApiModule } from './cat-api/cat-api.module';\nimport { JobModule } from './job/job.module';\nimport { WebappModule } from './webapp/webapp.module';\nimport { KeycloakModule } from './keycloak/keycloak.module';\n\n@Module({\n  imports: [AuthModule, CatApiModule, JobModule, WebappModule, KeycloakModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.enableCors(); // Enables CORS for all routes\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```js\nnpm install axios jsonwebtoken reflect-metadata rxjs\n```\n\n```js\nnpm run start\n```\n\n```text\nGET http://localhost:3000/facts/cats\n```\n\n```bash\n'https://catfact.ninja/breeds?limit=1'\n```\n\n```js\n@Controller('facts')\nexport class CatApiController {\n  constructor(private catApiService: CatApiService) {}\n\n  @Get('cats')\n  @UseGuards(KeycloakAuthGuard)\n  async getCatFacts() {\n    return this.catApiService.getCatFactsWithAxiosLib();\n  }\n}\n```\n\n```text\nhttp://localhost:8080/realms/master/protocol/openid-connect/certs\n```\n\n```json\n{\n  \"issuer\": \"http://localhost:8080/realms/my-nestjs-app\",\n  \"authorization_endpoint\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/auth\",\n  \"token_endpoint\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/token\",\n  \"introspection_endpoint\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/token/introspect\",\n  \"userinfo_endpoint\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/userinfo\",\n  \"end_session_endpoint\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/logout\",\n  \"frontchannel_logout_session_supported\": true,\n  \"frontchannel_logout_supported\": true,\n  \"jwks_uri\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/certs\",\n  \"check_session_iframe\": \"http://localhost:8080/realms/my-nestjs-app/protocol/openid-connect/login-status-iframe.html\",\n  \"grant_types_supported\": [\n    \"authorization_code\",\n    \"implicit\",\n    \"refresh_token\",\n    \"password\",\n    \"client_credentials\",\n    \"urn:openid:params:grant-type:ciba\",\n    \"urn:ietf:params:oauth:grant-type:device_code\"\n  ],\n// cut-off\n```\n\n```js\nconst pemStart = '-----BEGIN CERTIFICATE-----\\n';\nconst pemEnd = '\\n-----END CERTIFICATE-----';\nconst pem = pemStart + signingKey.x5c[0] + pemEnd;\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nx-www-form-urlencoded\n```\n\n```text\nauth.controller.ts\n```\n\n```text\nauth.module.ts\n```\n\n```text\ncat-api.module\n```\n\n```text\ncatApi.controller.ts\n```\n\n```text\ncatApi.service.ts\n```\n\n```text\nkeycloak.guard.ts\n```\n\n```text\nkeycloak.module.ts\n```\n\n```text\nkeycloak.service.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nmain.ts\n```\n\n```text\ncatApi.service.ts\n```\n\n========================================\n\nComments:\n- My keycloak server is not on a docker yet, I need to fix that before trying to apply your solution\n- @Mowso, I updated my answer add a docker part and overview diagram.\n- Thank you for that, I figured out my docker and updated my question. I am in nestjs so I guess your approach is to frontend for me ?\n- @Mowso, I revised all of the content switching from `React` to `nestjs` and update Keycloak version from v19 to v23, and using \"my-nestjs-app\" realm to match your realm. But I am still using Postman.\n- No idea why it did not work previously but I rewrote the whole thing following your advices and it worked !\n- I am happy to hear you got it. Can you up-vote too? It will give me an encourage to keep answer. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":40,"totalLines":631,"estimatedTokens":4085}}1085{"id":"stack-72198777","source":"stackoverflow","questionId":72198777,"title":"Testing if an event has been triggered in NestJS","tags":["node.js","typescript","jestjs","nestjs","eventemitter"],"text":"Title: Testing if an event has been triggered in NestJS\nTags: node.js, typescript, jestjs, nestjs, eventemitter\nSource: Stack Overflow\n\nQuestion:\nIn the project we are building, there is a standard sequence in the workflow.\n\n- Controller receives a request\n\n- Then fires an event through @nestjs/event-emitter\n\n- Event listener listens to it and executes some code depending on the event\n\nHow can we properly test if an event has been triggered but without actually executing the code inside?\n\nWe are using Jest for testing.\n\nMocking with Jest doesn't seem to work, because we want to test the actual trigger event and not the result.\n\nAny suggestions?\n\n```\n\"node\": \"16.14.2\"\n\"@nestjs/event-emitter\": \"^1.1.0\",\n\"jest\": \"^27.5.1\",\n```\n\n========================================\n\nTop Answer:\nFollowing the suggestion from @ovidijus-parsiunas we managed to spy on the \"OnEvent\" method successfully.\n\n```\nit.only(\"start selling\", async () => {\n const user = await userSeeder.createOne();\n\n const spy = jest\n .spyOn(StartSellingListener.prototype, 'startSelling')\n .mockImplementation(() => null);\n\n expect(eventEmitter.hasListeners(EventsEnum.USER_START_SELLING)).toBe(true);\n\n const startSelling = userService.startSelling(user);\n expect(startSelling).toBeTruthy();\n\n expect(spy).toBeCalledWith(user);\n\n spy.mockRestore();\n });\n```\n\n========================================\n\nCode:\n```text\n\"node\": \"16.14.2\"\n\"@nestjs/event-emitter\": \"^1.1.0\",\n\"jest\": \"^27.5.1\",\n```\n\n```text\nit.only(\"start selling\", async () => {\n    const user = await userSeeder.createOne();\n\n    const spy = jest\n      .spyOn(StartSellingListener.prototype, 'startSelling')\n      .mockImplementation(() => null);\n\n    expect(eventEmitter.hasListeners(EventsEnum.USER_START_SELLING)).toBe(true);\n\n    const startSelling = userService.startSelling(user);\n    expect(startSelling).toBeTruthy();\n\n    expect(spy).toBeCalledWith(user);\n\n    spy.mockRestore();\n  });\n```\n\n========================================\n\nComments:\n- Could you please add the code to show what have you done so far?\n- Worked like a charm! Thank you! I posted the test below as an example if someone is having the same issue\n- Can you show how you initialized your testing module? My registered events don't get added to the listeners.","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":85,"estimatedTokens":567}}1086{"id":"stack-72517471","source":"stackoverflow","questionId":72517471,"title":"What is a strategy in Nest JS?","tags":["nestjs","backend"],"text":"Title: What is a strategy in Nest JS?\nTags: nestjs, backend\nSource: Stack Overflow\n\nQuestion:\nI watch a guide regarding Nest JS and when working with guards the author wrote some JWT strategies but did not really focus on what they are and what is their purpose, so my question is what is a strategy?\n\n========================================\n\nComments:\n- docs.nestjs.com/security/authentication wanago.io/2020/05/25/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":11,"estimatedTokens":107}}1087{"id":"stack-69315819","source":"stackoverflow","questionId":69315819,"title":"Nest can't resolve dependencies of the JwtService","tags":["javascript","jwt","nestjs"],"text":"Title: Nest can't resolve dependencies of the JwtService\nTags: javascript, jwt, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have created some modules here but i am facing an error\n\nAuth module\n\n```\nimport { Module } from \"@nestjs/common\";\nimport { AuthService } from \"./auth.service\";\nimport { LocalStrategy } from \"./local.strategy\";\nimport { JwtStrategy } from \"./jwt.strategy\";\nimport { UsersModule } from \"../users/users.module\";\nimport { PassportModule } from \"@nestjs/passport\";\nimport { JwtModule, JwtService } from \"@nestjs/jwt\";\nimport { jwtConstants } from \"./constants\";\nimport { ConfigModule, ConfigService } from \"@nestjs/config\";\n\n@Module({\n imports: [\n UsersModule,\n PassportModule,\n JwtModule.register({\n secret: jwtConstants.secret,\n signOptions: { expiresIn: \"1d\" },\n }),\n ],\n providers: [AuthService, LocalStrategy, JwtStrategy],\n exports: [AuthService, LocalStrategy, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\nEmail module\n\n```\nimport { Module } from \"@nestjs/common\";\nimport EmailService from \"./email.service\";\n\nimport { ConfigModule } from \"@nestjs/config\";\n\nimport { EmailConfirmationService } from \"./emailConfirmation.service\";\nimport { EmailConfirmationController } from \"./emailConfirmation.controller\";\nimport { EmailConfirmationGuard } from \"./guards/emailConfirmation.guard\";\nimport { AuthModule } from \"src/auth/auth.module\";\nimport { UsersModule } from \"src/users/users.module\";\n\n@Module({\n imports: [ConfigModule,AuthModule,UsersModule],\n providers: [EmailService,EmailConfirmationService,EmailConfirmationGuard],\n exports: [EmailConfirmationService,EmailConfirmationGuard],\n controllers : [EmailConfirmationController]\n})\nexport class EmailModule {}\n```\n\nUser module\n\n```\nimport { Module } from \"@nestjs/common\";\nimport { UsersService } from \"./users.service\";\nimport { UsersController } from \"./users.controller\";\nimport { MongooseModule } from \"@nestjs/mongoose\";\nimport { UserSchema } from \"./entities/user.entity\";\nimport { EmailModule } from \"src/email/email.module\";\n\n@Module({\n imports: [MongooseModule.forFeature([{ name: \"User\", schema: UserSchema }]),EmailModule],\n providers: [UsersService],\n exports: [UsersService],\n controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\nError I am facing\n\n```\n[Nest] 9200 - 09/26/2021, 3:43:15 PM ERROR [ExceptionHandler] Nest cannot create the EmailModule instance.\nThe module at index [1] of the EmailModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [AppModule -> AuthModule -> UsersModule]\nError: Nest cannot create the EmailModule instance.\nThe module at index [1] of the EmailModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n```\n\nWhat am i missing ?\n\n```\nEmailConfirmationService is used in UsersController\nUserService is used in EmailConfirmationService\n```\n\n========================================\n\nTop Answer:\nYou have `JwtService` listed in your imports. Imports are for modules only.\n\n the code from `JwtService` as well so that we can make sure there are no other issues.\n\nUpdate:\nIf the `EmailModule` wants to use the exports from the `AuthModule` (JwtService in this case), it must add the `AuthModule` to its imports array.\n\nThis is the entire premise of the DI system, modules things between eachother by placing the thing they intend to in the `exports` array. After that, any module can add the Source module to its `imports` array to gain access to the things that the source exported. The error message literally spells it out for you:\n\n`If JwtService is exported from a separate @Module, is that module imported within EmailModule? @Module({ imports: [ /* the Module containing JwtService */ ] })`\n\n========================================\n\nCode:\n```text\nimport { Module } from \"@nestjs/common\";\nimport { AuthService } from \"./auth.service\";\nimport { LocalStrategy } from \"./local.strategy\";\nimport { JwtStrategy } from \"./jwt.strategy\";\nimport { UsersModule } from \"../users/users.module\";\nimport { PassportModule } from \"@nestjs/passport\";\nimport { JwtModule, JwtService } from \"@nestjs/jwt\";\nimport { jwtConstants } from \"./constants\";\nimport { ConfigModule, ConfigService } from \"@nestjs/config\";\n\n@Module({\n    imports: [\n        UsersModule,\n        PassportModule,\n        JwtModule.register({\n            secret: jwtConstants.secret,\n            signOptions: { expiresIn: \"1d\" },\n        }),\n    ],\n    providers: [AuthService, LocalStrategy, JwtStrategy],\n    exports: [AuthService, LocalStrategy, JwtStrategy],\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Module } from \"@nestjs/common\";\nimport EmailService from \"./email.service\";\n\nimport { ConfigModule } from \"@nestjs/config\";\n\nimport { EmailConfirmationService } from \"./emailConfirmation.service\";\nimport { EmailConfirmationController } from \"./emailConfirmation.controller\";\nimport { EmailConfirmationGuard } from \"./guards/emailConfirmation.guard\";\nimport { AuthModule } from \"src/auth/auth.module\";\nimport { UsersModule } from \"src/users/users.module\";\n\n@Module({\n    imports: [ConfigModule,AuthModule,UsersModule],\n    providers: [EmailService,EmailConfirmationService,EmailConfirmationGuard],\n    exports: [EmailConfirmationService,EmailConfirmationGuard],\n    controllers : [EmailConfirmationController]\n})\nexport class EmailModule {}\n```\n\n```text\nimport { Module } from \"@nestjs/common\";\nimport { UsersService } from \"./users.service\";\nimport { UsersController } from \"./users.controller\";\nimport { MongooseModule } from \"@nestjs/mongoose\";\nimport { UserSchema } from \"./entities/user.entity\";\nimport { EmailModule } from \"src/email/email.module\";\n\n@Module({\n    imports: [MongooseModule.forFeature([{ name: \"User\", schema: UserSchema }]),EmailModule],\n    providers: [UsersService],\n    exports: [UsersService],\n    controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\n```text\n[Nest] 9200  - 09/26/2021, 3:43:15 PM   ERROR [ExceptionHandler] Nest cannot create the EmailModule instance.\nThe module at index [1] of the EmailModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [AppModule -> AuthModule -> UsersModule]\nError: Nest cannot create the EmailModule instance.\nThe module at index [1] of the EmailModule \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [1] is of type \"undefined\". Check your import statements and the type of the module.\n```\n\n```text\nEmailConfirmationService is used in UsersController\nUserService is used in EmailConfirmationService\n```\n\n```text\nimports: [forwardRef(() => EmailModule)]\n```\n\n```text\nimports: [forwardRef(() => UserModule)]\n```\n\n```text\nJwtService\n```\n\n```text\nJwtService\n```\n\n```text\nEmailModule\n```\n\n```text\nAuthModule\n```\n\n```text\nAuthModule\n```\n\n```text\nexports\n```\n\n```text\nimports\n```\n\n```text\nIf JwtService is exported from a separate @Module, is that module imported within EmailModule?   @Module({     imports: [ /* the Module containing JwtService */ ]   })\n```\n\n```text\ntsconfig.json\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.575Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":249,"estimatedTokens":1947}}1088{"id":"stack-73019162","source":"stackoverflow","questionId":73019162,"title":"NestJS TypeORM mock a datasource of a repository","tags":["typescript","jestjs","nestjs","typeorm"],"text":"Title: NestJS TypeORM mock a datasource of a repository\nTags: typescript, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock out a repository. I don't want to do actual database calls. I (think I) am following the documentation on NestJS, and certain stackoverflow items.\n\nHowever, when I run the test I get the following error:\n\n```\nJwtStrategy โ€บ validate โ€บ throws an unauthorized exception as user cannot be found\nNest can't resolve dependencies of the UserEntityRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context.\n\nPotential solutions:\n- If DataSource is a provider, is it part of the current TypeOrmModule?\n- If DataSource is exported from a separate @Module, is that module imported within TypeOrmModule?\n @Module({\n imports: [ /* the Module containing DataSource */ ]\n })\n```\n\nNow as I understand, it seems that the UserEntityRepository is not properly mocked. As it is the first (index [0]) dependency in the user service class:\n\n**./user.service.ts**\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(UserEntity)\n private userRepository: Repository\n ) {}\n\n async findOneBy({ username }): Promise {\n return await this.userRepository.findOneBy({ username })\n }\n}\n```\n\n**./jwt.strategy.ts**\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n private userService: UserService,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET || config.get('jwt.secret'),\n })\n }\n\n async validate(payload: JwtPayload) {\n const { username } = payload;\n const user = await this.userService.findOneBy({username});\n\n if (!user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\n**./jwt.strategy.spect.ts**\n\n```\nconst mockUserRepositoryFactory = jest.fn(() => ({\n findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n let jwtStrategy: JwtStrategy;\n let userService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [UserModule],\n providers: [\n JwtStrategy,\n UserService,\n // shouldn't this correctly provide the datasource?\n {\n provide: getRepositoryToken(UserEntity),\n useFactory: mockUserRepositoryFactory,\n },\n\n ]\n }).compile();\n\n jwtStrategy = await module.get(JwtStrategy);\n userService = await module.get(UserService);\n });\n\n describe('validate', () => {\n it('validates and returns user based on JWT payload', async () => {\n const user = new UserEntity();\n user.username = 'TestUser';\n\n userService.findOneBy.mockResolvedValue(user);\n const result = await jwtStrategy.validate({ username: 'TestUser' });\n expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n expect(result).toEqual(user);\n });\n\n it('throws an unauthorized exception as user cannot be found', async () => {\n userService.findOneBy.mockResolvedValue(null);\n expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n });\n });\n});\n```\n\n**===== Update**\n\nCreated a minimal setup in a Codesandbox.\n\nhttps://codesandbox.io/s/xenodochial-benz-kve4eq?file=/test/jwt.test.js\n\nBut somehow the test tab isn't showing in the sandbox.\n\n========================================\n\nTop Answer:\nI have noticed that you are calling `findOneBy` in your service but mocked the `findOne` repository method.\n\nEither you have to mock the `findOne` method of your service or `findOneBy` of your repository. In the current approach, you mock the repository. The solution for this use case would look like this:\n\n```\nconst mockUserRepositoryFactory = jest.fn(() => ({\n // Change here from findOne to findOneBy\n findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n let jwtStrategy: JwtStrategy;\n let userService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [UserModule],\n providers: [\n JwtStrategy,\n UserService, {\n provide: getRepositoryToken(UserEntity),\n useFactory: mockUserRepositoryFactory,\n },\n\n ]\n }).compile();\n\n jwtStrategy = await module.get(JwtStrategy);\n userService = await module.get(UserService);\n });\n\n describe('validate', () => {\n it('validates and returns user based on JWT payload', async () => {\n const user = new UserEntity();\n user.username = 'TestUser';\n\n // change findOne to findOneBy here as well\n userService.findOneBy.mockResolvedValue(user);\n const result = await jwtStrategy.validate({ username: 'TestUser' });\n expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n expect(result).toEqual(user);\n });\n\n it('throws an unauthorized exception as user cannot be found', async () => {\n userService.findOneBy.mockResolvedValue(null);\n expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n });\n });\n});\n```\n\n========================================\n\nCode:\n```text\nJwtStrategy โ€บ validate โ€บ throws an unauthorized exception as user cannot be found\nNest can't resolve dependencies of the UserEntityRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context.\n\nPotential solutions:\n- If DataSource is a provider, is it part of the current TypeOrmModule?\n- If DataSource is exported from a separate @Module, is that module imported within TypeOrmModule?\n  @Module({\n    imports: [ /* the Module containing DataSource */ ]\n  })\n```\n\n```js\n@Injectable()\nexport class UserService {\n    constructor(\n        @InjectRepository(UserEntity)\n        private userRepository: Repository<UserEntity>\n    ) {}\n\n    async findOneBy({ username }): Promise<UserEntity> {\n        return await this.userRepository.findOneBy({ username })\n    }\n}\n```\n\n```js\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor(\n      private userService: UserService,\n  ) {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      secretOrKey: process.env.JWT_SECRET || config.get('jwt.secret'),\n    })\n  }\n\n  async validate(payload: JwtPayload) {\n    const { username } = payload;\n    const user = await this.userService.findOneBy({username});\n\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n\n    return user;\n  }\n}\n```\n\n```js\nconst mockUserRepositoryFactory = jest.fn(() => ({\n  findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n  let jwtStrategy: JwtStrategy;\n  let userService;\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      imports: [UserModule],\n      providers: [\n        JwtStrategy,\n        UserService,\n        // shouldn't this correctly provide the datasource?\n        {\n          provide: getRepositoryToken(UserEntity),\n          useFactory: mockUserRepositoryFactory,\n        },\n\n      ]\n    }).compile();\n\n    jwtStrategy = await module.get<JwtStrategy>(JwtStrategy);\n    userService = await module.get<UserService>(UserService);\n  });\n\n  describe('validate', () => {\n    it('validates and returns user based on JWT payload', async () => {\n      const user = new UserEntity();\n      user.username = 'TestUser';\n\n      userService.findOneBy.mockResolvedValue(user);\n      const result = await jwtStrategy.validate({ username: 'TestUser' });\n      expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n      expect(result).toEqual(user);\n    });\n\n    it('throws an unauthorized exception as user cannot be found', async () => {\n      userService.findOneBy.mockResolvedValue(null);\n      expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n    });\n  });\n});\n```\n\n```text\nimport { DataSource } from \"typeorm\";\n\n// @ts-ignore\nexport const dataSourceMockFactory: () => MockType<DataSource> = jest.fn(() => ({\n  <mock_function>: jest.fn(),\n}));\n\nexport type MockType<T> = {\n  [P in keyof T]?: jest.Mock<{}>;\n};\n```\n\n```text\ndescribe('---MSG---', () => {\n...\n  let dataSourceMock: MockType<DataSource>\n...\n  beforeAll(async () => {\n    const module = await Test.createTestingModule({\n      imports: [],\n      controllers: [<CONTROLLERS>],\n      providers: [ <PROVIDERS>\n        { provide: DataSource, useFactory: dataSourceMockFactory }],\n    }).compile()\n...\n    dataSourceMock = module.get(DataSource);\n...\n  })\n\n  describe('---MSG---', () => {\n    it('---MSG---', async () => {\n      await <Call mock function>\n      expect(dataSourceMock.<DataSource mocked function>).toBeCalled();\n    });\n  })\n```\n\n```text\nconst mockUserRepositoryFactory = jest.fn(() => ({\n  // Change here from findOne to findOneBy\n  findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n  let jwtStrategy: JwtStrategy;\n  let userService;\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      imports: [UserModule],\n      providers: [\n        JwtStrategy,\n        UserService,            {\n          provide: getRepositoryToken(UserEntity),\n          useFactory: mockUserRepositoryFactory,\n        },\n\n      ]\n    }).compile();\n\n    jwtStrategy = await module.get<JwtStrategy>(JwtStrategy);\n    userService = await module.get<UserService>(UserService);\n  });\n\n  describe('validate', () => {\n    it('validates and returns user based on JWT payload', async () => {\n      const user = new UserEntity();\n      user.username = 'TestUser';\n\n      // change findOne to findOneBy here as well\n      userService.findOneBy.mockResolvedValue(user);\n      const result = await jwtStrategy.validate({ username: 'TestUser' });\n      expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n      expect(result).toEqual(user);\n    });\n\n    it('throws an unauthorized exception as user cannot be found', async () => {\n      userService.findOneBy.mockResolvedValue(null);\n      expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n    });\n  });\n});\n```\n\n```text\nfindOneBy\n```\n\n```text\nfindOne\n```\n\n```text\nfindOne\n```\n\n```text\nfindOneBy\n```\n\n========================================\n\nComments:\n- Good one. I've updated my answer to match. But it also does not solve the problem sadly.\n- : jest.fn() getting error for this. Tried let mock_function = any it didn't work.\n- need to be call await here - test file","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":385,"estimatedTokens":2568}}1089{"id":"stack-68953458","source":"stackoverflow","questionId":68953458,"title":"NestJS Bull Log errors to Sentry","tags":["nestjs","sentry","bullmq"],"text":"Title: NestJS Bull Log errors to Sentry\nTags: nestjs, sentry, bullmq\nSource: Stack Overflow\n\nQuestion:\nI've recently added Bull to my project to offload things like synchronizing documents to 3rd party services and everything's working well, except errors occurring while processing jobs don't end up in Sentry. They're only logged on the jobs themselves, but since we're running our application on multiple configurations, it means I have to constantly monitor all these instances for job processing errors.\n\nI know I can add an error handler to a processor, but I have quite a few processors already, so I'd prefer another, more global, solution\n\nIs there any way to make sure these errors are also sent to Sentry?\n\n========================================\n\nCode:\n```js\nimport { OnQueueFailed } from '@nestjs/bull';\nimport { Logger } from '@nestjs/common';\nimport * as Sentry from '@sentry/node';\nimport { Job } from 'bull';\n\nexport abstract class BaseProcessor {\n  protected abstract logger: Logger;\n\n  @OnQueueFailed()\n  onError(job: Job<any>, error: any) {\n    Sentry.captureException(error);\n    this.logger.error(\n      `Failed job ${job.id} of type ${job.name}: ${error.message}`,\n      error.stack,\n    );\n  }\n}\n```\n\n```js\nimport { InjectQueue, Process, Processor } from '@nestjs/bull';\nimport { Logger } from '@nestjs/common';\nimport { Job, Queue } from 'bull';\nimport { BaseProcessor } from 'src/common/BaseProcessor';\nimport { BULL_QUEUES } from 'src/common/queues';\n\n@Processor(BULL_QUEUES.SOME_QUEUE_NAME)\nexport class SomeProcessor extends BaseProcessor {\n  protected readonly logger = new Logger(SomeProcessor.name);\n\n  constructor(\n    // dependencies\n  ) {\n    super();\n  }\n\n  @Process()\n  async processTask(job: Job) {\n    // processor code here\n  }\n}\n```\n\n========================================\n\nComments:\n- Thanks for the suggestion. I ended up doing something similar, but instead of writing a base class, I wrote a wrapper function that each runner needs to wrap itself into. Internally, it does a try-catch.","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":62,"estimatedTokens":509}}1090{"id":"stack-68976639","source":"stackoverflow","questionId":68976639,"title":"How to filter on relation in Prisma ORM","tags":["postgresql","nestjs","relation","prisma"],"text":"Title: How to filter on relation in Prisma ORM\nTags: postgresql, nestjs, relation, prisma\nSource: Stack Overflow\n\nQuestion:\nI am working currently on a course service. Users have the possibility to register and deregister for courses. The entire system is built in a microservice architecture, which means that users are managed by another service. Therefore, the data model of the course service looks like this:\n\n```\nmodel course {\n id Int @id @default(autoincrement())\n orderNumber Int @unique\n courseNumber String @unique @db.VarChar(255)\n courseName String @db.VarChar(255)\n courseOfficer String @db.VarChar(255)\n degree String @db.VarChar(255)\n ectCount Int\n faculty String @db.VarChar(255)\n isWinter Boolean @default(false)\n isSummer Boolean @default(false)\n courseDescription String? @db.VarChar(255)\n enrollmentCourse enrollmentCourse[]\n}\n\nmodel enrollmentCourse {\n id Int @id @default(autoincrement())\n userId String @db.VarChar(1024)\n course course @relation(fields: [courseId], references: [id])\n courseId Int\n}\n```\n\nI want to find all the courses in which a certain user has enrolled.\nI have written 2 queries. One goes over the courses and tries to filter on the enrollmentCourse. However, this one does not work and I get all the courses back. Whereas the second one goes over the enrollmentCourse and then uses a mapping to return the courses. This works, but I don't like this solution and would prefer the 1st query if it worked:\n(I have used this guide in order to write the first query: here)\n\n```\nconst result1 = await this.prisma.course.findMany({\n where: { enrollmentCourse: { every: { userId: user.id } } },\n include: { enrollmentCourse: true }\n});\n\nconsole.log('Test result 1: ');\nconsole.log(result1);\n\nconst result2 = await this.prisma.enrollmentCourse.findMany({\n where: { userId: user.id },\n include: { course: { include: { enrollmentCourse: true } } }\n});\n\nconsole.log('Test result 2: ');\nconsole.log(result2.map((enrollment) => enrollment.course));\n```\n\nIf now the user is not enrolled in a course the result of both queries are:\n\n```\nTest result 1:\n[\n {\n id: 2,\n orderNumber: 1,\n courseNumber: 'test123',\n courseName: 'testcourse',\n courseOfficer: 'testcontact',\n degree: 'Bachelor',\n ectCount: 5,\n faculty: 'testfaculty',\n isWinter: true,\n isSummer: false,\n courseDescription: 'test.pdf',\n enrollmentCourse: []\n }\n]\nTest result 2:\n[]\n```\n\nIf now the user has enrolled courses it looks like this:\n\n```\nTest result 1:\n[\n {\n id: 2,\n orderNumber: 1,\n courseNumber: 'test123',\n courseName: 'testcourse',\n courseOfficer: 'testcontact',\n degree: 'Bachelor',\n ectCount: 5,\n faculty: 'testfaculty',\n isWinter: true,\n isSummer: false,\n courseDescription: 'test.pdf',\n enrollmentCourse: [ [Object] ]\n }\n]\nTest result 2:\n[\n {\n id: 2,\n orderNumber: 1,\n courseNumber: 'test123',\n courseName: 'testcourse',\n courseOfficer: 'testcontact',\n degree: 'Bachelor',\n ectCount: 5,\n faculty: 'testfaculty',\n isWinter: true,\n isSummer: false,\n courseDescription: 'test.pdf',\n enrollmentCourse: [ [Object] ]\n }\n]\n```\n\nAs we can see the first query does not work correctly. Can anybody give me a hint? Is there anything that I'm missing?\n\n========================================\n\nCode:\n```text\nmodel course {\n  id                Int                @id @default(autoincrement())\n  orderNumber       Int                @unique\n  courseNumber      String             @unique @db.VarChar(255)\n  courseName        String             @db.VarChar(255)\n  courseOfficer     String             @db.VarChar(255)\n  degree            String             @db.VarChar(255)\n  ectCount          Int\n  faculty           String             @db.VarChar(255)\n  isWinter          Boolean            @default(false)\n  isSummer          Boolean            @default(false)\n  courseDescription String?            @db.VarChar(255)\n  enrollmentCourse  enrollmentCourse[]\n}\n\nmodel enrollmentCourse {\n  id       Int    @id @default(autoincrement())\n  userId   String @db.VarChar(1024)\n  course   course @relation(fields: [courseId], references: [id])\n  courseId Int\n}\n```\n\n```text\nconst result1 = await this.prisma.course.findMany({\n  where: { enrollmentCourse: { every: { userId: user.id } } },\n  include: { enrollmentCourse: true }\n});\n\nconsole.log('Test result 1: ');\nconsole.log(result1);\n\nconst result2 = await this.prisma.enrollmentCourse.findMany({\n  where: { userId: user.id },\n  include: { course: { include: { enrollmentCourse: true } } }\n});\n\nconsole.log('Test result 2: ');\nconsole.log(result2.map((enrollment) => enrollment.course));\n```\n\n```text\nTest result 1:\n[\n  {\n    id: 2,\n    orderNumber: 1,\n    courseNumber: 'test123',\n    courseName: 'testcourse',\n    courseOfficer: 'testcontact',\n    degree: 'Bachelor',\n    ectCount: 5,\n    faculty: 'testfaculty',\n    isWinter: true,\n    isSummer: false,\n    courseDescription: 'test.pdf',\n    enrollmentCourse: []\n  }\n]\nTest result 2:\n[]\n```\n\n```text\nTest result 1:\n[\n  {\n    id: 2,\n    orderNumber: 1,\n    courseNumber: 'test123',\n    courseName: 'testcourse',\n    courseOfficer: 'testcontact',\n    degree: 'Bachelor',\n    ectCount: 5,\n    faculty: 'testfaculty',\n    isWinter: true,\n    isSummer: false,\n    courseDescription: 'test.pdf',\n    enrollmentCourse: [ [Object] ]\n  }\n]\nTest result 2:\n[\n  {\n    id: 2,\n    orderNumber: 1,\n    courseNumber: 'test123',\n    courseName: 'testcourse',\n    courseOfficer: 'testcontact',\n    degree: 'Bachelor',\n    ectCount: 5,\n    faculty: 'testfaculty',\n    isWinter: true,\n    isSummer: false,\n    courseDescription: 'test.pdf',\n    enrollmentCourse: [ [Object] ]\n  }\n]\n```\n\n```text\nconst result1 = await this.prisma.course.findMany({\n  where: { enrollmentCourse: { some: { userId: user.id } } },\n  include: { enrollmentCourse: true }\n});\n```\n\n```text\nsome\n```\n\n```text\nevery\n```\n\n```text\nuser\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":240,"estimatedTokens":1445}}1091{"id":"stack-67290780","source":"stackoverflow","questionId":67290780,"title":"Column X of relation Y contains null values","tags":["node.js","typescript","postgresql","nestjs","typeorm"],"text":"Title: Column X of relation Y contains null values\nTags: node.js, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen inserting first admin into my database I get this error message and don't know how to solve it:\n\n```\n[Nest] 13803 - 04/27/2021, 23:03:02 [TypeOrmModule] Unable to connect to the database. Retrying (6)... +3176ms\nQueryFailedError: column \"name\" of relation \"admin\" contains null values\n```\n\nOther tables work just fine so far and without errors.\n\nColumn `name` in `admin` table is not null it contains value:\nhttps://i.sstatic.net/5RNII.png\n\nRegister service:\n\n```\nasync register(registerInput: RegisterInput): Promise {\n const { key, name, password, email } = registerInput;\n\n const hashedKey = createHash('sha256')\n .update(key)\n .digest('hex');\n\n const invite = await this.invitesRepository.findOne({ key: hashedKey });\n\n if (!invite) {\n throw new UnauthorizedException();\n }\n\n const newAdmin = await this.adminsRepository.create({\n name,\n password,\n email,\n });\n await this.adminsRepository.save(newAdmin);\n\n await this.invitesRepository.delete({ id: invite.id });\n }\n```\n\n========================================\n\nCode:\n```text\n[Nest] 13803   - 04/27/2021, 23:03:02   [TypeOrmModule] Unable to connect to the database. Retrying (6)... +3176ms\nQueryFailedError: column \"name\" of relation \"admin\" contains null values\n```\n\n```text\nasync register(registerInput: RegisterInput): Promise<void> {\n    const { key, name, password, email } = registerInput;\n\n    const hashedKey = createHash('sha256')\n      .update(key)\n      .digest('hex');\n\n    const invite = await this.invitesRepository.findOne({ key: hashedKey });\n\n    if (!invite) {\n      throw new UnauthorizedException();\n    }\n\n    const newAdmin = await this.adminsRepository.create({\n      name,\n      password,\n      email,\n    });\n    await this.adminsRepository.save(newAdmin);\n\n    await this.invitesRepository.delete({ id: invite.id });\n  }\n```\n\n```text\nname\n```\n\n```text\nadmin\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- what is the value of the prop `name` in `registerInput`?\n- I entered \"John Doe\" as displayed in table, but whatever value I input and however many admins I add the error doesn't go away.\n- Can you update the question with the related entity classes and the connection options you pass to connect to the database?\n- Also, try to delete your `dist` directory, rebuild the code and try again\n- This still works in 2022. I don't know why it's necessary, though. Added `rm -rf dist` in the `package.json` script for convenience.","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":97,"estimatedTokens":647}}1092{"id":"stack-71803978","source":"stackoverflow","questionId":71803978,"title":"Rimraf: Glob dependency not found. How do you set `disableGlob=true` in the cli?","tags":["node.js","powershell","heroku","nestjs","glob"],"text":"Title: Rimraf: Glob dependency not found. How do you set `disableGlob=true` in the cli?\nTags: node.js, powershell, heroku, nestjs, glob\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy my nestjs backed on Heroku and whenever it runs the `prebuild: rimraf dist` command from `package.json` it encounters this error. I have no idea what glob is but I'm assuming I don't need it... what is the syntax to set `disableGlob = true` in the cli/scripts?\n\nCurrent error:\n\n```\n/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:42\n throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')\n ^\nError: glob dependency not found, set `options.disableGlob = true` if intentional\n at defaults (/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:42:11)\n at rimraf (/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:60:3)\n at go (/tmp/build_ceb6e44a/node_modules/rimraf/bin.js:44:3)\n at Object. (/tmp/build_ceb6e44a/node_modules/rimraf/bin.js:68:3)\n at Module._compile (node:internal/modules/cjs/loader:1099:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)\n at Module.load (node:internal/modules/cjs/loader:975:32)\n at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)\n at node:internal/main/run_main_module:17:47\nNode.js v17.9.0\n```\n\nNote: Heroku is installing `node 17.9.0` when deploying in case it matters\n\npackage.json\n\n```\n{\n \"scripts\": {\n \"rimraf\": \"./node_modules/rimraf/bin.js\",\n \"prebuild\": \"rimraf dist\"\n },\n \"dependencies\": {\n \"glob\": \"^7.2.0\",\n \"rimraf\": \"^3.0.2\"\n }\n}\n```\n\nI tried all of the following with no success\n\n```\n\"prebuild\": \"rimraf -o disableGlob=true dist\"\n\"prebuild\": \"rimraf --options disableGlob=true dist\"\n\"prebuild\": \"rimraf options.disableGlob=true dist\"\n```\n\nI also installed glob as a dependency but it still errors. Any help?\n\n========================================\n\nCode:\n```text\n/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:42\n    throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')\n    ^\nError: glob dependency not found, set `options.disableGlob = true` if intentional\n    at defaults (/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:42:11)\n    at rimraf (/tmp/build_ceb6e44a/node_modules/rimraf/rimraf.js:60:3)\n    at go (/tmp/build_ceb6e44a/node_modules/rimraf/bin.js:44:3)\n    at Object.<anonymous> (/tmp/build_ceb6e44a/node_modules/rimraf/bin.js:68:3)\n    at Module._compile (node:internal/modules/cjs/loader:1099:14)\n    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)\n    at Module.load (node:internal/modules/cjs/loader:975:32)\n    at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)\n    at node:internal/main/run_main_module:17:47\nNode.js v17.9.0\n```\n\n```json\n{\n  \"scripts\": {\n    \"rimraf\": \"./node_modules/rimraf/bin.js\",\n    \"prebuild\": \"rimraf dist\"\n  },\n  \"dependencies\": {\n    \"glob\": \"^7.2.0\",\n    \"rimraf\": \"^3.0.2\"\n  }\n}\n```\n\n```text\n\"prebuild\": \"rimraf -o disableGlob=true dist\"\n\"prebuild\": \"rimraf --options disableGlob=true dist\"\n\"prebuild\": \"rimraf options.disableGlob=true dist\"\n```\n\n```text\nprebuild: rimraf dist\n```\n\n```text\npackage.json\n```\n\n```text\ndisableGlob = true\n```\n\n```text\nnode 17.9.0\n```\n\n```text\n\"prebuild\": \"rimraf -G dist\"\n```\n\n```text\nrimraf\n```\n\n```text\nrimraf\n```\n\n```text\n-G\n```\n\n```text\n--noglob\n```\n\n```text\nrimraf --help\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":133,"estimatedTokens":885}}1093{"id":"stack-67245560","source":"stackoverflow","questionId":67245560,"title":"NestJS - Avoid returning user's password","tags":["typescript","mongoose","graphql","nestjs"],"text":"Title: NestJS - Avoid returning user's password\nTags: typescript, mongoose, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a little problem with my project using GraphQL and Mongoose (code-first approach). I have a findCurrentUser query in my user's resolver that returns the information about the currently authenticated user, but I don't want to return the user's password, how I can avoid this?\n\nUser's Resolver:\n\n```\n@Query(() => User)\n@UseGuards(GqlAuthGuard)\nasync findCurrentUser(@CurrentUser() user: JwtPayload): Promise {\n return await this.usersService.findCurrent(user.id);\n}\n```\n\nUser's Service:\n\n```\nasync findCurrent(id: string): Promise {\n try {\n // find the user\n const user = await this.userModel.findOne({ _id: id });\n\n // if the user does not exists throw an error\n if (!user) {\n throw new BadRequestException('User not found');\n }\n\n // we should not return the user's password\n // TODO: this is a temporary solution, needs to be improved\n user.password = '';\n\n return user;\n } catch (error) {\n throw new InternalServerErrorException(error.message);\n }\n }\n```\n\nUser's Entity:\n\n```\nimport { ObjectType, Field, ID } from '@nestjs/graphql';\nimport { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Schema as MongooseSchema } from 'mongoose';\nimport { nanoid } from 'nanoid';\n\n@Schema()\n@ObjectType()\nexport class User {\n @Field(() => ID)\n _id: MongooseSchema.Types.ObjectId;\n\n @Field(() => String, { nullable: false })\n @Prop({ type: String, required: true, trim: true })\n firstName: string;\n\n @Field(() => String, { nullable: true })\n @Prop({ type: String, required: false, trim: true })\n lastName?: string;\n\n @Field(() => String, { nullable: true })\n @Prop({ type: String, required: false, default: nanoid(10) })\n username: string;\n\n @Field(() => String, { nullable: false })\n @Prop({\n type: String,\n unique: true,\n required: true,\n lowercase: true,\n trim: true\n })\n email: string;\n\n @Field(() => String, { nullable: false })\n @Prop({ type: String, required: true, trim: true, minlength: 6 })\n password: string;\n\n @Field(() => Boolean, { defaultValue: true })\n @Prop({ type: Boolean, default: true })\n isActive: boolean;\n\n @Field(() => Date, { defaultValue: Date.now() })\n @Prop({ type: Date, default: Date.now() })\n createdAt: Date;\n}\n\nexport type UserDocument = User & Document;\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\nIn the documentation, the NestJS team mentions \"Serialization, \" but I already tried and didn't work. I get the following error on my GraphQL Playground:\n\n\"message\": \"Cannot return null for non-nullable field User._id.\"\n\n========================================\n\nTop Answer:\nYou can avoid returning the password, by setting `select` Prop option to false.\n\n```\n@Prop({ ..., select: false })\npassword: string;\n```\n\nIf you don't want to return the password on operations other than a simple select (API create/update/login etc.), you can change the document's toJSON transform method as following :\n\n```\n//\nUserSchema.set('toJSON', {\n transform: (doc, ret, opt) => {\n delete ret.password;\n return ret;\n }\n});\n```\n\n========================================\n\nCode:\n```js\n@Query(() => User)\n@UseGuards(GqlAuthGuard)\nasync findCurrentUser(@CurrentUser() user: JwtPayload): Promise<User> {\n  return await this.usersService.findCurrent(user.id);\n}\n```\n\n```js\nasync findCurrent(id: string): Promise<User> {\n    try {\n      // find the user\n      const user = await this.userModel.findOne({ _id: id });\n\n      // if the user does not exists throw an error\n      if (!user) {\n        throw new BadRequestException('User not found');\n      }\n\n      // we should not return the user's password\n      // TODO: this is a temporary solution, needs to be improved\n      user.password = '';\n\n      return user;\n    } catch (error) {\n      throw new InternalServerErrorException(error.message);\n    }\n  }\n```\n\n```js\nimport { ObjectType, Field, ID } from '@nestjs/graphql';\nimport { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';\nimport { Document, Schema as MongooseSchema } from 'mongoose';\nimport { nanoid } from 'nanoid';\n\n@Schema()\n@ObjectType()\nexport class User {\n  @Field(() => ID)\n  _id: MongooseSchema.Types.ObjectId;\n\n  @Field(() => String, { nullable: false })\n  @Prop({ type: String, required: true, trim: true })\n  firstName: string;\n\n  @Field(() => String, { nullable: true })\n  @Prop({ type: String, required: false, trim: true })\n  lastName?: string;\n\n  @Field(() => String, { nullable: true })\n  @Prop({ type: String, required: false, default: nanoid(10) })\n  username: string;\n\n  @Field(() => String, { nullable: false })\n  @Prop({\n    type: String,\n    unique: true,\n    required: true,\n    lowercase: true,\n    trim: true\n  })\n  email: string;\n\n  @Field(() => String, { nullable: false })\n  @Prop({ type: String, required: true, trim: true, minlength: 6 })\n  password: string;\n\n  @Field(() => Boolean, { defaultValue: true })\n  @Prop({ type: Boolean, default: true })\n  isActive: boolean;\n\n  @Field(() => Date, { defaultValue: Date.now() })\n  @Prop({ type: Date, default: Date.now() })\n  createdAt: Date;\n}\n\nexport type UserDocument = User & Document;\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n```js\n// @Field(() => String, { nullable: false })\n@Prop({ type: String, required: true, trim: true, minlength: 6 })\npassword: string;\n```\n\n```text\n@Field\n```\n\n```text\npassword\n```\n\n```js\n@Prop({ ..., select: false })\npassword: string;\n```\n\n```js\n//\nUserSchema.set('toJSON', {\n    transform: (doc, ret, opt) => {\n        delete ret.password;\n        return ret;\n    }\n});\n```\n\n```text\nselect\n```\n\n```text\nconst user = gql`\nquery getUserDetails($email: String!, $name: String!, ...any other thing that you want to send to server[backend] ) {\n\n getUserDetails(email: $email, password: $password, ...any other thing that you \n want to send to server[backend] ) {\n  id\n  name\n  email\n  password\n }\n\n}\n`;\n```\n\n```text\nconst user = gql`\nquery getUserDetails($email: String!, $name: String!, ...any other thing that you want to send to server[backend] ) {\n\n getUserDetails(email: $email, password: $password, ...any other thing that you \n want to send to server[backend] ) {\n  id\n  name\n  email\n }\n\n}\n`;\n```\n\n========================================\n\nComments:\n- For me, in nestjs, password is still retrievable.","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":274,"estimatedTokens":1584}}1094{"id":"stack-67602673","source":"stackoverflow","questionId":67602673,"title":"Is there a way to get request context within a decorator in Nest JS","tags":["node.js","typescript","nestjs"],"text":"Title: Is there a way to get request context within a decorator in Nest JS\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a decorator to \"log\" request info\n\n```\nexport const Tracking = () => {\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = async function(...args: any[]) {\n console.log(/** Request info */)\n console.log(/** Headers, Body, Method, URL...*/)\n return method.call(this, ...args);\n }\n }\n}\n```\n\nand try to use it on a controller method like this.\n\n```\nexport class Controller {\n\n @Get('/path')\n @Tracking()\n public async getData(@Headers('user') user: User) {\n return this.service.getData(user.id);\n }\n}\n```\n\nIf this is impossible, is there a way to apply interceptor to some method of controller?\n\nOr is there a thread(like)-level context for request?\n\nThanks!!\n\n========================================\n\nCode:\n```text\nexport const Tracking = () => {\n  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n    const method = descriptor.value;\n    descriptor.value = async function(...args: any[]) {\n      console.log(/** Request info */)\n      console.log(/** Headers, Body, Method, URL...*/)\n      return method.call(this, ...args);\n    }\n  }\n}\n```\n\n```text\nexport class Controller {\n\n  @Get('/path')\n  @Tracking()\n  public async getData(@Headers('user') user: User) {\n    return this.service.getData(user.id);\n  }\n}\n```\n\n```text\n@Body()\n```\n\n```text\n@Req()\n```\n\n========================================\n\nComments:\n- you can bind interceptors to some method. No tsure about the second point but have you ever read about injection scopes?\n- I think what you need is a middleware - docs.nestjs.com/middleware\n- @MicaelLevi Thanks, I missed that important line when I read the docs... well i think they should list all the usage in the example section which i pay the most attention onto...\n- wonder how the validation pipes get the request body though\n- @juztcode there's a pipe handler inside of the internals of the framework code that has access to the request object and passes the proper values to each pipe's `transform` method, based on the grabbed metadata from the `@Body()` and similar decorators","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":82,"estimatedTokens":568}}1095{"id":"stack-68239942","source":"stackoverflow","questionId":68239942,"title":"Using https with Axios request in Nestjs","tags":["javascript","typescript","https","axios","nestjs"],"text":"Title: Using https with Axios request in Nestjs\nTags: javascript, typescript, https, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI currently have a Nestjs server setup and am attempting to perform an Axios request when one of the endpoints is hit with a GET request. Here is the controller.ts code:\n\n```\n@Controller()\nexport class TestController {\n constructor(private readonly testService: TestService) {}\n\n @Get('testData')\n testData() {\n return this.testService.testData();\n }\n}\n```\n\nService.ts:\n\n```\n@Injectable()\nexport class TestService {\n status(): string {\n return 'OK'\n }\n\n testData(): Promise {\n return helper.getTestData();\n }\n}\n```\n\nWhere `helper.getTestData()` is just a call to a helper file with the following function:\n\n```\nexport async function getTestData(): Promise {\n const result = await axios({\n url: tempURL,\n method: 'GET',\n timeout: 3000,\n httpsAgent: new https.Agent({\n rejectUnauthorized: false,\n }),\n });\n```\n\nI am able to hit this endpoint `tempURL` but encounter the following error message: `Cannot read property 'Agent' of undefined`. I know that the endpoint I am attempting to hit requires a cert, which is why I must include the httpsAgent argument inside the Axios request. If I don't include the `httpsAgent` argument, I receive the following message `Error: unable to verify the first certificate in nodejs`.\n\nIs there a way to configure Nestjs to work with https? Or is there another way to handle this authorization issue inside of Nestjs? Using Postman everything works fine so I'm assuming it is a Nestjs issue. Any help is appreciated.\n\n========================================\n\nCode:\n```text\n@Controller()\nexport class TestController {\n    constructor(private readonly testService: TestService) {}\n\n    @Get('testData')\n    testData() {\n        return this.testService.testData();\n    }\n}\n```\n\n```text\n@Injectable()\nexport class TestService {\n    status(): string {\n        return 'OK'\n    }\n\n    testData(): Promise<any> {\n        return helper.getTestData();\n    }\n}\n```\n\n```text\nexport async function getTestData(): Promise<any> {\n    const result = await axios({\n        url: tempURL,\n        method: 'GET',\n        timeout: 3000,\n        httpsAgent: new https.Agent({\n            rejectUnauthorized: false,\n        }),\n    });\n```\n\n```text\nhelper.getTestData()\n```\n\n```text\ntempURL\n```\n\n```text\nCannot read property 'Agent' of undefined\n```\n\n```text\nhttpsAgent\n```\n\n```text\nError: unable to verify the first certificate in nodejs\n```\n\n```text\nimport https from 'https';\n```\n\n```text\nimport * as https from 'https';\n```\n\n```text\nesModuleInterop\n```\n\n```text\ntrue\n```\n\n```text\ncompilerOptions\n```\n\n========================================\n\nComments:\n- looks like `https` is `undefined` somehow\n- @MicaelLevi https is defined, I have it properly imported into the file. Also, https is a native module, how could it be undefined?\n- depending on how you're importing it, it could. The line in the stack trace that the error `Cannot read property 'Agent' of undefined` appears is the same of the `httpsAgent: new https.Agent` one?\n- @MicaelLevi Yes, the error is on the `httpsAgent: new https.Agent` line. I import currently as follows: `import https from 'https';` at the top of the file.\n- @MicaelLevi you were correct, the issue was with how I was importing. `import https from 'https'` did not work but `import { Agent } from 'https'` did. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":140,"estimatedTokens":851}}1096{"id":"stack-65779031","source":"stackoverflow","questionId":65779031,"title":"NestJS: Dependency Injection and Provider Registration","tags":["node.js","dependency-injection","service","nestjs"],"text":"Title: NestJS: Dependency Injection and Provider Registration\nTags: node.js, dependency-injection, service, nestjs\nSource: Stack Overflow\n\nQuestion:\nCan anyone help me to understand DI Nest Fundamentals, my question:\n\n\"Is it possible to have a service class **without @Injectable annotattion**, and also this class **does not belong to any module**?\" I saw on internet an example like below:\n\nThis class exists in a common folder:\n\n```\nexport class NotificationService {\n constructor(\n @Inject(Logger) private readonly logger: LoggerService,\n private readonly appConfigService: AppConfigService,\n @Inject(HttpService) private readonly httpService: HttpService\n ) {}\n \n async sendNotification(msg: string) {\n ....\n } \n}\n```\n\nAnd then it was registered in another module in the the providers array:\n\n```\nimport { Module, Logger, forwardRef, HttpModule } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { NotificationService } from '../../commons/notification/notification.service';\n \n@Module({\n imports: [\n ...\n ],\n controllers: [InvoiceController],\n providers: [\n InvoiceService,\n NotificationService,\n Logger],\n exports: [InvoiceService]\n})\nexport class InvoiceModule { }\n```\n\nThen it was injected in other service's constructor method\n\n```\n@Injectable()\nexport class InvoiceService {\n \n constructor(\n @Inject(Logger) private readonly logger: LoggerService,\n private readonly notificationService: NotificationService) { }\n \n...\n}\n```\n\nThis works fine, but I don't know why. Why the notification service was injected correctly without add @Injectable, and without and import module?\n\n========================================\n\nCode:\n```text\nexport class NotificationService {\n  constructor(\n    @Inject(Logger) private readonly logger: LoggerService,\n    private readonly appConfigService: AppConfigService,\n    @Inject(HttpService) private readonly httpService: HttpService\n  ) {}\n \n  async sendNotification(msg: string) {\n   ....\n  } \n}\n```\n\n```text\nimport { Module, Logger, forwardRef, HttpModule } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { NotificationService } from '../../commons/notification/notification.service';\n \n@Module({\n    imports: [\n        ...\n    ],\n    controllers: [InvoiceController],\n    providers: [\n        InvoiceService,\n        NotificationService,\n        Logger],\n    exports: [InvoiceService]\n})\nexport class InvoiceModule { }\n```\n\n```text\n@Injectable()\nexport class InvoiceService {\n \n    constructor(\n        @Inject(Logger) private readonly logger: LoggerService,\n        private readonly notificationService: NotificationService) { }\n \n...\n}\n```\n\n```js\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\n```\n\n```js\nDelegatorService = __decorate([\n    common_1.Injectable(),\n    __metadata(\"design:paramtypes\", [http_interceptor_service_1.HttpInterceptorService,\n        websocket_interceptor_service_1.WebsocketInterceptorService,\n        rpc_interceptor_service_1.RpcInterceptorService,\n        gql_interceptor_service_1.GqlInterceptorService])\n], DelegatorService);\n```\n\n```text\n@Injectable()\n```\n\n```text\n@Injectable()\n```\n\n```text\n@Injectable()\n```\n\n```text\ntsconfig\n```\n\n```text\ntsc\n```\n\n```text\nemitDecoratorMetadata\n```\n\n```text\n\"design:paramtypes\"\n```\n\n```text\nimport type\n```\n\n```text\n@Inject()\n```\n\n```text\n@Injectable()\n```\n\n```text\n@Injectable()\n```\n\n```text\nNotificationsService\n```\n\n```text\nInvoiceModule\n```\n\n```text\nproviders\n```\n\n```text\nInvoiceModule\n```\n\n```text\nNotificationsService\n```\n\n```text\nemitDecoratorMetadata\n```\n\n========================================\n\nComments:\n- Thanks for your explanation, so I deduce that a class like NotificationService can exists without belonging to any module that exports it, and second, using *register provider* like in this case, Nest behind the scenes create a new instance of NotificationService, there is no need a useValue: new NotificationService","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":204,"estimatedTokens":1155}}1097{"id":"stack-65413061","source":"stackoverflow","questionId":65413061,"title":"How do I mock Mongoose's \"lean()\" query with Jest and NestJS?","tags":["javascript","typescript","mongoose","jestjs","nestjs"],"text":"Title: How do I mock Mongoose's \"lean()\" query with Jest and NestJS?\nTags: javascript, typescript, mongoose, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a Person entity with its own Repository class, which I want to test. This repository class injects the Mongoose model as suggested in the docs of NestJS, like so:\n\n```\n@InjectModel(Person.name)\n private model: Model\n```\n\nAnd the code I'm trying to test is a query similar to `const res = await this.model.find().lean();`\n\nMy issue, though, is when it comes to testing the lean() query, as it's a chained function to find() methods. I was able to get as far as I could, but when it comes to mocking it I am having some type conflicts:\n\n```\nconst modelMockObject = {\n find: jest.fn(),\n findOne: jest.fn(),\n findOneAndUpdate: jest.fn(),\n updateOne: jest.fn(),\n};\n\n// ...\n\n let MockPersonModel: Model;\n\n beforeEach(async () => {\n const mockModule: TestingModule = await Test.createTestingModule({\n providers: [\n ...,\n {\n provide: getModelToken(Person.name),\n useValue: modelMockObject,\n },\n ],\n }).compile();\n\n MockPersonModel = mockModule.get>(\n Person.name,\n );\n }); \n\n// ...\n// Inside a describe/it test...\n\n const personModel = new MockPersonModel({\n name: 'etc'\n });\n\n jest.spyOn(MockPersonModel, 'findOne').mockReturnValueOnce({\n lean: () => ({ exec: async () => personModel }),\n });\n```\n\nThe error the linter informs on `personModel` (second-last line) is the following:\n\n```\nType 'Promise' is not assignable to type 'Promise'.\n Type 'PersonModel' is not assignable to type 'P'.\n 'P' could be instantiated with an arbitrary type which could be unrelated to 'PersonModel'.ts(2322)\nindex.d.ts(2100, 5): The expected type comes from the return type of this signature.\n```\n\nThanks a lot for your help!\n\n========================================\n\nCode:\n```js\n@InjectModel(Person.name)\n    private model: Model<PersonModel>\n```\n\n```js\nconst modelMockObject = {\n  find: jest.fn(),\n  findOne: jest.fn(),\n  findOneAndUpdate: jest.fn(),\n  updateOne: jest.fn(),\n};\n\n// ...\n\n  let MockPersonModel: Model<PersonModel>;\n\n  beforeEach(async () => {\n    const mockModule: TestingModule = await Test.createTestingModule({\n      providers: [\n        ...,\n        {\n          provide: getModelToken(Person.name),\n          useValue: modelMockObject,\n        },\n      ],\n    }).compile();\n\n    MockPersonModel = mockModule.get<Model<PersonModel>>(\n      Person.name,\n    );\n  }); \n\n// ...\n// Inside a describe/it test...\n\n      const personModel = new MockPersonModel({\n        name: 'etc'\n      });\n\n      jest.spyOn(MockPersonModel, 'findOne').mockReturnValueOnce({\n        lean: () => ({ exec: async () => personModel }),\n      });\n```\n\n```text\nType 'Promise<PersonModel>' is not assignable to type 'Promise<P>'.\n  Type 'PersonModel' is not assignable to type 'P'.\n    'P' could be instantiated with an arbitrary type which could be unrelated to 'PersonModel'.ts(2322)\nindex.d.ts(2100, 5): The expected type comes from the return type of this signature.\n```\n\n```text\nconst res = await this.model.find().lean();\n```\n\n```text\npersonModel\n```\n\n```js\nMockPersonModel.findOne.mockImplementationOnce(() => ({\n    lean: jest.fn().mockReturnValue(personModel),\n}));\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":135,"estimatedTokens":803}}1098{"id":"stack-59299172","source":"stackoverflow","questionId":59299172,"title":"How to read a csv file and store it in and array of objects?","tags":["node.js","typescript","promise","nestjs"],"text":"Title: How to read a csv file and store it in and array of objects?\nTags: node.js, typescript, promise, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to read a CSV file and store it in a variable for future access preferably as an array of objects.\nBut doing the following \n\n```\nconst csv = fs\n .createReadStream('data.csv')\n .pipe(csv.default({ separator: '|' }))\n .on('data', (data) => {\n results.push(data);\n })\n .on('end', () => {\n console.log(results);\n });\n```\n\nonly gets me data inside the `on('end')` clause only. Outside it, accessing the variable result gives empty variable and even reassigning to another variable inside on end clause does not seem to work. please review and suggest a solution\n\n========================================\n\nTop Answer:\nIt is because the code outside would execute even before your program is done with reading data. Take a look at the following code:\n\n```\nlet results = [];\nconst csv = fs\n .createReadStream('data.csv')\n .pipe(csv.default({ separator: '|' }))\n .on('data', (data) => {\n results.push(data);\n })\n .on('end', () => {\n console.log(results);\n });\n\nconsole.log(results); You get the data only in `.on('end', ...)` because, the `.on('end')` callback gets executed when you are done with reading the file. So, when the `.on('end)` callback gets executed your `results` array is populated with data. That is why you get data only in `end` callback.\n\nNow, whatever you want to do with your `results` array, you should do it in the `.on('end')` callback.\n\n========================================\n\nCode:\n```text\nconst csv = fs\n  .createReadStream('data.csv')\n  .pipe(csv.default({ separator: '|' }))\n  .on('data', (data) => {\n    results.push(data);\n  })\n  .on('end', () => {\n    console.log(results);\n  });\n```\n\n```text\non('end')\n```\n\n```text\nconst csv = fs\n  .createReadStream('data.csv')\n  .pipe(csv.default({ separator: '|' }))\n  .on('data', (data) => {\n    results.push(data);\n  })\n  .on('end', () => {\n    console.log(results);\n    someFunction(results);\n  });\n\nfunction someFunction(data) {\n  // do anything with data\n}\n```\n\n```text\nresults\n```\n\n```text\nlet results = [];\nconst csv = fs\n  .createReadStream('data.csv')\n  .pipe(csv.default({ separator: '|' }))\n  .on('data', (data) => {\n    results.push(data);\n  })\n  .on('end', () => {\n    console.log(results);\n  });\n\nconsole.log(results); <- This line would execute before reading the file. So, results array is empty.\n```\n\n```text\n.on('end', ...)\n```\n\n```text\n.on('end')\n```\n\n```text\n.on('end)\n```\n\n```text\nresults\n```\n\n```text\nend\n```\n\n```text\nresults\n```\n\n```text\n.on('end')\n```\n\n```js\nvar data;\n$.ajax({\n    type: \"GET\",\n    url: \"csv_raaja_file.csv\",\n    dataType: \"text\",\n    success: function(response) {\n      data = $.csv.toArrays(response);\n      generateHtmlTable(data);\n    }\n});\n```\n\n========================================\n\nComments:\n- it does seem to work when i am using a function. however for better readability it would be better if i got the data outside the function. else all my logic working that data would have to go inside that. Is there anyway I can the get the resultant data to a variable instead of passing to function?","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":143,"estimatedTokens":790}}1099{"id":"stack-58961746","source":"stackoverflow","questionId":58961746,"title":"Is a Service provider really necessary in NestJS?","tags":["nestjs"],"text":"Title: Is a Service provider really necessary in NestJS?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to understand what the purpose of injecting service providers into a NestJS controller? The documentation here explains here how to use them, that's not the issue here: https://docs.nestjs.com/providers\n\nWhat I am trying to understand is, in most traditional web applications regardless of platform, a lot of the logic that would go into a NestJS service would otherwise just normally go right into a controller. Why did NestJS decide to move the provider into its own class/abstraction? What is the design advantages gained here for the developer?\n\n========================================\n\nCode:\n```text\n@Body()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":15,"estimatedTokens":184}}1100{"id":"stack-61939049","source":"stackoverflow","questionId":61939049,"title":"Nest.js swagger plugin not found under jenkins","tags":["jenkins","nestjs","nestjs-swagger"],"text":"Title: Nest.js swagger plugin not found under jenkins\nTags: jenkins, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nWith Nest.js i'm using @nestjs/swagger plugin. all works well on dev.\nin jekins, i'm pulling the code, and doing a build. For that, i have installed nest cli on the server.\ni'm getting this error at the build stage:\n\n```\n> nest build\nError \"@nestjs/swagger/plugin\" plugin could not be found!\n```\n\nwhat am i doing wrong?\nserver is ubuntu 17, in my nest-cli.json i have this:\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"plugins\": [\"@nestjs/swagger/plugin\"]\n }\n}\n```\n\nand again, it works fine locally. problem is only on jenkins workspace. thanks!\n\n========================================\n\nTop Answer:\nI had exactly the same issue.\n\nI solved it with this:\n\n- Make sure you have nestcli installed: `npm i -g @nestjs/cli`\n\n- Update nestcli on deployment before you make npm install: `nest update`\n\n- If this not helps, try another Swagger-Version. I had the problem with version 4.5.9, I upgraded to `@nestjs/swagger\": \"^4.5.11` and it helped.\n\nHope this works for you.\n\n========================================\n\nCode:\n```text\n> nest build\nError  \"@nestjs/swagger/plugin\" plugin could not be found!\n```\n\n```text\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger/plugin\"]\n  }\n}\n```\n\n```text\n\"compilerOptions\": {\n     \"plugins\": [\"@nestjs/swagger/dist/plugin\"]\n}\n```\n\n```text\nnpm i -g @nestjs/cli\n```\n\n```text\nnest update\n```\n\n```text\n@nestjs/swagger\": \"^4.5.11\n```\n\n```text\nnest\n```\n\n```text\nreflect-metadata\n```\n\n```text\nModule 'reflect-metadata' not found\n```\n\n```text\n\"engines\": {\n    \"node\": \">=16\"\n  }\n```\n\n========================================\n\nComments:\n- yeah! it helped me, reflect-metadata was exectly what I was missing! Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":102,"estimatedTokens":471}}1101{"id":"stack-60267806","source":"stackoverflow","questionId":60267806,"title":"NestJs transform GRPC exception to HTTP exception","tags":["javascript","nestjs","nestjs-gateways"],"text":"Title: NestJs transform GRPC exception to HTTP exception\nTags: javascript, nestjs, nestjs-gateways\nSource: Stack Overflow\n\nQuestion:\nI have a HTTP server that connects to a gateway over GRPC. the gateway also connects to other . GRPC microservices. the flow looks like this:\n\nClient -> HttpServer -> GRPC server (gateway) -> GRPC microservice server X\n\nThe way i handle errors currently is like so (please let me know if there is better practice) i will only show nessaccery code for brevity\n\n**GRPC microservice server X**\n\n```\n@GrpcMethod() get(clientDetails: Records.UserDetails.AsObject): Records.RecordResponse.AsObject {\n this.logger.log(\"Get Record for client\");\n throw new RpcException({message: 'some error', code: status.DATA_LOSS})\n }\n```\n\nthis simple throws an error to the GRPC client (which works fine)\n\n**GRPC Server**\n\n```\n@GrpcMethod() async get(data: Records.UserDetails.AsObject, metaData): Promise {\n try {\n return await this.hpGrpcRecordsService.get(data).toPromise();\n } catch(e) {\n throw new RpcException(e)\n }\n }\n```\n\nGrpc server catches the error which is in turn caught buy the global exception handler (this works fine)\n\n```\n@Catch(RpcException)\nexport class ExceptionFilter implements RpcExceptionFilter {\n catch(exception: RpcException, host: ArgumentsHost): Observable {\n if( Object.prototype.hasOwnProperty.call(exception, 'message') && \n Object.prototype.hasOwnProperty.call(exception.message, 'code') &&\n exception.message.code === 2\n ){ \n exception.message.code = 13\n }\n\n return throwError(exception.getError());\n }\n}\n```\n\nThis throws the error back to the Http server (grpc client, works fine)\n\nNow when it gets to the Http server i was hoping i could set up another RPC exception handler and transform the error into a HTTP except. but i'm unsure if it is possible, i have only been using nest for a few days and am yet to full understand it.\n\nHere is an example of what i was hoping to do (code is not working, just example of what i want). id prefer to globally catch the exceptions rather than have try/catch blocks everywhere\n\n```\n@Catch(RpcException)\nexport class ExceptionFilter implements RpcExceptionFilter {\n catch(exception: RpcException, host: ArgumentsHost): Observable {\n //Map UNKNOWN(2) grpc error to INTERNAL(13)\n if( Object.prototype.hasOwnProperty.call(exception, 'message') && \n Object.prototype.hasOwnProperty.call(exception.message, 'code') &&\n exception.message.code === 2\n ){ exception.message.code = 13 }\n\n throw new HttpException('GOT EM', HttpStatus.BAD_GATEWAY)\n }\n}\n```\n\n========================================\n\nTop Answer:\nI was able to create and return a custom error message from server to client since `RpcException`'s `getError()` method is of type `string | object`, its actual object is constructed at runtime. Here's what my implementation looks like\n\n**Microservice X**\n\n```\nimport { status } from '@grpc/grpc-js';\nimport { Injectable } from '@nestjs/common';\nimport { RpcException } from '@nestjs/microservices';\n\nimport { CreateUserRequest, CreateUserResponse } from 'xxxx';\n\ninterface CustomExceptionDetails {\n type: string;\n details: string,\n domain: string,\n metadata: { service: string }\n}\n\n@Injectable()\nexport class UsersService {\n\n users: CreateUserResponse[] = [];\n\n findOneById(id: string) {\n return this.users.find(e => e.id === id);\n }\n\n createUser(request: CreateUserRequest) {\n // verify if user already exists\n const userExists = this.findOneById(request.email);\n\n if (userExists) {\n const exceptionStatus = status.ALREADY_EXISTS;\n const details = {\n type: status[exceptionStatus],\n details: 'User with with email already exists',\n domain: 'xapis.com',\n metadata: {\n service: 'X_MICROSERVICE'\n }\n };\n\n throw new RpcException({\n code: exceptionStatus,\n message: JSON.stringify(details) // note here (payload is stringified)\n });\n }\n\n // create user\n const user = {\n id: request.email,\n firstname: request.firstname,\n lastname: request.lastname,\n phoneNumber: request.phoneNumber,\n email: request.email,\n };\n\n this.users.push(user);\n\n return user;\n }\n}\n```\n\n**Gateway Y Server (HttpExceptionFilter)**\n\n```\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, \nHttpStatus } from \"@nestjs/common\";\nimport { RpcException } from \"@nestjs/microservices\";\nimport { Request, Response } from 'express';\nimport { ErrorStatusMapper } from \"../utils/error-status-mapper.util\";\n\nimport { Metadata, status } from '@grpc/grpc-js';\n\ninterface CustomExceptionDetails {\n type: string;\n details: string,\n domain: string,\n metadata: { service: string }\n}\ninterface CustomException {\n code: status;\n details: T;\n metadata: Metadata;\n}\n\n@Catch(RpcException)\n export class HttpExceptionFilter implements ExceptionFilter {\n catch(exception: RpcException, host: ArgumentsHost) {\n const err = exception.getError();\n let _exception: CustomException;\n let details: CustomExceptionDetails;\n\n if (typeof err === 'object') {\n _exception = err as CustomException;\n details = (JSON.parse(_exception.details));\n }\n\n // **You can log your exception details here**\n // log exception (custom-logger)\n const loggerService: LoggerService =\n new LoggerService(FeatureService[\"CLIENT/UserAccountService\"]);\n\n loggerService.log(>{ type: LogType.ERROR, data: details });\n\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n // const request = ctx.getRequest();\n\n const mapper = new ErrorStatusMapper();\n const status = mapper.grpcToHttpMapper(_exception.code);\n const type = HttpStatus[status];\n\n response\n .status(status)\n .json({\n statusCode: status,\n message: details.details,\n error: type,\n });\n }\n}\n```\n\n**ErrorStatusMapper-util**\n\n```\nimport { status } from '@grpc/grpc-js';\nimport { Status } from \"@grpc/grpc-js/build/src/constants\";\nimport { HttpStatus, Injectable } from \"@nestjs/common\";\n\n@Injectable()\nexport class ErrorStatusMapper {\n grpcToHttpMapper(status: status): HttpStatus {\n let httpStatusEquivalent: HttpStatus;\n\n switch (status) {\n case Status.OK:\n httpStatusEquivalent = HttpStatus.OK;\n break;\n\n case Status.CANCELLED:\n httpStatusEquivalent = HttpStatus.METHOD_NOT_ALLOWED;\n break;\n\n case Status.UNKNOWN:\n httpStatusEquivalent = HttpStatus.BAD_GATEWAY;\n break;\n\n case Status.INVALID_ARGUMENT:\n httpStatusEquivalent = HttpStatus.UNPROCESSABLE_ENTITY;\n break;\n\n case Status.DEADLINE_EXCEEDED:\n httpStatusEquivalent = HttpStatus.REQUEST_TIMEOUT;\n break;\n\n case Status.NOT_FOUND:\n httpStatusEquivalent = HttpStatus.NOT_FOUND;\n break;\n\n case Status.ALREADY_EXISTS:\n httpStatusEquivalent = HttpStatus.CONFLICT;\n break;\n\n case Status.PERMISSION_DENIED:\n httpStatusEquivalent = HttpStatus.FORBIDDEN;\n break;\n\n case Status.RESOURCE_EXHAUSTED:\n httpStatusEquivalent = HttpStatus.TOO_MANY_REQUESTS;\n break;\n\n case Status.FAILED_PRECONDITION:\n httpStatusEquivalent = HttpStatus.PRECONDITION_REQUIRED;\n break;\n\n case Status.ABORTED:\n httpStatusEquivalent = HttpStatus.METHOD_NOT_ALLOWED;\n break;\n\n case Status.OUT_OF_RANGE:\n httpStatusEquivalent = HttpStatus.PAYLOAD_TOO_LARGE;\n break;\n\n case Status.UNIMPLEMENTED:\n httpStatusEquivalent = HttpStatus.NOT_IMPLEMENTED;\n break;\n\n case Status.INTERNAL:\n httpStatusEquivalent = HttpStatus.INTERNAL_SERVER_ERROR;\n break;\n\n case Status.UNAVAILABLE:\n httpStatusEquivalent = HttpStatus.NOT_FOUND;\n break;\n\n case Status.DATA_LOSS:\n httpStatusEquivalent = HttpStatus.INTERNAL_SERVER_ERROR;\n break;\n\n case Status.UNAUTHENTICATED:\n httpStatusEquivalent = HttpStatus.UNAUTHORIZED;\n break;\n\n default:\n httpStatusEquivalent = HttpStatus.INTERNAL_SERVER_ERROR;\n break;\n }\n\n return httpStatusEquivalent;\n }\n }\n```\n\n========================================\n\nCode:\n```text\n@GrpcMethod() get(clientDetails: Records.UserDetails.AsObject): Records.RecordResponse.AsObject {\n    this.logger.log(\"Get Record for client\");\n    throw new RpcException({message: 'some error', code: status.DATA_LOSS})\n  }\n```\n\n```text\n@GrpcMethod() async get(data: Records.UserDetails.AsObject, metaData): Promise<Records.RecordResponse.AsObject> {\n    try {\n      return await this.hpGrpcRecordsService.get(data).toPromise();\n    } catch(e) {\n      throw new RpcException(e)\n    }\n  }\n```\n\n```text\n@Catch(RpcException)\nexport class ExceptionFilter implements RpcExceptionFilter<RpcException> {\n  catch(exception: RpcException, host: ArgumentsHost): Observable<any> {\n    if( Object.prototype.hasOwnProperty.call(exception, 'message') && \n        Object.prototype.hasOwnProperty.call(exception.message, 'code') &&\n        exception.message.code === 2\n    ){ \n        exception.message.code = 13\n    }\n\n    return throwError(exception.getError());\n  }\n}\n```\n\n```text\n@Catch(RpcException)\nexport class ExceptionFilter implements RpcExceptionFilter<RpcException> {\n  catch(exception: RpcException, host: ArgumentsHost): Observable<any> {\n    //Map UNKNOWN(2) grpc error to INTERNAL(13)\n    if( Object.prototype.hasOwnProperty.call(exception, 'message') && \n        Object.prototype.hasOwnProperty.call(exception.message, 'code') &&\n        exception.message.code === 2\n    ){  exception.message.code = 13 }\n\n    throw new HttpException('GOT EM', HttpStatus.BAD_GATEWAY)\n  }\n}\n```\n\n```text\n@Catch(RpcException)\nexport class HttpExceptionFilter implements ExceptionFilter {\n  catch(exception: RpcException, host: ArgumentsHost) {\n\n    const err = exception.getError();\n    // console.log(err);\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n    response\n      .json({\n        message: err[\"details\"],\n        code: err['code'],\n        timestamp: new Date().toISOString(),\n        path: request.url,\n      });\n  }\n}\n```\n\n```text\nif(err['details'] === UserBusinessErrors.InvalidCredentials.message){\n this.logger.error(e);\n     throw new HttpException( UserBusinessErrors.InvalidCredentials.message, 409)\n } else {\n     this.logger.error(e);\n     throw new InternalServerErrorException();\n }\n```\n\n```text\nimport { status } from '@grpc/grpc-js';\nimport { Injectable } from '@nestjs/common';\nimport { RpcException } from '@nestjs/microservices';\n\nimport { CreateUserRequest, CreateUserResponse } from 'xxxx';\n\ninterface CustomExceptionDetails {\n    type: string;\n    details: string,\n    domain: string,\n    metadata: { service: string }\n}\n\n@Injectable()\nexport class UsersService {\n\n    users: CreateUserResponse[] = [];\n\n    findOneById(id: string) {\n        return this.users.find(e => e.id === id);\n    }\n\n    createUser(request: CreateUserRequest) {\n        // verify if user already exists\n        const userExists = this.findOneById(request.email);\n\n        if (userExists) {\n            const exceptionStatus = status.ALREADY_EXISTS;\n            const details = <CustomExceptionDetails>{\n                type: status[exceptionStatus],\n                details: 'User with with email already exists',\n                domain: 'xapis.com',\n                metadata: {\n                    service: 'X_MICROSERVICE'\n                }\n            };\n\n            throw new RpcException({\n                code: exceptionStatus,\n                message: JSON.stringify(details) // note here (payload is stringified)\n            });\n        }\n\n        // create user\n        const user = <CreateUserResponse>{\n            id: request.email,\n            firstname: request.firstname,\n            lastname: request.lastname,\n            phoneNumber: request.phoneNumber,\n            email: request.email,\n        };\n\n        this.users.push(user);\n\n        return user;\n    }\n}\n```\n\n```text\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, \nHttpStatus } from \"@nestjs/common\";\nimport { RpcException } from \"@nestjs/microservices\";\nimport { Request, Response } from 'express';\nimport { ErrorStatusMapper } from \"../utils/error-status-mapper.util\";\n\nimport { Metadata, status } from '@grpc/grpc-js';\n\ninterface CustomExceptionDetails {\n    type: string;\n    details: string,\n    domain: string,\n    metadata: { service: string }\n}\ninterface CustomException<T> {\n    code: status;\n    details: T;\n    metadata: Metadata;\n}\n\n@Catch(RpcException)\n export class HttpExceptionFilter implements ExceptionFilter {\n    catch(exception: RpcException, host: ArgumentsHost) {\n        const err = exception.getError();\n        let _exception: CustomException<string>;\n        let details: CustomExceptionDetails;\n\n        if (typeof err === 'object') {\n            _exception = err as CustomException<string>;\n            details = <CustomExceptionDetails>(JSON.parse(_exception.details));\n        }\n\n        // **You can log your exception details here**\n        // log exception (custom-logger)\n        const loggerService: LoggerService<CustomExceptionDetails> =\n        new LoggerService(FeatureService[\"CLIENT/UserAccountService\"]);\n\n        loggerService.log(<LogData<CustomExceptionDetails>>{ type: LogType.ERROR, data: details });\n\n        const ctx = host.switchToHttp();\n        const response = ctx.getResponse<Response>();\n        // const request = ctx.getRequest<Request>();\n\n        const mapper = new ErrorStatusMapper();\n        const status = mapper.grpcToHttpMapper(_exception.code);\n        const type = HttpStatus[status];\n\n        response\n            .status(status)\n            .json({\n                statusCode: status,\n                message: details.details,\n                error: type,\n            });\n    }\n}\n```\n\n```text\nimport { status } from '@grpc/grpc-js';\nimport { Status } from \"@grpc/grpc-js/build/src/constants\";\nimport { HttpStatus, Injectable } from \"@nestjs/common\";\n\n@Injectable()\nexport class ErrorStatusMapper {\n    grpcToHttpMapper(status: status): HttpStatus {\n        let httpStatusEquivalent: HttpStatus;\n\n        switch (status) {\n            case Status.OK:\n                httpStatusEquivalent = HttpStatus.OK;\n                break;\n\n            case Status.CANCELLED:\n                httpStatusEquivalent = HttpStatus.METHOD_NOT_ALLOWED;\n                break;\n\n            case Status.UNKNOWN:\n                httpStatusEquivalent = HttpStatus.BAD_GATEWAY;\n                break;\n\n            case Status.INVALID_ARGUMENT:\n                httpStatusEquivalent = HttpStatus.UNPROCESSABLE_ENTITY;\n                break;\n\n            case Status.DEADLINE_EXCEEDED:\n                httpStatusEquivalent = HttpStatus.REQUEST_TIMEOUT;\n                break;\n\n            case Status.NOT_FOUND:\n                httpStatusEquivalent = HttpStatus.NOT_FOUND;\n                break;\n\n            case Status.ALREADY_EXISTS:\n                httpStatusEquivalent = HttpStatus.CONFLICT;\n                break;\n\n            case Status.PERMISSION_DENIED:\n                httpStatusEquivalent = HttpStatus.FORBIDDEN;\n                break;\n\n            case Status.RESOURCE_EXHAUSTED:\n                httpStatusEquivalent = HttpStatus.TOO_MANY_REQUESTS;\n                break;\n\n            case Status.FAILED_PRECONDITION:\n                httpStatusEquivalent = HttpStatus.PRECONDITION_REQUIRED;\n                break;\n\n            case Status.ABORTED:\n                httpStatusEquivalent = HttpStatus.METHOD_NOT_ALLOWED;\n                break;\n\n            case Status.OUT_OF_RANGE:\n                httpStatusEquivalent = HttpStatus.PAYLOAD_TOO_LARGE;\n                break;\n\n            case Status.UNIMPLEMENTED:\n                httpStatusEquivalent = HttpStatus.NOT_IMPLEMENTED;\n                break;\n\n            case Status.INTERNAL:\n                httpStatusEquivalent = HttpStatus.INTERNAL_SERVER_ERROR;\n                break;\n\n            case Status.UNAVAILABLE:\n                httpStatusEquivalent = HttpStatus.NOT_FOUND;\n                break;\n\n            case Status.DATA_LOSS:\n                httpStatusEquivalent = HttpStatus.INTERNAL_SERVER_ERROR;\n               break;\n\n            case Status.UNAUTHENTICATED:\n                httpStatusEquivalent = HttpStatus.UNAUTHORIZED;\n                break;\n\n            default:\n                httpStatusEquivalent = HttpStatus.INTERNAL_SERVER_ERROR;\n                break;\n         }\n\n        return httpStatusEquivalent;\n    }\n }\n```\n\n```text\nRpcException\n```\n\n```text\ngetError()\n```\n\n```text\nstring | object\n```\n\n```js\n@Catch(HttpException)\n    export class HttpExceptionFilter implements ExceptionFilter {\n      catch(exception: HttpException, host: ArgumentsHost) {\n        const ctx = host.switchToHttp();\n        const response = ctx.getResponse<Response>();\n        const request = ctx.getRequest<Request>();\n        const status = exception.getStatus();\n    \n        response.status(status).json({\n          success: false,\n          statusCode: status,\n          message: exception.message,\n          path: request.url,\n        });\n      }\n    }\n```\n\n```js\n@Post('/register')\n  @Header('Content-Type', 'application/json')\n  async registerUser(@Body() credentials: CreateUserDto) {\n    return this.usersService.Register(credentials).pipe(\n      catchError((val) => {\n        throw new HttpException(val.message, 400);\n      }),\n    );\n  }\n```\n\n```text\npipe\n```\n\n```text\nRxJS\n```\n\n```text\npipe\n```\n\n========================================\n\nComments:\n- Nice one appoach\n- can you please the full code here, how to use HttpExceptionFilter in the controller and service?","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":642,"estimatedTokens":4287}}1102{"id":"stack-74516996","source":"stackoverflow","questionId":74516996,"title":"how to set multi type for one field (with type of array or object) of schema (Typescript , NestJs)","tags":["typescript","mongodb","mongoose","nestjs","schema"],"text":"Title: how to set multi type for one field (with type of array or object) of schema (Typescript , NestJs)\nTags: typescript, mongodb, mongoose, nestjs, schema\nSource: Stack Overflow\n\nQuestion:\nI want to set multi type for one field of my schema\n\nlike this:\n\n```\n@Schema({ validateBeforeSave: true, _id: false })\nclass example1 {\n a: string;\n b: number;\n}\n\n@Schema({ validateBeforeSave: true, _id: false })\nclass example2 {\n a: string;\n b: number;\n}\n\n@Schema({ collection: 'user', validateBeforeSave: true, timestamps: true })\nexport class User extends Document {\n @Prop({ type: example1 | example2 })\n firstProp: string;\n\n @Prop({ type: example1[] | example2[] })\n secondProp: example1[] | example2[];\n}\n```\n\nI want property with two type and an array with two or more type and i want to that mongoDB validate my schema\n\n========================================\n\nTop Answer:\nSeems like Mr. Alireza's answered is pretty decent.\n\n========================================\n\nCode:\n```text\n@Schema({ validateBeforeSave: true, _id: false })\nclass example1 {\n  a: string;\n  b: number;\n}\n\n@Schema({  validateBeforeSave: true, _id: false })\nclass example2 {\n  a: string;\n  b: number;\n}\n\n@Schema({ collection: 'user', validateBeforeSave: true, timestamps: true })\nexport class User extends Document {\n  @Prop({ type: example1 | example2 })\n  firstProp: string;\n\n  @Prop({ type: example1[] | example2[] })\n  secondProp: example1[] | example2[];\n}\n```\n\n```text\n@Prop([\n    { type: example1 },\n    { type: example2 },\n  ])\n  payMethod?: PayMethod[];\n```\n\n```text\n@Prop({\n  type:[\n    { type: example1 },\n    { type: example2 },\n  ]\n})\n  payMethod: PayMethod[];\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":82,"estimatedTokens":413}}1103{"id":"stack-55688331","source":"stackoverflow","questionId":55688331,"title":"Shared custom NestJS modules gives \"not a part of the currently processed module\" error","tags":["typescript","nestjs"],"text":"Title: Shared custom NestJS modules gives \"not a part of the currently processed module\" error\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nWe are running a couple of NestJS apps for different services. They all some common code, in our case a ConfigModule and a CacheModule. I want to break these out and put them in a corporate \"common\" npm package in order to minimize code copying.\n\nI'm running into a error though:\n\nNest cannot export a component/module that is not a part of the\ncurrently processed module (ConfigModule). Please verify whether each\nexported unit is available in this particular context\n\nI'm a bit lost as to what the problem actually is. Any help is much appreciated.\n\nIn `app.ts` on service A:\n\n```\nimport {ย ConfigModule } from '@company/npm-common';\n...\n@Module({\n imports: [ConfigModule, ...],\n})\nexport class AppModule {}\n```\n\nRight now `@company/npm-common` is imported in package.json with `file:../npm-common`\n\n`npm-common/index.ts`:\n\n```\nexport * from './Config';\n```\n\n`npm-common/Config/index.ts`\n\n```\nexport { ConfigService } from './config.service';\nexport { ConfigModule }ย from './config.module';\n```\n\n`npm-common/Config/config.service`:\n\n```\nimport { Global, Module } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Global()\n@Module({\n providers: [\n {\n provide: ConfigService,\n useValue: new ConfigService(),\n },\n ],\n exports: [ConfigService],\n})\nexport class ConfigModule {}\n```\n\n========================================\n\nCode:\n```js\nimport {ย ConfigModule } from '@company/npm-common';\n...\n@Module({\n  imports: [ConfigModule, ...],\n})\nexport class AppModule {}\n```\n\n```js\nexport *  from './Config';\n```\n\n```js\nexport { ConfigService } from './config.service';\nexport { ConfigModule }ย from './config.module';\n```\n\n```js\nimport { Global, Module } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Global()\n@Module({\n  providers: [\n    {\n      provide: ConfigService,\n      useValue: new ConfigService(),\n    },\n  ],\n  exports: [ConfigService],\n})\nexport class ConfigModule {}\n```\n\n```text\napp.ts\n```\n\n```text\n@company/npm-common\n```\n\n```text\nfile:../npm-common\n```\n\n```text\nnpm-common/index.ts\n```\n\n```text\nnpm-common/Config/index.ts\n```\n\n```text\nnpm-common/Config/config.service\n```\n\n========================================\n\nComments:\n- it looks like the code above is your config.module. can you please also the config.service file as well ?\n- Faced similar problem with ConfigHostModule that I don't use at all. How did you found the reason of the error?\n- I didn't. If I remember correctly I just noticed the difference in versions, change it so they both used the same, and then it worked. No idea why.\n- Wish I had seen this 5 days ago. Ran into the same issue, it was because the versions across the two applications/packages weren't aligned","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":129,"estimatedTokens":713}}1104{"id":"stack-63925257","source":"stackoverflow","questionId":63925257,"title":"diskStorage() not found in nestJs multer file upload","tags":["nestjs","multer"],"text":"Title: diskStorage() not found in nestJs multer file upload\nTags: nestjs, multer\nSource: Stack Overflow\n\nQuestion:\ni want use multer in my nestJs application like this:\n\n```\n@Post()\n@UseInterceptors(\n FileInterceptor('file', {\n storage: diskStorage({\n destination: './files',\n }),\n }),\n)\nasync upload(@Request() req, @Query() query: any, @UploadedFile() file) {\n console.log(file);\n}\n```\n\nBut my IDE (vscode) keeps saying: Cannot find name 'diskStorage' and is not compiling.\nI also register the MulterModule on the specified Module (FeatureModule).\n\nI can use\n\n```\n@UseInterceptors(\n FileInterceptor('file', { dest: '/data-path'}),\n)\n```\n\nBut i want change the filename for example. For this I need the diskStorage function\n\nWhat can i do, to resolve the issue?\n\n========================================\n\nCode:\n```text\n@Post()\n@UseInterceptors(\n    FileInterceptor('file', {\n        storage: diskStorage({\n            destination: './files',\n        }),\n    }),\n)\nasync upload(@Request() req, @Query() query: any, @UploadedFile() file) {\n    console.log(file);\n}\n```\n\n```text\n@UseInterceptors(\n    FileInterceptor('file', { dest: '/data-path'}),\n)\n```\n\n```text\nimport { diskStorage } from 'multer';\n```\n\n========================================\n\nComments:\n- Where are you importing `diskStorage` from?\n- import is from @nestjs/platform-express and in the @Module({ imports: [MulterModule.register()] .....\n- Shouldn't `diskStorage` come from the `multer` package?\n- no, the docu says platform-express:\n- The Nest module for `mutler` comes from `@nestjs&#47;platform-express`, but that function still comes from `multer`\n- @JayMcDoniel thanks for that hint. i got it working with the extra import what you said. `import { diskStorage } from 'multer';`","metadata":{"transformedAt":"2026-08-18T18:33:02.576Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":72,"estimatedTokens":438}}1105{"id":"stack-73703438","source":"stackoverflow","questionId":73703438,"title":"How to validate Dynamic key -> value DTO validation in nest js?","tags":["nestjs"],"text":"Title: How to validate Dynamic key -> value DTO validation in nest js?\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\n```\nimport { ApiProperty } from '@nestjs/swagger';\nimport { IsString, ValidateNested } from 'class-validator';\n\nexport class TestDto {\n @ApiProperty()\n test: string;\n}\n\nexport class UserReqDto {\n @ApiProperty()\n @IsString()\n id: string;\n\n @ApiProperty()\n @ValidateNested({ each: true })\n data: object;\n}\n\nconst sampleData = {\n id: 'asbd',\n data: {\n ['any dynamic key 1']: {\n test: '1',\n },\n ['any dynamic key 2']: {\n test: '2',\n },\n },\n};\n```\n\nHere `UserReqDto` is my main DTO and `TestDto` is child DTO.\nI need to validate `sampleData` type of data.\n\nHow can I do that?\n\nin data field i need to validate object of `TestDto` type's objects\n\n========================================\n\nCode:\n```text\nimport { ApiProperty } from '@nestjs/swagger';\nimport { IsString, ValidateNested } from 'class-validator';\n\nexport class TestDto {\n  @ApiProperty()\n  test: string;\n}\n\nexport class UserReqDto {\n  @ApiProperty()\n  @IsString()\n  id: string;\n\n  @ApiProperty()\n  @ValidateNested({ each: true })\n  data: object;\n}\n\nconst sampleData = {\n  id: 'asbd',\n  data: {\n    ['any dynamic key 1']: {\n      test: '1',\n    },\n    ['any dynamic key 2']: {\n      test: '2',\n    },\n  },\n};\n```\n\n```text\nUserReqDto\n```\n\n```text\nTestDto\n```\n\n```text\nsampleData\n```\n\n```text\nTestDto\n```\n\n```text\n@ApiProperty()\n@ValidateNested({ each: true })\ndata: Map<string, TestDto>\n```\n\n```text\n@ApiProperty()\n@ValidateNested({ each: true })\n@Type(() => TestDto)\ndata: Map<string, TestDto>\n```\n\n```text\nMap<string, TestDto>\n```\n\n```text\ndata\n```\n\n```text\n@ValidateNested\n```\n\n```text\nclass-transformer\n```\n\n```text\nTestDto\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":127,"estimatedTokens":426}}1106{"id":"stack-63173296","source":"stackoverflow","questionId":63173296,"title":"Testing Service with Mongoose in NestJS","tags":["javascript","unit-testing","nestjs","nestjs-testing"],"text":"Title: Testing Service with Mongoose in NestJS\nTags: javascript, unit-testing, nestjs, nestjs-testing\nSource: Stack Overflow\n\nQuestion:\nI am trying to test my LoggingService in NestJS and while I cannot see anything that is wrong with the test the error I am getting is `Error: Cannot spy the save property because it is not a function; undefined given instead`\n\nThe function being tested (trimmed for brevity):\n\n```\n@Injectable()\nexport class LoggingService {\n constructor(\n @InjectModel(LOGGING_AUTH_MODEL) private readonly loggingAuthModel: Model,\n @InjectModel(LOGGING_EVENT_MODEL) private readonly loggingEventModel: Model,\n ) {\n }\n \n async authLogging(req: Request, requestId: unknown, apiKey: string, statusCode: number, internalMsg: string) {\n \n const authLog: IOpenApiAuthLog = {\n///\n }\n \n await new this.loggingAuthModel(authLog).save();\n }\n}\n```\n\nThis is pretty much my first NestJS test and as best I can tell this is the correct way to test it, considering the error is right at the end it seems about right.\n\n```\ndescribe('LoggingService', () => {\n let service: LoggingService;\n let mockLoggingAuthModel: IOpenApiAuthLogDocument;\n let request;\n \n beforeEach(async () => {\n request = new JestRequest();\n \n const module: TestingModule = await Test.createTestingModule({\n providers: [\n LoggingService,\n {\n provide: getModelToken(LOGGING_AUTH_MODEL),\n useValue: MockLoggingAuthModel,\n },\n {\n provide: getModelToken(LOGGING_EVENT_MODEL),\n useValue: MockLoggingEventModel,\n },\n ],\n }).compile();\n \n service = module.get(LoggingService);\n mockLoggingAuthModel = module.get(getModelToken(LOGGING_AUTH_MODEL));\n });\n \n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n \n it('authLogging', async () => {\n const reqId = 'mock-request-id';\n const mockApiKey = 'mock-api-key';\n const mockStatusCode = 200;\n const mockInternalMessage = 'mock-message';\n \n await service.authLogging(request, reqId, mockApiKey, mockStatusCode, mockInternalMessage);\n \n const authSpy = jest.spyOn(mockLoggingAuthModel, 'save');\n expect(authSpy).toBeCalled();\n });\n});\n```\n\nThe mock Model:\n\n```\nclass MockLoggingAuthModel {\n constructor() {\n }\n \n public async save(): Promise {\n }\n}\n```\n\n========================================\n\nTop Answer:\nThe issue comes from the fact that you pass a class to the `TestingModule` while telling it that it's a value.\n\nUse `useClass` to create the `TestingModule`:\n\n```\nbeforeEach(async () => {\n request = new JestRequest();\n \n const module: TestingModule = await Test.createTestingModule({\n providers: [\n LoggingService,\n {\n provide: getModelToken(LOGGING_AUTH_MODEL),\n // Use useClass\n useClass: mockLoggingAuthModel,\n },\n {\n provide: getModelToken(LOGGING_EVENT_MODEL),\n // Use useClass\n useClass: MockLoggingEventModel,\n },\n ],\n }).compile();\n \n service = module.get(LoggingService);\n mockLoggingAuthModel = module.get(getModelToken(LOGGING_AUTH_MODEL));\n});\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LoggingService {\n  constructor(\n    @InjectModel(LOGGING_AUTH_MODEL) private readonly loggingAuthModel: Model<IOpenApiAuthLogDocument>,\n    @InjectModel(LOGGING_EVENT_MODEL) private readonly loggingEventModel: Model<IOpenApiEventLogDocument>,\n  ) {\n  }\n  \n  async authLogging(req: Request, requestId: unknown, apiKey: string, statusCode: number, internalMsg: string) {\n    \n    const authLog: IOpenApiAuthLog = {\n///\n    }\n    \n    await new this.loggingAuthModel(authLog).save();\n  }\n}\n```\n\n```text\ndescribe('LoggingService', () => {\n  let service: LoggingService;\n  let mockLoggingAuthModel: IOpenApiAuthLogDocument;\n  let request;\n  \n  beforeEach(async () => {\n    request = new JestRequest();\n    \n    const module: TestingModule = await Test.createTestingModule({\n      providers: [\n        LoggingService,\n        {\n          provide: getModelToken(LOGGING_AUTH_MODEL),\n          useValue: MockLoggingAuthModel,\n        },\n        {\n          provide: getModelToken(LOGGING_EVENT_MODEL),\n          useValue: MockLoggingEventModel,\n        },\n      ],\n    }).compile();\n    \n    service = module.get(LoggingService);\n    mockLoggingAuthModel = module.get(getModelToken(LOGGING_AUTH_MODEL));\n  });\n  \n  it('should be defined', () => {\n    expect(service).toBeDefined();\n  });\n  \n  it('authLogging', async () => {\n    const reqId = 'mock-request-id';\n    const mockApiKey = 'mock-api-key';\n    const mockStatusCode = 200;\n    const mockInternalMessage = 'mock-message';\n    \n    await service.authLogging(request, reqId, mockApiKey, mockStatusCode, mockInternalMessage);\n    \n    const authSpy = jest.spyOn(mockLoggingAuthModel, 'save');\n    expect(authSpy).toBeCalled();\n  });\n});\n```\n\n```text\nclass MockLoggingAuthModel {\n  constructor() {\n  }\n  \n  public async save(): Promise<void> {\n  }\n}\n```\n\n```text\nError: Cannot spy the save property because it is not a function; undefined given instead\n```\n\n```text\nthis.model(data)\n```\n\n```text\nbeforeEach(async () => {\n  request = new JestRequest();\n  \n  const module: TestingModule = await Test.createTestingModule({\n    providers: [\n      LoggingService,\n      {\n        provide: getModelToken(LOGGING_AUTH_MODEL),\n        // Use useClass\n        useClass: mockLoggingAuthModel,\n      },\n      {\n        provide: getModelToken(LOGGING_EVENT_MODEL),\n        // Use useClass\n        useClass: MockLoggingEventModel,\n      },\n    ],\n  }).compile();\n  \n  service = module.get(LoggingService);\n  mockLoggingAuthModel = module.get(getModelToken(LOGGING_AUTH_MODEL));\n});\n```\n\n```text\nTestingModule\n```\n\n```text\nuseClass\n```\n\n```text\nTestingModule\n```\n\n========================================\n\nComments:\n- That gives me a new error: `TypeError: this.loggingAuthModel is not a constructor`\n- updated the OP with the rest of what's in the service file, not much more to it. Thanks\n- Thanks, @Baboo_ for the help, but after finding github.com/jmcdo29/testing-nestjs/tree/master/apps/mongo-sam&zwnj;&#8203;ple I ended up just changing the code, the example also suggests avoiding doing what I have done as it makes testing very complicated.","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":249,"estimatedTokens":1517}}1107{"id":"stack-78113113","source":"stackoverflow","questionId":78113113,"title":"nest start removes my json files from dist","tags":["typescript","nestjs","yarnpkg"],"text":"Title: nest start removes my json files from dist\nTags: typescript, nestjs, yarnpkg\nSource: Stack Overflow\n\nQuestion:\nwhen I build my nestjs application, I need certain json files to be copied to the dist. especially I have an \"engines\" folder, and I need the json files to be on dist/and prod, as they are in src/engines.\n\nHowever, nest start removes the dist folder and recreates with only d.ts, js and js.map, and my json files are removed.\n\nI tried to do the following in my `package.json` `scripts`:\n\n```\n\"copy:json\": \"copyfiles -u 2 src/engines/**/*.json dist/engines\",\n\"start\": \"nest start && yarn copy:json\",\n\"start:dev\": \"nest start --watch && yarn copy:json\",\n\"start:debug\": \"nest start --debug --watch && yarn copy:json\",\n\"start:prod\": \"node dist/main && yarn copy:json\",\n```\n\nI don't know why, but when I do start:dev, I still have any *json* file in my `dist` directory.\nThe `yarn copy:json` alone works well (copies the right files in the right location)\n\n========================================\n\nTop Answer:\nSolution: avoid `src` in the path configuration for assets\n\nWhile many examples on the internet include the `src` prefix in the path (e.g., `src/engines/**/*.json`), it's unnecessary. The correct approach is simply to omit `src` from the path.\n\nFor example:\n`\"include\": \"engines/**/*.json\"`\n\n========================================\n\nCode:\n```text\n\"copy:json\": \"copyfiles -u 2 src/engines/**/*.json dist/engines\",\n\"start\": \"nest start && yarn copy:json\",\n\"start:dev\": \"nest start --watch && yarn copy:json\",\n\"start:debug\": \"nest start --debug --watch && yarn copy:json\",\n\"start:prod\": \"node dist/main && yarn copy:json\",\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\ndist\n```\n\n```text\nyarn copy:json\n```\n\n```text\n\"compilerOptions\": {\n    \"deleteOutDir\": true,\n    \"assets\": [\"engines/**/*.json\"],\n    \"watchAssets\": true\n  }\n```\n\n```text\n*.json\n```\n\n```text\nnest-cli.json\n```\n\n```text\nsrc\n```\n\n```text\nsrc\n```\n\n```text\nsrc/engines/**/*.json\n```\n\n```text\nsrc\n```\n\n```text\n\"include\": \"engines/**/*.json\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":94,"estimatedTokens":511}}1108{"id":"stack-56088510","source":"stackoverflow","questionId":56088510,"title":"How to log all exceptions to a custom logger in nest.js?","tags":["typescript","nestjs"],"text":"Title: How to log all exceptions to a custom logger in nest.js?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a custom logging service which outputs structured logs in a way that can be shipped to a third party log collection service.\n\nI'm wondering what the best way to make sure that I catch all errors, from HTTP errors, to unhandled JS errors (e.g. TypeErrors, Uncaught Rejected Promises, etc), and ship them to said logger.\n\nMost of the examples I have seen address HTTP errors only.\n\n========================================\n\nTop Answer:\nThis is an example from the nestjs documentation that catches all the exceptions, does the logging, without modifying the actual response.\n\n```\nimport {\n ExceptionFilter,\n Catch,\n ArgumentsHost,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\nimport { HttpAdapterHost } from '@nestjs/core';\n\nimport { MyLogger } from '../modules/logger/logger.service';\n\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n constructor(private readonly httpAdapterHost: HttpAdapterHost) {}\n\n catch(exception: unknown, host: ArgumentsHost): void {\n const { httpAdapter } = this.httpAdapterHost;\n const ctx = host.switchToHttp();\n\n const logger = new MyLogger();\n logger.setContext(exception['name']);\n logger.error(exception['message']);\n\n const httpStatus =\n exception instanceof HttpException\n ? exception.getStatus()\n : HttpStatus.INTERNAL_SERVER_ERROR;\n\n httpAdapter.reply(ctx.getResponse(), exception['response'], httpStatus);\n }\n}\n```\n\nThen, in `main.ts`:\n\n```\napp.useGlobalFilters(new AllExceptionsFilter(app.get(HttpAdapterHost)));\n```\n\n========================================\n\nCode:\n```text\nApp.useGlobalFilters(new MyFilter())\n```\n\n```text\nProvide: APP_FILTER,\nuseClass: MyFilter\n```\n\n```text\napp.useGlobalInterceptors(new YourInterceptor());\n```\n\n```text\nimport { Logger, LoggerErrorInterceptor } from 'nestjs-pino';\n\n// bootstrap function\n// const app = ...\nconst logger = app.get(Logger);\n\napp.useLogger(logger);\napp.useGlobalInterceptors(new LoggerErrorInterceptor());\n// ...rest\n```\n\n```text\nimport {\n  ExceptionFilter,\n  Catch,\n  ArgumentsHost,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\nimport { HttpAdapterHost } from '@nestjs/core';\n\nimport { MyLogger } from '../modules/logger/logger.service';\n\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}\n\n  catch(exception: unknown, host: ArgumentsHost): void {\n    const { httpAdapter } = this.httpAdapterHost;\n    const ctx = host.switchToHttp();\n\n    const logger = new MyLogger();\n    logger.setContext(exception['name']);\n    logger.error(exception['message']);\n\n    const httpStatus =\n      exception instanceof HttpException\n        ? exception.getStatus()\n        : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    httpAdapter.reply(ctx.getResponse(), exception['response'], httpStatus);\n  }\n}\n```\n\n```text\napp.useGlobalFilters(new AllExceptionsFilter(app.get(HttpAdapterHost)));\n```\n\n```text\nmain.ts\n```\n\n========================================\n\nComments:\n- My question was related specifically with the framework Nest.JS, which has a very specific error/exception handling approach. This answer may be correct of a pure node question, but is not relevant to working inside a Nest.JS application.\n- The problems is you can have a globalFilter to catch all the errors using useGlobalFilters (docs.nestjs.com/exception-filters) but thatโ€™s just the common error. Your question was related to all the errors which is not related to nestjs. I let you find your way in the link above.\n- Your edit is more relevant, and since asking my question, the approach I have taken. It does indeed catch TypeErrors, and errors that occur at boot, provided that they happen at least after the Nest app has been created.","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":132,"estimatedTokens":959}}1109{"id":"stack-72495885","source":"stackoverflow","questionId":72495885,"title":"Error after updgrading @nestjs/mongoose from 9.0.3 to 9.1.0 \"Error: Nest can't resolve dependencies of the WatchlistService\"","tags":["mongoose","nestjs"],"text":"Title: Error after updgrading @nestjs/mongoose from 9.0.3 to 9.1.0 \"Error: Nest can't resolve dependencies of the WatchlistService\"\nTags: mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nAfter updating @nestjs/mongoose from 9.0.3 to 9.1.0, I encountered following error:\n\n```\n[Nest] 3818 - 06/04/2022, 12:50:13 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the WatchlistService (?). Please make sure that the argument PortfolioModel at index [0] is available in the AppModule context.\n\nPotential solutions:\n- If PortfolioModel is a provider, is it part of the current AppModule?\n- If PortfolioModel is exported from a separate @Module, is that module imported within AppModule?\n @Module({\n imports: [ /* the Module containing PortfolioModel */ ]\n })\n\nError: Nest can't resolve dependencies of the WatchlistService (?). Please make sure that the argument PortfolioModel at index [0] is available in the AppModule context.\n\nPotential solutions:\n- If PortfolioModel is a provider, is it part of the current AppModule?\n- If PortfolioModel is exported from a separate @Module, is that module imported within AppModule?\n @Module({\n imports: [ /* the Module containing PortfolioModel */ ]\n })\n\n at Injector.lookupComponentInParentModules (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:231:19)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at Injector.resolveComponentInstance (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:184:33)\n at resolveParam (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:106:38)\n at async Promise.all (index 0)\n at Injector.resolveConstructorParams (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:121:27)\n at Injector.loadInstance (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:52:9)\n at Injector.loadProvider (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:74:9)\n at async Promise.all (index 4)\n at InstanceLoader.createInstancesOfProviders (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:44:9)\n at /home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:29:13\n at async Promise.all (index 1)\n at InstanceLoader.createInstances (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:28:9)\n at InstanceLoader.createInstancesOfDependencies (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:18:9)\n at /home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/nest-factory.js:96:17\n at Function.asyncRun (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/errors/exceptions-zone.js:22:13)\n```\n\nThis is my setup:\n\n***portfolio.entity.ts***\n\n```\nexport class Portfolio extends Document {\n @Prop({ required: true, trim: true, maxlength: 100, minlength: 1 })\n name: string\n}\n\nexport const PortfolioSchema = SchemaFactory.createForClass(Portfolio)\n```\n\n***database.module.ts***\n\n```\nconst databaseModules = [\n MongooseModule.forRoot(uris.MONGO_PRIMARY_CONNECTION_STRING, {\n connectionName: 'primary_connection'\n }),\n MongooseModule.forFeature(\n [{ name: Portfolio.name, schema: PortfolioSchema }],\n 'primary_connection'\n ),\n]\n\n@Module({\n imports: [...databaseModules],\n exports: [...databaseModules]\n})\nexport class DatabaseModule {}\n```\n\n***app.module.ts***\n\n```\n@Module({\n imports: [DatabaseModule],\n controllers: [\n AccountController\n ],\n providers: [\n AccountService\n ]\n})\nexport class AppModule {}\n```\n\n***account.service.ts***\n\n```\n@Injectable()\nexport class AccountService {\n constructor(\n @InjectModel(Portfolio.name) private portfolioModel: Model\n ) {}\n}\n```\n\n***package.json***\n\n```\n{\n \"name\": \"api-new\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"private\": true,\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"prebuild\": \"rimraf dist\",\n \"build\": \"nest build\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n \"start\": \"nest start\",\n \"start:dev\": \"nest start --watch\",\n \"start:debug\": \"nest start --debug --watch\",\n \"start:prod\": \"node dist/main\",\n \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n \"test\": \"jest --testTimeout=30000 --runInBand --forceExit\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"8.4.6\",\n \"@nestjs/core\": \"8.4.6\",\n \"@nestjs/mapped-types\": \"*\",\n \"@nestjs/mongoose\": \"9.1.0\",\n \"@nestjs/platform-express\": \"^8.0.0\",\n \"@nestjs/swagger\": \"^5.1.4\",\n \"@types/lodash\": \"^4.14.181\",\n \"class-transformer\": \"^0.4.0\",\n \"class-validator\": \"^0.13.1\",\n \"lodash\": \"^4.17.21\",\n \"mongodb-memory-server\": \"^8.4.2\",\n \"mongoose\": \"^6.0.12\",\n \"reflect-metadata\": \"^0.1.13\",\n \"rimraf\": \"^3.0.2\",\n \"rxjs\": \"^7.2.0\",\n \"swagger-ui-express\": \"^4.1.6\"\n },\n \"devDependencies\": {\n \"@nestjs/cli\": \"^8.2.4\",\n \"@nestjs/schematics\": \"^8.0.0\",\n \"@nestjs/testing\": \"^8.0.0\",\n \"@types/express\": \"^4.17.13\",\n \"@types/express-session\": \"^1.17.4\",\n \"@types/jest\": \"^27.0.1\",\n \"@types/node\": \"^16.0.0\",\n \"@types/supertest\": \"^2.0.11\",\n \"@typescript-eslint/eslint-plugin\": \"^4.28.2\",\n \"@typescript-eslint/parser\": \"^4.28.2\",\n \"eslint\": \"^7.30.0\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-prettier\": \"^3.4.0\",\n \"jest\": \"^27.0.6\",\n \"prettier\": \"^2.3.2\",\n \"supertest\": \"^6.1.3\",\n \"ts-jest\": \"^27.0.3\",\n \"ts-loader\": \"^9.2.3\",\n \"ts-node\": \"^10.0.0\",\n \"tsconfig-paths\": \"^3.10.1\",\n \"typescript\": \"^4.3.5\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\n[Nest] 3818  - 06/04/2022, 12:50:13 AM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the WatchlistService (?). Please make sure that the argument PortfolioModel at index [0] is available in the AppModule context.\n\nPotential solutions:\n- If PortfolioModel is a provider, is it part of the current AppModule?\n- If PortfolioModel is exported from a separate @Module, is that module imported within AppModule?\n  @Module({\n    imports: [ /* the Module containing PortfolioModel */ ]\n  })\n\nError: Nest can't resolve dependencies of the WatchlistService (?). Please make sure that the argument PortfolioModel at index [0] is available in the AppModule context.\n\nPotential solutions:\n- If PortfolioModel is a provider, is it part of the current AppModule?\n- If PortfolioModel is exported from a separate @Module, is that module imported within AppModule?\n  @Module({\n    imports: [ /* the Module containing PortfolioModel */ ]\n  })\n\n    at Injector.lookupComponentInParentModules (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:231:19)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n    at Injector.resolveComponentInstance (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:184:33)\n    at resolveParam (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:106:38)\n    at async Promise.all (index 0)\n    at Injector.resolveConstructorParams (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:121:27)\n    at Injector.loadInstance (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:52:9)\n    at Injector.loadProvider (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/injector.js:74:9)\n    at async Promise.all (index 4)\n    at InstanceLoader.createInstancesOfProviders (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:44:9)\n    at /home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:29:13\n    at async Promise.all (index 1)\n    at InstanceLoader.createInstances (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:28:9)\n    at InstanceLoader.createInstancesOfDependencies (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/injector/instance-loader.js:18:9)\n    at /home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/nest-factory.js:96:17\n    at Function.asyncRun (/home/tobias/Github/Financl/financl-api/node_modules/@nestjs/core/errors/exceptions-zone.js:22:13)\n```\n\n```js\nexport class Portfolio extends Document {\n  @Prop({ required: true, trim: true, maxlength: 100, minlength: 1 })\n  name: string\n}\n\nexport const PortfolioSchema = SchemaFactory.createForClass(Portfolio)\n```\n\n```js\nconst databaseModules = [\n  MongooseModule.forRoot(uris.MONGO_PRIMARY_CONNECTION_STRING, {\n    connectionName: 'primary_connection'\n  }),\n  MongooseModule.forFeature(\n    [{ name: Portfolio.name, schema: PortfolioSchema }],\n    'primary_connection'\n  ),\n]\n\n@Module({\n  imports: [...databaseModules],\n  exports: [...databaseModules]\n})\nexport class DatabaseModule {}\n```\n\n```js\n@Module({\n  imports: [DatabaseModule],\n  controllers: [\n    AccountController\n  ],\n  providers: [\n    AccountService\n  ]\n})\nexport class AppModule {}\n```\n\n```js\n@Injectable()\nexport class AccountService {\n  constructor(\n    @InjectModel(Portfolio.name) private portfolioModel: Model<Portfolio>\n  ) {}\n}\n```\n\n```json\n{\n  \"name\": \"api-new\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest --testTimeout=30000 --runInBand --forceExit\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"8.4.6\",\n    \"@nestjs/core\": \"8.4.6\",\n    \"@nestjs/mapped-types\": \"*\",\n    \"@nestjs/mongoose\": \"9.1.0\",\n    \"@nestjs/platform-express\": \"^8.0.0\",\n    \"@nestjs/swagger\": \"^5.1.4\",\n    \"@types/lodash\": \"^4.14.181\",\n    \"class-transformer\": \"^0.4.0\",\n    \"class-validator\": \"^0.13.1\",\n    \"lodash\": \"^4.17.21\",\n    \"mongodb-memory-server\": \"^8.4.2\",\n    \"mongoose\": \"^6.0.12\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^7.2.0\",\n    \"swagger-ui-express\": \"^4.1.6\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^8.2.4\",\n    \"@nestjs/schematics\": \"^8.0.0\",\n    \"@nestjs/testing\": \"^8.0.0\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/express-session\": \"^1.17.4\",\n    \"@types/jest\": \"^27.0.1\",\n    \"@types/node\": \"^16.0.0\",\n    \"@types/supertest\": \"^2.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^4.28.2\",\n    \"@typescript-eslint/parser\": \"^4.28.2\",\n    \"eslint\": \"^7.30.0\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-prettier\": \"^3.4.0\",\n    \"jest\": \"^27.0.6\",\n    \"prettier\": \"^2.3.2\",\n    \"supertest\": \"^6.1.3\",\n    \"ts-jest\": \"^27.0.3\",\n    \"ts-loader\": \"^9.2.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"tsconfig-paths\": \"^3.10.1\",\n    \"typescript\": \"^4.3.5\"\n  }\n}\n```\n\n```js\n@InjectModel(Portfolio.name, 'primary_connection') private portfolioModel: Model<Portfolio>\n```\n\n```text\nInjectModel\n```\n\n========================================\n\nComments:\n- This gets rid of the error. But I did not have to do this before the upgrade. Nestjs was able to find the correct model without specifying the connection name. What changed?\n- I don't know. But by looking at the current source code of `@nestjs&#47;mongoose`, this ins't possible due to how provider's token is build.","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":341,"estimatedTokens":2989}}1110{"id":"stack-73905987","source":"stackoverflow","questionId":73905987,"title":"TypeORM No metadata for \\\"MyEntity\\\" was found","tags":["postgresql","nestjs","datasource","typeorm"],"text":"Title: TypeORM No metadata for \\\"MyEntity\\\" was found\nTags: postgresql, nestjs, datasource, typeorm\nSource: Stack Overflow\n\nQuestion:\nI 1. have the following datasource on \"app-data-source.ts\"\n\n```\nimport { DataSource } from \"typeorm\";\nimport { App } from \"./entities/app\";\n\nexport const appDataSource = new DataSource({\n type: 'postgres',\n host: process.env.CONFIG_DB_HOST,\n port: 5432,\n username: process.env.CONFIG_DB_USER,\n password: process.env.CONFIG_DB_PASSWORD,\n database: process.env.CONFIG_DB_DATABASE,\n entities: [App],\n synchronize: false,\n});\n```\n\n- Which uses the entity App on \"entities/app.ts\"\n\n```\nimport { Column, Entity, PrimaryColumn } from \"typeorm\";\n\n@Entity('apps')\nexport class App {\n @PrimaryColumn()\n tenant_id: number;\n \n @Column()\n client_id: string;\n \n @Column()\n legacy_client_id: string;\n\n @Column()\n user_pool: string;\n}\n```\n\n- And the following module that queries the Entity **App**(Shown above on number 2).\n\n```\nimport { App } from './entities/app';\nimport { appDataSource } from './app-data-source';\n\nexport class AuthService {\n async getApp() {\n let tenant= await appDataSource.getRepository(App).findOneBy({\n client_id: clientId\n });\n }\n}\n```\n\nHowever I get the following Error.\n\n```\n{\n \"errorMessage\": \"No metadata for \\\"App\\\" was found.\",\n \"errorType\": \"EntityMetadataNotFoundError\",\n \"stackTrace\": [\n \"EntityMetadataNotFoundError: No metadata for \\\"App\\\" was found.\",\n \" at DataSource.getMetadata (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:181364:19)\",\n \" at get metadata [as metadata] (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185119:40)\",\n \" at Repository.findOneBy (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185312:44)\",\n \" at AuthService.getAccessToken (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:57451:89)\",\n \" at handler (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:32:27)\"\n ]\n}\n```\n\n========================================\n\nCode:\n```js\nimport { DataSource } from \"typeorm\";\nimport { App } from \"./entities/app\";\n\nexport const appDataSource = new DataSource({\n    type: 'postgres',\n    host: process.env.CONFIG_DB_HOST,\n    port: 5432,\n    username: process.env.CONFIG_DB_USER,\n    password: process.env.CONFIG_DB_PASSWORD,\n    database: process.env.CONFIG_DB_DATABASE,\n    entities: [App],\n    synchronize: false,\n});\n```\n\n```js\nimport { Column, Entity, PrimaryColumn } from \"typeorm\";\n\n@Entity('apps')\nexport class App {\n    @PrimaryColumn()\n    tenant_id: number;\n    \n    @Column()\n    client_id: string;\n    \n    @Column()\n    legacy_client_id: string;\n\n    @Column()\n    user_pool: string;\n}\n```\n\n```js\nimport { App } from './entities/app';\nimport { appDataSource } from './app-data-source';\n\nexport class AuthService {\n   async getApp() {\n     let tenant=  await appDataSource.getRepository(App).findOneBy({\n                client_id: clientId\n            });\n     }\n}\n```\n\n```json\n{\n    \"errorMessage\": \"No metadata for \\\"App\\\" was found.\",\n    \"errorType\": \"EntityMetadataNotFoundError\",\n    \"stackTrace\": [\n        \"EntityMetadataNotFoundError: No metadata for \\\"App\\\" was found.\",\n        \"    at DataSource.getMetadata (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:181364:19)\",\n        \"    at get metadata [as metadata] (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185119:40)\",\n        \"    at Repository.findOneBy (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185312:44)\",\n        \"    at AuthService.getAccessToken (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:57451:89)\",\n        \"    at handler (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:32:27)\"\n    ]\n}\n```\n\n```js\n// initialize\nawait appDataSource.initialize();\nlet tenant=  await appDataSource.getRepository(App).findOneBy({\n    client_id: clientId\n}); \n\n// destroy the connection\nawait appDataSource.destroy()\n```\n\n```text\nappDataSource.initialize();\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":156,"estimatedTokens":948}}1111{"id":"stack-67158855","source":"stackoverflow","questionId":67158855,"title":"Messages Patterns - RabbitMQ/NestJS","tags":["rabbitmq","nestjs","node-amqplib"],"text":"Title: Messages Patterns - RabbitMQ/NestJS\nTags: rabbitmq, nestjs, node-amqplib\nSource: Stack Overflow\n\nQuestion:\nI'm trying to integrate to a project done using NestJS, a simple api where you can publish messages with a name (or pattern) and send it to that system that has implemented a handler that matches the name.\n\nThe system I'm building is really small, it wouldn't make much of a sense using NestJS for that.\n\nThe problem I'm having is the following:\n\nI'm creating a simple api that triggers the publish of the message onto a queue.\nThe consumer is on a system using NestJS.\n\nI can't figure out how to give that messages a pattern that is recognized by that system.\nFor example:\n\nLet's say I want to publish a message that has a name of \"CreateRecord\" with a payload to be processed from the other system that has a handler with the same name with an implementation.\n\nUsing amqplib how do I give messages a name or pattern?\n\n========================================\n\nCode:\n```text\npublish(\n  'my_exchange',\n  'routing_key',\n  { pattern: 'CreateRecord', data: 'Record' },\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":31,"estimatedTokens":272}}1112{"id":"stack-69853812","source":"stackoverflow","questionId":69853812,"title":"Typeorm/Nestjs Raw query usage forcing lowercase to column name","tags":["sql","typescript","postgresql","nestjs","typeorm"],"text":"Title: Typeorm/Nestjs Raw query usage forcing lowercase to column name\nTags: sql, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI need a help on executing a query using nest/typeorm;\n\nIm using Typeorm \"InjectConnection\" to build a raw query into my Postgres Database, the field giving me the error is the column user_roles_role.userId (note that I from userId is uppercase)\n\nHeres the code:\n\n```\nconst queryText = `SELECT * FROM user_roles_role WHERE user_roles_role.userId = ${id}`\n\ntry {\n const rawData = await this.connection.query(queryText);\n return rawData;\n} catch (err) {\n console.log(err);\n return err;\n}\n```\n\nI get an error while doing this query, because somehow Typeorm is forcing lowercase on the column name, as seen below on typeorm error (from catch(Err))\n\nquery: 'SELECT * FROM user_roles_role WHERE user_roles_role.userId =\n1', parameters: undefined, driverError: error: column\nuser_roles_role.userid does not exist\n\nI've tried:\n\nUsing single quotes and double quotes (didn't work)\n\nFull Error:\n\n\"query\": \"SELECT * FROM user_roles_role WHERE user_roles_role.userId = 1\",\n\"driverError\": {\n\"length\": 189,\n\"name\": \"error\",\n\"severity\": \"ERROR\",\n\"code\": \"42703\",\n\"hint\": \"Perhaps you meant to reference the column >\"user_roles_role.userId\".\",\n\"position\": \"37\",\n\"file\": \"parse_relation.c\",\n\"line\": \"3599\",\n\"routine\": \"errorMissingColumn\"\n}\n\n========================================\n\nCode:\n```text\nconst queryText = `SELECT * FROM user_roles_role WHERE user_roles_role.userId = ${id}`\n\ntry {\n  const rawData = await this.connection.query(queryText);\n  return rawData;\n} catch (err) {\n  console.log(err);\n  return err;\n}\n```\n\n```text\n`SELECT * FROM user_roles_role WHERE user_roles_role.\"userId\" = ${id}`\n```\n\n========================================\n\nComments:\n- Does not work, when I do this I get the following error: query: 'SELECT * FROM user_roles_role WHERE \"user_roles_role.userId\" = 1', parameters: undefined, driverError: error: column \"user_roles_role.userId\" does not exist, looks like Its a typeorm issue\n- SELECT * FROM user_roles_role where user_roles_role.\"userId\" = 1 worked, Ill accept the answer cuz it led me to this solution, thank you\n- yes you are right we should to the quotes only for the column, I'll update my answer for the others who need the solution, you're welcome","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":73,"estimatedTokens":584}}1113{"id":"stack-70572992","source":"stackoverflow","questionId":70572992,"title":"ConfigService advantages over dotenv","tags":["javascript","node.js","typescript","nestjs"],"text":"Title: ConfigService advantages over dotenv\nTags: javascript, node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nIs there any advantages (or disadvantages) on using @NestJS/Config instead of using dotenv to retrieve envvar? In both cases I could create a class that is responsible for all envvars, but should I?\n\nI know @NestJS/Config uses dotenv behind the curtains, but is there any reason why one should choose one over the other?\n\n========================================\n\nTop Answer:\nMy understanding is using `@nestjs/config` is easy for you to manage your config/envvars as a module in your project. So it can be easily swapped in different place:\n\ne.g. if you need a different set of config for test, you don't have to actually modify your process.env.xxx or use a different .env file.\n\nHowever if you do that, it requires all/most your other services to utilize this pattern as well. It wouldn't be so helpful if you have all your other service to be a pure function export.\n\n========================================\n\nCode:\n```text\nprocess.env\n```\n\n```text\nprocess.env\n```\n\n```text\nConfigService\n```\n\n```text\n@nestjs/config\n```\n\n========================================\n\nComments:\n- Thanks for the answer, but I actually prefer ConfigService over process.env ^^ About the things you mentioned... I heard a coworker saying it was \"adding unecessary complexity to the project and that's why we use dotenv\", but the thing is, I consider that to be a silver bullet (the anti-pattern), Java has a very similar way of dealing with envvar, much like the ConfigService does, that's why I was inclined to use (and ended up using) the ConfigService on my project. Nice to know I'm not alone!","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":41,"estimatedTokens":426}}1114{"id":"stack-64298963","source":"stackoverflow","questionId":64298963,"title":"How to use session object in guards with nest-session","tags":["nestjs"],"text":"Title: How to use session object in guards with nest-session\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nIn NestJS, using `nest-session`, I would like to use session object within a guard (`CanActivate`).\n\nInside a controller's action this is done by using `@Session()` but I can't find nor figure out how to fetch this data withing a guard.\n\n========================================\n\nCode:\n```text\nnest-session\n```\n\n```text\nCanActivate\n```\n\n```text\n@Session()\n```\n\n```js\nimport { Request } from 'express';\nexport interface IRequest extends Request {\n   session: any;\n}\n```\n\n```js\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { IRequest } from './app.interface'; //Import interface\n\n@Injectable()\nexport class Guard implements CanActivate {\n  constructor() {}\n  canActivate(context: ExecutionContext): boolean {\n    const req: IRequest = context.switchToHttp().getRequest(); //Request Object\n    const session = req.session; //Session Object\n    /*\n        Do whatever you want with your session here ...\n    */\n    return true;\n  }\n}\n```\n\n========================================\n\nComments:\n- Thanks, works like a charm! I had to change the typing to keep the original properties of `session`: `export type IRequest = Request & { session: any };`. (Obviously I didn't used `any`.)","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":53,"estimatedTokens":331}}1115{"id":"stack-68201452","source":"stackoverflow","questionId":68201452,"title":"How to rate limit a NestJS API by multiple time intervals?","tags":["javascript","nestjs"],"text":"Title: How to rate limit a NestJS API by multiple time intervals?\nTags: javascript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to rate limit my API with @NestJs/throttler.\nI want to set **two** different limit caps:\n\n- 100 requests per 1 second\n\n- 10,000 requests per 24 hours.\n\nSetting either one of these rate limits is explained in the docs and is pretty straight forwad. But, setting both limitations is not articulated in the docs.\n\nHow can I rate limit my API by **both** time intervals?\n\n========================================\n\nTop Answer:\nAs I told you on Discord, with `@nestjs/throttler`, this functionality currently doesn't exist. You can have one or the other, or you can override the global config to be more specific for one endpoint, but there's not currently a way to have two limits set up.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n    ThrottlerModule.forRoot([\n      {\n        name: 'short',\n        ttl: 1000,\n        limit: 3,\n      },\n      {\n        name: 'medium',\n        ttl: 10000,\n        limit: 20\n      },\n      {\n        name: 'long',\n        ttl: 60000,\n        limit: 100\n      }\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\n```text\n// Override default configuration for Rate limiting and duration.\n@Throttle({ default: { limit: 3, ttl: 60000 } })\n@Get()\nfindAll() {\n  return \"List users works with custom rate limiting.\";\n}\n```\n\n```text\n@SkipThrottle()\n@Controller('users')\nexport class UsersController {\n  // Rate limiting is applied to this route.\n  @SkipThrottle({ default: false })\n  dontSkip() {\n    return 'List users work with Rate limiting.';\n  }\n  // This route will skip rate limiting.\n  doSkip() {\n    return 'List users work without Rate limiting.';\n  }\n}\n```\n\n```text\n@nestjs/throttler\n```\n\n========================================\n\nComments:\n- did u find a solution for it ?\n- @IsaacKamel Newer versions of `@nestjs&#47;throttler` allow for multiple time and limit configurations","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":83,"estimatedTokens":495}}1116{"id":"stack-72125220","source":"stackoverflow","questionId":72125220,"title":"Connecting Redis microservice in NestJS causes app to get stuck","tags":["javascript","nestjs"],"text":"Title: Connecting Redis microservice in NestJS causes app to get stuck\nTags: javascript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up a simple hybrid app using Nest's documentation, but the app gets stuck without throwing.\n\n`main.ts`\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Logger } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { MicroserviceOptions, Transport } from '@nestjs/microservices';\n\nconst logger = new Logger('Main');\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n const configService = app.get(ConfigService);\n const redisConfig = configService.get('database.redis');\n\n app.connectMicroservice({\n transport: Transport.REDIS,\n options: {\n url: `redis://${redisConfig.host}:${redisConfig.port}`,\n },\n });\n\n await app.startAllMicroservices();\n await app.listen(configService.get('app.port'));\n}\n\nbootstrap()\n .then(() => logger.log('App running'))\n .catch((e) => logger.error(e));\n```\n\nWhen I comment out `app.startAllMicroservices()` or the code connecting the microservice, the `App running` line is logged, with it, the app is stuck.\n\nI am 100% certain Redis is up and running and responsive, I am using Bull which uses the same config and it runs just fine.\n\nI have tried commenting out everything irrelevant to the above (everything besides the `ConfigModule`) in the `app.module` to no avail. Any help would be appreciated.\n\nI am running the latest version of NestJS and its peer dependencies.\n\n========================================\n\nCode:\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { Logger } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { MicroserviceOptions, Transport } from '@nestjs/microservices';\n\nconst logger = new Logger('Main');\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const configService = app.get(ConfigService);\n  const redisConfig = configService.get('database.redis');\n\n  app.connectMicroservice<MicroserviceOptions>({\n    transport: Transport.REDIS,\n    options: {\n      url: `redis://${redisConfig.host}:${redisConfig.port}`,\n    },\n  });\n\n  await app.startAllMicroservices();\n  await app.listen(configService.get('app.port'));\n}\n\nbootstrap()\n  .then(() => logger.log('App running'))\n  .catch((e) => logger.error(e));\n```\n\n```text\nmain.ts\n```\n\n```text\napp.startAllMicroservices()\n```\n\n```text\nApp running\n```\n\n```text\nConfigModule\n```\n\n```text\napp.module\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":101,"estimatedTokens":644}}1117{"id":"stack-66779350","source":"stackoverflow","questionId":66779350,"title":"NestJS MongoDB nested object schema","tags":["mongoose","nestjs","typegoose"],"text":"Title: NestJS MongoDB nested object schema\nTags: mongoose, nestjs, typegoose\nSource: Stack Overflow\n\nQuestion:\nI am currently running the code :\n\n```\nexport class SystemInformationContent {\n createdAt: number;\n\n createdBy: User | mongoose.Schema.Types.ObjectId | null;\n\n updatedAt?: number;\n\n updatedBy?: User | mongoose.Schema.Types.ObjectId | null;\n}\n\n@Schema()\nexport class SystemInformation {\n @Prop(\n raw({\n createdAt: { type: Number, required: true },\n createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },\n updatedAt: { type: Number, default: 0 },\n updatedBy: {\n type: mongoose.Schema.Types.ObjectId,\n ref: 'User',\n default: null,\n },\n }),\n )\n system: SystemInformationContent;\n}\n```\n\nI did not found any way of \"extending\" the schema of `SystemInformationContent` and so used the `raw()` function in the `@Prop()` decorator, but I am wondering if there is a way to do something like this:\n\n```\nexport class SystemInformationContent {\n @Prop({ required: true })\n createdAt: number;\n\n @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })\n createdBy: User | mongoose.Schema.Types.ObjectId | null;\n\n @Prop({ default: 0 })\n updatedAt?: number;\n\n @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null })\n updatedBy?: User | mongoose.Schema.Types.ObjectId | null;\n}\n\n@Schema()\nexport class SystemInformation {\n @Prop(???)\n system: SystemInformationContent;\n}\n```\n\nI did not found anything working to put into the `SystemInformation.system` `@Prop()` that take in account the schema of `SystemInformationContent`.\n\nDo you guys know if there is an other way than the `raw` or if I am missing something ?\n\nEdit: All classes of my NestJS application are extending SystemInformation so they all look like :\n\n```\n{\n ...,\n system: {\n createdAt: 1616778310610,\n createdBy: \"605e14469d860eb1f0641cad\",\n editedAt: 0,\n createdBy: null,\n },\n}\n```\n\n========================================\n\nTop Answer:\nif you are using `typegoose` (7.0 or later), then what you currently have should be enough, if you have `emitDecoratorMetadata` enabled in the tsconfig\n\nexample with typegoose (the code below uses option extensions from ~7.4):\n\n```\nexport class SystemInformationContent {\n @Prop({ required: true })\n createdAt: number;\n\n @Prop({ type: mongoose.Schema.Types.ObjectId, ref: () => User })\n createdBy: Ref;\n\n @Prop({ default: 0 })\n updatedAt?: number;\n\n @Prop({ type: mongoose.Schema.Types.ObjectId, ref: () => User }) // default is \"undefined\"\n updatedBy?: Ref;\n}\n\nexport class SystemInformation {\n @Prop() // thanks to \"emitDecoratorMetadata\" no explicit types are needed \n system: SystemInformationContent;\n\n // but if wanting to do explicit types\n @Prop({ type: () => SystemInformationContent })\n system: SystemInformationContent;\n}\n```\n\nPS: i dont know where your function `raw` comes from, but this is not an typegoose function\n\n========================================\n\nCode:\n```js\nexport class SystemInformationContent {\n  createdAt: number;\n\n  createdBy: User | mongoose.Schema.Types.ObjectId | null;\n\n  updatedAt?: number;\n\n  updatedBy?: User | mongoose.Schema.Types.ObjectId | null;\n}\n\n@Schema()\nexport class SystemInformation {\n  @Prop(\n    raw({\n      createdAt: { type: Number, required: true },\n      createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },\n      updatedAt: { type: Number, default: 0 },\n      updatedBy: {\n        type: mongoose.Schema.Types.ObjectId,\n        ref: 'User',\n        default: null,\n      },\n    }),\n  )\n  system: SystemInformationContent;\n}\n```\n\n```js\nexport class SystemInformationContent {\n  @Prop({ required: true })\n  createdAt: number;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })\n  createdBy: User | mongoose.Schema.Types.ObjectId | null;\n\n  @Prop({ default: 0 })\n  updatedAt?: number;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null })\n  updatedBy?: User | mongoose.Schema.Types.ObjectId | null;\n}\n\n@Schema()\nexport class SystemInformation {\n  @Prop(???)\n  system: SystemInformationContent;\n}\n```\n\n```json\n{\n  ...,\n  system: {\n    createdAt: 1616778310610,\n    createdBy: \"605e14469d860eb1f0641cad\",\n    editedAt: 0,\n    createdBy: null,\n  },\n}\n```\n\n```text\nSystemInformationContent\n```\n\n```text\nraw()\n```\n\n```text\n@Prop()\n```\n\n```text\nSystemInformation.system\n```\n\n```text\n@Prop()\n```\n\n```text\nSystemInformationContent\n```\n\n```text\nraw\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport * as mongoose from 'mongoose';\nimport { User } from '~/schemas/user.schema';\n\n@Schema({ _id: false })\nexport class SystemInformationContent {\n  @Prop({ type: Number, required: true })\n  createdAt: number;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })\n  createdBy: User;\n\n  @Prop({ type: Number, default: 0 })\n  updatedAt?: number;\n\n  @Prop({\n    type: mongoose.Schema.Types.ObjectId,\n    ref: 'User',\n    default: null,\n  })\n  updatedBy?: User;\n}\n\nexport const SystemInformationContentSchema = SchemaFactory.createForClass(\n  SystemInformationContent,\n);\n```\n\n```js\nimport { Prop, Schema } from '@nestjs/mongoose';\nimport {\n  SystemInformationContent,\n  SystemInformationContentSchema,\n} from '~/schemas/systemInformationContent.schema';\n\n@Schema()\nexport default class SystemInformation {\n  @Prop({ required: true, type: SystemInformationContentSchema })\n  system: SystemInformationContent;\n}\n```\n\n```json\n{\n  ...,\n  \"system\": {\n    \"updatedBy\": null,\n    \"updatedAt\": 0,\n    \"createdAt\": 1616847116986,\n    \"createdBy\": {\n      \"$oid\": \"605f210cc9fe3bcbdf01c95d\"\n    }\n  },\n  ...,\n}\n```\n\n```text\nSystemInformationContent\n```\n\n```text\n@Schema({ _id: false })\n```\n\n```text\nexport class SystemInformationContent {\n  @Prop({ required: true })\n  createdAt: number;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: () => User })\n  createdBy: Ref<User>;\n\n  @Prop({ default: 0 })\n  updatedAt?: number;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: () => User }) // default is \"undefined\"\n  updatedBy?: Ref<User>;\n}\n\nexport class SystemInformation {\n  @Prop() // thanks to \"emitDecoratorMetadata\" no explicit types are needed \n  system: SystemInformationContent;\n\n  // but if wanting to do explicit types\n  @Prop({ type: () => SystemInformationContent })\n  system: SystemInformationContent;\n}\n```\n\n```text\ntypegoose\n```\n\n```text\nemitDecoratorMetadata\n```\n\n```text\nraw\n```\n\n```text\n@Schema()\nexport class SystemInformationContent {\n  // put your @Prop() attributes here, that need to be available in every other schema\n}\n\n@Schema()\nexport class SystemInformation extends SystemInformationContent {\n  // no need to do anything else here\n  // the attributes are inherited from SystemInformationContent \n}\n```\n\n```text\n@Schema()\n```\n\n```text\nSystemInformationContent\n```\n\n========================================\n\nComments:\n- Hi, am using NestJS that use their own implementation of type goose (github.com/kpfromer/nestjs-typegoose) Thanks a lot for the answer I will look into it !\n- I tried your solution, and it did not work, the `emitDecoratorMetadata` is enabled but I think the NestJS typegoose does not work that way...\n- Hey man, this wasn't the solution I was looking for, but for some reason, your answer unlocked something in my head that made me found the solution, many thanks !","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":336,"estimatedTokens":1817}}1118{"id":"stack-62766396","source":"stackoverflow","questionId":62766396,"title":"How to test a async function in Nest js with jest","tags":["jestjs","nestjs"],"text":"Title: How to test a async function in Nest js with jest\nTags: jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nim doing a simple test with my new framework Nest js, but the first time I run the command npm run test im getting this error\n\n```\nโ— Cannot log after tests are done. Did you forget to wait for something async in your test?\n Attempted to log \"SUCCESS conection to MEMCACHED server\".\n\n 21 | // this function Stores a new value in Memcached.\n 22 | setKey(key : string, value : string , timeExp:number) : Promise{\n > 23 | // Transform the callback into a promise to be used in the controller\n | ^\n 24 | return new Promise((resolve,reject) =>{\n 25 | // Using memcached api to set a key\n 26 | memcached.set(key, value, timeExp, async function (err) {\n\n at BufferedConsole.log (../node_modules/@jest/console/build/BufferedConsole.js:201:10)\n at modules/cache/application/cache.service.ts:23:17\n at allocate (../node_modules/jackpot/index.js:125:5)\n at Socket.either (../node_modules/jackpot/index.js:166:5)\n```\n\nbut this is my test file\n\n```\ndescribe('Cache Controller', () => {\n let controller: CacheController;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [CacheController],\n }).compile();\n\n controller = module.get(CacheController);\n });\n\n it('should be defined', () => {\n expect(controller).toBeDefined();\n });\n});\n```\n\n- This is the function that are getting the error (don't know why if im not testing this function)\n\n```\n// this function Stores a new value in Memcached.\n async setKey(key : string, value : string , timeExp:number) : Promise{\n // Transform the callback into a promise to be used in the controller\n return await new Promise((resolve,reject) =>{\n // Using memcached api to set a key\n memcached.set(key, value, timeExp, function (err) {\n if (err) return reject(err);\n resolve(true)\n }); \n });\n }\n```\n\n========================================\n\nCode:\n```text\nโ—  Cannot log after tests are done. Did you forget to wait for something async in your test?\n    Attempted to log \"SUCCESS conection to MEMCACHED server\".\n\n      21 |   // this function Stores a new value in Memcached.\n      22 |   setKey(key : string, value : string , timeExp:number) : Promise<boolean>{\n    > 23 |     // Transform the callback into a promise to be used in the controller\n         |                 ^\n      24 |     return new Promise((resolve,reject) =>{\n      25 |       // Using memcached api to set a key\n      26 |       memcached.set(key, value, timeExp, async function (err) {\n\n      at BufferedConsole.log (../node_modules/@jest/console/build/BufferedConsole.js:201:10)\n      at modules/cache/application/cache.service.ts:23:17\n      at allocate (../node_modules/jackpot/index.js:125:5)\n      at Socket.either (../node_modules/jackpot/index.js:166:5)\n```\n\n```text\ndescribe('Cache Controller', () => {\n  let controller: CacheController;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      controllers: [CacheController],\n    }).compile();\n\n    controller = module.get<CacheController>(CacheController);\n  });\n\n  it('should be defined', () => {\n    expect(controller).toBeDefined();\n  });\n});\n```\n\n```text\n// this function Stores a new value in Memcached.\n  async setKey(key : string, value : string , timeExp:number) : Promise<boolean>{\n    // Transform the callback into a promise to be used in the controller\n    return await new Promise((resolve,reject) =>{\n      // Using memcached api to set a key\n      memcached.set(key, value, timeExp, function (err) {\n        if (err) return reject(err);\n        resolve(true)\n      });  \n    });\n  }\n```\n\n```text\nit('Test case name', async () => {\n   // Await something\n   // Expect something\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":120,"estimatedTokens":941}}1119{"id":"stack-60753807","source":"stackoverflow","questionId":60753807,"title":"NestJS custom decorator returns undefined","tags":["typescript","nestjs","typeorm"],"text":"Title: NestJS custom decorator returns undefined\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nGood morning,\n\nI'm trying to create a custom decorator:\n`user.decorator.ts`\n\n```\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n (data: string, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n const user = request.user;\n\n return data ? user && user[data] : user;\n },\n);\n```\n\n`user.entity.ts`\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from \"typeorm\";\nimport * as bcrypt from 'bcryptjs';\nimport * as jwt from 'jsonwebtoken';\nimport { UserRO } from \"./user.dto\";\n\n@Entity(\"user\")\nexport class UserEntity {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({\n type: 'varchar',\n length: 50,\n unique: true,\n })\n username: string;\n\n @Column('text')\n password: string;\n\n @Column('text')\n role: string;\n\n (...)\n}\n```\n\nAnd finally, `user.controller.ts` (only the useful part):\n\n```\n(...)\n @Post('login')\n @UsePipes(new ValidationPipe())\n login(@Body() data: UserDTO, @User('role') role: string) {\n console.log(`hello ${role}`);\n return this.userService.login(data);\n(...)\n }\n```\n\nMy problem: console.log(...) returns me `hello undefined`, when the expected response should be `hello admin` (as admin is the role of the user in the database)\n\nEDIT: I also tried to `console.log(user)` in my decorator and it is undefined too.\n\nEDIT2: My HttpErrorFilter also says: `Cannot read property 'role' of undefined`\n\nI followed closely the documentation and I can't figure out where the problem is (https://docs.nestjs.com/custom-decorators).\n\nThank you for your time.\n\n========================================\n\nTop Answer:\nI found a solution.\n\nIn `user.decorator.ts`:\n\nChange `const user = request.user;` with `const user = request.body;`\n\nAccording to nestjs's doc, it should be `.user` but when I looked deeper into the request, I noticed there were no 'user' but a 'body' with all in the informations. (https://docs.nestjs.com/custom-decorators)\n\nCan't tell if I messed up earlier or if the doc is just outdated.\n\nProblem solved whatsoever !\n\nEDIT: 2nd solution:\n\nI forgot to use `@UseGuards(new AuthGuard())` on top, and the `request.user` is created with the AuthGuard..\n\n========================================\n\nCode:\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n  (data: string, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    const user = request.user;\n\n    return data ? user && user[data] : user;\n  },\n);\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from \"typeorm\";\nimport * as bcrypt from 'bcryptjs';\nimport * as jwt from 'jsonwebtoken';\nimport { UserRO } from \"./user.dto\";\n\n@Entity(\"user\")\nexport class UserEntity {\n\n    @PrimaryGeneratedColumn('uuid')\n    id: string;\n\n    @Column({\n        type: 'varchar',\n        length: 50,\n        unique: true,\n    })\n    username: string;\n\n    @Column('text')\n    password: string;\n\n    @Column('text')\n    role: string;\n\n    (...)\n}\n```\n\n```text\n(...)\n    @Post('login')\n    @UsePipes(new ValidationPipe())\n    login(@Body() data: UserDTO,  @User('role') role: string) {\n        console.log(`hello ${role}`);\n        return this.userService.login(data);\n(...)\n    }\n```\n\n```text\nuser.decorator.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.controller.ts\n```\n\n```text\nhello undefined\n```\n\n```text\nhello admin\n```\n\n```text\nconsole.log(user)\n```\n\n```text\nCannot read property 'role' of undefined\n```\n\n```typescript\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    return ctx.getArgByIndex(2).req.user;\n  }\n);\n```\n\n```text\nconst request = ctx.switchToHttp().getRequest();\n```\n\n```text\ngetRequest()\n```\n\n```text\ngetArgByIndex()\n```\n\n```text\nuser.decorator.ts\n```\n\n```text\nconst user = request.user;\n```\n\n```text\nconst user = request.body;\n```\n\n```text\n.user\n```\n\n```text\n@UseGuards(new AuthGuard())\n```\n\n```text\nrequest.user\n```\n\n```text\nexport const CurrentUser = createParamDecorator(\n    (data: unknown, context: ExecutionContext) => {\n        const ctx = GqlExecutionContext.create(context);\n        return ctx.getContext().req.user;\n    },\n);\n```\n\n```text\nif (ctx.getType() == 'http') {\n  return ctx.switchToHttp().getRequest().user;\n} else {\n  const gqlContext = GqlExecutionContext.create(ctx);\n  return gqlContext.getContext().user;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":243,"estimatedTokens":1151}}1120{"id":"stack-61031079","source":"stackoverflow","questionId":61031079,"title":"How do I process a query parameter using NestJS?","tags":["typescript","rest","nestjs"],"text":"Title: How do I process a query parameter using NestJS?\nTags: typescript, rest, nestjs\nSource: Stack Overflow\n\nQuestion:\nThe subject line is pretty much it.\n\nI have a NestJS-based REST API server. I want to process a query parameter like so:\n\n```\nhttp://localhost:3000/todos?complete=false\n```\n\nI can't seem to work out how to have the controller process that. \n\nright now I have:\n\n```\n@Get()\n async getTodos(@Query('complete') isComplete: boolean) {\n const todosEntities = await this.todosService.getTodosWithComlete(isComplete);\n const todos = classToPlain(todosEntities);\n return todos;\n }\n```\n\nbut that always returns the completed todos, not the ones where complete = false.\n\nHere's the call to `getTodosWithComlete`:\n\n```\nasync getTodosWithComplete(isComplete?: boolean): Promise {\n return this.todosRepository.find({\n complete: isComplete,\n isDeleted: false,\n });\n }\n```\n\nHow do I return the proper `todos` based on a query parameter?\n\n========================================\n\nCode:\n```text\nhttp://localhost:3000/todos?complete=false\n```\n\n```text\n@Get()\n  async getTodos(@Query('complete') isComplete: boolean) {\n    const todosEntities = await this.todosService.getTodosWithComlete(isComplete);\n    const todos = classToPlain(todosEntities);\n    return todos;\n  }\n```\n\n```text\nasync getTodosWithComplete(isComplete?: boolean): Promise<Todo[]> {\n    return this.todosRepository.find({\n      complete: isComplete,\n      isDeleted: false,\n    });\n  }\n```\n\n```text\ngetTodosWithComlete\n```\n\n```text\ntodos\n```\n\n```text\n@Get()\n  async getTodos(@Query('complete', ParseBoolPipe) isComplete: boolean) {\n    const todosEntities = await this.todosService.getTodosWithComlete(isComplete);\n    const todos = classToPlain(todosEntities);\n    return todos;\n }\n```\n\n========================================\n\nComments:\n- Oh, that is so much better. Thanks very much.\n- Well, interesting, the parameter as used above always returns true, no matter what is passed in the URL.\n- Since version 7, there are implicit param conversion, docs.nestjs.com/&hellip; But I never tested that.","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":89,"estimatedTokens":518}}1121{"id":"stack-75172699","source":"stackoverflow","questionId":75172699,"title":"NestJs validation pipe not working properly","tags":["javascript","node.js","typescript","validation","nestjs"],"text":"Title: NestJs validation pipe not working properly\nTags: javascript, node.js, typescript, validation, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have the following DTO class in my project:\n\n```\nimport { IsNotEmpty, IsString } from \"class-validator\";\n\nexport class CreateDomainDTO {\n\n @IsString()\n codigo_website: string;\n\n @IsString()\n website_name: string\n\n}\n```\n\nI have NestJs default validation pipe applied for my entire project:\n\nmain.ts file\n\nHowever, NestJs is messing up the validation and returning a response that doesn't make sense to me.\n\nWhen I send this payload in my request:\n\n```\n{\n \"codigo_website\": \"lipgMEjz4altEmeb9hms\",\n \"website_name\": \"Modelo 2.1\"\n}\n```\n\nI get the following validation error:\n\n```\n\"property {\\\"codigo_website\\\":\\\"lipgMEjz4altEmeb9hms\\\",\\\"website_name\\\":\\\"Modelo 2.1\\\"} should not exist\",\"codigo_website must be a string\",\"website_name must be a string\"\n```\n\nIt is considering my entire body as being a single property and I don't have any idea why. Plus, this error seems to only happen in production, but within a few days ago it was working fine.\n\nDoes anyone have any idea why this is happening? Should I create a custom validation pipe?\n\nGrateful in advance.\n\n========================================\n\nCode:\n```text\nimport { IsNotEmpty, IsString } from \"class-validator\";\n\nexport class CreateDomainDTO {\n\n  @IsString()\n  codigo_website: string;\n\n  @IsString()\n  website_name: string\n\n}\n```\n\n```text\n{\n    \"codigo_website\": \"lipgMEjz4altEmeb9hms\",\n    \"website_name\": \"Modelo 2.1\"\n}\n```\n\n```text\n\"property {\\\"codigo_website\\\":\\\"lipgMEjz4altEmeb9hms\\\",\\\"website_name\\\":\\\"Modelo 2.1\\\"} should not exist\",\"codigo_website must be a string\",\"website_name must be a string\"\n```\n\n```text\napplication/json\n```\n\n========================================\n\nComments:\n- \"DO NOT post images of code, data, error messages, etc.\" How to Ask Can you provide the request headers and the body.\n- How do you send the request? What's the `Content-Type`? It looks like the payload isn't getting deserialized\n- Here's a part of my headers. Connection: keep-alive Content-Length: 69 Content-Type: application/x-www-form-urlencoded Host: lipsum.lipsum.com I think the error is being caused by the Content-Type header as @JayMcDoniel mentioned above. I'll try to fix it.","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":86,"estimatedTokens":572}}1122{"id":"stack-54507041","source":"stackoverflow","questionId":54507041,"title":"empty JSON parameters for array POST in swagger","tags":["javascript","node.js","typescript","swagger","nestjs"],"text":"Title: empty JSON parameters for array POST in swagger\nTags: javascript, node.js, typescript, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using nest.js and I have a post route to add new news to database\nso I used postman to send array of objects like this:\n\n```\n[\n{ \n \"newsTitle\" : \"title1\",\n \"newsDescription\": \"description1\"\n},\n{ \n \"newsTitle\" : \"title2\",\n \"newsDescription\": \"description2\"\n}\n]\n```\n\nand this the code for post in my controller:\n\n```\n@Post()\n async create(@Body() body: NewsDto[]) {\n\n const len = body.length;\n\n if (len == 1) {\n }\n\n else if (len > 1) {\n }\n\n return this.newsService.createNews(body);\n }\n```\n\nso everything work fine in post and saving data in database\nbut when I use swagger I get the Model of for the dto of this controller like this:\n\nhttps://i.sstatic.net/Jv4VH.png\n\nYou can see that the the parameters of dto not displayed here and I get the \"Array\" title instead because I use `@Body() body: NewsDto[]` and it's array as you see\n\nhttps://i.sstatic.net/21rDI.png\n\nalso here in the post I can't get the JSON so I can add it or post it in another word\n\nso how to handle this so when the length of array only 1 object then I return NewsDto parameters and if the length of array more than 1 object so return the NewsDto parameters too instead of Array?\n\n========================================\n\nCode:\n```text\n[\n{ \n    \"newsTitle\" : \"title1\",\n    \"newsDescription\": \"description1\"\n},\n{ \n    \"newsTitle\" : \"title2\",\n    \"newsDescription\": \"description2\"\n}\n]\n```\n\n```text\n@Post()\n  async create(@Body() body: NewsDto[]) {\n\n    const len = body.length;\n\n    if (len == 1) {\n    }\n\n    else if (len > 1) {\n    }\n\n    return this.newsService.createNews(body);\n  }\n```\n\n```text\n@Body() body: NewsDto[]\n```\n\n```text\nexport class NewsDto {\n  @ApiModelProperty()\n  newsTitle: string;\n\n  @ApiModelProperty()\n  newsDescription: string;\n}\n```\n\n```text\n@Post()\n@ApiImplicitBody({ name: 'news', type: [NewsDto]})\nasync create(@Body('news') body: NewsDto[]) {\n```\n\n```text\n@ApiModelProperty()\n```\n\n```text\n@ApiImplicitBody()\n```\n\n========================================\n\nComments:\n- I'm already add this! and for other post functions where I use dto not as array like now the swagger work fine and the parameters of dto displayed well @Kim Kern\n- For an array type, you also have to add `ApiImplicitBody` to the controller method, see my edit.\n- When using typescript, nestJs or swagger in controllers, you can use this as well; @Post() @ApiBody({ type: [objectItem] }) async create(@Body() body: objectItem[]) {","metadata":{"transformedAt":"2026-08-18T18:33:02.577Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":118,"estimatedTokens":636}}1123{"id":"stack-58273342","source":"stackoverflow","questionId":58273342,"title":"How to get a date from Postgres in my timezone","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to get a date from Postgres in my timezone\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI try to deploy a JS application using TypeORM and Postgres on a host. Locally I had a Postgress DB so running in my own TZ. The remote host happens to have its system time set to UTC:\n\n```\n$ date\nMon Oct 7 15:45:00 UTC 2019\n\n$ psql\n> select localtimestamp;\n2019-10-07 15:45:00.123456\n```\n\nI have a table with an automatically updated date in it (meaning it updates when record is updated).\n\n```\n// my.entity.ts\n@UpdateDateColumn({type: 'timestamp', name: 'lastUpdate', default: () => 'LOCALTIMESTAMP' })\nlastUpdate: Date;\n```\n\nA row is inserted at 12:00 CEST:\n\n```\n> select \"lastUpdate\" from myTable;\n2019-10-07 10:00:00.000000+00\n```\n\nI would like to get the date out in my timezone (CEST) regardless of the server time, so it should return me 2019-10-07 12:00. I prefer to not hardcode any tricks because it should also work on my CEST machine.\n\nPostgress has all the info:\n\n```\n> show timezone;\nUCT\n```\n\n- it knows it runs on UTC time\n\n- I can tell it in which timezone I want the date\n\nSo I would expect it to be easy to convert this to my requested format. However, the following examples I found don't seem to work:\n\n```\n> select (\"lastUpdate\" at time zone 'CEST') from myTable;\n2019-10-07 08:00:00.000000+00\n\n> select timezone('CEST', \"lastUpdate\") from myTable;\n2019-10-07 08:00:00.000000+00\n```\n\nThere is one way I can get it right, and thats by specifying the current timezone:\n\n```\n> select (\"lastUpdate\" at time zone 'UTC' at time zone 'CEST') from myTable;\n2019-10-07 12:00:00.000000\n```\n\nHowever, like I said I don't want to hardcode this (as other DB's run at other TZs) and Postgres knows it's own timezone.\n\nIs there another syntax to do this correctly?\n\n========================================\n\nTop Answer:\nselect created_at at time zone 'utc' at time zone 'america/los_angeles'\nfrom users;\n\n========================================\n\nCode:\n```text\n$ date\nMon Oct 7 15:45:00 UTC 2019\n\n$ psql\n> select localtimestamp;\n2019-10-07 15:45:00.123456\n```\n\n```text\n// my.entity.ts\n@UpdateDateColumn({type: 'timestamp', name: 'lastUpdate', default: () => 'LOCALTIMESTAMP' })\nlastUpdate: Date;\n```\n\n```text\n> select \"lastUpdate\" from myTable;\n2019-10-07 10:00:00.000000+00\n```\n\n```text\n> show timezone;\nUCT\n```\n\n```text\n> select (\"lastUpdate\" at time zone 'CEST') from myTable;\n2019-10-07 08:00:00.000000+00\n\n> select timezone('CEST', \"lastUpdate\") from myTable;\n2019-10-07 08:00:00.000000+00\n```\n\n```text\n> select (\"lastUpdate\" at time zone 'UTC' at time zone 'CEST') from myTable;\n2019-10-07 12:00:00.000000\n```\n\n```text\n=> create table demo ( time timestamp, timetz timestamptz );\nCREATE TABLE\n\n=> insert into demo values ('2019-10-07 10:00', '2019-10-07 12:00 +0200');\nINSERT 0 1\n\n=> select * from demo;\n        time         |         timetz         \n---------------------+------------------------\n 2019-10-07 10:00:00 | 2019-10-07 10:00:00+00\n```\n\n```text\n=> set time zone 'Antarctica/Troll';\n\n=> select * from demo;\n        time         |         timetz         \n---------------------+------------------------\n 2019-10-07 10:00:00 | 2019-10-07 12:00:00+02\n```\n\n```text\n=> select timetz at time zone 'CEST' from demo;\n      timezone       \n---------------------\n 2019-10-07 12:00:00\n```\n\n```text\ntimestamp\n```\n\n```text\ntimestamptz\n```\n\n```text\ntimestamp\n```\n\n```text\ntimestamptz\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- Perhaps you should try to work only with type `timestamptz` and not sometimes with type `timestamp`. Try to set the default to `now()`. Of what type is your column?\n- Anyways, `select '2019-10-07 10:00:00.000000+00' at time zone 'CEST';` works fine for me.. (Output: `2019-10-07 12:00:00`)\n- If you are confused about types and the `AT TIME ZONE` operator perhaps the docs might help: postgresql.org/docs/current/&hellip;\n- Since `\"lastUpdate\"` and `(\"lastUpdate\" at time zone 'CEST')` both have a time zone in your given example, I guess there is something wrong with it.\n- Thanks, using timestamptz is indeed the simple solution!\n- select created_at at time zone 'utc' at time zone 'pst' from users;\n- select * from pg_timezone_names;","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":175,"estimatedTokens":1063}}1124{"id":"stack-57457231","source":"stackoverflow","questionId":57457231,"title":"How nestjs uses @nestjs/swagger to generate documentation on Passport strategies route","tags":["nestjs"],"text":"Title: How nestjs uses @nestjs/swagger to generate documentation on Passport strategies route\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI am making @nestjs/swagger to generate api documentation. But how do I generate a document for an authenticated route?\n\nnest version\n\n```\nฮป nest i\nNodeJS Version : v10.16.0\n[Nest Information]\nplatform-express version : 6.0.0\npassport version : 6.1.0\nswagger version : 3.1.0\ncommon version : 6.0.0\ncore version : 6.0.0\njwt version : 6.1.1\n```\n\nThis is a normal route, I can use '@ApiImplicitBody' to make a document:\n\n```\n@Delete()\n @ApiImplicitBody({\n name: 'id',\n required: true,\n type: String,\n })\n @ApiOkResponse({\n description: 'successfully deleted',\n })\n delete(@Body('id') typeId) {\n return this.typesService.delete(typeId);\n }\n```\n\nThis route requires authentication, how can I document this type of route?\n\n```\n@UseGuards(AuthGuard('local'))\n @Post('login')\n @ApiOkResponse({\n description: 'result Token',\n })\n async login(@Request() req) {\n return this.authService.login(req.user);\n }\n```\n\nI looked at the Swagger documentation and tried some of the apis in the '@nestjs/swagger' package, but it didn't work.\n\n========================================\n\nTop Answer:\nYou can use the decorator `@ApiBearerAuth()` here in the docs to get an authenticated route to show up in your swagger file.\n\n========================================\n\nCode:\n```text\nฮป nest i\nNodeJS Version : v10.16.0\n[Nest Information]\nplatform-express version : 6.0.0\npassport version         : 6.1.0\nswagger version          : 3.1.0\ncommon version           : 6.0.0\ncore version             : 6.0.0\njwt version              : 6.1.1\n```\n\n```text\n@Delete()\n  @ApiImplicitBody({\n    name: 'id',\n    required: true,\n    type: String,\n  })\n  @ApiOkResponse({\n    description: 'successfully deleted',\n  })\n  delete(@Body('id') typeId) {\n    return this.typesService.delete(typeId);\n  }\n```\n\n```text\n@UseGuards(AuthGuard('local'))\n  @Post('login')\n  @ApiOkResponse({\n    description: 'result Token',\n  })\n  async login(@Request() req) {\n    return this.authService.login(req.user);\n  }\n```\n\n```text\nimport { UserLoginDto } from './dto/user-login.dto';\n\n  @UseGuards(AuthGuard('local'))\n  @Post('login')\n  @ApiImplicitBody({ name: '', type: UserLoginDto, })\n  @ApiOkResponse({ description: 'result Token' })\n  async login(@Request() req) {\n    return this.authService.login(req.user);\n  }\n```\n\n```text\nimport { IsNotEmpty, IsString } from 'class-validator';\nimport { ApiModelProperty } from '@nestjs/swagger';\n\nexport class UserLoginDto {\n  @IsString()\n  @IsNotEmpty()\n  @ApiModelProperty({ example: 'ajanuw', description: '่ดฆๅท' })\n  readonly username: string;\n\n  @IsString()\n  @IsNotEmpty()\n  @ApiModelProperty({\n    example: '123456',\n    description: 'ๅฏ†็ ',\n  })\n  readonly password: string;\n}\n```\n\n```text\n@ApiBearerAuth()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":134,"estimatedTokens":710}}1125{"id":"stack-59449975","source":"stackoverflow","questionId":59449975,"title":"Nest.js is unable to resolve Mongoose model dependency in unit test","tags":["node.js","nestjs"],"text":"Title: Nest.js is unable to resolve Mongoose model dependency in unit test\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen writing a unit test for a controller, Nest is unable to resolve my Mongoose model dependency:\n\n Nest can't resolve dependencies of the UsersService (?). Please make\n sure that the argument USER_MODEL at index [0] is available in the\n _RootTestModule context.\n\n```\nPotential solutions:\n- If USER_MODEL is a provider, is it part of the current _RootTestModule?\n- If USER_MODEL is exported from a separate @Module, is that module imported within _RootTestModule?\n @Module({\n imports: [ /* the Module containing USER_MODEL */ ]\n })\n```\n\nMy model is injected via my service constructor in the users.service.ts:\n\n```\nimport { IUserModel } from './interfaces';\nimport { Model } from 'mongoose';\nimport { USER_MODEL } from './constants/users.constants';\n\n@Injectable()\nexport class UsersService {\n\n constructor (\n @Inject(USER_MODEL)\n private readonly userModel: Model,\n ) {}\n\n ...\n}\n```\n\nand my test is defined as:\n\n```\nconst mockUserModel = {};\n\ndescribe('Users Controller', () => {\n let usersController: UsersController;\n let usersService: UsersService;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n controllers: [UsersController],\n providers: [\n {\n provide: getModelToken(USER_MODEL),\n useValue: mockUserModel,\n },\n UsersService,\n ],\n }).compile();\n\n usersController = module.get(UsersController);\n usersService = module.get(UsersService);\n });\n\n it('should define user controller and service', () => {\n expect(usersController).toBeDefined();\n expect(usersService).toBeDefined();\n });\n});\n```\n\nAll of these classes are defined in the same module. I'm not quite sure what Nest is looking for. I'm following the guide at: https://docs.nestjs.com/fundamentals/testing and have looked through several older Github issues as well.\n\nI've also tried creating a custom class provider as defined here: https://docs.nestjs.com/fundamentals/custom-providers to supply the typed Mongoose Model, but that returned the same error.\n\nCan anyone help me out?\n\n========================================\n\nCode:\n```text\nPotential solutions:\n- If USER_MODEL is a provider, is it part of the current _RootTestModule?\n- If USER_MODEL is exported from a separate @Module, is that module imported within _RootTestModule?\n  @Module({\n    imports: [ /* the Module containing USER_MODEL */ ]\n  })\n```\n\n```typescript\nimport { IUserModel } from './interfaces';\nimport { Model } from 'mongoose';\nimport { USER_MODEL } from './constants/users.constants';\n\n@Injectable()\nexport class UsersService {\n\n  constructor (\n    @Inject(USER_MODEL)\n    private readonly userModel: Model<IUserModel>,\n  ) {}\n\n  ...\n}\n```\n\n```typescript\nconst mockUserModel = {};\n\ndescribe('Users Controller', () => {\n  let usersController: UsersController;\n  let usersService: UsersService;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      controllers: [UsersController],\n      providers: [\n        {\n          provide: getModelToken(USER_MODEL),\n          useValue: mockUserModel,\n        },\n        UsersService,\n      ],\n    }).compile();\n\n    usersController = module.get<UsersController>(UsersController);\n    usersService = module.get<UsersService>(UsersService);\n  });\n\n  it('should define user controller and service', () => {\n    expect(usersController).toBeDefined();\n    expect(usersService).toBeDefined();\n  });\n});\n```\n\n```text\n@Inject(USER_MODEL)\n```\n\n```text\nprovide: USER_MODEL\n```\n\n```text\ngetModelToken\n```\n\n```text\n@InjectModel()\n```\n\n```text\n@Inject()\n```\n\n========================================\n\nComments:\n- Thanks, but how am I supposed to create the testing module? Do you have any example code or documentation?\n- I have an entire repository dedicated to test examples. Feel free to check them out. Your set up is mostly right, just providing the wrong `mock token` for your model.\n- Perfect. Thank you very much for the great documentation!\n- Looking through the repo, I'm not seeing anything in regards to Passport and testing controllers with AuthGuards. Searches aren't coming up with a lot of examples. In the past I've opted for E2E tests and setting up a separate database for testing. If you have an alternative approach, I'd appreciate some suggestions.\n- I'd say using docker-compose for e2e testing is something important to work with. It's something I'm slowly working on in regards to the testing repository, along with showing an e2e of passport testing.\n- So for now, would you suggest skipping unit tests on controllers protected with AuthGuards in favor of e2e tests for those routes?\n- I think unit tests on the controller are fine to have, the controller should basically just return whatever the service it calls does. You can also unit test your guards to make sure that logic works as expected. If you are looking to test that the guards work in combination with the controller though, that has to be done with e2e tests\n- Gotcha. I guess I can always construct a fake user object to assign to the request and mock the request with node-mocks-http to pass into those functions. Thanks for the tips!","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":167,"estimatedTokens":1304}}1126{"id":"stack-55567053","source":"stackoverflow","questionId":55567053,"title":"Test NestJs Service with Jest","tags":["javascript","node.js","unit-testing","jestjs","nestjs"],"text":"Title: Test NestJs Service with Jest\nTags: javascript, node.js, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to test my *NestJs* PlayerController with Jest.\nMy controller and service declaration:\n\n```\nimport { QueryBus, CommandBus, EventBus } from '@nestjs/cqrs';\n\n/**\n * The service assigned to query the database by means of commands\n */\n@Injectable()\nexport class PlayerService {\n /**\n * Ctor\n * @param queryBus\n */\n constructor(\n private readonly queryBus: QueryBus,\n private readonly commandBus: CommandBus,\n private readonly eventBus: EventBus\n ) { }\n\n@Controller('player')\n@ApiUseTags('player')\nexport class PlayerController {\n /**\n * Ctor\n * @param playerService\n */\n constructor(private readonly playerService: PlayerService) { }\n```\n\nMy test:\n\n```\ndescribe('Player Controller', () => {\n let controller: PlayerController;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [PlayerService, CqrsModule],\n controllers: [PlayerController],\n providers: [\n PlayerService,\n ],\n }).compile();\n\n controller = module.get(PlayerController);\n });\n\n it('should be defined', () => {\n expect(controller).toBeDefined();\n });\n...\n```\n\n Nest can't resolve dependencies of the PlayerService (?, CommandBus,\n EventBus). Please make sure that the argument at index [0] is\n available in the PlayerService context.\n\n```\nat Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)\n```\n\nAny way to work around this dependency issue?\n\n========================================\n\nCode:\n```text\nimport { QueryBus, CommandBus, EventBus } from '@nestjs/cqrs';\n\n/**\n * The service assigned to query the database by means of commands\n */\n@Injectable()\nexport class PlayerService {\n    /**\n     * Ctor\n     * @param queryBus\n     */\n    constructor(\n        private readonly queryBus: QueryBus,\n        private readonly commandBus: CommandBus,\n        private readonly eventBus: EventBus\n    ) { }\n\n\n@Controller('player')\n@ApiUseTags('player')\nexport class PlayerController {\n    /**\n     * Ctor\n     * @param playerService\n     */\n    constructor(private readonly playerService: PlayerService) { }\n```\n\n```text\ndescribe('Player Controller', () => {\n  let controller: PlayerController;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      imports: [PlayerService, CqrsModule],\n      controllers: [PlayerController],\n      providers: [\n        PlayerService,\n      ],\n    }).compile();\n\n\n    controller = module.get<PlayerController>(PlayerController);\n  });\n\n  it('should be defined', () => {\n    expect(controller).toBeDefined();\n  });\n...\n```\n\n```text\nat Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)\n```\n\n```text\nimports: [PlayerService, CqrsModule]\n          ^^^^^^^^^^^^^\n```\n\n```text\nPlayerService\n```\n\n```text\nproviders\n```\n\n```text\nPlayerService\n```\n\n```text\nCqrsModule\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":149,"estimatedTokens":745}}1127{"id":"stack-72466834","source":"stackoverflow","questionId":72466834,"title":"NestJS logs have weird characters in log-management tools","tags":["javascript","logging","nestjs","datadog"],"text":"Title: NestJS logs have weird characters in log-management tools\nTags: javascript, logging, nestjs, datadog\nSource: Stack Overflow\n\nQuestion:\na simple question with a possibly simple answer I just cant seem to find:\n\nWe're using NestJS as our server-side javascript framework for a micro-service based infrastructure.\n\nWorking locally with the built in NestJS logger, or with our own class extending and implementing the logger functions, the console seems to print out the logs exactly as expected, for example:\n\n```\n[Nest] 41477 - 06/01/2022, 5:46:39 PM LOG [Bootstrap] Mapped {/api/v1/accounts/:accountId/positions/:positionId/matches, GET} route\n```\n\nHowever, when running these service on cloud platforms, many (if not all) show-me-the-pod-logs tools add many \"special\" characters, for example:\n\n```\n[32m[Nest] 19 - [39m06/01/2022, 3:29:51 PM [32m LOG[39m [38;5;3m[RouterExplorer] [39m[32mMapped {/api/v1/accounts/:accountId/positions/:positionId/matches, GET} route[39m[38;5;3m +1ms[39m\n```\n\nAs you can see, it's almost the same, but not quite..\nwhat are all of these `[32m` and `[39m` being added all over the place?\nThis appears to be the same case in many of our tools: Datadog, ArgoCD pod logs, Rancher pod logs, etc.\n\nWhat are these, and how can we get rid of them?\n\n========================================\n\nCode:\n```text\n[Nest] 41477  - 06/01/2022, 5:46:39 PM     LOG [Bootstrap] Mapped {/api/v1/accounts/:accountId/positions/:positionId/matches, GET} route\n```\n\n```text\n[32m[Nest] 19  - [39m06/01/2022, 3:29:51 PM [32m    LOG[39m [38;5;3m[RouterExplorer] [39m[32mMapped {/api/v1/accounts/:accountId/positions/:positionId/matches, GET} route[39m[38;5;3m +1ms[39m\n```\n\n```text\n[32m\n```\n\n```text\n[39m\n```\n\n```text\nNO_COLOR\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":49,"estimatedTokens":435}}1128{"id":"stack-79315398","source":"stackoverflow","questionId":79315398,"title":"NestJS as BFF for angular 19 using SSR","tags":["angular","nestjs","server-side-rendering"],"text":"Title: NestJS as BFF for angular 19 using SSR\nTags: angular, nestjs, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nAngular 19 comes along with big improvements to how SSR works. In particular, the server part is now actually used when booting up the vite dev server. Which means that I can use express as my reverse proxy so I do not have to define my proxies as a json config for development and once again in code for production. Great!\n\nThis got me thinking; I know about separation of concerns and frontends should only do frontend and backends should only do backend, right? But using SSR, my frontend is already served from a backend. Why should I have a backend for frontend and another separate backend for backend? Well, I don't think I need to. The changes made to @angular/ssr package allows me to have a full blown expressjs server as my BFF dev and prod server with all the percs that follows. So not only serving my frontend with hybrid rehydration and providing reverse proxies, I can also define my actual backend api here. All from just a simple `ng serve`.\n\nBut it is kind of tiresome to define backend endpoints and their logic in express. I would want to leverage a backend framework like NestJS instead. This is where I come to a halt, because I just cannot get my NestJS controllers to respond in this setup.\n\nThis works:\n\n```\nfunction widgetRoutes(server: express.Express) {\n const widgetData = [\n { id: 1, name: 'Weather', componentName: 'weather' },\n { id: 2, name: 'Taxes', componentName: 'widget2' },\n { id: 3, name: 'Something else', componentName: 'widget3' },\n ];\n\n server.get('/api/widgets', (req, res) => {\n res.json(widgetData);\n });\n\n /**\n * Fetch a single widget by ID.\n */\n server.get('/api/widgets/:id', (req, res) => {\n if (req.params.id) {\n const widget = widgetData.find((w) => w.id === +req.params.id);\n if (!widget) {\n res.status(404).json({ error: 'Widget not found' });\n } else {\n res.json([widget]);\n }\n }\n console.log('[APP]', req.method, req.url, res.statusCode);\n });\n}\n\nexport function bootstrap(): express.Express {\n const server = express();\n const serverDistFolder = dirname(fileURLToPath(import.meta.url));\n const browserDistFolder = resolve(serverDistFolder, '../browser');\n\n // Here, we now use the `AngularNodeAppEngine` instead of the `CommonEngine`\n const angularNodeAppEngine = new AngularNodeAppEngine();\n\n // Setup api routes\n widgetRoutes(server);\n\n // Setup reverse proxy routes\n Object.entries(proxyRoutes).forEach(([path, config]) =>\n server.get(path, createProxyMiddleware(config)),\n );\n\n // Serve static files from the browser distribution folder\n server.get(\n '**',\n express.static(browserDistFolder, {\n maxAge: '1y',\n index: 'index.html',\n }),\n );\n\n server.get('**', (req, res, next) => {\n // Yes, this is executed in devMode via the Vite DevServer\n console.log('[APP]', req.method, req.url, res.statusCode);\n\n angularNodeAppEngine\n .handle(req, { server: 'express' })\n .then((response) =>\n response ? writeResponseToNodeResponse(response, res) : next(),\n )\n .catch(next);\n });\n\n return server;\n}\n\nconst server = bootstrap();\nif (isMainModule(import.meta.url)) {\n const port = process.env['PORT'] || 4000;\n server.listen(port, () => {\n console.log(`Node Express server listening on http://localhost:\\${port}`);\n });\n}\n\nconsole.warn('Node Express server started');\n\n// This exposes the RequestHandler\nexport const reqHandler = createNodeRequestHandler(server);\n```\n\nThis doesn't:\n\n```\n@Controller('api/widgets')\nexport class WidgetController {\n widgetData = [\n { id: 1, name: 'Weather', componentName: 'weather' },\n { id: 2, name: 'Taxes', componentName: 'widget2' },\n { id: 3, name: 'Something else', componentName: 'widget3' },\n ];\n\n @Get()\n findAll() {\n return this.widgetData;\n }\n\n @Get(':id')\n findOne(@Param('id') id: string) {\n return this.widgetData.find((w) => w.id === +id);\n }\n}\n\n@Module({\n // Setup api routes\n controllers: [WidgetController],\n})\nexport class AppModule {}\n \nexport async function bootstrap() {\n const app = await NestFactory.create(AppModule);\n // Get the express instance from the NestJS app\n const server = app.getHttpAdapter().getInstance();\n const serverDistFolder = dirname(fileURLToPath(import.meta.url));\n const browserDistFolder = resolve(serverDistFolder, '../browser');\n \n // Here, we now use the `AngularNodeAppEngine` instead of the `CommonEngine`\n const angularNodeAppEngine = new AngularNodeAppEngine();\n \n // Setup reverse proxy routes\n Object.entries(proxyRoutes).forEach(([path, config]) =>\n server.get(path, createProxyMiddleware(config)),\n );\n \n // Serve static files from the browser distribution folder\n server.get(\n '**',\n express.static(browserDistFolder, {\n maxAge: '1y',\n index: 'index.html',\n }),\n );\n\n server.get('**', (req, res, next) => {\n // Yes, this is executed in devMode via the Vite DevServer\n console.log('[APP]', req.method, req.url, res.statusCode);\n\n angularNodeAppEngine\n .handle(req, { server: 'express' })\n .then((response) =>\n response ? writeResponseToNodeResponse(response, res) : next(),\n )\n .catch(next);\n });\n\n return app;\n}\n \nconst server = await bootstrap();\nif (isMainModule(import.meta.url)) {\n const port = process.env['PORT'] || 4000;\n server.listen(port, () => {\n console.log(`Node Express server listening on http://localhost:\\${port}`);\n });\n}\n \n// This exposes the RequestHandler\nexport const reqHandler = createNodeRequestHandler(\n server.getHttpAdapter().getInstance(),\n);\n```\n\nWhat am I doing wrong? The setup looks to be the same, but the NestJS controller does not respond.\nOr, if my thoughts stink, why should I not venture down this road?\n\n========================================\n\nCode:\n```js\nfunction widgetRoutes(server: express.Express) {\n  const widgetData = [\n    { id: 1, name: 'Weather', componentName: 'weather' },\n    { id: 2, name: 'Taxes', componentName: 'widget2' },\n    { id: 3, name: 'Something else', componentName: 'widget3' },\n  ];\n\n  server.get('/api/widgets', (req, res) => {\n    res.json(widgetData);\n  });\n\n  /**\n   * Fetch a single widget by ID.\n   */\n  server.get('/api/widgets/:id', (req, res) => {\n    if (req.params.id) {\n      const widget = widgetData.find((w) => w.id === +req.params.id);\n      if (!widget) {\n        res.status(404).json({ error: 'Widget not found' });\n      } else {\n        res.json([widget]);\n      }\n    }\n    console.log('[APP]', req.method, req.url, res.statusCode);\n  });\n}\n\nexport function bootstrap(): express.Express {\n  const server = express();\n  const serverDistFolder = dirname(fileURLToPath(import.meta.url));\n  const browserDistFolder = resolve(serverDistFolder, '../browser');\n\n  // Here, we now use the `AngularNodeAppEngine` instead of the `CommonEngine`\n  const angularNodeAppEngine = new AngularNodeAppEngine();\n\n  // Setup api routes\n  widgetRoutes(server);\n\n  // Setup reverse proxy routes\n  Object.entries(proxyRoutes).forEach(([path, config]) =>\n    server.get(path, createProxyMiddleware(config)),\n  );\n\n  // Serve static files from the browser distribution folder\n  server.get(\n    '**',\n    express.static(browserDistFolder, {\n      maxAge: '1y',\n      index: 'index.html',\n    }),\n  );\n\n  server.get('**', (req, res, next) => {\n    // Yes, this is executed in devMode via the Vite DevServer\n    console.log('[APP]', req.method, req.url, res.statusCode);\n\n    angularNodeAppEngine\n      .handle(req, { server: 'express' })\n      .then((response) =>\n        response ? writeResponseToNodeResponse(response, res) : next(),\n      )\n      .catch(next);\n  });\n\n  return server;\n}\n\nconst server = bootstrap();\nif (isMainModule(import.meta.url)) {\n  const port = process.env['PORT'] || 4000;\n  server.listen(port, () => {\n    console.log(`Node Express server listening on http://localhost:\\${port}`);\n  });\n}\n\nconsole.warn('Node Express server started');\n\n// This exposes the RequestHandler\nexport const reqHandler = createNodeRequestHandler(server);\n```\n\n```js\n@Controller('api/widgets')\nexport class WidgetController {\n  widgetData = [\n    { id: 1, name: 'Weather', componentName: 'weather' },\n    { id: 2, name: 'Taxes', componentName: 'widget2' },\n    { id: 3, name: 'Something else', componentName: 'widget3' },\n  ];\n\n  @Get()\n  findAll() {\n    return this.widgetData;\n  }\n\n  @Get(':id')\n  findOne(@Param('id') id: string) {\n    return this.widgetData.find((w) => w.id === +id);\n  }\n}\n\n@Module({\n  // Setup api routes\n  controllers: [WidgetController],\n})\nexport class AppModule {}\n  \nexport async function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(AppModule);\n  // Get the express instance from the NestJS app\n  const server = app.getHttpAdapter().getInstance();\n  const serverDistFolder = dirname(fileURLToPath(import.meta.url));\n  const browserDistFolder = resolve(serverDistFolder, '../browser');\n  \n  // Here, we now use the `AngularNodeAppEngine` instead of the `CommonEngine`\n  const angularNodeAppEngine = new AngularNodeAppEngine();\n  \n  // Setup reverse proxy routes\n  Object.entries(proxyRoutes).forEach(([path, config]) =>\n    server.get(path, createProxyMiddleware(config)),\n  );\n  \n  // Serve static files from the browser distribution folder\n  server.get(\n    '**',\n    express.static(browserDistFolder, {\n      maxAge: '1y',\n      index: 'index.html',\n    }),\n  );\n\n  server.get('**', (req, res, next) => {\n    // Yes, this is executed in devMode via the Vite DevServer\n    console.log('[APP]', req.method, req.url, res.statusCode);\n\n    angularNodeAppEngine\n      .handle(req, { server: 'express' })\n      .then((response) =>\n        response ? writeResponseToNodeResponse(response, res) : next(),\n      )\n      .catch(next);\n  });\n\n  return app;\n}\n  \nconst server = await bootstrap();\nif (isMainModule(import.meta.url)) {\n  const port = process.env['PORT'] || 4000;\n  server.listen(port, () => {\n    console.log(`Node Express server listening on http://localhost:\\${port}`);\n  });\n}\n  \n// This exposes the RequestHandler\nexport const reqHandler = createNodeRequestHandler(\n  server.getHttpAdapter().getInstance(),\n);\n```\n\n```text\nng serve\n```\n\n```js\n@Controller('api/widgets')\nexport class WidgetController {\n  widgetData = [\n    { id: 1, name: 'Weather', componentName: 'weather' },\n    { id: 2, name: 'Taxes', componentName: 'widget2' },\n    { id: 3, name: 'Something else', componentName: 'widget3' },\n  ];\n\n  @Get()\n  findAll() {\n    return this.widgetData;\n  }\n\n  @Get(':id')\n  findOne(@Param('id') id: string) {\n    return this.widgetData.find((w) => w.id === +id);\n  }\n}\n\n@Module({\n  // Setup api routes\n  controllers: [WidgetController],\n})\nexport class ApiModule {}\n  \nexport async function bootstrap() {\n  // Create the NestJS application\n  const app = await NestFactory.create<NestExpressApplication>(ApiModule);\n  // Get the Express instance\n  const server = app.getHttpAdapter().getInstance();\n\n  // Setup reverse proxy routes\n  Object.entries(proxyRoutes).forEach(([path, config]) =>\n    server.get(path, createProxyMiddleware(config)),\n  );\n\n  // Serve static files from the browser distribution folder\n  const serverDistFolder = dirname(fileURLToPath(import.meta.url));\n  const browserDistFolder = resolve(serverDistFolder, '../browser');\n  server.get(\n    '**',\n    express.static(browserDistFolder, {\n      maxAge: '1y',\n      index: 'index.html',\n    }),\n  );\n\n  // SSR middleware: Render out the angular application server-side\n  const angularNodeAppEngine = new AngularNodeAppEngine();\n  server.get('**', (req, res, next) => {\n    angularNodeAppEngine\n      .handle(req, { server: 'express' })\n      .then((response) => {\n        // If the Angular app returned a response, write it to the Express response\n        if (response) {\n          const n = writeResponseToNodeResponse(response, res);\n          console.log('[SSR]', req.method, req.url, response.status);\n          return n;\n        }\n        // If not, this is not an Angular route, so continue to the next middleware\n        return next();\n      })\n      .catch(next);\n  });\n\n  // Initialize the NestJS application and return the server\n  app.init(); // <-- This is what makes it work\n  return server;\n}\n  \nconst server = await bootstrap();\nif (isMainModule(import.meta.url)) {\n  const port = process.env['PORT'] || 4000;\n  server.listen(port, () => {\n    console.log(`Node Express server listening on http://localhost:\\${port}`);\n  });\n}\n  \n// This exposes the RequestHandler\nexport const reqHandler = createNodeRequestHandler(server);\n```\n\n```text\napp.init()\n```\n\n```text\ninit()\n```\n\n```text\n.listen\n```\n\n```text\n.listen\n```\n\n========================================\n\nComments:\n- thank you so much, that really good, I'm have the same issue, can you provide the example of your code? I cannot make it run with nestJS\n- Sure: github.com/OysteinAmundsen/home\n- Have you tried this with Dependency Injection in place - i.e. injecting a Service into the WidgetController? I tried to reproduce this example on my machine and figured that DI does not work / is never executed and the injected service remains undefined.\n- This works fine @Silverdust. I got an error on my first attempt to inject the service, but I forgot to provide the service in the api module so it was never introduced to the injector in the first place.\n- This is how I did it: github.com/OysteinAmundsen/home/commit/&hellip;\n- Hi @&#216;ysteinAmundsen I tried to build your project on my local machine but I can't even manage to install the npm packages using \"npm i\": npm error While resolving: @swc/cli@0.3.14 npm error Found: chokidar@4.0.3 npm error node_modules/chokidar npm error chokidar@\"^4.0.0\" from @angular/compiler-cli@19.0.7 After I install it with the force flag enabled, the npm packages are installed but I can't get anything to run: Failed to process project graph. Run \"nx reset\" to fix this. Please report the issue if you keep seeing it. \"nx reset\" doesn't help either! What am I doing wrong?\n- @Silverdust the project is built using `bun` as package manager and not `npm`. You will probably get a conflict from nx if you try to run this with both a `bun.lockb` file and a `package-lock.json` file present. And also, the scripts in my package.json references `bun`, so if you use those you will probably get an error.\n- @&#216;ysteinAmundsen I see that was indeed the problem ;-) I now tried to achieve the same result without nx but I cannot get it up and running: github.com/Amadeus82/angular-demo A screenshot of the appearing errors are in the error-screenshot folder. Would you mind taking a look? Besides, I don't understand how Angular and NestJs could ever work using the same compiler settings as to my knowledge, Angular creats ESM modules while NestJS generates CommonJS modules. How can the work together? Also, why did you have to manually install @nestjs/microservices and @grpc/proto-loader?\n- @Silverdust node does not require commonjs modules, you can just as easily run esm modules. The output will be a *.mjs file which is executable through node (or bun). But I think the source of your problem is the compilerOption `emitDecoratorMetadata: true`, which is required by NestJS but emits warnings by angular. Try setting this and see if that perhaps resolves your `ng serve`. For the build, I would suggest either installing the packages it complains about manually, or adding them to your `angular.json` build options as `externalDependencies`.\n- @&#216;ysteinAmundsen I just had the same thought as you (using the ssr server as an actual backend). What experience did you make with it so far, are you still happy with the approach? And can you still run the app with the angular dev server for local development, even if you use node only packages for the server?\n- @Patric I still play around with this repository, yes. And I'm still happy with this approach, although I've had to limit third-party packages to ESM only. Anything required to use commonJS will probably fail. But I've still yet to find anything that completely blocks this approach. Building the service-worker demands a bit of a workaround as angular does not support hooking into the build cycle to get all artifacts. But that can be worked around.","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":460,"estimatedTokens":4027}}1129{"id":"stack-74386377","source":"stackoverflow","questionId":74386377,"title":"Prevent default response code in Swagger/OpenAPI definition with NestJS","tags":["swagger","nestjs","nestjs-swagger"],"text":"Title: Prevent default response code in Swagger/OpenAPI definition with NestJS\nTags: swagger, nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\n### What I'm trying\n\nI'm implementing a DELETE route using NestJS.\n\nSince the route is only ever supposed to return a `HTTP 204 No Content` on successful deletion, utilizing the `@nestjs/swagger` decorators, I've annotated it as follows:\n\n```\n@ApiParam({\n name: 'id',\n required: true,\n type: 'string',\n example: 'abc123',\n})\n@ApiNoContentResponse({\n description: 'All items for the given id have been deleted',\n})\n@Delete('/accounts/:id/items')\nasync deleteItems(\n @Param('id') id: string,\n) {\n // do stuff\n}\n```\n\n### Stack\n\n```\n@nestjs/cli: 9.1.6\n@nestjs/common: 9.1.6\n@nestjs/core: 9.1.6\n@nestjs/platform-express: 9.1.6\n@nestjs/swagger: 6.1.2\n```\n\n### nest-cli.json\n\n```\n{\n \"$schema\": \"https://json.schemastore.org/nest-cli\",\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"plugins\": [\n \"@nestjs/swagger/plugin\"\n ]\n }\n}\n```\n\n### Question\n\nHow can I prevent this (default?) response from being generated?\n\n### What happens\n\nWhen running the server with `npm run start:dev`, the swagger description for my route is created. Although I've not explicitly defined it, the description now contains an entry for `HTTP 200` in the `Response` section of the route. The entry contains no description and no indicator that it's not explicitly defined.\n\n### What I expected to happen\n\nWhen running the server with `npm run start:dev`, the swagger description for my route is created. The description only contains and entry for `HTTP 204` in the `Response` section of the route.\n\n### What I've tried\n\nExplicitly defined an `@ApiOkResponse`:\n\n```\n// they all have no effect\n@ApiOkResponse()\n// OR\n@ApiOkResponse({})\n// OR\n@ApiOkResponse({ status: 204 })\n```\n\nDefined an `@ApiDefaultResponse`:\n\n```\n// they all create a response 'default' with no description\n@ApiDefaultResponse() \n// OR\n@ApiDefaultResponse({})\n// OR\n@ApiDefaultResponse({ status: 204 })\n```\n\n========================================\n\nCode:\n```js\n@ApiParam({\n  name: 'id',\n  required: true,\n  type: 'string',\n  example: 'abc123',\n})\n@ApiNoContentResponse({\n  description: 'All items for the given id have been deleted',\n})\n@Delete('/accounts/:id/items')\nasync deleteItems(\n  @Param('id') id: string,\n) {\n  // do stuff\n}\n```\n\n```text\n@nestjs/cli: 9.1.6\n@nestjs/common: 9.1.6\n@nestjs/core: 9.1.6\n@nestjs/platform-express: 9.1.6\n@nestjs/swagger: 6.1.2\n```\n\n```json\n{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\n      \"@nestjs/swagger/plugin\"\n    ]\n  }\n}\n```\n\n```js\n// they all have no effect\n@ApiOkResponse()\n// OR\n@ApiOkResponse({})\n// OR\n@ApiOkResponse({ status: 204 })\n```\n\n```js\n// they all create a response 'default' with no description\n@ApiDefaultResponse() \n// OR\n@ApiDefaultResponse({})\n// OR\n@ApiDefaultResponse({ status: 204 })\n```\n\n```text\nHTTP 204 No Content\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nHTTP 200\n```\n\n```text\nResponse\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nHTTP 204\n```\n\n```text\nResponse\n```\n\n```text\n@ApiOkResponse\n```\n\n```text\n@ApiDefaultResponse\n```\n\n```text\n@HttpCode(204)\n```\n\n```text\nDELETE\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":197,"estimatedTokens":828}}1130{"id":"stack-71227024","source":"stackoverflow","questionId":71227024,"title":"how to validate a phone number in nestjs-graphQL","tags":["graphql","nestjs"],"text":"Title: how to validate a phone number in nestjs-graphQL\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nNest.js\n\n```\nimport { Field, InputType } from '@nestjs/graphql';\n@InputType()\nexport class SignUpInput {\n @Field()\n phone: string;\n\n}\n```\n\nhow to validate a phone number?\n\n========================================\n\nCode:\n```text\nimport { Field, InputType } from '@nestjs/graphql';\n@InputType()\nexport class SignUpInput {\n  @Field()\n  phone: string;\n\n}\n```\n\n```text\nimport { InputType, Field } from '@nestjs/graphql';\nimport { IsPhoneNumber } from 'class-validator';\n\n@InputType()\nexport class SignUpInput {\n  @Field()\n  @IsPhoneNumber()\n  phone: string;\n}\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-validator\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":51,"estimatedTokens":182}}1131{"id":"stack-72125335","source":"stackoverflow","questionId":72125335,"title":"Why does partialType not make properties nullable?","tags":["typescript","nestjs"],"text":"Title: Why does partialType not make properties nullable?\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nDoes anyone know why `partialType` does not make properties nullable? It adds `@IsOptional` to properties which also allow `null` as a valid value, however the type returned from `partialType` only returns `T | undefined` instead of `T | undefined | null`, which causes a problem in TypeScript's strict null check mode. I opened an issue about it; the contributor said it's an expected behavior, but I don't see how.\n\n========================================\n\nCode:\n```text\npartialType\n```\n\n```text\n@IsOptional\n```\n\n```text\nnull\n```\n\n```text\npartialType\n```\n\n```text\nT | undefined\n```\n\n```text\nT | undefined | null\n```\n\n```text\ntype Nullable<T> = {\n  [P in keyof T]: T[P] | null;\n};\n\nexport function NullableType<T>(classRef: Type<T>): Type<Nullable<T>> {\n  return classRef as Type<Nullable<T>>;\n}\n```\n\n```text\npartialType\n```\n\n```text\nNullableType\n```\n\n========================================\n\nComments:\n- That's what \"optional\" refers to in TypeScript, `T | undefined` (see e.g. the built-in `Partial` utility type). That's consistent with the runtime behaviour - if you don't explicitly set a property or pass a parameter, the default value is `undefined` (*not* `null`). `| null` would usually be described as \"nullable\"; if `null` is valid that should be part of the type *before* making it optional.\n- @jonrsharpe The official definition of `@IsOptional` is that `It checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property.` which clearly means it can be ` | null ` both theoretically and in action however `partialType` ignores the ` | null` fact even though it applies `@IsOptional` decorator to all properties. How is it expected that `T | defined` may end up being ` === null`?\n- Nice. You can also include the partial and make it recursive if you want the nullable partiality to apply all the way down a deep nested structure, like `type DeepNullable = Partial | null;}>`","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":58,"estimatedTokens":514}}1132{"id":"stack-73651307","source":"stackoverflow","questionId":73651307,"title":"NestJs: Why is monorepo mode only packaging root app,","tags":["typescript","nestjs","nestjs-config"],"text":"Title: NestJs: Why is monorepo mode only packaging root app,\nTags: typescript, nestjs, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI have a Nest project set up in monorepo mode. However, when I run yarn build, Nest only puts the root app in the `dist` folder. Here's when my project structure looks like:\n\n```\n.\nโ””โ”€โ”€ cloud-kruser-backend\n โ”œโ”€โ”€ apps\n โ”‚ โ”œโ”€โ”€ root-app\n โ”‚ โ”‚ โ”œโ”€โ”€ src\n โ”‚ โ”‚ โ””โ”€โ”€ test\n โ”‚ โ””โ”€โ”€ hello\n โ”‚ โ”œโ”€โ”€ src\n โ”‚ โ””โ”€โ”€ test\n โ””โ”€โ”€ dist\n โ””โ”€โ”€ apps\n โ””โ”€โ”€ root-app\n```\n\nAfter running `yarn build` I would expect `dist` to have both `root-app` and `hello`.\n\nHere are the relevant config files:\n\n./nest-cli.json\n\n```\n{\n \"$schema\": \"https://json.schemastore.org/nest-cli\",\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"apps/root-app/src\",\n \"monorepo\": true,\n \"root\": \"apps/root-app\",\n \"compilerOptions\": {\n \"webpack\": true,\n \"tsConfigPath\": \"apps/root-app/tsconfig.app.json\"\n },\n \"projects\": {\n \"root-app\": {\n \"type\": \"application\",\n \"root\": \"apps/root-app\",\n \"entryFile\": \"main\",\n \"sourceRoot\": \"apps/root-app/src\",\n \"compilerOptions\": {\n \"tsConfigPath\": \"apps/root-app/tsconfig.app.json\"\n }\n },\n \"hello\": {\n \"type\": \"application\",\n \"root\": \"apps/hello\",\n \"entryFile\": \"main\",\n \"sourceRoot\": \"apps/hello/src\",\n \"compilerOptions\": {\n \"tsConfigPath\": \"apps/hello/tsconfig.app.json\"\n }\n }\n }\n}\n```\n\n./apps/root-app/tsconfig.app.json\n\n```\n{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"declaration\": false,\n \"outDir\": \"../../dist/apps/root-app\"\n },\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules\", \"dist\", \"test\", \"**/*spec.ts\"]\n}\n```\n\n./apps/hello/tsconfig.app.json\n\n```\n{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"declaration\": false,\n \"outDir\": \"../../dist/apps/hello\"\n },\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules\", \"dist\", \"test\", \"**/*spec.ts\"]\n}\n```\n\n========================================\n\nCode:\n```text\n.\nโ””โ”€โ”€ cloud-kruser-backend\n    โ”œโ”€โ”€ apps\n    โ”‚   โ”œโ”€โ”€ root-app\n    โ”‚   โ”‚   โ”œโ”€โ”€ src\n    โ”‚   โ”‚   โ””โ”€โ”€ test\n    โ”‚   โ””โ”€โ”€ hello\n    โ”‚       โ”œโ”€โ”€ src\n    โ”‚       โ””โ”€โ”€ test\n    โ””โ”€โ”€ dist\n        โ””โ”€โ”€ apps\n            โ””โ”€โ”€ root-app\n```\n\n```text\n{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"apps/root-app/src\",\n  \"monorepo\": true,\n  \"root\": \"apps/root-app\",\n  \"compilerOptions\": {\n    \"webpack\": true,\n    \"tsConfigPath\": \"apps/root-app/tsconfig.app.json\"\n  },\n  \"projects\": {\n    \"root-app\": {\n      \"type\": \"application\",\n      \"root\": \"apps/root-app\",\n      \"entryFile\": \"main\",\n      \"sourceRoot\": \"apps/root-app/src\",\n      \"compilerOptions\": {\n        \"tsConfigPath\": \"apps/root-app/tsconfig.app.json\"\n      }\n    },\n    \"hello\": {\n      \"type\": \"application\",\n      \"root\": \"apps/hello\",\n      \"entryFile\": \"main\",\n      \"sourceRoot\": \"apps/hello/src\",\n      \"compilerOptions\": {\n        \"tsConfigPath\": \"apps/hello/tsconfig.app.json\"\n      }\n    }\n  }\n}\n```\n\n```text\n{\n  \"extends\": \"../../tsconfig.json\",\n  \"compilerOptions\": {\n    \"declaration\": false,\n    \"outDir\": \"../../dist/apps/root-app\"\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"dist\", \"test\", \"**/*spec.ts\"]\n}\n```\n\n```text\n{\n  \"extends\": \"../../tsconfig.json\",\n  \"compilerOptions\": {\n    \"declaration\": false,\n    \"outDir\": \"../../dist/apps/hello\"\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"dist\", \"test\", \"**/*spec.ts\"]\n}\n```\n\n```text\ndist\n```\n\n```text\nyarn build\n```\n\n```text\ndist\n```\n\n```text\nroot-app\n```\n\n```text\nhello\n```\n\n```text\nnest build\n```\n\n```text\nnest start\n```\n\n```text\nnest build <app-name>\n```\n\n```text\nnest build hello\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":201,"estimatedTokens":890}}1133{"id":"stack-72851516","source":"stackoverflow","questionId":72851516,"title":"How to use typescript mapping for ElasticSearch response?","tags":["javascript","node.js","typescript","elasticsearch","nestjs"],"text":"Title: How to use typescript mapping for ElasticSearch response?\nTags: javascript, node.js, typescript, elasticsearch, nestjs\nSource: Stack Overflow\n\nQuestion:\nHow do I set the Post SearchResult interface to the search return value\n\nI can't set the interface to get the return results\nYou can review the code below\n\n***dependencies***\n\n```\n\"@nestjs/elasticsearch\": \"^8.1.0\",\n \"@elastic/elasticsearch\": \"^8.2.1\",\n \"@types/elasticsearch\": \"^5.0.40\",\n```\n\n***interface Post***\n\n```\nexport interface PostSearchResultInterface {\n hits: {\n total: {\n value: number;\n };\n hits: Array;\n };\n}\n```\n\n***code***\n\n```\nconst search = await this.elasticsearchService.search({\n index: this.index,\n from: offset,\n size: limit,\n body: {\n query: {\n bool: {\n should: {\n multi_match: {\n query: text,\n fields: ['title', 'story', 'other_titles']\n }\n },\n filter: {\n range: {\n id: {\n gte: startId\n }\n }\n }\n },\n },\n sort: {\n id: {\n order: 'asc'\n }\n }\n }\n }) ;\n\n // error here \n let count = search.hits.total.value\n \n const hits = search.hits.hits;\n const results = hits.map((item) => item._source);\n return {\n count : startId ? separateCount : count,\n results\n }\n```\n\nerror TS2339: Property 'value' does not exist on type 'number | SearchTotalHits'.\nProperty 'value' does not exist on type 'number'.\n\n```\nERROR: let count = search.hits.total.value\n```\n\n========================================\n\nCode:\n```bash\n\"@nestjs/elasticsearch\": \"^8.1.0\",\n   \"@elastic/elasticsearch\": \"^8.2.1\",\n   \"@types/elasticsearch\": \"^5.0.40\",\n```\n\n```js\nexport interface PostSearchResultInterface {\n    hits: {\n        total: {\n            value: number;\n        };\n        hits: Array<{\n            total: {\n                value: number;\n            }\n            _source: PostSearchBodyInterface;\n        }>;\n    };\n}\n```\n\n```js\nconst  search  = await this.elasticsearchService.search<PostSearchBodyInterface>({\n                index: this.index,\n                from: offset,\n                size: limit,\n                body: {\n                    query: {\n                        bool: {\n                            should: {\n                                multi_match: {\n                                    query: text,\n                                    fields: ['title', 'story', 'other_titles']\n                                }\n                            },\n                            filter: {\n                                range: {\n                                    id: {\n                                        gte: startId\n                                    }\n                                }\n                            }\n                        },\n                    },\n                    sort: {\n                        id: {\n                            order: 'asc'\n                        }\n                    }\n                }\n            }) ;\n\n\n             // error here \n            let count = search.hits.total.value\n           \n            const hits = search.hits.hits;\n            const results = hits.map((item) => item._source);\n            return {\n                count : startId ? separateCount : count,\n                results\n            }\n```\n\n```js\nERROR: let count = search.hits.total.value\n```\n\n```json\n\"@nestjs/elasticsearch\": \"^8.1.0\",\n\"@elastic/elasticsearch\": \"^8.2.1\",\n\"@types/elasticsearch\": \"^5.0.40\",\n```\n\n```js\nexport type Document = { \n  title: string, \n  tags: string[]\n};\n```\n\n```js\nconst a = await this.elastic.search<Document>({ //...request... });\n\nconst total = a.hits.total;\nconst documents = a.hits.hits.map(document => {\n  // query metadata fields returned by elastic\n  document._id;\n\n  // get fields for <Document> type\n  document._source.title...\n  document._source.tags...\n})\n```\n\n========================================\n\nComments:\n- are you sure that elasticsearch is not reurning any error in response and search is returning 200 response code ?\n- yes if i skip the interface it's run but it's not recognize interface","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":186,"estimatedTokens":987}}1134{"id":"stack-71257348","source":"stackoverflow","questionId":71257348,"title":"How do I read an uploaded file (text/.csv) using nestjs and Multer","tags":["javascript","node.js","file","nestjs","multer"],"text":"Title: How do I read an uploaded file (text/.csv) using nestjs and Multer\nTags: javascript, node.js, file, nestjs, multer\nSource: Stack Overflow\n\nQuestion:\nI need to read my CSV file in the controller to add CSV file data into my DB. But I don't know the way to that. I search for an answer so many times but I can't find an answer to related my question. I really need your help with this. Thank you.\n\nMy Controller method :-\n\n```\n@Post()\n @UseInterceptors(FileInterceptor('filename', { dest: './uploads' }))\n async upload(@UploadedFile() files: Express.Multer.File) {\n console.log(files);\n }\n```\n\nMy console log output:-\n\nhttps://i.sstatic.net/WeP1E.png\n\n========================================\n\nCode:\n```text\n@Post()\n  @UseInterceptors(FileInterceptor('filename', { dest: './uploads' }))\n  async upload(@UploadedFile() files: Express.Multer.File) {\n    console.log(files);\n  }\n```\n\n```js\n@Post('upload')\n  @UseInterceptors(FileInterceptor('file', {\n    storage: diskStorage({\n      destination: './uploads/csv',\n      filename: csvFileName,\n    }),\n    fileFilter: csvFileFilter,\n  }))\n  uploadFile(@UploadedFile() file: Express.Multer.File) {\n    const response = {\n      message: \"File uploaded successfully!\",\n      data: { \n        originalname: file.originalname,\n        filename: file.filename,\n      }\n    };\n    return response;\n  }\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Coin } from './coin.entity';\nimport { CoinsController } from './coins.controller';\nimport { CoinsService } from './coins.service';\nimport {CsvModule} from \"nest-csv-parser\";\nimport {MulterModule} from \"@nestjs/platform-express\";\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([Coin]),\n      CsvModule,\n    MulterModule.register({\n      dest: './uploads/csv',\n    }),\n  ],\n  controllers: [\n    CoinsController,\n  ],\n  providers: [CoinsService]\n})\nexport class CoinsModule { }\n```\n\n```js\nimport {extname, join} from 'path';\n\nexport const csvFileFilter = (req, file, callback) => {\n    if (!file.originalname.match(/\\.(csv)$/)) {\n        return callback(new Error('Only CSV files are allowed!'), false);\n    }\n    callback(null, true);\n};\n\nexport const csvFileName = (req, file, callback) => {\n    //const name = file.originalname.split('.')[0];\n    const fileExtName = extname(file.originalname);\n    callback(null, `data${fileExtName}`);\n};\n\nexport const getCSVFile = () => {\n    //const name = file.originalname.split('.')[0];\n    const filePath = join(__dirname, \"..\", \"..\", \"uploads/csv\", \"data.csv\");\n    return filePath;\n};\n\nexport const editFileName = (req, file, callback) => {\n    const name = file.originalname.split('.')[0];\n    const fileExtName = extname(file.originalname);\n    const randomName = Array(4)\n        .fill(null)\n        .map(() => Math.round(Math.random() * 16).toString(16))\n        .join('');\n    callback(null, `${name}-${randomName}${fileExtName}`);\n};\n```\n\n```js\n// You have to define entity that is as 2nd argument of csvParsing and also a mendatory.\nclass Coin {\n  unix: number\n  date: string\n  symbol: string\n  open: number\n  close: number\n  high: number\n  low: number\n  \"Volume BTC\": number\n  \"Volume USDT\": number\n  tradecount: number\n}\n\n\n// An import end route\n@Get('import')\n  async import(){\n    const csvPath = getCSVFile();\n    console.log(\" => \", csvPath);\n    const stream = fs.createReadStream(csvPath)\n    const entities: Coin[] = await this.csvParser.parse(stream, Coin)\n    // You will get JSON\n    console.log(entities);\n  }\n```\n\n```text\nuploads/csv\n```\n\n```text\n/upload\n```\n\n========================================\n\nComments:\n- Have you tried parsing the file using packages like `csv-parser` or `nest-csv-parser` ?\n- Thank you very much....๐Ÿ˜Š\n- How does your http request headers look like? i keep getting a 415 \"Unsupported Media Type\" error. I have content-type set to multipart/form-data.","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":153,"estimatedTokens":976}}1135{"id":"stack-72921086","source":"stackoverflow","questionId":72921086,"title":"How to pass class-validator @isArray when single item comes from query param","tags":["typescript","validation","nestjs","class-validator"],"text":"Title: How to pass class-validator @isArray when single item comes from query param\nTags: typescript, validation, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm trying to validate request with class-validator if it's array.\n\ninputs comes from query param with `/api/items?someTypes=this`\n\nmy request dto looks like this.\n\n```\n(...)\n @IsArray()\n @IsEnum(SOMETHING, {each: true})\n readonly someTypes: keyof typeof SOMETHING[];\n (...)\n```\n\nwhen I give only one item, @IsArray gives validation error, saying it is not an array.\n\nI want to make it array too when one item comes from query param, but I don't know how.\n\nI know using `/api/items?someTypes[]=this` will pass validation.\n\nbut I want to know if there is another way to solve this.\n\n========================================\n\nTop Answer:\nYou already set the `each` option, so you don't need to use `@IsArray`.\nvalidating-arrays\n\n========================================\n\nCode:\n```text\n(...)\n    @IsArray()\n    @IsEnum(SOMETHING, {each: true})\n    readonly someTypes: keyof typeof SOMETHING[];\n    (...)\n```\n\n```text\n/api/items?someTypes=this\n```\n\n```text\n/api/items?someTypes[]=this\n```\n\n```text\nimport { IsArray, IsEnum } from 'class-validator';\n\nenum SomeType {\n  A,\n  B,\n  C,\n}\n\nclass SearchQuery {\n  @IsArray()\n  @IsEnum(SomeType, { each: true })\n  types: SomeType[];\n}\n\n\n@Controller()\nexport class AppController {\n  @Get()\n  async search(@Query() searchQuery: SearchQuery): Promise<void> \n  { ... }\n}\n```\n\n```text\n?types[]=A&types[]=B&types[]=C\n```\n\n```text\n?types[]=A\n```\n\n```text\nclass SearchQuery {\n  @IsArray()\n  @IsEnum(SomeType, { each: true })\n  @Transform(({ value }) =>\n    value\n      .trim()\n      .split(',')\n      .map((type) => SomeType[type]),\n  )\n  types: SomeType[];\n}\n```\n\n```text\neach: true\n```\n\n```text\n@IsEnum()\n```\n\n```text\ntypes=A,B,C\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-tranformer\n```\n\n```text\neach\n```\n\n```text\n@IsArray\n```\n\n========================================\n\nComments:\n- solved with @Transform() decorator. thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":130,"estimatedTokens":509}}1136{"id":"stack-68610924","source":"stackoverflow","questionId":68610924,"title":"How to use else condition in validationif decorator nestjs class-validator?","tags":["typescript","nestjs","class-validator"],"text":"Title: How to use else condition in validationif decorator nestjs class-validator?\nTags: typescript, nestjs, class-validator\nSource: Stack Overflow\n\nQuestion:\nI need to conditional validate an input filed in nestjs, class-validator. There is a validateif decorator but how to add another validation in else section? For example: if first input was email use email decorator if it was phone match my regex.\n\n```\n@IsNotEmpty()\n @IsEnum(UsernameType)\n public type: UsernameType;\n\n// enum has two value: phone and email\n\n @IsNotEmpty()\n @ValidateIf(o => o.type === UsernameType.PHONE )\n @Matches(/(09)[0-9]{9}/)\n username: number;\n\n @IsNotEmpty()\n @ValidateIf(o => o.type === UsernameType.EMAIL)\n @IsEmail()\n username: string;\n```\n\n========================================\n\nCode:\n```text\n@IsNotEmpty()\n    @IsEnum(UsernameType)\n    public type: UsernameType;\n\n// enum has two value: phone and email\n\n    @IsNotEmpty()\n    @ValidateIf(o => o.type === UsernameType.PHONE )\n    @Matches(/(09)[0-9]{9}/)\n    username: number;\n\n    @IsNotEmpty()\n    @ValidateIf(o => o.type === UsernameType.EMAIL)\n    @IsEmail()\n    username: string;\n```\n\n```text\nimport { IsEmail, IsEnum, IsNotEmpty, Matches, Validate, ValidateIf } from \"class-validator\";\nimport { UsernameValidation } from \"src/validations/username-validation\";\nimport { UsernameType } from \"../username-type.enum\";\n\nexport class TypeDto {\n\n    @IsNotEmpty()\n    @IsEnum(UsernameType)\n    public type: UsernameType;\n\n    @Validate(UsernameValidation)\n    @IsNotEmpty()\n    username: string;\n}\n```\n\n```text\nimport { TypeDto } from '../user/dto/type.dto';\nimport { UsernameType } from '../user/username-type.enum';\nimport { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, Matches } from 'class-validator';\n\n@ValidatorConstraint({ name: 'UsernameValidation', async: false })\nexport class UsernameValidation implements ValidatorConstraintInterface {\n    validate(username: string, args: ValidationArguments) {\n\n        if (JSON.parse(JSON.stringify(args.object)).type === UsernameType.PHONE) {\n\n\n            var regexp = new RegExp('(09)[0-9]{9}');\n            // \"regexp\" variable now validate iranian phone number.\n            return regexp.test(username);\n        } else {\n            regexp = new RegExp(\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\");\n            // \"regexp\" variable now validate email address.\n            return regexp.test(username);\n        }\n\n    }\n\n    defaultMessage(args: ValidationArguments) {\n\n        if (JSON.parse(JSON.stringify(args.object)).type === UsernameType.PHONE) {\n            return 'Enter a valid phone number.'\n        } else {\n            return 'Enter a valid email address.'\n        }\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":96,"estimatedTokens":679}}1137{"id":"stack-68584092","source":"stackoverflow","questionId":68584092,"title":"using between for query Dates on api Repository Typeorm","tags":["postgresql","nestjs","typeorm"],"text":"Title: using between for query Dates on api Repository Typeorm\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am doing an endpoint that will receive an **array of strings** , **from date** and **to date**\n\nlike this:\n\n```\n{\n \"cage\": [\n \"100000\",\n \"100100\",\n \"130109\",\n \"130106\"\n ],\n \"from\": \"2020-05-01T00:00:00Z\",\n \"to\": \"2021-12-29T23:32:33.464Z\"\n}\n```\n\nThis is my query:\n\n```\nreturn await this.returnRepository.findAndCount({\n where: {\n cod_locality: In(cage),\n status_id: 1,\n shipment_id: IsNull(),\n asn_date: Between(from, to)\n //asn_date: Raw(asnDate => `${asnDate} => :from AND ${asnDate} **Question**\n\nIs a good idea to filter the dates using Between? Dates always are hard for me so its a little confusing.\n\nI was thinking that the Between will be comparing 2 strings but not Date Object so I dont know if this would work fine\n\nThe other option I seek was the comment one but I'm not sure how to use it properly.\n\nWhat do you guy think? Between will work or I need to change it for another one?\n\nps. I just remember the thing about the timezone of the database -.-\n\nthank you very much\n\n========================================\n\nCode:\n```text\n{\n  \"cage\": [\n    \"100000\",\n    \"100100\",\n    \"130109\",\n    \"130106\"\n  ],\n  \"from\": \"2020-05-01T00:00:00Z\",\n  \"to\": \"2021-12-29T23:32:33.464Z\"\n}\n```\n\n```text\nreturn await this.returnRepository.findAndCount({\n                where: {\n                    cod_locality: In(cage),\n                    status_id: 1,\n                    shipment_id: IsNull(),\n                    asn_date: Between(from, to)\n                    //asn_date: Raw(asnDate => `${asnDate} => :from AND ${asnDate} <= :to`, { from, to }),\n                }\n            })\n```\n\n```js\nimport { Between } from 'typeorm';\nimport { format } from 'date-fns';\n\n// TypeORM Query Operators\nexport const BetweenDates = (from: Date | string, to: Date | string) =>\n  Between(\n    format(typeof from === 'string' ? new Date(from) : from, 'YYYY-MM-DD HH:MM:SS'),\n    format(typeof to === 'string' ? new Date(to) : to, 'YYYY-MM-DD HH:MM:SS'),\n  );\n\n// Query\nreturn await this.returnRepository\n                  .findAndCount({\n                    where: {\n                      cod_locality: In(cage),\n                      status_id: 1,\n                      shipment_id: IsNull(),\n                      asn_date: BetweenDates(from, to),\n                    }\n                  });\n```\n\n```text\nBetween\n```\n\n========================================\n\nComments:\n- Typeerror when the date field is of type date","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":104,"estimatedTokens":635}}1138{"id":"stack-65870541","source":"stackoverflow","questionId":65870541,"title":"TypeOrm - NestJS using queryBuilder","tags":["mysql","node.js","nestjs","query-builder","typeorm"],"text":"Title: TypeOrm - NestJS using queryBuilder\nTags: mysql, node.js, nestjs, query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have this db schema in mysql:\n\n```\nusers_tbl\n --------------------------------------------\n id | first_name | last_name\n --------------------------------------------\n 1 | Jon | Doe\n 2 | Mark | Smith\n\n address_tbl\n ------------------------------------------------------------\n id | address | city | user_id\n ------------------------------------------------------------\n 1 | some address | some city | 1\n```\n\nThen, I wanted to use TypeOrm's queryBuilder inorder to get the address of Jon Doe.\n\nMy raw sql query:\n`SELECT users.first_name, users.last_name, address.address, address.city FROM users INNER JOIN address ON address.user_id=users.id`\n\nMy TypeOrm queryBuilder:\n\n```\nconst users = await this.userRepo\n .createQueryBuilder('users')\n .select('users.first_name', 'fName')\n .addSelect('users.last_name', 'lName')\n .addSelect('adr.address', 'address')\n .addSelect('adr.city', 'city')\n .innerJoin('address', 'adr', 'adr.user_id=users.id')\n .getMany();\nreturn users;\n```\n\nThere doesn't seem to have any error as I am able to run a `GET` request. However, it returns an empty object. In my console, NestJS (or TypeORM) logs the generated mysql query. Here it is:\n\n`SELECT adr.city AS city, adr.country AS country, adr.id AS adr_id, users.first_name AS fName, users.last_name AS lName FROM users users INNER JOIN address adr ON adr.user_id = users.id`\n\nI copied and pasted it to perform a manual query in phpmyadmin. And the query seems to work, and gives me the expected output. Am I missing something in my code, or is this some TypeORM limitation?\n\n========================================\n\nCode:\n```text\nusers_tbl\n     --------------------------------------------\n     id        |  first_name         | last_name\n     --------------------------------------------\n     1         |  Jon                | Doe\n     2         |  Mark               | Smith\n\n\n     address_tbl\n     ------------------------------------------------------------\n     id        |  address            | city             | user_id\n     ------------------------------------------------------------\n     1         |  some address       | some city        | 1\n```\n\n```text\nconst users = await this.userRepo\n      .createQueryBuilder('users')\n      .select('users.first_name', 'fName')\n      .addSelect('users.last_name', 'lName')\n      .addSelect('adr.address', 'address')\n      .addSelect('adr.city', 'city')\n      .innerJoin('address', 'adr', 'adr.user_id=users.id')\n      .getMany();\nreturn users;\n```\n\n```text\nSELECT users.first_name, users.last_name, address.address, address.city FROM users INNER JOIN address ON address.user_id=users.id\n```\n\n```text\nGET\n```\n\n```text\nSELECT adr.city AS city, adr.country AS country, adr.id AS adr_id, users.first_name AS fName, users.last_name AS lName FROM users users INNER JOIN address adr ON adr.user_id = users.id\n```\n\n```text\nreturn await this.userRepo\n      .createQueryBuilder('users')\n      .select('users.first_name', 'fName')\n      .addSelect('users.last_name', 'lName')\n      .addSelect('adr.address', 'address')\n      .addSelect('adr.city', 'city')\n      .innerJoin('address', 'adr', 'adr.user_id=users.id')\n      .printSql() \n      .getRawMany();\n```\n\n```text\ngetRawMany\n```\n\n```text\ngetMany\n```\n\n========================================\n\nComments:\n- Can you you controller method?","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":859}}1139{"id":"stack-67595929","source":"stackoverflow","questionId":67595929,"title":"NestJS gRPC Middlware","tags":["nestjs","grpc"],"text":"Title: NestJS gRPC Middlware\nTags: nestjs, grpc\nSource: Stack Overflow\n\nQuestion:\nDoes NestJS support middleware with gRPC? I'm following the example project here and then the middleware for logging the request entrypoint here.\n\nIn the example project it looks like there is an Express server along with the gRPC server. I'm using just a gRPC server.\n\n```\nconst app = await NestFactory.createMicroservice(...);\nawait app.listenAsync();\n```\n\nSo adding the following to the main app module:\n\n```\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(LoggerMiddleware)\n .forRoutes('*');\n }\n}\n```\n\nBut nothing is logging.\n\n========================================\n\nCode:\n```text\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(...);\nawait app.listenAsync();\n```\n\n```text\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes('*');\n  }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.578Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":45,"estimatedTokens":253}}1140{"id":"stack-67752064","source":"stackoverflow","questionId":67752064,"title":"NestJs - Calling a method from a service inside a Custom Decorator","tags":["node.js","typescript","nestjs","decorator"],"text":"Title: NestJs - Calling a method from a service inside a Custom Decorator\nTags: node.js, typescript, nestjs, decorator\nSource: Stack Overflow\n\nQuestion:\nBased on this answer, I tried to implement a function from another service inside a decorator.\n\nHere is my attempt:\n\n```\nexport function ClearCache() {\n const injectCacheService = Inject(CacheService);\n\n return (target: any, _: string, propertyDescriptor: PropertyDescriptor) => {\n injectCacheService(target, 'service'); // this is the same as using constructor(private readonly logger: LoggerService) in a class\n\n //get original method\n const originalMethod = propertyDescriptor.value;\n\n //redefine descriptor value within own function block\n propertyDescriptor.value = async function (...args: any[]) {\n try {\n console.log(this);\n const service: CacheService = this.service;\n service.clearCacheById(args[1]);\n\n return await originalMethod.apply(this, args);\n } catch (error) {\n console.error(error);\n }\n };\n };\n}\n```\n\nBut I got `Property 'service' does not exist on type 'PropertyDescriptor'.ts(2339)`\n\nAny idea on what part I am missing?\n\n**Update:**\n\ntsconfig.json has \"strict\":true. If it is enabled, then \"this\" would be strictly use the PropertyDescriptor interface.\n\nFixed the issue by changing \"strict\": false in the tsconfig.json.\n\n**How to reproduce?**\n\n- Use \"strict\":true on tsconfig.json\n\n========================================\n\nTop Answer:\nYou can fix it easier with the : `const service: CacheService = (this as any).service;`\n\nGreetings, Florian\n\n========================================\n\nCode:\n```text\nexport function ClearCache() {\n  const injectCacheService = Inject(CacheService);\n\n  return (target: any, _: string, propertyDescriptor: PropertyDescriptor) => {\n    injectCacheService(target, 'service'); // this is the same as using constructor(private readonly logger: LoggerService) in a class\n\n    //get original method\n    const originalMethod = propertyDescriptor.value;\n\n    //redefine descriptor value within own function block\n    propertyDescriptor.value = async function (...args: any[]) {\n      try {\n        console.log(this);\n        const service: CacheService = this.service;\n        service.clearCacheById(args[1]);\n\n        return await originalMethod.apply(this, args);\n      } catch (error) {\n        console.error(error);\n      }\n    };\n  };\n}\n```\n\n```text\nProperty 'service' does not exist on type 'PropertyDescriptor'.ts(2339)\n```\n\n```text\nexport function ClearCache() {\n    \n    const injector = Inject(CACHE_MANAGER)\n\n    return (target: any, _key?: string | symbol, descriptor?: TypedPropertyDescriptor<any>) => {\n        \n        injector(target, 'cacheManager')\n\n        const originalMethod = descriptor.value\n\n        descriptor.value = async function (...args: any[]) {\n            try {\n                const service: Cache = this.cacheManager\n                service.delete(args[1])\n                return await originalMethod.apply(this, args)\n            } catch (err) {\n                console.error(err)\n                return originalMethod(args)\n            }\n        }\n    }\n}\n```\n\n```text\n\"strict\":true\n```\n\n```text\n\"strict\": false\n```\n\n```text\nconst service: CacheService = (this as any).service;\n```\n\n========================================\n\nComments:\n- I'd say that `PropertyDescriptor` is too generic so typescript will not find the `service` method in it. I'm not sure what is the best approach to circumvent this. But you could use this typescriptlang.org/docs/handbook/release-notes/&hellip;\n- Not sure about that one either\n- I've got the cache manager injected in CacheService, it's inside the same module, but not injected in the controller.\n- is the value of your injectCacheService defined and your CacheService have the @Injectable decorator? It could help to see a minimal repo to reproduce.\n- The injectCacheService already has the Injectable decorator. but the injectCacheService only has [Function (anonymous)]...\n- Your code snippet above still has `Property 'cacheManager' does not exist on type 'TypedPropertyDescriptor'`\n- Thatโ€™s copy pasted from a fresh app I spun up just for your question and it worked fine. Iโ€™ll post it tomorrowโ€™s am away from compy but the issue will be is that the service is not in scope. As above, it would help if you could post a minimal repo\n- ah I missed the minimal repo part ๐Ÿ˜…, I'll get that one ready... Anyways, thank you so much!\n- No worries, I know how frustrating these things can be so just powered up my box and pushed the repo up. Link in my answer.\n- I can't seem to find the repo @The Geek\n- Am an idiot. Was a private repo... made it public now :)\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":141,"estimatedTokens":1169}}1141{"id":"stack-66250525","source":"stackoverflow","questionId":66250525,"title":"Google login with PassportStrategy in NestJS backend not working called by React WebApp","tags":["reactjs","passport.js","nestjs","google-signin"],"text":"Title: Google login with PassportStrategy in NestJS backend not working called by React WebApp\nTags: reactjs, passport.js, nestjs, google-signin\nSource: Stack Overflow\n\nQuestion:\nI've implemented Google login with PassportStrategy in NestJS backend (NestJS backend development is based on this guide: https://medium.com/@nielsmeima/auth-in-nest-js-and-angular-463525b6e071).\n\n```\n@Get('google')\n@UseGuards(AuthGuard('google'))\ngoogleLogin()\n{\n // initiates the Google OAuth2 login flow\n}\n\n@Get('google/callback')\n@UseGuards(AuthGuard('google'))\ngoogleLoginCallback(@Req() req, @Res() res)\n{\n // handles the Google OAuth2 callback\n const jwt: string = req.user.jwt;\n if (jwt)\n return res.status(HttpStatus.OK).cookie('jwt', jwt, {\n httpOnly: true\n }).redirect('/');\n else \n res.redirect('http://localhost:4200/login/failure');\n}\n```\n\nWith @UseGuards(AuthGuard('google')) should start the google login:\n\n```\nsuper({\n clientID : 'XXX', // If I put the call auth/google in the address bar of a browser it works.\n\nIf I call the method auth/google from a React WebApp it doesn't work and the network requests are those in the screenshot. I've no data in response.\n\nApp Requests\n\nGoogle Detail\n\nIt seems that the callback doesn't start, but \"passReqToCallback: true\" works.\n\nReact frontend request:\n\n```\nfetch(\"http:///auth/google\", {\n method: \"GET\",\n mode: 'no-cors',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n})\n.then(\n (result) => {\n if (result) {\n history.push({\n pathname: '/home'\n });\n }\n },\n (error) => {\n \n }\n);\n```\n\nBackend logs when login goes well:\n\n2021-02-18T10:34:02.724706+00:00 heroku[router]: at=info method=GET path=\"/auth/google/\" host=myapp.herokuapp.com request_id=310ac45a-3657-4c5f-96dc-f0a1350429db fwd=\"93.146.33.170\" dyno=web.1 connect=1ms service=10ms status=302 bytes=371 protocol=http\n\n2021-02-18T10:34:03.321194+00:00 app[web.1]: {\n\n2021-02-18T10:34:03.321209+00:00 app[web.1]: id: 'XXX',\n\n2021-02-18T10:34:03.321210+00:00 app[web.1]: displayName: 'XXX',\n\nBackend logs when login goes bad:\n\n2021-02-18T10:36:29.284759+00:00 heroku[router]: at=info method=GET path=\"/auth/google\" host=myapp.herokuapp.com request_id=2f56f65b-9236-4710-b029-dd973ec0c9a3 fwd=\"54.187.137.25\" dyno=web.1 connect=0ms service=3ms status=302 bytes=371 protocol=http\n\nnothing else\n\nAny ideas? Could you help me?\n\nThank you.\n\n========================================\n\nCode:\n```text\n@Get('google')\n@UseGuards(AuthGuard('google'))\ngoogleLogin()\n{\n    // initiates the Google OAuth2 login flow\n}\n\n@Get('google/callback')\n@UseGuards(AuthGuard('google'))\ngoogleLoginCallback(@Req() req, @Res() res)\n{\n    // handles the Google OAuth2 callback\n    const jwt: string = req.user.jwt;\n    if (jwt)\n        return res.status(HttpStatus.OK).cookie('jwt', jwt, {\n            httpOnly: true\n        }).redirect('/');\n    else \n        res.redirect('http://localhost:4200/login/failure');\n}\n```\n\n```text\nsuper({\n        clientID    : 'XXX',     // <- Replace this with your client id\n        clientSecret: 'XXX', // <- Replace this with your client secret\n        callbackURL : 'http://myapp.herokuapp.com/auth/google/callback',\n        passReqToCallback: true,\n        scope: ['profile']\n    })\n```\n\n```text\nfetch(\"http://<url>/auth/google\", {\n  method: \"GET\",\n  mode: 'no-cors',\n  headers: {\n    'Content-Type': 'application/json',\n    'Accept': 'application/json'\n  }\n})\n.then(\n  (result) => {\n        if (result) {\n          history.push({\n            pathname: '/home'\n          });\n        }\n  },\n  (error) => {\n    \n  }\n);\n```\n\n```text\n/google\n```\n\n```text\n/google/callback\n```\n\n```text\ngoogle\n```\n\n========================================\n\nComments:\n- You'll need to show more code about what gets the cookie to be set and what doesn't. What calls are you making? And why was this tagged with \"nestjs\"? Are you using that as your backend framework?\n- I tried to add more details.\n- Thank you, but it doesn't solve. I tried to add more details.\n- Try without redirecting on the server side. Since you are making an ajax request you shouldn't rely on server redirects. Instead, redirect on front-end side on success.\n- Same. I think it's something in the backend login flow.\n- I think I understand your problem now. I've edited my answer.\n- @UroลกAnฤ‘eliฤ‡ I am also having issue here a bit, I hope you dont mind clarifying your answer. You said \"Try without redirecting on the server side\". I am having an issue that Google Strategy is automatically redirecting my request the the server (it is returning 302 to redirect to callbackURL). I am passing the access_token inside Authorization header \"Bearer access_token\" (which I obtained from google server directly from my SPA). How can I \"tell\" Google Strategy to not redirect me but go to verify (validate) function? Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":170,"estimatedTokens":1202}}1142{"id":"stack-63925078","source":"stackoverflow","questionId":63925078,"title":"GET request with custom \"company_id\" header works locally but header not present in GCP App Engine","tags":["node.js","express","google-app-engine","google-cloud-platform","nestjs"],"text":"Title: GET request with custom \"company_id\" header works locally but header not present in GCP App Engine\nTags: node.js, express, google-app-engine, google-cloud-platform, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm manually attaching the 'company_id' header from the frontend. I can confirm with the browser that the header is correct and present in production.\n\nIt also works locally without any issues and the header is retrieved.\n\nHowever, when deployed to production as App Engine with Nodejs 12 in GCP -- the custom header will no longer be present on any request.\n\nI've logged all headers and the whole request object on the console to see what's actually available in-memory and I can confirm that the express app does not see the custom header.\n\nAny help debugging this further is appreciated.\n\n========================================\n\nCode:\n```js\n'use strict';\n\n// [START gae_node_request_example]\nconst express = require('express');\n\nconst app = express();\n\napp.get('/', (req, res) => {\n  res.status(200).send(JSON.stringify(req.headers)).end();\n});\n\n// Start the server\nconst PORT = process.env.PORT || 8080;\napp.listen(PORT, () => {\n  console.log(`App listening on port ${PORT}`);\n  console.log('Press Ctrl+C to quit.');\n});\n// [END gae_node_request_example]\n\nmodule.exports = app;\n```\n\n```text\ncompany-id\n```\n\n========================================\n\nComments:\n- Looks like GCP automatically removes some headers. Do you use any of these?\n- @JayMcDoniel I have indeed checked against that list but 'company_id' is not listed on it.\n- That is true -- i ended up doing the same thing, but why? why doesn't it just let us decide that?\n- @SebastianG this behaviour is not documented by looks like the same behaviour on NGINX, but is not possible to change it on app engine, if my answer was useful please mark as accepted\n- HOLY SHIT YOU SAVED ME. thank you so much, its not even documented.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":53,"estimatedTokens":476}}1143{"id":"stack-60316235","source":"stackoverflow","questionId":60316235,"title":"NestJS: New instance of HttpModule per module import","tags":["typescript","axios","nestjs"],"text":"Title: NestJS: New instance of HttpModule per module import\nTags: typescript, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy nestjs system is a system that connects to multiple systems via API calls.\n\nFor each system, I created a Module to handle their processes. Each of these modules imports `HttpModule`.\n\nI want to have separate Axios interceptors for each of these modules' HttpModule.\n\nThis is my attempt to test the functionality:\n\non `a.module.ts`:\n\n```\n@Module({\n imports: [\n HttpModule,\n // Other imports\n ],\n // controllers, providers and exports here\n})\nexport class ModuleA implements OnModuleInit {\n constructor(private readonly httpService: HttpService) { }\n public onModuleInit() {\n this.httpService.axiosRef.interceptors.request.use(async (config: Axios.AxiosRequestConfig) => {\n console.log('Module A Interceptor'); \n return config;\n });\n }\n}\n```\n\nThe module class for Module B is similar, with a different message in the `console.log` call.\n\nI tried making a http call to System B using a service in Module B, but both messages are displayed in the console.\n\nI figured that the http module is a singleton across the system, so how do I instantiate a separate `HttpModule` for Module A and Module B?\n\n========================================\n\nCode:\n```js\n@Module({\n  imports: [\n    HttpModule,\n    // Other imports\n  ],\n  // controllers, providers and exports here\n})\nexport class ModuleA implements OnModuleInit {\n  constructor(private readonly httpService: HttpService) { }\n  public onModuleInit() {\n    this.httpService.axiosRef.interceptors.request.use(async (config: Axios.AxiosRequestConfig) => {\n      console.log('Module A Interceptor');    \n      return config;\n    });\n  }\n}\n```\n\n```text\nHttpModule\n```\n\n```text\na.module.ts\n```\n\n```text\nconsole.log\n```\n\n```text\nHttpModule\n```\n\n```js\n@Module({\n  imports: [\n    HttpModule.register({}),\n  ],\n  // providers and exports\n})\n```\n\n```text\nregister()\n```\n\n```text\nHttpModule\n```\n\n```text\nregister()\n```\n\n```text\n@Module\n```\n\n========================================\n\nComments:\n- Don't you know how to access this particular instance of HttpService while testing?","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":107,"estimatedTokens":535}}1144{"id":"stack-65006550","source":"stackoverflow","questionId":65006550,"title":"Use module service into entity NestJS","tags":["nestjs"],"text":"Title: Use module service into entity NestJS\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nOn a NestJS API, I would like to use a module service into an entity to populate this entity with non-database attributes.\n\nIn my case, I want to get the number of articles of the category I am retrieving.\n\n```\n@Entity({ name: 'categories' })\nexport class Category {\n constructor(private readonly service: CategoriesService) { }\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @Index({ unique: true })\n title: string;\n\n @OneToMany(() => Article, articles => articles.category)\n articles: Article[];\n\n numberOfExercices: number;\n\n @AfterLoad()\n async countExercices() {\n this.numberOfExercices = await this.service.getNumberOfArticles(this.id);\n }\n}\n```\n\nBut I get this error :\n\n```\nNest can't resolve dependencies of the GlobalPrevCategoriesService (GlobalPrevCategoriesRepository, ?).\nPlease make sure that the argument dependency at index [1] is available in the GlobalPrevCategoriesModule context.\n```\n\nI tried this little variant but I get the same error.\n\n```\nconstructor(\n @Inject(GlobalPrevCategoriesService)\n private readonly service: GlobalPrevCategoriesService) { }\n)\n```\n\nHere is my module:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forFeature([CategoriesRepository]),\n ArticlesModule\n ],\n controllers: [CategoriesController],\n providers: [CategoriesService],\n exports: [CategoriesService]\n})\nexport class CategoriesModule { }\n```\n\nIs using a service into a entity even possible ?\n\n========================================\n\nCode:\n```js\n@Entity({ name: 'categories' })\nexport class Category {\n    constructor(private readonly service: CategoriesService) { }\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    @Index({ unique: true })\n    title: string;\n\n    @OneToMany(() => Article, articles => articles.category)\n    articles: Article[];\n\n    numberOfExercices: number;\n\n    @AfterLoad()\n    async countExercices() {\n        this.numberOfExercices = await this.service.getNumberOfArticles(this.id);\n    }\n}\n```\n\n```text\nNest can't resolve dependencies of the GlobalPrevCategoriesService (GlobalPrevCategoriesRepository, ?).\nPlease make sure that the argument dependency at index [1] is available in the GlobalPrevCategoriesModule context.\n```\n\n```js\nconstructor(\n    @Inject(GlobalPrevCategoriesService)\n    private readonly service: GlobalPrevCategoriesService) { }\n)\n```\n\n```js\n@Module({\n    imports: [\n        TypeOrmModule.forFeature([CategoriesRepository]),\n        ArticlesModule\n    ],\n    controllers: [CategoriesController],\n    providers: [CategoriesService],\n    exports: [CategoriesService]\n})\nexport class CategoriesModule { }\n```\n\n========================================\n\nComments:\n- Thank you. I had a little trouble doing this as I had to deal with TypeOrm `innerJoin()` method, but works fine now with the Active-Record pattern.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":122,"estimatedTokens":718}}1145{"id":"stack-64805150","source":"stackoverflow","questionId":64805150,"title":"Nestjs azure active directory and graphql - UseGuard","tags":["graphql","azure-active-directory","passport.js","nestjs"],"text":"Title: Nestjs azure active directory and graphql - UseGuard\nTags: graphql, azure-active-directory, passport.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nBuilding an API with nestjs and graphql I want to implement Azure Active Directory for authorization.\nThey provide a `passport-azure-ad` package with a strategy.\nIt is working just fine when I add a nestjs guard to a REST endpoint, but with a GrapQL resolver it is throwing an error `Cannot read property 'query' of undefined`.\n\nNestjs docs give some hint, but I have no idea how to implement and make the graphql query available to the passport strategy.\n\nMy guard looks as follows:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { PassportStrategy, AuthGuard } from '@nestjs/passport';\nimport { BearerStrategy } from 'passport-azure-ad';\nimport * as dotenv from 'dotenv';\ndotenv.config();\n\nconst clientID = process.env.AZURE_AD_CLIENT_ID;\nconst tenantID = process.env.AZURE_AD_TENANT_ID;\n\n/**\n * Extracts ID token from header and validates it.\n */\n@Injectable()\nexport class AzureADStrategy extends PassportStrategy(\n BearerStrategy,\n 'azure-ad',\n) {\n constructor() {\n super({\n identityMetadata: `https://login.microsoftonline.com/${tenantID}/v2.0/.well-known/openid-configuration`,\n clientID,\n });\n }\n \n async validate(data) {\n console.log(data);\n return data;\n }\n}\n\nexport const AzureADGuard = AuthGuard('azure-ad');\n```\n\nGraphQL config from `app.module.ts`\n\n```\n...\nimports: [\n GraphQLModule.forRoot({\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n sortSchema: true,\n context: ({ req }) => ({ req }),\n }),\n...\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { PassportStrategy, AuthGuard } from '@nestjs/passport';\nimport { BearerStrategy } from 'passport-azure-ad';\nimport * as dotenv from 'dotenv';\ndotenv.config();\n\nconst clientID = process.env.AZURE_AD_CLIENT_ID;\nconst tenantID = process.env.AZURE_AD_TENANT_ID;\n\n/**\n * Extracts ID token from header and validates it.\n */\n@Injectable()\nexport class AzureADStrategy extends PassportStrategy(\n  BearerStrategy,\n  'azure-ad',\n) {\n  constructor() {\n    super({\n      identityMetadata: `https://login.microsoftonline.com/${tenantID}/v2.0/.well-known/openid-configuration`,\n      clientID,\n    });\n  }\n  \n  async validate(data) {\n    console.log(data);\n    return data;\n  }\n}\n\nexport const AzureADGuard = AuthGuard('azure-ad');\n```\n\n```text\n...\nimports: [\n GraphQLModule.forRoot({\n      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n      sortSchema: true,\n      context: ({ req }) => ({ req }),\n    }),\n...\n```\n\n```text\npassport-azure-ad\n```\n\n```text\nCannot read property 'query' of undefined\n```\n\n```text\napp.module.ts\n```\n\n```js\n@Injectable()\nexport class AzureADGuard extends AuthGuard('azure-ad') {\n  getRequest(context: ExecutionContext) {\n    const gql = GqlExecutionContext.create(context);\n    return gql.getContext().req;\n  }\n}\n```\n\n```text\nquery\n```\n\n```text\nrequest\n```\n\n```text\nextends AuthGuard('azure-ad')\n```\n\n```text\ngetRequest()\n```\n\n```text\nreq\n```\n\n========================================\n\nComments:\n- That was it. The custom guard can now be used for the GraphQL queries and the \"pure\" Guard from my post can be used for the REST queries as well","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":154,"estimatedTokens":817}}1146{"id":"stack-61143152","source":"stackoverflow","questionId":61143152,"title":"How to ignore global cache on some routes in NestJs","tags":["typescript","caching","interceptor","nestjs"],"text":"Title: How to ignore global cache on some routes in NestJs\nTags: typescript, caching, interceptor, nestjs\nSource: Stack Overflow\n\nQuestion:\nI activate the global cache by `APP_INTERCEPTOR` in my NestJS app.\nBut now, I need to ignore it on some routes.\nHow can I do that?\n\n========================================\n\nTop Answer:\nI found the solution. Before all, I made a `CustomHttpCacheInterceptor` that extends the `CacheInterceptor`:\n\n```\n@Injectable()\nexport default class CustomHttpCacheInterceptor extends CacheInterceptor {\n httpServer: any;\n trackBy(context: ExecutionContext): string | undefined {\n const request = context.switchToHttp().getRequest();\n const isGetRequest = request.method === 'GET';\n const requestURl = request.path;\n const excludePaths = ['/my/custom/route'];\n\n if (\n !isGetRequest ||\n (isGetRequest && excludePaths.some(url => requestURl.includes(url)))\n ) {\n return undefined;\n }\n return requestURl;\n }\n}\n```\n\nand then I add it as a global cache interceptor in `app.module`\n\n```\n//...\n providers: [\n AppService,\n {\n provide: APP_INTERCEPTOR,\n useClass: CustomHttpCacheInterceptor,\n },\n ],\n//...\n```\n\n========================================\n\nCode:\n```text\nAPP_INTERCEPTOR\n```\n\n```text\n@Injectable()\nexport class CustomCacheInterceptor extends CacheInterceptor {\n\n  excludePaths = [\"/my/custom/route\"];\n\n  isRequestCacheable(context: ExecutionContext): boolean {\n    const req = context.switchToHttp().getRequest();\n    return (\n      this.allowedMethods.includes(req.method) &&\n      !this.excludePaths.includes(req.url)\n    );\n  }\n}\n```\n\n```js\n@Injectable()\nexport default class CustomHttpCacheInterceptor extends CacheInterceptor {\n  httpServer: any;\n  trackBy(context: ExecutionContext): string | undefined {\n    const request = context.switchToHttp().getRequest();\n    const isGetRequest = request.method === 'GET';\n    const requestURl = request.path;\n    const excludePaths = ['/my/custom/route'];\n\n    if (\n      !isGetRequest ||\n      (isGetRequest && excludePaths.some(url => requestURl.includes(url)))\n    ) {\n      return undefined;\n    }\n    return requestURl;\n  }\n}\n```\n\n```js\n//...\n  providers: [\n    AppService,\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: CustomHttpCacheInterceptor,\n    },\n  ],\n//...\n```\n\n```text\nCustomHttpCacheInterceptor\n```\n\n```text\nCacheInterceptor\n```\n\n```text\napp.module\n```\n\n```js\nexport const NO_CACHE_KEY = 'noCache';\n\nexport const NoCache = () => SetMetadata(NO_CACHE_KEY, true);\n```\n\n```js\n@Injectable()\nexport class CacheInterceptor extends DefaultCacheInterceptor {\n  isRequestCacheable(context: ExecutionContext) {\n    const noCache = this.reflector.getAllAndOverride<boolean>(NO_CACHE_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n\n    if (noCache) return false;\n\n    return super.isRequestCacheable(context);\n  }\n}\n```\n\n```text\n@NoCache()\n```\n\n```text\nisRequestCacheable\n```\n\n========================================\n\nComments:\n- your concept is great, thanks. However, in order to not change the default behavior, I did this little change: // return requestURl; return super.trackBy(context);","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":151,"estimatedTokens":776}}1147{"id":"stack-55729585","source":"stackoverflow","questionId":55729585,"title":"Is it possible to intercept providers in Nest.js?","tags":["javascript","node.js","typescript","interceptor","nestjs"],"text":"Title: Is it possible to intercept providers in Nest.js?\nTags: javascript, node.js, typescript, interceptor, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to intercept Nest.js providers and it doesn't seem to work. \n\nCan anyone confirm this? If yes, is there any specific design reason for that?\n\nUsually it's possible to intercept any `bean` in dependency injection containers.\n\n========================================\n\nCode:\n```text\nbean\n```\n\n========================================\n\nComments:\n- can you give an example of what you are trying to do?\n- Hello @shusson. Imagine you have a controller method that calls two different providers (each one triggers a different remote call) and you want to measure the performance of each provider separately, using let's say a MonitoringInterceptor. So you would annotate each provider with @UseInterceptors(MonitoringInterceptor) and expect to collect metrics on both.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":23,"estimatedTokens":231}}1148{"id":"stack-57295523","source":"stackoverflow","questionId":57295523,"title":"Nest can't resolve dependencies of the GraphQLModule","tags":["graphql","nestjs"],"text":"Title: Nest can't resolve dependencies of the GraphQLModule\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nIm trying to add a graphql server to nestjs based on documentation, but im getting this error:\n\n```\nNest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context. +19ms\n```\n\nError: Nest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context.\n\n========================================\n\nTop Answer:\nYour Versions does not compatible.\n\nFrom the docs itself: https://docs.nestjs.com/graphql/quick-start\n\n```\nWARNING\n@nestjs/graphql@^9 is compatible with Apollo v3 (check out Apollo Server 3 migration guide for more details), while @nestjs/graphql@^8 only supports Apollo v2 (e.g., apollo-server-express@2.x.x package). Both versions (v9 and v8) are fully compatible with Nest v8 (@nestjs/common@^8, @nestjs/core@^8, etc.).\n```\n\n========================================\n\nCode:\n```text\nNest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context. +19ms\n```\n\n```text\nWARNING\n@nestjs/graphql@^9 is compatible with Apollo v3 (check out Apollo Server 3 migration guide for more details), while @nestjs/graphql@^8 only supports Apollo v2 (e.g., apollo-server-express@2.x.x package). Both versions (v9 and v8) are fully compatible with Nest v8 (@nestjs/common@^8, @nestjs/core@^8, etc.).\n```\n\n========================================\n\nComments:\n- Is this a new GraphQL module that you're adding in? It's coming from the @nestjs/graphql package right? Where are you importing the GraphQLModule? Without seeing more code it's practically impossible to tell where the error is. Are you sure you have all the necessary dependencies installed?\n- Yes, of course is weird i created new project a add this package and all work. I don't know why not work with my previous project. I was investigating the code and the error seems to have to do so applicationConfig: ApplicationConfig is not passed to the module constructor\n- Have you updated all your dependencies? Can you the code that's introducing the problem? It's pretty hard to help otherwise.\n- Sometimes deleting your node_modules directory and running npm install again fixes bugs like this. Be sure that the GraphQL dependences are in your package.json.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":672}}1149{"id":"stack-54788978","source":"stackoverflow","questionId":54788978,"title":"How to change a promise with async await function to observable?","tags":["javascript","typescript","observable","es6-promise","nestjs"],"text":"Title: How to change a promise with async await function to observable?\nTags: javascript, typescript, observable, es6-promise, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a Nestjs rest server with a controller and a service.\n\nIn my controller, there is the get function, when someone makes a get request:\n\n```\n@Get()\ngetAllFoos() {\n return this.fooService.getAllFoos();\n}\n```\n\nIn my service, there is this function to get the documents from a database\n\n```\nasync getAllFoos(): Promise {\n try {\n return await this.fooModel.find().exec();\n } catch(e) {\n return e;\n }\n```\n\nThis works!\nI now need to change this to make it work with observables.\nI changed the controller to:\n\n```\n@Get()\ngetAllFoos() {\n this.fooService.getAllFoos().subscribe(\n response => {\n console.log(response);\n\n },\n error => {\n console.log(error);\n },\n () => {\n console.log('completed');\n\n });\n}\n```\n\nAnd the service to this:\n\n```\ngetAllFoos(): Observable {\n try {\n this.fooModel.find().exec();\n } catch(e) {\n return e;\n }\n }\n```\n\nThe error I get is\n\n```\n[Nest] 7120 - 2019-2-20 15:29:51 [ExceptionsHandler] Cannot read property 'subscribe' of undefined +4126ms\n```\n\nThe error comes from \n\n```\nthis.fooService.getAllFoos().subscribe(\n```\n\nthis line from the controller. I really have no clue, what to change to make it work now.\n\nAny help or idea is appreciated!\n\n========================================\n\nCode:\n```text\n@Get()\ngetAllFoos() {\n    return this.fooService.getAllFoos();\n}\n```\n\n```text\nasync getAllFoos(): Promise<foos[]> {\n    try {\n        return await this.fooModel.find().exec();\n    } catch(e) {\n        return e;\n    }\n```\n\n```text\n@Get()\ngetAllFoos() {\n    this.fooService.getAllFoos().subscribe(\n        response => {\n            console.log(response);\n\n        },\n        error => {\n            console.log(error);\n        },\n        () => {\n            console.log('completed');\n\n    });\n}\n```\n\n```text\ngetAllFoos(): Observable<foos[]> {\n        try {\n            this.fooModel.find().exec();\n        } catch(e) {\n            return e;\n        }\n    }\n```\n\n```text\n[Nest] 7120   - 2019-2-20 15:29:51   [ExceptionsHandler] Cannot read property 'subscribe' of undefined +4126ms\n```\n\n```text\nthis.fooService.getAllFoos().subscribe(\n```\n\n```js\ngetAllFoos(): Observable<foos[]> {\n    return Observable.from(this.fooModel.find().exec());\n}\n```\n\n```js\ngetAllFoos(): Observable<foos[]> {\n    return Observable.fromPromise(this.fooModel.find().exec());\n}\n```\n\n```text\nObservable.from()\n```\n\n========================================\n\nComments:\n- In the service inside try{} donโ€™t you need a return statement similar to your catch{}..\n- I tried that. My IDE is marking the line red then with this message: \"Type 'Promise' is missing the following properties from type 'Observable': _isScalar, soure, operator, lift and 6 more.\n- I dont know why it expects a promise still?!\n- What about not using observable as shown here stackoverflow.com/a/54770820/10634638","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":155,"estimatedTokens":736}}1150{"id":"stack-63584034","source":"stackoverflow","questionId":63584034,"title":"NestJS, PortsgreSQL and TypeORM - Migrations not running properly","tags":["postgresql","nestjs","typeorm"],"text":"Title: NestJS, PortsgreSQL and TypeORM - Migrations not running properly\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen trying to run the TypeORM Migrations, either automatically in the application startup or manually via the TypeORM CLI, only the migrations table gets created (and it stays empty). The migration files themselves are not being executed.\n\nHere is my tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n}\n```\n\nHere is my package.json\n\n```\n...\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\",\n...\n```\n\nHere is my ormconfig.json\n\n```\n...\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n\"synchronize\": true,\n\"migrationsRun\": true,\n\"migrations \": [\"dist/migrations/*{.ts,.js}\"],\n\"cli\": {\n \"migrationsDir\": \"src/migrations\"\n }\n...\n```\n\nThe migration files are being created through the TypeORM CLI and they are to populate some tables (insert statements). They are not related to changes in the database schema.\n\nPlease, can anyone help me make it work?\n\n========================================\n\nTop Answer:\nyou should have synchronized to false `synchronize:false`\n\nAnd from the terminal run\n\n`npx typeorm migration:generate -n AnyNameYouWant`\n\nAfter that, you can run\n\n`npx typeorm migration:run`\n\nYou may also have to run `nest build` before running these commands.\n\n========================================\n\nCode:\n```text\n{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true\n  }\n}\n```\n\n```text\n...\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\",\n...\n```\n\n```text\n...\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n\"synchronize\": true,\n\"migrationsRun\": true,\n\"migrations \": [\"dist/migrations/*{.ts,.js}\"],\n\"cli\": {\n    \"migrationsDir\": \"src/migrations\"\n  }\n...\n```\n\n```text\normconfig.json\n```\n\n```text\n\"migrations \":\n```\n\n```text\nsynchronize:false\n```\n\n```text\nnpx typeorm migration:generate -n AnyNameYouWant\n```\n\n```text\nnpx typeorm migration:run\n```\n\n```text\nnest build\n```\n\n========================================\n\nComments:\n- run this command `npx typeorm migration:run`\n- I tried it but the only thing that happens is that the migrations table gets created (if it's not yet created). It's as if the migration files I created with the insert statements are not being found. I checked `\"migrations\": [\"dist&#47;migrations&#47;*{.ts,.js}\"]`and the files (.ts and .js) are all there.\n- I forgot to mention that the migration files I created are to populate some tables (insert statements). They are not related to changes in the database schema... I will edit the question with this info. I tried with `synchronize:false` but the result was the same.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":137,"estimatedTokens":798}}1151{"id":"stack-65092351","source":"stackoverflow","questionId":65092351,"title":"How to install Express middleware (express-openapi-validator) in NestJS?","tags":["express","validation","nestjs","middleware","openapi"],"text":"Title: How to install Express middleware (express-openapi-validator) in NestJS?\nTags: express, validation, nestjs, middleware, openapi\nSource: Stack Overflow\n\nQuestion:\nI am writing a NestJS application. Now I want to install the Express middleware express-openapi-validator.\n\nHowever, I can't get it to work. There is a description for how to install the express-openapi-validator in express, but it always results in errors.\n\nFor example\n\n```\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(middleware({apiSpec \"./bff-api.yaml\"}))\n .forRoutes(OrganizationController)\n }\n}\n```\n\nresults in\n\n```\nerror TS2345: Argument of type 'OpenApiRequestHandler[]' is not assignable to parameter of type 'Function | Type'.\n Type 'OpenApiRequestHandler[]' is missing the following properties from type 'Type': apply, call, bind, prototype, and 4 more.\n```\n\nHow can I install this middleware in NestJS?\n\n========================================\n\nTop Answer:\nI have now got it working:\n\n```\nconfigure(consumer: MiddlewareConsumer) {\n middleware({\n apiSpec: `${__dirname}/../api-doc/bff-api.yaml`\n }).forEach(value => consumer.apply(value).forRoutes(OrganizationController))\n}\n```\n\n========================================\n\nCode:\n```text\nexport class AppModule implements NestModule {\n    configure(consumer: MiddlewareConsumer) {\n        consumer.apply(middleware({apiSpec \"./bff-api.yaml\"}))\n            .forRoutes(OrganizationController)\n    }\n}\n```\n\n```text\nerror TS2345: Argument of type 'OpenApiRequestHandler[]' is not assignable to parameter of type 'Function | Type<any>'.\n      Type 'OpenApiRequestHandler[]' is missing the following properties from type 'Type<any>': apply, call, bind, prototype, and 4 more.\n```\n\n```js\n@Module({\n  imports: [PingModule],\n  providers: [{ provide: APP_FILTER, useClass: OpenApiExceptionFilter }],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(\n        ...OpenApiValidator.middleware({\n          apiSpec: join(__dirname, './api.yaml'),\n        }),\n      )\n      .forRoutes('*');\n  }\n}\n```\n\n```js\nimport { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';\nimport { Response } from 'express';\nimport { error } from 'express-openapi-validator';\n\n@Catch(...Object.values(error))\nexport class OpenApiExceptionFilter implements ExceptionFilter {\n  catch(error: ValidationError, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n\n    response.status(error.status).json(error);\n  }\n}\n\ninterface ValidationError {\n  status: number;\n  message: string;\n  errors: Array<{\n    path: string;\n    message: string;\n    error_code?: string;\n  }>;\n  path?: string;\n  name: string;\n}\n```\n\n```text\nAppModule\n```\n\n```text\nexpress-openapi-validator\n```\n\n```text\nconfigure(consumer: MiddlewareConsumer) {\n    middleware({\n        apiSpec: `${__dirname}/../api-doc/bff-api.yaml`\n    }).forEach(value => consumer.apply(value).forRoutes(OrganizationController))\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":120,"estimatedTokens":768}}1152{"id":"stack-58666739","source":"stackoverflow","questionId":58666739,"title":"NestJS + Mongoose + GraphQL : \"populate\" not working","tags":["mongodb","mongoose","graphql","nestjs","mongoose-populate"],"text":"Title: NestJS + Mongoose + GraphQL : \"populate\" not working\nTags: mongodb, mongoose, graphql, nestjs, mongoose-populate\nSource: Stack Overflow\n\nQuestion:\nthanks for the great framework!\n\nI use mongoose with GraphQL and have the following problem:\n\nIf I want to resolve the ObjectIDs stored in the array \"arguments\" of a user with `populate`, in GraphQL I get the user with an empty arguments array as answer.\n\nI suspect the error when defining the reference `ArgumentSchema` (name of the MongoDB schema) or the populate `arguments` (name of the attributes of the user). How does this work correctly?\n\n**argument.schema**\n\n```\nexport const ArgumentSchema = new mongoose.Schema({\n argument: { type: String, required: true },\n userId: { type: String, required: true },\n username: { type: String, required: true },\n});\n```\n\n**user.schema**\n\n```\nexport const UserSchema = new mongoose.Schema({\n username: { type: String, required: true },\n email: { type: String, required: true },\n age: { type: Number, required: true },\n arguments: { type: [mongoose.Schema.Types.ObjectId], required: false, ref: 'ArgumentSchema' },\n});\n```\n\n**argument.model**\n\n```\n@ObjectType()\nexport class ArgumentGQL {\n @Field(() => ID)\n readonly _id: string;\n\n @Field()\n readonly argument: string;\n\n @Field()\n readonly userId: string;\n\n @Field()\n readonly username: string;\n}\n```\n\n**user.model**\n\n```\n@ObjectType()\nexport class UserGQL {\n @Field(() => ID)\n readonly _id: string;\n\n @Field()\n readonly username: string;\n\n @Field()\n readonly email: string;\n\n @Field()\n readonly age: number;\n\n @Field(() => [ArgumentGQL], { nullable: true })\n readonly arguments: ArgumentGQL[];\n}\n```\n\n**user.service**\n\n```\nasync getOne(id: string): Promise {\n try {\n return await this.userModel.findById(id).populate('arguments').exec();\n } catch (e) {\n throw new BadRequestException(e);\n }\n }\n```\n\n**GraphlQL Query example**\n\n```\nquery {\n getUser(id: \"5dbcaf9f5ba1eb2de93a9301\") {\n _id,\n username,\n email,\n age,\n arguments {\n argument,\n username\n }\n }\n}\n```\n\nI think I haven't understood something fundamental yet...\n\nI would be grateful for any help!\nCheers\n\n========================================\n\nCode:\n```text\nexport const ArgumentSchema = new mongoose.Schema({\n  argument: { type: String, required: true },\n  userId: { type: String, required: true },\n  username: { type: String, required: true },\n});\n```\n\n```text\nexport const UserSchema = new mongoose.Schema({\n  username: { type: String, required: true },\n  email: { type: String, required: true },\n  age: { type: Number, required: true },\n  arguments: { type: [mongoose.Schema.Types.ObjectId], required: false, ref: 'ArgumentSchema' },\n});\n```\n\n```text\n@ObjectType()\nexport class ArgumentGQL {\n  @Field(() => ID)\n  readonly _id: string;\n\n  @Field()\n  readonly argument: string;\n\n  @Field()\n  readonly userId: string;\n\n  @Field()\n  readonly username: string;\n}\n```\n\n```text\n@ObjectType()\nexport class UserGQL {\n  @Field(() => ID)\n  readonly _id: string;\n\n  @Field()\n  readonly username: string;\n\n  @Field()\n  readonly email: string;\n\n  @Field()\n  readonly age: number;\n\n  @Field(() => [ArgumentGQL], { nullable: true })\n  readonly arguments: ArgumentGQL[];\n}\n```\n\n```text\nasync getOne(id: string): Promise<UserGQL> {\n    try {\n      return await this.userModel.findById(id).populate('arguments').exec();\n    } catch (e) {\n      throw new BadRequestException(e);\n    }\n  }\n```\n\n```text\nquery {\n  getUser(id: \"5dbcaf9f5ba1eb2de93a9301\") {\n      _id,\n      username,\n      email,\n      age,\n      arguments {\n          argument,\n          username\n      }\n  }\n}\n```\n\n```text\npopulate\n```\n\n```text\nArgumentSchema\n```\n\n```text\narguments\n```\n\n```js\n{\n arguments: [{ type: [mongoose.Schema.Types.ObjectId], , ref: 'ArgumentSchema' }],\n}\n```\n\n```text\nuser.schema\n```\n\n========================================\n\nComments:\n- I'm having the same problem do you have this project repository?\n- Thank you very much Sir! You saved me hours ;)\n- @stoniemahonie You are welcome :) By the way, I use Typegoose and I think it's a bit cleaner.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":219,"estimatedTokens":1008}}1153{"id":"stack-65815006","source":"stackoverflow","questionId":65815006,"title":"Said cons to using Next.js don't seem like they would be any different from other SSR frameworks","tags":["reactjs","nuxt.js","next.js","nestjs","server-side-rendering"],"text":"Title: Said cons to using Next.js don't seem like they would be any different from other SSR frameworks\nTags: reactjs, nuxt.js, next.js, nestjs, server-side-rendering\nSource: Stack Overflow\n\nQuestion:\nI've yet to take a deep dive into SSR until now, but I'm about jump in, and first doing some preliminary research to try to get me and the agency going in the most-likely best direction. This is one of the determining factors in choosing Angular, React, or Vue as the company's choice in F/E frameworks which will become our go-to. As it has come to seem like React and Next are likely the best way forward for us at this time. I'm focusing on a few said cons of using Next, as they are things that I want to make sure are not deal breakers.\n\nIn one particular article comparing Next, Nuxt, and Nest, I am seeing a bullet point where it says that \"Next.js is not backend\". Elsewhere it's mentioned that Next should be supplemented with a Node.js server for a backend. My question to this is, is that suggesting that Nuxt and Nest *are* backend? So there wouldn't ever be any reason to supplement Nuxt and Nest with Node or another server? That doesn't seem to me like it would *usually* or *always* be the case. Like somehow Nuxt and Nest are so amazing that they handle most or all of the server needs you would ever have? It doesn't seem like that's necessarily their purpose... Or is it?\n\nIn the same article there are similarly three other bullet points as cons for Next that I have a hard time seeing how the other two frameworks would be any different. The other points are:\n\nโ€ข If youโ€™re creating a simple app, it can be overkill\n\nโ€ข All data needs to be loadable from both the client and server\n\nโ€ข Migrating a server-side app to Next.js is not a quick process, and depending on your project it may be too much work\n\n- More so than the other SSRs?\n\n- It seems like every SSR and frontend would need to load from the client and server. Isn't that the point?\n\n- It seems like migrating any backend to F/E and SSR would not be a quick process.\n\nI could be wrong, but it seems like these considerations were breezed over in the writing of the page. There would be good reason for noting these cons against the other frameworks just to not give the impression that Next is necessarily a miracle against the other two where development and migration were always going to be a breeze.\n\nObviously as a SO question, we would like to avoid opinion weighing in here, which this question seems like it might attract. I am looking for *specific* information about ways to make me believe Nuxt and Nest are advantageous over Next in these few regards.\n\nI realize that people who could speak to every one of these SSR frameworks are probably scarce, but if you can speak to one or the other, that would still be very helpful.\n\nAdditionally, the article was written in April of 2019, and things may well have changed.\n\n========================================\n\nCode:\n```text\nprocess.browser\n```\n\n========================================\n\nComments:\n- VERY helpful. Ty both.\n- Don't forget to accept the answer if this helped.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":43,"estimatedTokens":779}}1154{"id":"stack-54523160","source":"stackoverflow","questionId":54523160,"title":"NestJs - Catching MongoDB errors with a custom filter and @Catch(MongoError)","tags":["javascript","node.js","mongodb","typescript","nestjs"],"text":"Title: NestJs - Catching MongoDB errors with a custom filter and @Catch(MongoError)\nTags: javascript, node.js, mongodb, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS to create a custom API with MongoDB. I've got the following setup:\n\n```\n// users.controller.ts\n\n @Post('sign-up')\n @UseFilters(MongoExceptionFilter)\n async signUp(@Body() createUserDto: CreateUserDto): Promise {\n return await this.userService.signUp(createUserDto).catch(error => {\n throw new BadRequestException(error);\n });\n }\n```\n\n```\n// user.service.ts\n\n async signUp(createUserDto: CreateUserDto): Promise {\n const createUser = new this.userModel(createUserDto);\n return await createUser.save();\n }\n```\n\n```\n// mongo-exception.filter.ts\n\n import { ArgumentsHost,Catch, ConflictException, ExceptionFilter } from '@nestjs/common';\n import { MongoError } from 'mongodb';\n\n @Catch(MongoError)\n export class MongoExceptionFilter implements ExceptionFilter {\n catch(exception: MongoError, host: ArgumentsHost) {\n console.log('>>>>>>>>>>>>>>>>>>>> exception: ', exception);\n }\n }\n```\n\n```\n// package.json\n \"dependencies\": {\n \"@nestjs/common\": \"^5.4.0\",\n \"@nestjs/core\": \"^5.4.0\",\n \"@nestjs/jwt\": \"^0.2.1\",\n \"@nestjs/mongoose\": \"^5.2.2\",\n \"@nestjs/passport\": \"^5.1.0\",\n \"@nestjs/typeorm\": \"^5.2.2\",\n \"fancy-log\": \"^1.3.3\",\n \"mongoose\": \"^5.4.7\",\n \"nestjs-config\": \"^1.3.0\",\n \"passport\": \"^0.4.0\",\n \"passport-http-bearer\": \"^1.0.1\",\n \"passport-jwt\": \"^4.0.0\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.2.2\",\n \"typeorm\": \"^0.2.12\",\n \"typescript\": \"^3.0.1\",\n \"util\": \"^0.11.1\"\n },\n```\n\nNow whenever I do a POST call to the /sign-up route, `save()` should be called in the `user.service.ts`. This all works. Next when I POST the /sign-up route another time it should trigger a MongoDB error since the user with the same email address is already (email address is unique and thus duplicate keys). I see the error is thrown when I just log the error in the `.catch(err => ...);`, but the problem is the custom `MongoExceptionFilter`. I won't trigger on the MongoError. When I leave the `@Catch()` blank it does trigger but can't process the exception.\n\nWhat am I doing wrong? Since I saw this post and used this as a foundation I can't seem to get it to work. Is it an update of Mongoose or NestJS why this isn't working anymore?\n\n========================================\n\nCode:\n```text\n// users.controller.ts\n\n  @Post('sign-up')\n  @UseFilters(MongoExceptionFilter)\n  async signUp(@Body() createUserDto: CreateUserDto): Promise<any> {\n    return await this.userService.signUp(createUserDto).catch(error => {\n      throw new BadRequestException(error);\n    });\n  }\n```\n\n```text\n// user.service.ts\n\n  async signUp(createUserDto: CreateUserDto): Promise<User> {\n  const createUser = new this.userModel(createUserDto);\n    return await createUser.save();\n  }\n```\n\n```text\n// mongo-exception.filter.ts\n\n  import { ArgumentsHost,Catch, ConflictException, ExceptionFilter } from '@nestjs/common';\n  import { MongoError } from 'mongodb';\n\n  @Catch(MongoError)\n  export class MongoExceptionFilter implements ExceptionFilter {\n    catch(exception: MongoError, host: ArgumentsHost) {\n      console.log('>>>>>>>>>>>>>>>>>>>> exception: ', exception);\n    }\n  }\n```\n\n```text\n// package.json\n  \"dependencies\": {\n    \"@nestjs/common\": \"^5.4.0\",\n    \"@nestjs/core\": \"^5.4.0\",\n    \"@nestjs/jwt\": \"^0.2.1\",\n    \"@nestjs/mongoose\": \"^5.2.2\",\n    \"@nestjs/passport\": \"^5.1.0\",\n    \"@nestjs/typeorm\": \"^5.2.2\",\n    \"fancy-log\": \"^1.3.3\",\n    \"mongoose\": \"^5.4.7\",\n    \"nestjs-config\": \"^1.3.0\",\n    \"passport\": \"^0.4.0\",\n    \"passport-http-bearer\": \"^1.0.1\",\n    \"passport-jwt\": \"^4.0.0\",\n    \"reflect-metadata\": \"^0.1.12\",\n    \"rimraf\": \"^2.6.2\",\n    \"rxjs\": \"^6.2.2\",\n    \"typeorm\": \"^0.2.12\",\n    \"typescript\": \"^3.0.1\",\n    \"util\": \"^0.11.1\"\n  },\n```\n\n```text\nsave()\n```\n\n```text\nuser.service.ts\n```\n\n```text\n.catch(err => ...);\n```\n\n```text\nMongoExceptionFilter\n```\n\n```text\n@Catch()\n```\n\n```text\nreturn await this.userService.signUp(createUserDto).catch(error => {\n      throw new BadRequestException(error);\n    });\n```\n\n```text\n@Catch()\nexport class BadRequestFilter implements ExceptionFilter {\n  catch(exception: Error, host: ArgumentsHost) {\n    const response = host.switchToHttp().getResponse();\n    response.status(400).json({message: exception.message});\n  }\n}\n```\n\n```text\n@Catch(MongoError)\nexport class MongoFilter implements ExceptionFilter {\n  catch(exception: MongoError, host: ArgumentsHost) {\n    const response = host.switchToHttp().getResponse();\n    if (exception.code === 11000) {\n      response.status(400).json({ message: 'User already exists.' });\n    } else {\n      response.status(500).json({ message: 'Internal error.' });\n    }\n  }\n}\n```\n\n```text\n@UseFilters(BadRequestFilter, MongoFilter)\nasync signUp(@Body() createUserDto: CreateUserDto): Promise<any> {\n```\n\n```text\nBadRequestExceptions\n```\n\n```text\nMongoExceptionFilter\n```\n\n```text\ninstanceof MongoError\n```\n\n```text\nBadRequestException\n```\n\n```text\n.catch()\n```\n\n========================================\n\nComments:\n- Can you give me some more context? So you mean the .catch shouldnt be there? Can you post an example of what you mean?\n- Yes, you can just remove the `.catch`. The catch transforms any error from your `signUp` method into a `BadRequestException`. The transformation happens before your `MongoExceptionFilter` gets called with the error. Since it is now a `BadRequestException` and not a `MongoError` any more, the `MongoExceptionFilter` won't handle it. Instead of transforming an internal error to an exception that is understandable for the client (e.g. 404) in the controller, do exactly that in your exception filter.\n- This is because you cannot throw exceptions in an exception filter, you have to create the response directly. I've added an example to my answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.579Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":213,"estimatedTokens":1466}}1155{"id":"stack-58806309","source":"stackoverflow","questionId":58806309,"title":"Nest can't resolve dependencies of the UserService","tags":["javascript","nest","nestjs"],"text":"Title: Nest can't resolve dependencies of the UserService\nTags: javascript, nest, nestjs\nSource: Stack Overflow\n\nQuestion:\nIยดm having this error\n\n```\nNest can't resolve dependencies of the UserService (?, SettingsService). Please make sure that the argument UserModel at index [0] is available in the AuthModule context.\n\n Potential solutions:\n - If UserModel is a provider, is it part of the current AuthModule?\n - If UserModel is exported from a separate @Module, is that module imported within AuthModule?\n @Module({\n imports: [ /* the Module containing UserModel */ ]\n })\n```\n\n**auth.module.ts**\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n secretOrPrivateKey: config.auth.secret,\n signOptions: {\n expiresIn: config.auth.expiresIn,\n },\n }),\n UserModule,\n SettingsModule,\n ],\n controllers: [AuthController],\n providers: [\n AuthService,\n JwtStrategy,\n LocalStrategy,\n UserService,\n SettingsService,\n Logger,\n ... other services,\n ],\n exports: [PassportModule, AuthService],\n})\nexport class AuthModule {}\n```\n\n**user.module.ts**\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n SettingsModule,\n ],\n controllers: [UserController],\n providers: [UserService],\n exports: [UserService],\n})\nexport class UserModule {}\n```\n\n**app.module.ts**\n\n```\n@Module({\n imports: [\n AuthModule,\n UserModule,\n SettingsModule,\n MongooseModule.forRoot(config.db.url),\n WinstonModule.forRoot({\n level: config.logger.debug.level,\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n**user.service.ts**\n\n```\n@Injectable()\nexport class UserService {\n constructor(@InjectModel('User') private readonly userModel: Model,\n private readonly settingsService: SettingsService) {}\n\n public async create(user: any): Promise {\n ...\n }\n```\n\nI tried everything and can't find the issue, everything seems correct, i even checked every google page results to try to find it but i'm stuck.\nThe error tells me that i need to import UserModel into AuthModule, but it's already there, i tried to delete every single user model, or the AuthModule and mix them into everything and it still doesnt work, i know i have to export UserService to AuthModule, but can't find the correct way.\n\n========================================\n\nTop Answer:\nDouble-check your module imports:\n\n```\n@Module({\n imports: [\n MongooseModule.forFeature([\n { name: 'User', schema: UserSchema }\n ]),\n ...\n ],\n ...\n})\nexport class XModule {}\n```\n\nAnd look for silly mistakes! because even if you pass schema and schema name instead of each other, there will be no type errors! The general `Nest can't resolve dependencies` will be all you get for so many mistakes that are probable here...\n\n========================================\n\nCode:\n```text\nNest can't resolve dependencies of the UserService (?, SettingsService). Please make sure that the argument UserModel at index [0] is available in the AuthModule context.\n\n    Potential solutions:\n    - If UserModel is a provider, is it part of the current AuthModule?\n    - If UserModel is exported from a separate @Module, is that module imported within AuthModule?\n      @Module({\n        imports: [ /* the Module containing UserModel */ ]\n      })\n```\n\n```text\n@Module({\n  imports: [\n    PassportModule.register({ defaultStrategy: 'jwt' }),\n    JwtModule.register({\n      secretOrPrivateKey: config.auth.secret,\n      signOptions: {\n        expiresIn: config.auth.expiresIn,\n      },\n    }),\n    UserModule,\n    SettingsModule,\n  ],\n  controllers: [AuthController],\n  providers: [\n    AuthService,\n    JwtStrategy,\n    LocalStrategy,\n    UserService,\n    SettingsService,\n    Logger,\n    ... other services,\n  ],\n  exports: [PassportModule, AuthService],\n})\nexport class AuthModule {}\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),\n    SettingsModule,\n  ],\n  controllers: [UserController],\n  providers: [UserService],\n  exports: [UserService],\n})\nexport class UserModule {}\n```\n\n```text\n@Module({\n  imports: [\n    AuthModule,\n    UserModule,\n    SettingsModule,\n    MongooseModule.forRoot(config.db.url),\n    WinstonModule.forRoot({\n      level: config.logger.debug.level,\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n@Injectable()\nexport class UserService {\n  constructor(@InjectModel('User') private readonly userModel: Model<User>,\n              private readonly settingsService: SettingsService) {}\n\n  public async create(user: any): Promise<UserDto> {\n    ...\n  }\n```\n\n```text\nUserService\n```\n\n```text\nAuthModule\n```\n\n```text\nUserModule\n```\n\n```text\nAuthModule\n```\n\n```text\nUserModel\n```\n\n```text\n@Module({\n  imports: [\n    MongooseModule.forFeature([\n       { name: 'User', schema: UserSchema }\n    ]),\n    ...\n  ],\n  ...\n})\nexport class XModule {}\n```\n\n```text\nNest can't resolve dependencies\n```\n\n========================================\n\nComments:\n- Can you post your `UserService` class ?\n- @Nicolas i updated my question with part of the file, the functions are just comon crud operations.\n- What's the constructor of your `AuthService` look like? Standard DI syntax: `constructor(private readonly userService: UserService, private readonly settingsService: SettingsService){}`?\n- That's right, i have it just like you posted.\n- I commented UserService and SettingsService and it worked.","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":246,"estimatedTokens":1365}}1156{"id":"stack-59487531","source":"stackoverflow","questionId":59487531,"title":"NestJS HttpService call multiple endpoints","tags":["typescript","axios","nestjs"],"text":"Title: NestJS HttpService call multiple endpoints\nTags: typescript, axios, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm usually a PHP developer with almost no experience with javascript/typescript. Just started using NestJS - I want to have an endpoint that returns a list of `requisitions` that was retrieved from another system via its endpoint. \n\nThe rough idea:\n\n- Call the login endpoint with credentials\n\n- Call the `requisition` listing endpoint with the token from the login endpoint\n\n- Return the result\n\nI have experimented around with calling an endpoint like so:\n\n```\nconst url ='https://the-requisition-endpoint';\nconst config: AxiosRequestConfig = {\n headers: {\n 'Accept': 'application/json',\n 'Authorization': 'a_hard_coded_token_string' // hard coded for experimentation\n }\n };\nlet result = this.httpService.get(url, config);\nresult.subscribe(response =>\n console.log(response.data);\n});\n```\n\nNow I need to change it so that the token is not hardcoded - to use the token from the login endpoint.\n\nI'm not sure how to force the requisition endpoint to only be called once the login endpoint returns the token. I've searched and found that either a `Promise.all()` or a function called `zip` might help,\nbut I don't know how to make it work.\n\n========================================\n\nCode:\n```js\nconst url ='https://the-requisition-endpoint';\nconst config: AxiosRequestConfig = {\n      headers: {\n        'Accept': 'application/json',\n        'Authorization': 'a_hard_coded_token_string' // hard coded for experimentation\n      }\n    };\nlet result = this.httpService.get(url, config);\nresult.subscribe(response =>\n  console.log(response.data);\n});\n```\n\n```text\nrequisitions\n```\n\n```text\nrequisition\n```\n\n```text\nPromise.all()\n```\n\n```text\nzip\n```\n\n```js\n@Injcetable()\nexport class MyService {\n\n  constructor(private readonly httpService: HttpService) {}\n\n  getRequisitions(): Observable<any> {\n    // change to POST signature is login is a post. post(url, body, config)\n    return this.httpService.get(url, config).pipe(\n      // optional, but it makes working with responses easier\n      map(resp => resp.data),\n      // make new http call and switch to this observable\n      switchMap(loginData => this.httpService.get(url, configWithLoginData)),\n      / again, optional, but useful for keeping data easily readable\n      map(resp => resp.data),\n      // optional, but useful for checking what is returned\n      tap(data => console.log(data))\n  }\n}\n```\n\n```js\nmap((resp) => {\n  return resp.data;\n})\n```\n\n```text\n.pipe\n```\n\n```text\nmap\n```\n\n```text\nArray.prototype.map\n```\n\n```text\nswitchMap\n```\n\n```text\nmergeMap\n```\n\n```text\nconcatMap\n```\n\n```text\nswitchMap\n```\n\n```text\ntap\n```\n\n```text\nsubscribe\n```\n\n```text\nmap(resp => resp.data)\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Hi, thanks for the response and the link, it was very helpful. One question though, how do I \"execute\" the whole thing? I have something like this: `let requisitionData = this.login().pipe( ...`, then when I do `console.log(requisitionData);` it says that it's an Observable.\n- If this is for an HTTP response, i.e. some service called by a controller, you can just return the Observable and let NestJS subscribe under the hood. If this is manual execution, you can add `.subscribe({ next: (val) => void, error: (err) => void, complete: () => void})` (those are the signatures, you can play around with them as needed, just make sure they return void) and see what values are coming back in the `next` function. You can see some more rxjs sample in my server here. Also check out the tests to see subscribe","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":145,"estimatedTokens":909}}1157{"id":"stack-55985763","source":"stackoverflow","questionId":55985763,"title":"Nestjs server does not serve socket.io client","tags":["nestjs"],"text":"Title: Nestjs server does not serve socket.io client\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a split app using `nestjs` on the server and an `Angular` app as the client. Setting up websockets with socket.io seemed pretty easy using the `@nestjs/websockets` module and on the client I used `ngx-socket-io`. I used this repo as basis. Now when I update the project's `@nestjs/websockets` dependency to the latest version I get \n\n- CORS errors and\nan error that the client couldn't load the socket.io client js file\nhttps://i.sstatic.net/dHRGQ.png\n\nI expected CORS problems and after the update, I could fix them by adding \n\n```\napp.enableCors({\n origin: 'http://localhost:4200',\n credentials: true,\n });\n```\n\nto my `main.ts` file, but I don't know why the client file is not served. With the version of the repo (5.7.x) there are neither CORS errors nor problems with serving the file.\n\nI tried a couple of settings of `@WebSocketGateway()`, moving to a different port, setting `serveClient` (even though it should be `true` by default), but nothing seemed to work. Any advice?\n\nthanks\n\n========================================\n\nTop Answer:\nIn my case\nI replaced\n\n```\napp.useWebSocketAdapter(new WsAdapter(app));\n```\n\nfrom\n\n```\nimport { WsAdapter } from '@nestjs/platform-ws';\n```\n\nwith\n\n```\napp.useWebSocketAdapter(new IoAdapter(app));\n```\n\nin main `.ts` from\n\n```\nimport { IoAdapter } from '@nestjs/platform-socket.io';\n```\n\nWorked like a charm!\n\n========================================\n\nCode:\n```js\napp.enableCors({\n    origin: 'http://localhost:4200',\n    credentials: true,\n  });\n```\n\n```text\nnestjs\n```\n\n```text\nAngular\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\nngx-socket-io\n```\n\n```text\n@nestjs/websockets\n```\n\n```text\nmain.ts\n```\n\n```text\n@WebSocketGateway()\n```\n\n```text\nserveClient\n```\n\n```text\ntrue\n```\n\n```text\nnestjs\n```\n\n```text\nsocket.io\n```\n\n```text\nexpress\n```\n\n```text\nfastify\n```\n\n```text\nnestjs\n```\n\n```text\nnpm install --save @nestjs/platform-socket.io\n```\n\n```text\nsocket.io\n```\n\n```text\nnpm install --save @nestjs/platform-express\n```\n\n```js\napp.useWebSocketAdapter(new WsAdapter(app));\n```\n\n```js\nimport { WsAdapter } from '@nestjs/platform-ws';\n```\n\n```js\napp.useWebSocketAdapter(new IoAdapter(app));\n```\n\n```js\nimport { IoAdapter } from '@nestjs/platform-socket.io';\n```\n\n```text\n.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":153,"estimatedTokens":583}}1158{"id":"stack-73211673","source":"stackoverflow","questionId":73211673,"title":"NestJs how to test response controller","tags":["typescript","express","testing","nestjs"],"text":"Title: NestJs how to test response controller\nTags: typescript, express, testing, nestjs\nSource: Stack Overflow\n\nQuestion:\nI would like to test with jest the responses for my API.\n\nthis is method from controller\n\n```\n@Post('send-banana')\n async sendBanana(\n @Body() request: BananaRequest,\n @Res() res: Response,\n ) {\n const responseCodeService = await this.bananaService.sendBanana(\n request,\n )\n\n res.status(responseCodeService).send({\n code: responseCodeService,\n message: HttpStatus[responseCodeService],\n })\n }\n```\n\nthis is the test\n\n```\ndescribe('Banana Controller', () => {\n fit('should return httpcode(201)', async () => {\n const result = await Promise['']\n\n const request = {\n origin: 'dummy origin',\n receiver: 'dummy@dummy',\n data: {\n name: 'Elsa Pallo',\n },\n } as BananaRequest\n\n const response = jest.fn((resObj) => ({\n status: jest.fn((status) => ({\n res: { ...resObj, statusCode: status },\n })),\n }))\n\n jest\n .spyOn(bananaService, 'sendBanana')\n .mockImplementation(() => result)\n\n expect(\n await bananaController.sendBanana(request, response),\n ).toBe(result)\n })\n })\n```\n\nThis is the error that I get\n\nhttps://i.sstatic.net/Q64MB.png\n\nCan someone guide me how I can mock the response?\n\n========================================\n\nTop Answer:\nIn case anyone is using `foo.pipe(res)`, I made this class to test it:\n\n```\nclass ResponseMock extends Writable {\n private responseText = '';\n\n public _write(\n chunk: string,\n encoding: BufferEncoding,\n callback: (error?: Error | null) => void\n ): void {\n this.responseText += chunk;\n callback();\n }\n\n /**\n * Wait for the response to complete and return it\n */\n public async getResponse(): Promise {\n return await new Promise((resolve): void => {\n this.on('finish', (): void => {\n resolve(this.responseText);\n });\n });\n }\n}\n```\n\nwhich can be used like\n\n```\nimport { Response } from 'express';\n\nconst responseMock = new ResponseMock();\n\nawait controller.query(\n param1,\n param2,\n responseMock as unknown as Response\n);\n\nawait expect(responseMock.getResponse()).resolves.toEqual('foo');\n```\n\n========================================\n\nCode:\n```text\n@Post('send-banana')\n  async sendBanana(\n    @Body() request: BananaRequest,\n    @Res() res: Response,\n  ) {\n    const responseCodeService = await this.bananaService.sendBanana(\n      request,\n    )\n\n    res.status(responseCodeService).send({\n      code: responseCodeService,\n      message: HttpStatus[responseCodeService],\n    })\n  }\n```\n\n```text\ndescribe('Banana Controller', () => {\n    fit('should return httpcode(201)', async () => {\n      const result = await Promise['']\n\n      const request = {\n        origin: 'dummy origin',\n        receiver: 'dummy@dummy',\n        data: {\n          name: 'Elsa Pallo',\n        },\n      } as BananaRequest\n\n      const response = jest.fn((resObj) => ({\n        status: jest.fn((status) => ({\n          res: { ...resObj, statusCode: status },\n        })),\n      }))\n\n      jest\n        .spyOn(bananaService, 'sendBanana')\n        .mockImplementation(() => result)\n\n      expect(\n        await bananaController.sendBanana(request, response),\n      ).toBe(result)\n    })\n  })\n```\n\n```js\nconst statusResponseMock = {\n  send: jest.fn((x) => x),\n}\n\nconst responseMock = {\n  status: jest.fn((x) => statusResponseMock),\n  send: jest.fn((x) => x),\n} as unknown as Response\n```\n\n```js\nclass ResponseMock extends Writable {\n    private responseText = '';\n\n    public _write(\n        chunk: string,\n        encoding: BufferEncoding,\n        callback: (error?: Error | null) => void\n    ): void {\n        this.responseText += chunk;\n        callback();\n    }\n\n    /**\n     * Wait for the response to complete and return it\n     */\n    public async getResponse(): Promise<string> {\n        return await new Promise<string>((resolve): void => {\n            this.on('finish', (): void => {\n                resolve(this.responseText);\n            });\n        });\n    }\n}\n```\n\n```js\nimport { Response } from 'express';\n\nconst responseMock = new ResponseMock();\n\nawait controller.query(\n    param1,\n    param2,\n    responseMock as unknown as Response\n);\n\nawait expect(responseMock.getResponse()).resolves.toEqual('foo');\n```\n\n```text\nfoo.pipe(res)\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":215,"estimatedTokens":1045}}1159{"id":"stack-77131375","source":"stackoverflow","questionId":77131375,"title":"How to Allow null or Empty String in class-validator for Specific Fields?","tags":["postgresql","nestjs","prisma","dto","class-validator"],"text":"Title: How to Allow null or Empty String in class-validator for Specific Fields?\nTags: postgresql, nestjs, prisma, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm using class-validator in my NestJS application and have a challenge with certain fields. For instance, I have a field sample_result which can contain a number, but I'd like to be able to update or set this field to null or an empty string ('') under certain circumstances (e.g., if I want to remove the value from the database). The same applies for another field sample_comment which is a string.\n\nHere's the relevant code:\n\n```\n@ApiProperty({ required: false })\n @IsNumber()\n @IsOptional()\n sample_result?: number;\n\n @ApiProperty({ required: false })\n @IsString()\n @IsOptional()\n sample_comment?: string;\n```\n\nThe challenge is that when I send a null or '' for sample_result or sample_comment, I receive a validation error. What's the correct approach or configuration with class-validator to allow null or an empty string for these specific fields while ensuring that when values are provided, they adhere to their respective validations (i.e., number for sample_result and string for sample_comment)?\n\nAny guidance or suggestions would be greatly appreciated. Thanks!\n\nmust be a string\nmust be a number conforming to the specified constraints\n\n========================================\n\nTop Answer:\nYou can set the nullable to true, like below;\n\n```\n@ApiProperty({ required: false, nullable: true })\n @IsNumber()\n @IsOptional()\n sample_result?: number;\n\n @ApiProperty({ required: false, nullable: true })\n @IsString()\n @IsOptional()\n sample_comment?: string;\n```\n\n========================================\n\nCode:\n```text\n@ApiProperty({ required: false })\n  @IsNumber()\n  @IsOptional()\n  sample_result?: number;\n\n  @ApiProperty({ required: false })\n  @IsString()\n  @IsOptional()\n  sample_comment?: string;\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\nimport { IsNumber, IsString, IsOptional, ValidateIf } from 'class-validator';\n\nexport class YourDto {\n  @ApiProperty({ required: false })\n  @IsNumber()\n  @ValidateIf((obj) => obj.sample_result !== null && obj.sample_result !== '')\n  sample_result?: number | null;\n\n  @ApiProperty({ required: false })\n  @IsString()\n  @ValidateIf((obj) => obj.sample_comment !== null && obj.sample_comment !== '')\n  sample_comment?: string | null;\n}\n```\n\n```text\n@ApiProperty({ required: false, nullable: true })\n  @IsNumber()\n  @IsOptional()\n  sample_result?: number;\n\n  @ApiProperty({ required: false, nullable: true })\n  @IsString()\n  @IsOptional()\n  sample_comment?: string;\n```\n\n========================================\n\nComments:\n- Thank u it still throws an error like: ``` \"isNumber\": \"sample_result must be a number conforming to the specified constraints\" ```\n- That didn't work, unfortunatelly","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":94,"estimatedTokens":707}}1160{"id":"stack-76521910","source":"stackoverflow","questionId":76521910,"title":"How do you manage interfaces/models/validation classes in Nest JS?","tags":["mongodb","mongoose","nestjs","mongoose-schema","dto"],"text":"Title: How do you manage interfaces/models/validation classes in Nest JS?\nTags: mongodb, mongoose, nestjs, mongoose-schema, dto\nSource: Stack Overflow\n\nQuestion:\nI just started using NestJs for a new project I started, and I'm feeling quite frustrated with all of the boilerplate code at the moment, particularly when it comes to DTO classes, Mongoose schemas and interfaces. The way I have been doing it so far is I have an interface that describes the fields I need in my collection documents, then I have DTO classes for validation, which implement those interfaces, and then there are also Schemas for Mongoose which have to simply mirror the interface (as they can't directly implement them afaik *(edit: this is somewhat wrong; I explain in my edit)*). This means that if I change one thing in the structure of my documents, I have to update it in **THREE** different places. And then there is also doubled-up validation: on the schema as well as on the DTO classes.\n\nCan I not just completely do away with the DTO classes and just use interfaces and schemas, and simply do validation when inserting documents into the database? If that is not a good idea, is there a different alternative that doesn't require me to change code in three different places? What about using the DTO create class instead of the interface?\n\n**EDIT: I have finally found the best solution for me, so here it is for those who stumble upon this question:**\n\nI use an interface that describes the model, I now use Schema classes (using the @Schema decorator from @nestjs/mongoose, as suggested by **Yahya Eddhissa**), and I always have them implement the interface. And I do still use DTOs, which do validation and also implement the same interface. If there are fields that need not be passed in on creation, but do need to be stored in the DB, I just make them optional on the interface and leave them out when implementing the interface in the DTO. If necessary, I include some of those fields in the update DTO, so that they can still be edited **after** creation.\n\nWith this system, if I do change something in the interface, both the DTO and the schema will show errors, reminding me to implement those changes, which is fine, because it's not often that you need to make DB migrations in most projects. And the interface can obviously also be used in other places in my code. So I do still need to update all three files, but, since they serve different functions, I believe this is the most elegant solution. Here is a simple example from my project, starting with the interface:\n\n```\nimport { EventFormat } from '../enums';\n\ninterface IEvent {\n eventId: string;\n name: string;\n rank: number;\n format: EventFormat;\n}\n\nexport default IEvent;\n```\n\nThen the schema class:\n\n```\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { HydratedDocument } from 'mongoose';\nimport IEvent from '~/shared_helpers/interfaces/Event';\nimport { EventFormat } from '~/shared_helpers/enums';\n\n@Schema({ timestamps: true })\nexport class Event implements IEvent {\n @Prop({ required: true, immutable: true, unique: true })\n eventId: string;\n\n @Prop({ required: true })\n name: string;\n\n @Prop({ required: true })\n rank: number;\n\n @Prop({ enum: EventFormat, required: true })\n format: EventFormat;\n}\n\n// Used as the return type for DB queries\nexport type EventDocument = HydratedDocument;\n// Used for dependency injection\nexport const EventSchema = SchemaFactory.createForClass(Event);\n```\n\nAnd lastly the DTOs:\n\n```\nimport { IsEnum, IsNumber, IsString, Min, MinLength } from 'class-validator';\nimport IEvent from '~/shared_helpers/interfaces/Event';\nimport { EventFormat } from '~/shared_helpers/enums';\n\nexport class CreateEventDto implements IEvent {\n @IsString()\n @MinLength(3)\n eventId: string;\n\n @IsString()\n @MinLength(3)\n name: string;\n\n @IsNumber()\n @Min(0)\n rank: number;\n\n @IsEnum(EventFormat)\n format: EventFormat;\n}\n```\n\n```\nimport { PartialType } from '@nestjs/mapped-types';\nimport { CreateEventDto } from './create-event.dto';\n\nexport class UpdateEventDto extends PartialType(CreateEventDto) {\n // If there were optional fields in the interface that were left\n // out from the create DTO, because they are not needed on\n // creation, I would put them here, if they need to be editable.\n}\n```\n\n========================================\n\nCode:\n```js\nimport { EventFormat } from '../enums';\n\ninterface IEvent {\n  eventId: string;\n  name: string;\n  rank: number;\n  format: EventFormat;\n}\n\nexport default IEvent;\n```\n\n```js\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { HydratedDocument } from 'mongoose';\nimport IEvent from '~/shared_helpers/interfaces/Event';\nimport { EventFormat } from '~/shared_helpers/enums';\n\n@Schema({ timestamps: true })\nexport class Event implements IEvent {\n  @Prop({ required: true, immutable: true, unique: true })\n  eventId: string;\n\n  @Prop({ required: true })\n  name: string;\n\n  @Prop({ required: true })\n  rank: number;\n\n  @Prop({ enum: EventFormat, required: true })\n  format: EventFormat;\n}\n\n// Used as the return type for DB queries\nexport type EventDocument = HydratedDocument<Event>;\n// Used for dependency injection\nexport const EventSchema = SchemaFactory.createForClass(Event);\n```\n\n```js\nimport { IsEnum, IsNumber, IsString, Min, MinLength } from 'class-validator';\nimport IEvent from '~/shared_helpers/interfaces/Event';\nimport { EventFormat } from '~/shared_helpers/enums';\n\nexport class CreateEventDto implements IEvent {\n  @IsString()\n  @MinLength(3)\n  eventId: string;\n\n  @IsString()\n  @MinLength(3)\n  name: string;\n\n  @IsNumber()\n  @Min(0)\n  rank: number;\n\n  @IsEnum(EventFormat)\n  format: EventFormat;\n}\n```\n\n```js\nimport { PartialType } from '@nestjs/mapped-types';\nimport { CreateEventDto } from './create-event.dto';\n\nexport class UpdateEventDto extends PartialType(CreateEventDto) {\n  // If there were optional fields in the interface that were left\n  // out from the create DTO, because they are not needed on\n  // creation, I would put them here, if they need to be editable.\n}\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { IsNotEmpty, IsString, IsEmail } from 'class-validator';\nimport { HydratedDocument } from 'mongoose';\n\nexport type UserDocument = HydratedDocument<User>;\n\n@Schema()\nexport class User {\n  @IsNotEmpty()\n  @IsString()\n  @Prop({ required: true })\n  name: string;\n\n  @IsNotEmpty()\n  @IsEmail()\n  @Prop({ required: true, unique: true })\n  email: string;\n\n  @IsNotEmpty()\n  @IsString()\n  @Prop({ required: true })\n  password: string;\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User);\n```\n\n```text\ntype CreateEventDTO = Omit<Event, \"property1\" | \"property2\">\ntype UpdateEventDTO = Partial<CreateEventDTO>\n```\n\n```text\nEvent\n```\n\n```text\nclass-validator\n```\n\n```text\nCreateEventDto\n```\n\n```text\nUpdateEventDto\n```\n\n```text\nOmit\n```\n\n```text\nPartial\n```\n\n```text\nOmit\n```\n\n```text\nPartial\n```\n\n========================================\n\nComments:\n- and what about the fields that we don't want to receive/include in DTO how do we segregate them?\n- What I get from your question is that you want to exclude certain fields from the DTO for different scenarios like creating a user or updating it, if that's the case, I suggest you create subsets of the `User` DTO by using the Typescript `Omit` operator, which allows you to exclude keys from interfaces and classes.\n- I read your answer when you first posted it, but didn't fully understand it. I have now learned a fair bit more about NestJs and can see how much better this is than what I had. I edited my question with the solution that I use now, although I do still have separate DTOs and Schemas. Is it possible to use these same classes for request body validation? If so then I will probably start using your method for those models that are the same in the DTO and the Schema.\n- @CodeToCode I have just edited my answer to include the possibility of defining DTOs implicitly without having to separate them from the Schema definition.","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":242,"estimatedTokens":2010}}1161{"id":"stack-73771212","source":"stackoverflow","questionId":73771212,"title":"How to use externally generated swagger.json in NestJS?","tags":["node.js","swagger","nestjs"],"text":"Title: How to use externally generated swagger.json in NestJS?\nTags: node.js, swagger, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have generated swagger.yaml/swagger.json from external documentation library. Now, I wanted to import and host that as API documentation on my API platform which is running on NestJS. I know, we can generate and export swagger from NestJS code, but for me the need is reverse, we have the swagger.json, we need to render it in the NestJS platform, like `https://example.com/docs`\n\n========================================\n\nCode:\n```text\nhttps://example.com/docs\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule } from '@nestjs/swagger';\nimport { readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  // read the JSON file to string and parse the string to object literal\n  const document = JSON.parse(\n    (await readFile(join(process.cwd(), 'swagger.json'))).toString('utf-8')\n  )\n  SwaggerModule.setup('api', app, document);\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nswagger.json\n```\n\n```text\nSwaggerModule.createDocument\n```\n\n```text\nDocumentBuilder\n```\n\n```text\nSwaggerModule.setup()\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":50,"estimatedTokens":324}}1162{"id":"stack-71771803","source":"stackoverflow","questionId":71771803,"title":"Typescript + NestJs + Class Transformer: How to use generic types in response DTO?","tags":["typescript","pagination","nestjs","class-transformer"],"text":"Title: Typescript + NestJs + Class Transformer: How to use generic types in response DTO?\nTags: typescript, pagination, nestjs, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have multiple endpoints that return a response including pagination details. I would like to use one parent type for the pagination and pass in different data-types for the `data` param.\n\nI tried the following, but this was not working because the statement in `@Type` gives the error `'T' only refers to a type, but is being used as a value here.`, so it expects a value/class and not a type:\n\n```\nexport class PaginatedResponseDto {\n @Expose()\n @ApiProperty()\n skip: number;\n\n @Expose()\n @ApiProperty()\n take: number;\n\n @Expose()\n @ApiProperty()\n count: number;\n\n @Expose()\n @ApiProperty()\n @Type(() => T[]) // I searched and found this, which is basically working, but unfortunately it seems to transform the response twice, which causes issues with dates.\n\nIs there any other way to do this (instead of writing multiple `PaginatedResponseDto`-classes?\n\n========================================\n\nCode:\n```text\nexport class PaginatedResponseDto<T> {\n  @Expose()\n  @ApiProperty()\n  skip: number;\n\n  @Expose()\n  @ApiProperty()\n  take: number;\n\n  @Expose()\n  @ApiProperty()\n  count: number;\n\n  @Expose()\n  @ApiProperty()\n  @Type(() => T[]) // <- this is not working, because I cannot use `T` here\n  data: T[];\n\n  constructor(data: any) {\n    Object.assign(this, data);\n  }\n}\n```\n\n```text\ndata\n```\n\n```text\n@Type\n```\n\n```text\n'T' only refers to a type, but is being used as a value here.\n```\n\n```text\nPaginatedResponseDto\n```\n\n```text\nexport class PaginatedResponseDto<T> {\n\n  @Exclude()\n  private type: Function;\n\n  @Expose()\n  @ApiProperty()\n  @Type(opt => (opt.newObject as PaginatedResponseDto<T>).type)\n  data: T[];\n\n  constructor(type: Function) {\n    this.type = type;\n  }\n}\n```\n\n========================================\n\nComments:\n- Not sure about that, because my validation doesnt check the `data` object. Validation of main CloudEvent works properly, but data object is not checked at all. Did I understand something wrong? Really sorry for formatting. `export class CloudEvent {` `@Exclude()` `private dataType?: Function;` `@IsString()` `id: string;` `@ValidateNested()` `@Type(options => (options.newObject as CloudEvent).dataType)` `data: T;` `constructor(dataType: Function) {` `this.dataType = dataType;` `}` `}` `export class CustomerCloudEventDto extends CloudEvent {}`\n- @AleksandraG did you manage to solve this issue? tried it as well, but it doesnt validate inner object\n- @SagiRika I ended up with: export class CloudEventDto { @IsString() id: string; @IsString() version: string; @IsEnum(EVENT) type: EVENT; @ValidateNested() @Type((type: TypeHelpOptions | undefined) => { if (type?.object) { const cloudEvent: CloudEventDto = type.object as CloudEventDto; switch (cloudEvent.type) { case EVENT.C_CREATED: return CCreatedDto; case EVENT.C_UPDATED: return CUpdatedDto; } } return CCreatedDto; }) data: CCreatedDto || CUpdatedDto; }\n- In my case using `opt.newObject.type` didn't work, but using `opt.object.type` worked as the object is the actual object instance that is being decorated","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":798}}1163{"id":"stack-53579955","source":"stackoverflow","questionId":53579955,"title":"API Controller : Cannot PUT, Cannot DELETE (404 not found)","tags":["node.js","rest","express","postman","nestjs"],"text":"Title: API Controller : Cannot PUT, Cannot DELETE (404 not found)\nTags: node.js, rest, express, postman, nestjs\nSource: Stack Overflow\n\nQuestion:\nWith Nest.js, and a basic controller :\n\n```\nimport { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';\nimport { Hero } from '../entities/hero.entity';\nimport { HeroService } from './hero.service';\n\n@Controller('hero')\nexport class HeroController {\n constructor(private readonly heroesService: HeroService) {}\n\n @Get()\n async get(@Query() query): Promise {\n return await this.heroesService.find(query);\n }\n\n @Get(':id')\n async getById(@Param('id') id): Promise {\n return await this.heroesService.findById(id);\n }\n\n @Post()\n async add(@Body() hero: Hero): Promise {\n return await this.heroesService.save(hero);\n }\n\n //TODO: doesn't seem to work, never called (request 404)\n @Put(':id')\n async update(@Param('id') id, @Body() hero): Promise {\n console.log('hey');\n return await this.heroesService.update(id, hero);\n }\n\n //TODO: doesn't seem to work, never called (request 404)\n @Delete('/delete/:id')\n async remove(@Param('id') id): Promise {\n console.log('hey');\n return await this.heroesService.remove(id);\n }\n}\n```\n\nFollowing the basic documentation of nest.js, a module with a controller and a service, injecting a typeorm repository for the entity 'Hero'.\n\nUsing Postman, both @Get, @Get(':id') and @Post work perfectly, my entity->repository->service->controller connects to my local Postgres DB, and I can get/add/update data from the Hero table with those API endpoints.\n\nHowever, PUT and DELETE requests respond with :\n\n```\n{\n \"statusCode\": 404,\n \"error\": \"Not Found\",\n \"message\": \"Cannot PUT /hero\"\n}\n\nX-Powered-By โ†’Express\nContent-Type โ†’application/json; charset=utf-8\nContent-Length โ†’67\nETag โ†’W/\"43-6vi9yb61CRVGqX01+Xyko0QuUAs\"\nDate โ†’Sun, 02 Dec 2018 11:40:41 GMT\nConnection โ†’keep-alive\n```\n\nThe request for this is localhost:3000/hero (same endpoint as GET and POST), i've tried either by adding a id:1 in Params or in the Body with x-www-form-urlencoded.\n\nThe requests don't ever seem to arrive at the controller (nothing called), i've added a globalinterceptor to Nest.js that just does this :\n\n```\nintercept(\n context: ExecutionContext,\n call$: Observable,\n ): Observable {\n console.log(context.switchToHttp().getRequest());\n return call$;\n }\n```\n\nBut again it only logs GET and POST requests, the others never appear.\n\nWhat confuses me is that I've pretty much followed the Nest.js doc, made a basic controller and service, entity/repository connected to DB, there doesn't seem to be anything else needed for this to work, and yet PUT and DELETE appear to not exist.\n\n========================================\n\nCode:\n```text\nimport { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';\nimport { Hero } from '../entities/hero.entity';\nimport { HeroService } from './hero.service';\n\n@Controller('hero')\nexport class HeroController {\n  constructor(private readonly heroesService: HeroService) {}\n\n  @Get()\n  async get(@Query() query): Promise<Hero[]> {\n    return await this.heroesService.find(query);\n  }\n\n  @Get(':id')\n  async getById(@Param('id') id): Promise<Hero> {\n    return await this.heroesService.findById(id);\n  }\n\n  @Post()\n  async add(@Body() hero: Hero): Promise<Hero> {\n    return await this.heroesService.save(hero);\n  }\n\n  //TODO: doesn't seem to work, never called (request 404)\n  @Put(':id')\n  async update(@Param('id') id, @Body() hero): Promise<Hero> {\n    console.log('hey');\n    return await this.heroesService.update(id, hero);\n  }\n\n  //TODO: doesn't seem to work, never called (request 404)\n  @Delete('/delete/:id')\n  async remove(@Param('id') id): Promise<Hero> {\n    console.log('hey');\n    return await this.heroesService.remove(id);\n  }\n}\n```\n\n```text\n{\n    \"statusCode\": 404,\n    \"error\": \"Not Found\",\n    \"message\": \"Cannot PUT /hero\"\n}\n\nX-Powered-By โ†’Express\nContent-Type โ†’application/json; charset=utf-8\nContent-Length โ†’67\nETag โ†’W/\"43-6vi9yb61CRVGqX01+Xyko0QuUAs\"\nDate โ†’Sun, 02 Dec 2018 11:40:41 GMT\nConnection โ†’keep-alive\n```\n\n```text\nintercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    console.log(context.switchToHttp().getRequest());\n    return call$;\n  }\n```\n\n```text\nlocalhost:3000/hero/<id_here>\n```\n\n```text\nlocalhost:3000/hero/delete/<id_here>\n```\n\n========================================\n\nComments:\n- Judging from msg `Cannot PUT &#47;hero` you are making a `&#47;hero` request rather than for example `&#47;hero&#47;1`.\n- Wow do I feel silly. I got confused by Postman and thought the ID for a put/delete had to be a param.","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":167,"estimatedTokens":1157}}1164{"id":"stack-74143751","source":"stackoverflow","questionId":74143751,"title":"How to ignore DUPLICATE ENTRY error when updating multiple records at once using TypeORM","tags":["sql","node.js","nestjs","typeorm"],"text":"Title: How to ignore DUPLICATE ENTRY error when updating multiple records at once using TypeORM\nTags: sql, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to update hundreds of database records using the TypeORM library. Problem is that sometimes DUPLICATE ERR is returned from SQL when the bulk upload is performed and stops the whole operation. Is possible to set up TypeORM in a way so duplicate entries are ignored and the insert is performed?\nThe table is using two primary keys:\nhttps://i.sstatic.net/uSZ0f.png\n\nThis is my insert command (TypeORM + Nestjs):\n\n```\npublic async saveBulk(historicalPrices: IHistoricalPrice[]) {\n if (!historicalPrices.length) {\n return;\n }\n const repoPrices = historicalPrices.map((p) => this.historicalPricesRepository.create(p));\n await this.historicalPricesRepository.save(repoPrices, { chunk: 200 });\n }\n```\n\nThanks in advance\n\n========================================\n\nCode:\n```js\npublic async saveBulk(historicalPrices: IHistoricalPrice[]) {\n    if (!historicalPrices.length) {\n      return;\n    }\n    const repoPrices = historicalPrices.map((p) => this.historicalPricesRepository.create(p));\n    await this.historicalPricesRepository.save(repoPrices, { chunk: 200 });\n  }\n```\n\n```text\nfor (let i = 0; i < historicalPrices.length; i += 200) {\n  const chunk = historicalPrices.slice(i, i + 200);\n  const targetEntity = this.historicalPricesRepository.target;\n  await this.historicalPricesRepository\n    .createQueryBuilder()\n    .insert()\n    .into(targetEntity)\n    .values(chunk)\n    .orIgnore()\n    .execute();\n}\n```\n\n```text\nInsertQueryBuilder\n```\n\n```text\nrepository.save\n```\n\n```text\nInsertQueryBuilder\n```\n\n```text\norIgnore()\n```\n\n```text\nIGNORE\n```\n\n```text\nINSERT\n```\n\n```text\nInsertQueryBuilder\n```\n\n========================================\n\nComments:\n- I've never worked with `typeorm`, but it looks like they've had support for `onIgnore` since Q4 2018, at least based on this pull request. That will treat duplicate inserts as warnings instead of causing error.\n- Thanks for your commentary. It points to correct solution\n- Thank you for the explanation and solution. Chunking to code on my own is completely fine as it removes unnecessary layer of abstraction","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":84,"estimatedTokens":560}}1165{"id":"stack-69235421","source":"stackoverflow","questionId":69235421,"title":"Typeorm and operator without using querybuilder","tags":["typescript","nestjs","typeorm"],"text":"Title: Typeorm and operator without using querybuilder\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn NestJS / Typeform I want to make a query that sues to conditions as an `AND` condition.\n\nI tried something like this\n\n```\nasync getByUniqueConstraints(user: User){\n const {email, phoneNumber} = user\n const foundUser = await this.userRepository.findOne({where: [email, phoneNumber], });\n\n }\n```\n\nThe problem with this is that it uses an `OR` condition. Is there a way to use this with an `AND` operator instead without using a querybuilder or any more advanced concepts?\n\n========================================\n\nCode:\n```text\nasync getByUniqueConstraints(user: User){\n        const {email, phoneNumber} = user\n        const foundUser = await this.userRepository.findOne({where: [email, phoneNumber], });\n\n    }\n```\n\n```text\nAND\n```\n\n```text\nOR\n```\n\n```text\nAND\n```\n\n```text\nwhere\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":45,"estimatedTokens":228}}1166{"id":"stack-74361203","source":"stackoverflow","questionId":74361203,"title":"How can I configure postgreSQL in the Nestjs way?","tags":["javascript","postgresql","nestjs"],"text":"Title: How can I configure postgreSQL in the Nestjs way?\nTags: javascript, postgresql, nestjs\nSource: Stack Overflow\n\nQuestion:\nSo I'm in the process of learning NestJs ways. I have a small NestJs backend with only a few routes. Some of them call postgreSQL. I don't want to use any ORM and directly use pg package.\nSo my next step is learning how to use ConfigService. I have successfully used it to configure all env vars in the backend, but I'm struggling to use it in a small file I use to configure postgreSQL. This is the configuration file (pgconnect.ts):\n\n```\nimport { Pool } from 'pg';\nimport configJson from './config/database.json';\nimport dotenv from 'dotenv';\ndotenv.config();\n\nconst config = configJson[process.env.NODE_ENV];\n\nconst poolConfig = {\n user: config.username,\n host: config.host,\n database: config.database,\n password: config.password,\n port: config.port,\n max: config.maxClients\n};\n\nexport const pool = new Pool(poolConfig)\n```\n\ndatabase.json is a json file where I have all connect values divided by environment. Then in service classes I just:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { Response } from 'express';\nimport { pool } from 'src/database/pgconnect';\n\n@Injectable()\nexport class MyService {\n\n getDocumentByName(res: Response, name: string) {\n pool.query(\n \n });\n }\n\n more queries for insert, update, other selects, etc\n}\n```\n\nSo how could I use ConfigService inside my configuration file ? I already tried to instance class like this:\n\n```\nlet configService = new ConfigService();\n```\n\nand what I would like to do is:\n\n```\nconst config = configJson[configService.get('NODE_ENV')];\n```\n\nbut it didn't work. You have to pass .env file path to `new ConfigService()`. And I need to use NODE_ENV var to get it, because it depends on environment. To get NODE_ENV without using ConfigService I would have to use dotenv, but if I'm going to use dotenv I don't need ConfigService in the first place.\n\nSo then I tried to create a class:\n\n```\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config'\nconst { Pool } = require('pg');\n\nimport configJson from './config/database.json';\n\n@Injectable()\nexport class PgPool {\n constructor(private configService: ConfigService) { };\n\n config = configJson[this.configService.get('NODE_ENV')];\n\n poolConfig = {\n user: this.config.username,\n host: this.config.host,\n database: this.config.database,\n password: this.config.password,\n port: this.config.port,\n max: this.config.maxClients\n };\n \n static pool = new Pool(this.poolConfig);\n}\n\nexport const PgPool.pool;\n```\n\nBut this doesn't work in several ways. If I use non-static members, I canยดt export pool member which is the only thing I need. If I use static members one can't access the other or at least I'm not understanding how one access the other.\n\nSo, the questions are: How do I use ConfigService outside of a class or how can I change pgconnect.ts file to do it's job ? If it's through a class the best would be to export only pool method.\n\nAlso if you think there's a better way to configure postgreSQL I would be glad to hear.\n\n========================================\n\nTop Answer:\nI normally have my own pg module handling the pool with either an additional config file (json) or via processing a .env file:\n\nnode-pg-sql.js:\n\n```\n/* INFO: Require json config file */\nconst fileNameConfigPGSQL = require('./config/pgconfig.json');\n\n/* INFO: Require file operations package */\nconst { Pool } = require('pg');\n\nconst pool = new Pool(fileNameConfigPGSQL);\n\nmodule.exports = {\n query: (text, params, callback) => {\n const start = Date.now()\n return pool.query(text, params, (err, res) => {\n const duration = Date.now() - start\n // console.log('executed query', { text, duration, rows: res.rowCount })\n callback(err, res)\n })\n },\n getClient: (callback) => {\n pool.connect((err, client, done) => {\n const query = client.query.bind(client)\n\n // monkey patch for the query method to track last queries\n client.query = () => {\n client.lastQuery = arguments\n client.query.apply(client, arguments)\n }\n\n // Timeout of 5 secs,then last query is logged\n const timeout = setTimeout(() => {\n // console.error('A client has been checked out for more than 5 seconds!')\n // console.error(`The last executed query on this client was: ${client.lastQuery}`)\n }, 5000)\n\n const release = (err) => {\n // calling 'done'-method to return client to pool\n done(err)\n\n // cleat timeout\n clearTimeout(timeout)\n\n // reset query-methode before the Monkey Patch\n client.query = query\n }\n\n callback(err, client, done)\n })\n }\n}\n```\n\npgconfig.json:\n\n```\n{\n \"user\":\"postgres\",\n \"host\":\"localhost\",\n \"database\":\"mydb\",\n \"password\":\"mypwd\",\n \"port\":\"5432\",\n \"ssl\":true\n}\n```\n\nIf you prefer processing a .env file:\n\n```\nNODE_ENV=develepment\nNODE_PORT=45500\nHOST_POSTGRESQL='localhost'\nPORT_POSTGRESQL='5432'\nDB_POSTGRESQL='mydb'\nUSER_POSTGRESQL='postgres'\nPWD_POSTGRESQL='mypwd'\n```\n\nand process the file and export vars:\n\n```\nvar path = require('path');\n\nconst dotenvAbsolutePath = path.join(__dirname, '.env');\n\n/* INFO: Require dotenv package for retieving and setting env-vars at runtime via absolute path due to pkg */\n\n const dotenv = require('dotenv').config({\n path: dotenvAbsolutePath\n });\n if (dotenv.error) {\n console.log(`ERROR WHILE READING ENV-VARS:${dotenv.error}`);\n throw dotenv.error;\n }\n\nmodule.exports = {\n nodeEnv: process.env.NODE_ENV,\n nodePort: process.env.NODE_PORT,\n hostPostgresql: process.env.HOST_POSTGRESQL,\n portPostgresql: process.env.PORT_POSTGRESQL,\n dbPostgresql: process.env.DB_POSTGRESQL,\n userPostgresql: process.env.USER_POSTGRESQL,\n pwdPostgresql: process.env.PWD_POSTGRESQL,\n};\n```\n\n========================================\n\nCode:\n```text\nimport { Pool } from 'pg';\nimport configJson from './config/database.json';\nimport dotenv from 'dotenv';\ndotenv.config();\n\nconst config = configJson[process.env.NODE_ENV];\n\nconst poolConfig = {\n  user: config.username,\n  host: config.host,\n  database: config.database,\n  password: config.password,\n  port: config.port,\n  max: config.maxClients\n};\n\nexport const pool = new Pool(poolConfig)\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { Response } from 'express';\nimport { pool } from 'src/database/pgconnect';\n\n@Injectable()\nexport class MyService {\n\n    getDocumentByName(res: Response, name: string) {\n        pool.query(\n               <query, error treatment, etc>\n            });\n    }\n\n    <...> more queries for insert, update, other selects, etc\n}\n```\n\n```text\nlet configService = new ConfigService();\n```\n\n```text\nconst config = configJson[configService.get<string>('NODE_ENV')];\n```\n\n```text\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config'\nconst { Pool } = require('pg');\n\nimport configJson from './config/database.json';\n\n@Injectable()\nexport class PgPool {\n    constructor(private configService: ConfigService) { };\n\n    config = configJson[this.configService.get<string>('NODE_ENV')];\n\n    poolConfig = {\n        user: this.config.username,\n        host: this.config.host,\n        database: this.config.database,\n        password: this.config.password,\n        port: this.config.port,\n        max: this.config.maxClients\n    };\n    \n    static pool = new Pool(this.poolConfig);\n}\n\nexport const PgPool.pool;\n```\n\n```text\nnew ConfigService()\n```\n\n```js\n@Module({\n  imports: [ConfigModule],\n  providers: [\n    {\n      provide: 'PG_OPTIONS',\n      inject: [ConfigService],\n      useFactory: (config) => ({\n        host: config.get('DB_HOST'),\n        port:  config.get('DB_PORT'),\n        ...etc\n      }),\n    },\n    {\n      provide: 'PG_POOL',\n      inject: ['PG_OPTIONS'],\n      useFactory: (options) => new Pool(options),\n    }\n  ],\n  exports: ['PG_POOL'],\n})\nexport class PgModule {}\n```\n\n```text\npg\n```\n\n```text\nPgModule\n```\n\n```text\nPool\n```\n\n```text\nPool\n```\n\n```text\nPgModule\n```\n\n```text\nimports\n```\n\n```text\n@Inject('PG_POOL') private readonly pg: Pool\n```\n\n```text\nconstructor\n```\n\n```text\n/* INFO: Require json config file */\nconst fileNameConfigPGSQL = require('./config/pgconfig.json');\n\n/* INFO: Require file operations package */\nconst { Pool } = require('pg');\n\nconst pool = new Pool(fileNameConfigPGSQL);\n\nmodule.exports = {\n  query: (text, params, callback) => {\n    const start = Date.now()\n    return pool.query(text, params, (err, res) => {\n      const duration = Date.now() - start\n  //    console.log('executed query', { text, duration, rows: res.rowCount })\n      callback(err, res)\n    })\n  },\n  getClient: (callback) => {\n    pool.connect((err, client, done) => {\n      const query = client.query.bind(client)\n\n      // monkey patch for the query method to track last queries\n      client.query = () => {\n        client.lastQuery = arguments\n        client.query.apply(client, arguments)\n      }\n\n      // Timeout of 5 secs,then last query is logged\n      const timeout = setTimeout(() => {\n     //   console.error('A client has been checked out for more than 5 seconds!')\n     //   console.error(`The last executed query on this client was: ${client.lastQuery}`)\n      }, 5000)\n\n      const release = (err) => {\n        // calling 'done'-method to return client to pool\n        done(err)\n\n        // cleat timeout\n        clearTimeout(timeout)\n\n        // reset query-methode before the Monkey Patch\n        client.query = query\n      }\n\n      callback(err, client, done)\n    })\n  }\n}\n```\n\n```text\n{\n    \"user\":\"postgres\",\n    \"host\":\"localhost\",\n    \"database\":\"mydb\",\n    \"password\":\"mypwd\",\n    \"port\":\"5432\",\n    \"ssl\":true\n}\n```\n\n```text\nNODE_ENV=develepment\nNODE_PORT=45500\nHOST_POSTGRESQL='localhost'\nPORT_POSTGRESQL='5432'\nDB_POSTGRESQL='mydb'\nUSER_POSTGRESQL='postgres'\nPWD_POSTGRESQL='mypwd'\n```\n\n```text\nvar path = require('path');\n\n\nconst dotenvAbsolutePath = path.join(__dirname, '.env');\n\n/* INFO: Require dotenv package for retieving and setting env-vars at runtime via absolute path due to pkg */\n\n  const dotenv = require('dotenv').config({\n    path: dotenvAbsolutePath\n  });\n  if (dotenv.error) {\n    console.log(`ERROR WHILE READING ENV-VARS:${dotenv.error}`);\n    throw dotenv.error;\n  }\n\nmodule.exports = {\n  nodeEnv: process.env.NODE_ENV,\n  nodePort: process.env.NODE_PORT,\n  hostPostgresql: process.env.HOST_POSTGRESQL,\n  portPostgresql: process.env.PORT_POSTGRESQL,\n  dbPostgresql: process.env.DB_POSTGRESQL,\n  userPostgresql: process.env.USER_POSTGRESQL,\n  pwdPostgresql: process.env.PWD_POSTGRESQL,\n};\n```\n\n========================================\n\nComments:\n- I had to read a bit to understand what you have made, but it was very useful and what I needed to understand NestJs better. Worked like a charm. Thanks. I saw that you are one of NestJs contributors. I'm really liking NestJs and intend to use it as my backend of choice from now on. Please transmit my congratulations for this awesome fw to you coleagues on NestJs team. Next step: configuring Passport-jwt with a decent asymetric algorithm :)\n- Yes, I had been using something similar in other projects. But notice that I wanted to know the \"NestJs way\" of doing things :) But thanks anyway.","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":450,"estimatedTokens":2789}}1167{"id":"stack-71172139","source":"stackoverflow","questionId":71172139,"title":"NestJS Mongoose extend Schema and override property of parent","tags":["node.js","typescript","mongodb","mongoose","nestjs"],"text":"Title: NestJS Mongoose extend Schema and override property of parent\nTags: node.js, typescript, mongodb, mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want my **Class B** to extend a **Class A**. This works as expected, but now I need to override a property of Class A in Class B.\n\nTo be specific, I have to make the property from Class A optional for Class B:\n\n```\nexport class B extends A {\n // This property is available in Class A\n @Prop({ required: false, index: true })\n @ApiProperty()\n propertyToOverride: number;\n}\n```\n\n========================================\n\nCode:\n```text\nexport class B extends A {\n  // This property is available in Class A\n  @Prop({ required: false, index: true })\n  @ApiProperty()\n  propertyToOverride: number;\n}\n```\n\n========================================\n\nComments:\n- I'm having the same issue, trying to make a field that has unique constraint in the parent class, not unique in the child, but it doesn't work. The `Prop` decorator options doesn't get overridden in the child, it still creates a unique index even if setting `unique: false` :(\n- I ended up using the Mongoose Discrimnator (link see here). I fixed the unique problem by setting the property in the parent class to optional and then setting the property on its Create-DTO to unique. The validations are not on the db, but at least the api is securing it.\n- Thanks for your anwser! I ended up using the discriminator, it works fine :)","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":36,"estimatedTokens":361}}1168{"id":"stack-71736795","source":"stackoverflow","questionId":71736795,"title":"Cannot use TypeOrm in nx-nestjs project: ERR_REQUIRE_ESM","tags":["webpack","nestjs","typeorm","monorepo","nrwl-nx"],"text":"Title: Cannot use TypeOrm in nx-nestjs project: ERR_REQUIRE_ESM\nTags: webpack, nestjs, typeorm, monorepo, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nI am migrating my NestJS-TypeOrm app to a monorepo (NX workspace).\n\nWhenever I try to run the app, I get this error:\n\n```\nC:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16\nreturn originalLoader.apply(this, arguments);\n^\nError [ERR_REQUIRE_ESM]: require() of ES Module C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs not supported.\nInstead change the require of C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs to a dynamic import() which is available in all CommonJS modules.\nat Function.Module._load (C:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16:31)\nat ...\n```\n\nI debugged for hours and tracked the problem down to the \"import\" of my entities to TypeOrm, in AppModule:\n\n```\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({...myConfig, entities: [Foo]}),\n /*...*/\n})\nexport class AppModule {/*...*/}\n```\n\nBut also using `forFeature()` causes the same error:\n\n```\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Foo])],\n /*...*/\n})\nexport class MyFeatureModule {/*...*/}\n```\n\nIt seems like the problem might be caused by nx/webpack creating a single main.js file with all the code, whereas before the dist folder contained all the code files seperately.\n\nPeople suggested using `\"module\": \"commonjs\"` in my tsconfig, or `\"type\": \"module\"` in package.json, but this doesn't do anything :(\n\nAny solution ideas highly appreciated ๐Ÿ™\n\n========================================\n\nCode:\n```js\nC:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16\nreturn originalLoader.apply(this, arguments);\n^\nError [ERR_REQUIRE_ESM]: require() of ES Module C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs not supported.\nInstead change the require of C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs to a dynamic import() which is available in all CommonJS modules.\nat Function.Module._load (C:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16:31)\nat ...\n```\n\n```js\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({...myConfig, entities: [Foo]}),\n    /*...*/\n})\nexport class AppModule {/*...*/}\n```\n\n```js\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([Foo])],\n  /*...*/\n})\nexport class MyFeatureModule {/*...*/}\n```\n\n```text\nforFeature()\n```\n\n```text\n\"module\": \"commonjs\"\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\nrequire()\n```\n\n========================================\n\nComments:\n- Similar issue, that would've probably taken me hours to notice. My problem was that I was importing the `Injectable` decorator from `@angular&#47;core` instead of `@nestjs&#47;common`.\n- my mono repo did not have any project or libs tagged which resulted int the same mistake. one of the libs had a dependency that pointed into an angular service. morale of the story, use the the tag system that Nx provides.","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":792}}1169{"id":"stack-71414932","source":"stackoverflow","questionId":71414932,"title":"Jest doesn't find the route in nestjs","tags":["jestjs","nestjs"],"text":"Title: Jest doesn't find the route in nestjs\nTags: jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm new with nest and jest.\nI'm trying to create a database for each e2e test.\nthe first route is correct, the second one `/api/v1/auth/email/register` is 404 (it works on my code)\n\n```\nimport { Test } from '@nestjs/testing'\nimport * as request from 'supertest'\nimport { AppModule } from './../../src/app.module'\nimport { Connection } from 'mongoose';\nimport {\n TESTER_EMAIL,\n TESTER_PASSWORD,\n MAIL_HOST,\n MAIL_PORT,\n} from '../utils/constants';\nimport { getConnectionToken, MongooseModule } from '@nestjs/mongoose';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { UsersModule } from '../../src/users/users.module';\nimport supertest = require('supertest');\nimport { AuthModule } from '../../src/auth/auth.module';\n\ndescribe('Authentication (e2e)', () => {\n let app: NestExpressApplication;\n const mail = `http://${MAIL_HOST}:${MAIL_PORT}`;\n const newUserName = `Tester${Date.now()}`;\n const newUsername = `E2E.${Date.now()}`;\n const newUserEmail = `User.${Date.now()}@example.com`;\n const newUserPassword = `secret`;\n const apiClient = () => {\n return supertest(app.getHttpServer());\n };\n\n beforeAll(async() => {\n const moduleRef = await Test.createTestingModule({\n imports: [\n MongooseModule.forRoot('mongodb://127.0.0.1:27017', { dbName: 'test' }), // we use Mongoose here, but you can also use TypeORM\n AuthModule,\n UsersModule,\n AppModule,\n\n ],\n }).compile();\n\n app = moduleRef.createNestApplication();\n await app.listen(3001);\n })\n\n beforeEach(async () => {\n\n })\n\n afterAll(async () => {\n await (app.get(getConnectionToken()) as Connection).db.dropDatabase();\n await app.close();\n });\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(200)\n .expect('{\"message\":\"This is a simple example of item returned by your APIs.\"}')\n })\n\n it('Register a default user: /api/v1/auth/email/register (POST)', async () => {\n return request(app.getHttpServer())\n .post('/api/v1/auth/email/register')\n .send({\n \"name\": newUserName,\n \"username\": newUsername,\n \"email\": TESTER_EMAIL,\n \"password\" : TESTER_PASSWORD\n })\n .expect(201);\n });\n\n})\n```\n\nI imported all my modules and I'm sure that the route `POST 'http://127.0.0.1:3001/api/v1/auth/email/register'` exists\n\n========================================\n\nCode:\n```js\nimport { Test } from '@nestjs/testing'\nimport * as request from 'supertest'\nimport { AppModule } from './../../src/app.module'\nimport { Connection } from 'mongoose';\nimport {\n  TESTER_EMAIL,\n  TESTER_PASSWORD,\n  MAIL_HOST,\n  MAIL_PORT,\n} from '../utils/constants';\nimport { getConnectionToken, MongooseModule } from '@nestjs/mongoose';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { UsersModule } from '../../src/users/users.module';\nimport supertest = require('supertest');\nimport { AuthModule } from '../../src/auth/auth.module';\n\ndescribe('Authentication (e2e)', () => {\n  let app: NestExpressApplication;\n  const mail = `http://${MAIL_HOST}:${MAIL_PORT}`;\n  const newUserName = `Tester${Date.now()}`;\n  const newUsername = `E2E.${Date.now()}`;\n  const newUserEmail = `User.${Date.now()}@example.com`;\n  const newUserPassword = `secret`;\n  const apiClient = () => {\n    return supertest(app.getHttpServer());\n  };\n\n  beforeAll(async() => {\n    const moduleRef = await Test.createTestingModule({\n      imports: [\n        MongooseModule.forRoot('mongodb://127.0.0.1:27017', { dbName: 'test' }), // we use Mongoose here, but you can also use TypeORM\n        AuthModule,\n        UsersModule,\n        AppModule,\n\n      ],\n    }).compile();\n\n    app = moduleRef.createNestApplication<NestExpressApplication>();\n    await app.listen(3001);\n  })\n\n  beforeEach(async () => {\n\n  })\n\n  afterAll(async () => {\n    await (app.get(getConnectionToken()) as Connection).db.dropDatabase();\n    await app.close();\n  });\n\n\n  it('/ (GET)', () => {\n    return request(app.getHttpServer())\n      .get('/')\n      .expect(200)\n      .expect('{\"message\":\"This is a simple example of item returned by your APIs.\"}')\n  })\n\n\n  it('Register a default user: /api/v1/auth/email/register (POST)', async () => {\n    return request(app.getHttpServer())\n      .post('/api/v1/auth/email/register')\n      .send({\n        \"name\": newUserName,\n        \"username\": newUsername,\n        \"email\": TESTER_EMAIL,\n        \"password\" : TESTER_PASSWORD\n      })\n      .expect(201);\n  });\n\n\n})\n```\n\n```text\n/api/v1/auth/email/register\n```\n\n```text\nPOST 'http://127.0.0.1:3001/api/v1/auth/email/register'\n```\n\n```js\nbeforeAll(async() => {\n  const moduleRef = await Test.createTestingModule({\n    imports: [\n      MongooseModule.forRoot('mongodb://127.0.0.1:27017', { dbName: 'test' }),\n      AuthModule,\n      UsersModule,\n      AppModule,\n    ],\n  }).compile();\n\n  app = moduleRef.createNestApplication<NestExpressApplication>();\n  app.setGlobalPrefix('/api');\n  app.enableVersioning({\n    type: VersioningType.URI,\n    defaultVersion: '1',\n  });\n  await app.listen(3001);\n});\n```\n\n```text\napp\n```\n\n```text\n'/api/v1/auth/email/register'\n```\n\n```text\n'/auth/email/register'\n```\n\n```text\n/api/v1\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":209,"estimatedTokens":1287}}1170{"id":"stack-69749494","source":"stackoverflow","questionId":69749494,"title":"login and register in nestjs with firebase","tags":["firebase","nestjs"],"text":"Title: login and register in nestjs with firebase\nTags: firebase, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to create Nestjs app which do login and register like frontend, before I write this code in my Nodejs app like this:\n\n```\nconst firebase = require('firebase');\nfirebase.initializeApp(config.firebase);\n\napp.post('/login',(req,res)=>{\n firebase\n .auth()\n .signInWithEmailAndPassword(req.body.email, req.body.password)\n .then((e) => {\n firebase\n .auth()\n .currentUser.getIdToken(true)\n .then((idToken) => { \n res.json({idToken});\n });\n })\n .catch((err) => {\n console.log(err);\n });\n\n});\n```\n\nnow I want use it in Nestjs but I got some errors.\n\nI tried this but not working:\n\n```\nimport * as firebase from 'firebase/app';\nimport * as auth from 'firebase/auth';\nfirebase.initializeApp(clientAccount);\n\nauth.initializeAuth(firebase.getApp());\n@Controller('auth')\nexport class AuthController {\n constructor(private authService: AuthService) {}\n\n @Post('/register')\n registerUser(@Body() body) {\n const { email, password } = body;\n console.log({ email, password });\n auth\n .createUserWithEmailAndPassword(auth.getAuth(), email, password)\n .then(async (user) => {\n return user;\n })\n .catch((err: any) => {\n // res.status(500).send(err);\n throw new BadGatewayException(err);\n });\n }\n```\n\n**createUserWithEmailAndPassword** function takes three arguments but I don't know what's the first argument?\n\nI get this error : BadGatewayException: Firebase: Error (auth/configuration-not-found).\n\n========================================\n\nCode:\n```text\nconst firebase = require('firebase');\nfirebase.initializeApp(config.firebase);\n\napp.post('/login',(req,res)=>{\n    firebase\n        .auth()\n        .signInWithEmailAndPassword(req.body.email, req.body.password)\n        .then((e) => {\n            firebase\n                .auth()\n                .currentUser.getIdToken(true)\n                .then((idToken) => {                    \n                    res.json({idToken});\n                });\n        })\n        .catch((err) => {\n            console.log(err);\n        });\n\n\n});\n```\n\n```text\nimport * as firebase from 'firebase/app';\nimport * as auth from 'firebase/auth';\nfirebase.initializeApp(clientAccount);\n\nauth.initializeAuth(firebase.getApp());\n@Controller('auth')\nexport class AuthController {\n  constructor(private authService: AuthService) {}\n\n  @Post('/register')\n  registerUser(@Body() body) {\n    const { email, password } = body;\n    console.log({ email, password });\n    auth\n      .createUserWithEmailAndPassword(auth.getAuth(), email, password)\n      .then(async (user) => {\n        return user;\n      })\n      .catch((err: any) => {\n        // res.status(500).send(err);\n        throw new BadGatewayException(err);\n      });\n  }\n```\n\n========================================\n\nComments:\n- What Error you get?\n- this error: BadGatewayException: Firebase: Error (auth/configuration-not-found). @Youba\n- check the package name if is the same in config, read this\n- I know that I should have enabled authentication in firebase console, in authentication menu.\n- thanks for reply, but I wrote comment before in question comments","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":125,"estimatedTokens":785}}1171{"id":"stack-68477501","source":"stackoverflow","questionId":68477501,"title":"ApiProperty not reflecting the type of data i want","tags":["nestjs","nestjs-swagger"],"text":"Title: ApiProperty not reflecting the type of data i want\nTags: nestjs, nestjs-swagger\nSource: Stack Overflow\n\nQuestion:\nI'm creating a POST endpoint that will receive an object with one property: returnIds. This return ids will be an array of NUMBERS\n\n```\n{\n \"returnIds\": [1, 2, 3, 4, 5]\n}\n```\n\nFor this i create this DTO\n\n```\n@ApiProperty() \n returnIds: number[]\n```\n\nThe problem is that swagger is showing me this\n\nhttps://i.sstatic.net/NjmX5.png\n\nwhat i need to change that the shown example is instead \"string\" a 0 or something related with a number?\n\nThis is my endpoint\n\nhttps://i.sstatic.net/t8TZL.png\n\nThank u a lot\n\n========================================\n\nCode:\n```text\n{\n  \"returnIds\": [1, 2, 3, 4, 5]\n}\n```\n\n```text\n@ApiProperty()  \n returnIds: number[]\n```\n\n```text\n@ApiProperty({ type: [Number] })\n```\n\n========================================\n\nComments:\n- Thank u for the answer Jay. But i need to the answer be { returnIds:[NUMBERS] }\n- Nevermind, i read wrong. That was the answer. Thank u a lot and sorry for the dumb question. I forgot something very basic","metadata":{"transformedAt":"2026-08-18T18:33:02.580Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":55,"estimatedTokens":270}}1172{"id":"stack-68104807","source":"stackoverflow","questionId":68104807,"title":"How to correctly deploy/setup NestJS backend using Nginx?","tags":["angular","nginx","nestjs","nginx-config","nginx-location"],"text":"Title: How to correctly deploy/setup NestJS backend using Nginx?\nTags: angular, nginx, nestjs, nginx-config, nginx-location\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy my webapplication using Angular and NestJs using Nginx on an Ubuntu remote server.\nI got the frontend working on https://ikse.fransenit.nl/products but cannot get the backend to work. It was working fine locally. When I try to go to /api/products I get a 502 bad gateway.\n\nWhen starting the NestJS backend:\nhttps://i.sstatic.net/McHIH.png\n\n### nginx config\n\n```\nserver {\n listen 80 default_server;\n listen [::]:80 default_server;\n\n root /var/www/ikse/html;\n\n server_name ikse.fransenit.nl www.ikse.fransenit.nl;\n \n index index.html index.htm;\n\n location / {\n # First attempt to serve request as file, then\n # as directory, then fall back to displaying a 404.\n try_files $uri $uri/ /index.html;\n # proxy_pass http://localhost:8080;\n # proxy_http_version 1.1;\n # proxy_set_header Upgrade $http_upgrade;\n # proxy_set_header Connection 'upgrade';\n # proxy_set_header Host $host;\n # proxy_cache_bypass $http_upgrade;\n }\n\n location /api/ {\n proxy_pass https://localhost:3000;\n }\n\n listen [::]:443 ssl; # managed by Certbot\n listen 443 ssl; # managed by Certbot\n ssl_certificate /etc/letsencrypt/live/ikse.fransenit.nl/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/ikse.fransenit.nl/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n}\n```\n\nWhat am I missing and/or doing wrong?\n\n========================================\n\nCode:\n```text\nserver {\n    listen 80 default_server;\n    listen [::]:80 default_server;\n\n    root /var/www/ikse/html;\n\n    server_name ikse.fransenit.nl www.ikse.fransenit.nl;\n    \n    index index.html index.htm;\n\n        location / {\n                # First attempt to serve request as file, then\n                # as directory, then fall back to displaying a 404.\n                try_files $uri $uri/ /index.html;\n                # proxy_pass http://localhost:8080;\n                # proxy_http_version 1.1;\n                # proxy_set_header Upgrade $http_upgrade;\n                # proxy_set_header Connection 'upgrade';\n                # proxy_set_header Host $host;\n                # proxy_cache_bypass $http_upgrade;\n        }\n\n        location /api/ {\n            proxy_pass https://localhost:3000;\n        }\n\n    listen [::]:443 ssl; # managed by Certbot\n    listen 443 ssl; # managed by Certbot\n    ssl_certificate /etc/letsencrypt/live/ikse.fransenit.nl/fullchain.pem; # managed by Certbot\n    ssl_certificate_key /etc/letsencrypt/live/ikse.fransenit.nl/privkey.pem; # managed by Certbot\n    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n}\n```\n\n```text\n/api/\n```\n\n```text\nhttps://localhost:3000\n```\n\n```text\nproxy_pass\n```\n\n```text\nhttps://doma.in.com/api/api/profile\n```\n\n========================================\n\nComments:\n- can you try and replace localhost with 127.0.0.1 and try again and see if it works? Also change https to http (unless you have https in nodejs server) from the location - /api/ block.\n- I fixed it a while back and this was indeed the answer, thanks though\n- This way static serving (via NestJS) doesn't work, do you've any solution for that @JesseyFransen","metadata":{"transformedAt":"2026-08-18T18:33:02.581Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":112,"estimatedTokens":860}}1173{"id":"stack-68989465","source":"stackoverflow","questionId":68989465,"title":"Problems with ValidationPipe in NestJS when I need to validate the contents of an array","tags":["node.js","typescript","nestjs"],"text":"Title: Problems with ValidationPipe in NestJS when I need to validate the contents of an array\nTags: node.js, typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a situation where my client user can enter zero or multiple addresses. My problem is that if he enters an address, some fields need to be mandatory.\n\n**user.controller.ts**\n\n```\n@Post()\n@UsePipes(ValidationPipe)\nasync createUser(\n @Body() createUser: CreateUserDto,\n) {\n return await this.service.saveUserAndAddress(createUser);\n}\n```\n\n**create-user.dto.ts**\n\n```\nexport class CreateUserDto {\n @IsNotEmpty({ message: 'ERROR_REQUIRED_FULL_NAME' })\n fullName?: string;\n\n @IsNotEmpty({ message: 'ERROR_REQUIRED_PASSWORD' })\n password?: string;\n\n @IsNotEmpty({ message: 'ERROR_REQUIRED_EMAIL' })\n @IsEmail({}, { message: 'ERROR_INVALID_EMAIL' })\n email?: string;\n\n ...\n\n addresses?: CreateUserAddressDto[];\n}\n```\n\n**create-user-address.dto.ts**\n\n```\nexport class CreateUserAddressDto {\n ...\n\n @IsNotEmpty()\n street: string;\n\n ...\n}\n```\n\n`CreateUserDto` data is validated correctly and generates `InternalServerErrorResponse`, but `CreateUserAddressDto` data is not validated when there is some item in my array. Any idea how I can do this validation?\n\n========================================\n\nTop Answer:\nWhat you are trying to do is - to basically add logic to primitive validators provided out of the box with nest - aka - defining a custom validator.\n\nThis can be done by using the two classes `ValidatorConstraint` and `ValidatorConstraintInterface` provided by the class validator.\n\nIn order to sort this, transform the incoming input / club whatever data you want to validate at once into an object - either using a pipe in nestjs or sent it as an object in the API call itself, then attach a validator on top of it.\n\n### To define a custom validator:\n\n```\nimport { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';\n\n/**\n * declare your custom validator here\n */\n@ValidatorConstraint({ name: 'MyValidator', async: false })\nexport class MyValidator implements ValidatorConstraintInterface {\n \n /** return true when tests pass **/\n validate(incomingObject: myIncomingDataInterface) {\n try {\n // your logic regarding what all is required in the object\n const output = someLogic(incomingObject);\n return output;\n } catch (e) {\n return false;\n }\n }\n\n defaultMessage() {\n return 'Address update needs ... xyz';\n }\n}\n```\n\nOnce you have defined this, keep this safe somewhere as per your project structure. Now you just need to call it whenever you want to put this validation.\n\n**In the data transfer object**,\n\n```\n// import the validator\nimport { Validate } from 'class-validator';\nimport { MyValidator } from './../some/safe/place'\n\nexport class SomeDto{\n @ApiProperty({...})\n @Validate(MyValidator)\n thisBecomesIncomingObjectInFunction: string;\n}\n```\n\nAs simple as that.\n\n========================================\n\nCode:\n```text\n@Post()\n@UsePipes(ValidationPipe)\nasync createUser(\n    @Body() createUser: CreateUserDto,\n) {\n    return await this.service.saveUserAndAddress(createUser);\n}\n```\n\n```text\nexport class CreateUserDto {\n    @IsNotEmpty({ message: 'ERROR_REQUIRED_FULL_NAME' })\n    fullName?: string;\n\n    @IsNotEmpty({ message: 'ERROR_REQUIRED_PASSWORD' })\n    password?: string;\n\n    @IsNotEmpty({ message: 'ERROR_REQUIRED_EMAIL' })\n    @IsEmail({}, { message: 'ERROR_INVALID_EMAIL' })\n    email?: string;\n\n    ...\n\n    addresses?: CreateUserAddressDto[];\n}\n```\n\n```text\nexport class CreateUserAddressDto {\n    ...\n\n    @IsNotEmpty()\n    street: string;\n\n    ...\n}\n```\n\n```text\nCreateUserDto\n```\n\n```text\nInternalServerErrorResponse\n```\n\n```text\nCreateUserAddressDto\n```\n\n```text\nimport { Type } from 'class-transformer';\nimport { ..., ValidateNested } from 'class-validator';\n\nexport class CreateUserAddressDto {\n    ...\n\n\n    @ValidateNested({ each: true })\n    @Type(() => CreateUserAddressDto)\n    addresses?: CreateUserAddressDto[];\n\n    ...\n}\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\nCreateUserDto\n```\n\n```js\nimport { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';\n\n\n/**\n * declare your custom validator here\n */\n@ValidatorConstraint({ name: 'MyValidator', async: false })\nexport class MyValidator implements ValidatorConstraintInterface {\n  \n   /** return true when tests pass **/\n   validate(incomingObject: myIncomingDataInterface) {\n    try {\n     // your logic regarding what all is required in the object\n     const output = someLogic(incomingObject);\n     return output;\n    } catch (e) {\n      return false;\n    }\n  }\n\n  defaultMessage() {\n    return 'Address update needs ... xyz';\n  }\n}\n```\n\n```js\n// import the validator\nimport { Validate } from 'class-validator';\nimport { MyValidator } from './../some/safe/place'\n\nexport class SomeDto{\n    @ApiProperty({...})\n    @Validate(MyValidator)\n    thisBecomesIncomingObjectInFunction: string;\n}\n```\n\n```text\nValidatorConstraint\n```\n\n```text\nValidatorConstraintInterface\n```\n\n========================================\n\nComments:\n- Perfect! Thanks :)","metadata":{"transformedAt":"2026-08-18T18:33:02.581Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":242,"estimatedTokens":1270}}1174{"id":"stack-67848830","source":"stackoverflow","questionId":67848830,"title":"How to write down nested schemas for mongoose using NestJS nomenclature","tags":["javascript","typescript","mongodb","schema","nestjs"],"text":"Title: How to write down nested schemas for mongoose using NestJS nomenclature\nTags: javascript, typescript, mongodb, schema, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am learning NestJS, and Mongoose. I was wondering how to write down/code nested schemas in Mongoose using NextJS nomenclature.\n\nIncoming data structure looks like this -\n\n```\n{\n something: {\n info: {\n title: string,\n score: number,\n description: string,\n time: string,\n DateOfCreation: string\n },\n Store: {\n item: {\n question: string,\n options: {\n item: {\n answer: string,\n description: string,\n id: string,\n key: string,\n option: string\n }\n }\n }\n }\n }\n}\n```\n\n**Challenge: writing down that using NestJS internal APIs.**\n\nI am using NestJS and Mongoose. I want to write a schema for the data structure given above. ***I can't find examples for nested schemas***. Any insigth is welcome.\n\nI am a beginner in all NestJS, Mongoose and MongoDB. So please don't assume that I know something. Thus, any insight on Mongoose as well is welcome.\n\nThanks a lot.\n\nEdit - Here's something I came up with after following this SO post - Mongoose Subdocuments in Nest.js . But I am just throwing stones in the dark.\n\n```\nimport { Prop, Schema, SchemaFactory } from \"@nestjs/mongoose\";\n\n@Schema()\nexport class Cat {\n @Prop()\n name: string\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n\n@Schema()\nclass testInfo {\n @Prop()\n title: string;\n @Prop()\n score: number;\n @Prop()\n description: string;\n @Prop()\n time: string;\n @Prop()\n DateOfCreation: string;\n}\n\nconst testInfoSchema = SchemaFactory.createForClass(testInfo);\n\n@Schema()\nclass OptionContent {\n @Prop()\n answer: string;\n @Prop()\n description: string;\n @Prop()\n id: string;\n @Prop()\n key: string;\n @Prop()\n option: string\n}\nconst OptionContentSchema = SchemaFactory.createForClass(OptionContent);\n\n@Schema({ strict: false })\nclass Option {\n @Prop({ type: OptionContentSchema })\n item: OptionContent;\n}\n\nconst OptionSchema = SchemaFactory.createForClass(Option);\n\n@Schema({ strict: false })\nclass Page {\n @Prop()\n question: string;\n @Prop({ type: OptionSchema })\n options: Option;\n}\n\nconst PageSchema = SchemaFactory.createForClass(Page);\n\n@Schema({ strict: false })\nclass McqStore {\n @Prop({ type: PageSchema })\n item: Page;\n}\n\nconst McqStoreSchema = SchemaFactory.createForClass(McqStore);\n\n@Schema()\nexport class Test {\n @Prop({ type: testInfoSchema })\n info: testInfo\n\n @Prop({ type: McqStoreSchema })\n McqStore: McqStore\n}\n\nconst TestSchema = SchemaFactory.createForClass(Test);\n\n@Schema()\nexport class TestContainer {\n @Prop({ type: TestSchema })\n name: Test\n}\n\nexport const TestContainerSchema = SchemaFactory.createForClass(TestContainer);\n\nexport type userDocument = TestContainer & Document;\n```\n\n========================================\n\nCode:\n```text\n{\n    something: {\n        info: {\n            title: string,\n            score: number,\n            description: string,\n            time: string,\n            DateOfCreation: string\n        },\n        Store: {\n            item: {\n                question: string,\n                options: {\n                    item: {\n                        answer: string,\n                        description: string,\n                        id: string,\n                        key: string,\n                        option: string\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from \"@nestjs/mongoose\";\n\n@Schema()\nexport class Cat {\n    @Prop()\n    name: string\n}\n\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n\n\n@Schema()\nclass testInfo {\n    @Prop()\n    title: string;\n    @Prop()\n    score: number;\n    @Prop()\n    description: string;\n    @Prop()\n    time: string;\n    @Prop()\n    DateOfCreation: string;\n}\n\nconst testInfoSchema = SchemaFactory.createForClass(testInfo);\n\n@Schema()\nclass OptionContent {\n    @Prop()\n    answer: string;\n    @Prop()\n    description: string;\n    @Prop()\n    id: string;\n    @Prop()\n    key: string;\n    @Prop()\n    option: string\n}\nconst OptionContentSchema = SchemaFactory.createForClass(OptionContent);\n\n@Schema({ strict: false })\nclass Option {\n    @Prop({ type: OptionContentSchema })\n    item: OptionContent;\n}\n\nconst OptionSchema = SchemaFactory.createForClass(Option);\n\n@Schema({ strict: false })\nclass Page {\n    @Prop()\n    question: string;\n    @Prop({ type: OptionSchema })\n    options: Option;\n}\n\nconst PageSchema = SchemaFactory.createForClass(Page);\n\n@Schema({ strict: false })\nclass McqStore {\n    @Prop({ type: PageSchema })\n    item: Page;\n}\n\nconst McqStoreSchema = SchemaFactory.createForClass(McqStore);\n\n@Schema()\nexport class Test {\n    @Prop({ type: testInfoSchema })\n    info: testInfo\n\n    @Prop({ type: McqStoreSchema })\n    McqStore: McqStore\n}\n\nconst TestSchema = SchemaFactory.createForClass(Test);\n\n@Schema()\nexport class TestContainer {\n    @Prop({ type: TestSchema })\n    name: Test\n}\n\nexport const TestContainerSchema = SchemaFactory.createForClass(TestContainer);\n\nexport type userDocument = TestContainer & Document;\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\n\nexport type CatDocument = Cat & Document;\n\n\n@Schema()\nexport class Owners {\n  @Prop()\n  names: [string];\n}\n\n@Schema()\nexport class Cat {\n  @Prop()\n  name: string;\n\n  @Prop()\n  age: number;\n\n  @Prop()\n  breed: string;\n\n  @Prop()\n  owners: Owners;//schema for owner\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\n```text\nimport { Prop, Schema, SchemaFactory } from \"@nestjs/mongoose\";\nimport { Document } from \"mongoose\";\n\n@Schema()\nclass testInfo {\n    @Prop()\n    title: string;\n    @Prop()\n    score: number;\n    @Prop()\n    description: string;\n    @Prop()\n    time: string;\n    @Prop()\n    dateOfCreation: string;\n}\n\n@Schema()\nclass OptionContent {\n    @Prop()\n    answer: string;\n    @Prop()\n    description: string;\n    @Prop()\n    id: string;\n    @Prop()\n    key: string;\n    @Prop()\n    option: string\n}\n\n@Schema()\nclass Option {\n    @Prop()\n    option: OptionContent;\n}\n\n@Schema()\nclass Page {\n    @Prop()\n    question: string;\n    @Prop()\n    options: Option;\n}\n\n@Schema()\nclass McqStore {\n    @Prop()\n    page: Page;\n}\n\n@Schema()\nexport class Test {\n    @Prop()\n    info: testInfo\n\n    @Prop()\n    McqStore: McqStore\n}\n\n@Schema()\nexport class TestContainer {\n    @Prop({ type: Map })\n    name: Test\n}\n\nexport const TestContainerSchema = SchemaFactory.createForClass(TestContainer);\n\nexport type userDocument = Test & Document;\n```\n\n```text\npopulate\n```\n\n========================================\n\nComments:\n- Does this answer your question? create object parent which nested children in mongoose\n- I am sorry it doesn't. Although it's possible to write things using mongoose in NestJS, I want to write the schema in NestJS way. I can't find any examples for that particular problem.\n- Perfect answer! Marking this as correct answer.\n- glad to help, it is pricely when we can help! ๐Ÿ™ƒ๐Ÿ™ƒ\n- Hi! @Jorge Guerra Pires. Although your answer helped me a lot, I made some changes to fit the answer for my own needs. I am waiting this topic to open again so that I can post my code in the answers for future readers.\n- Glad I helped, I edited it, as so it can reopen. No idea if they will reopen. I am thinking to create a video on my channel, loved your question! Please, send me the final answer to jorgeguerrapires@yahoo.com.br\n- my channel: youtube.com/channel/UCFtxji3SCiowhynu_OVhcsA/videos\n- This solution creates an _id for the nested document. This is something I was trying to avoid while looking for an answer using mixed types (plain objects) in NestJS schemas. One way to avoid it is to add {_id: false} to the @Schema() decorator -> @Schema({_id: false}). That will avoid creating an _id only for the current level. Any additional nested schemas will generate an _id for their level.","metadata":{"transformedAt":"2026-08-18T18:33:02.581Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":378,"estimatedTokens":1971}}1175{"id":"stack-67521900","source":"stackoverflow","questionId":67521900,"title":"Connection \"default\" was not found with NestJS Unit Testing of Service","tags":["typescript","unit-testing","mocking","nestjs","typeorm"],"text":"Title: Connection \"default\" was not found with NestJS Unit Testing of Service\nTags: typescript, unit-testing, mocking, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am currently unit testing my NestJS service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.\n\nWhile I was able to mock the `Repository` that is used in the Service, I was unable to establish a mock `getConnection` in a method that had to call `getConection()`.\n\nWhen I tried unit testing with `npm run test:watch`, I get the error that `ConnectionNotFoundError: Connection \"default\" was not found.` I have looked into (and in fact, taken much from) How to stub EntityManager and Connection in TypeORM with Jest, but this post does not seem to elaborate on a connection that was not established, which is my problem.\n\nIn any case, here's my service with the relevant parts:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { getConnection, Repository } from \"typeorm\";\nimport {User} from '../entities/user.entity';\n\n@Injectable()\nexport class ServiceName {\n constructor(@InjectRepository(User) private usersRepository: Repository) {}\n\n // Creating and inserting a new user into the database table using Repository\n // unit testing for this one works fine\n async createUserRepository(user: User): Promise {\n const newUser = this.usersRepository.create(user); \n return await this.usersRepository.save(newUser);\n }\n\n // Creating and inserting a new user into the database table using QueryBuilder and getConnection\n // unit testing for this one does not work so well \n async createUserQueryBuilder(user: User): Promise {\n await getConnection()\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n user, \n ])\n .execute();\n return user; \n }\n```\n\nAnd here's my spec.ts file for unit testing:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { ServiceName } from './app_codes_rms_area.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from '../entities/user.entity';\nimport { Connection, Repository } from 'typeorm';\n\ndescribe('service tests', () => {\n\n const repositoryMockFactory: () => MockType> = jest.fn(() => ({ \n create: jest.fn(),\n save: jest.fn(),\n // other functions\n }));\n\n const mockConnectionFactory = jest.fn(() => ({\n getConnection: jest.fn().mockReturnValue({\n createQueryBuilder: jest.fn().mockReturnThis(),\n getMany: jest.fn().mockReturnValue(allUsers),\n insert: jest.fn().mockReturnThis(),\n into: jest.fn().mockReturnThis(),\n values: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnValue(user),\n })\n }));\n \n let service: ServiceName;\n let mockRepository: MockType>;\n let mockConnection: Connection;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n ServiceName,\n {\n provide: getRepositoryToken(User), // a User Repository is injected to the service \n useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test\n },\n {\n provide: Connection,\n useFactory: mockConnectionFactory,\n }\n ],\n }).compile();\n\n service = module.get(ServiceName);\n mockRepository = module.get(getRepositoryToken(User));\n mockConnection = module.get(Connection);\n });\n it('should create a new user and return it using Repository', async () => {\n // some test that passes using mockRepository\n });\n\n it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () => {\n expect(await service.createUserQueryBuilder(user)).toEqual(user);\n expect(mockConnection.createQueryBuilder).toBeCalled();\n expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['into']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['values']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();\n })\n```\n\nIt is the second test, `it('should create a new user and return it using QueryBuilder (with mocked Connection)'`, that triggers the following error:\n\n```\nโ— service tests โ€บ Service Functions โ€บ should create a new user and return it using QueryBuilder (with mocked Connection)\n\n ConnectionNotFoundError: Connection \"default\" was not found.\n\n at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n at ConnectionManager.Object..ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n at Object.getConnection (index.ts:252:35)\n at ServiceName.createUserQueryBuilder (somefile:19:11)\n at Object.it (somefile:134:34)\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { getConnection, Repository } from \"typeorm\";\nimport {User} from '../entities/user.entity';\n\n\n@Injectable()\nexport class ServiceName {\n  constructor(@InjectRepository(User) private usersRepository: Repository<User>) {}\n\n  // Creating and inserting a new user into the database table using Repository\n  // unit testing for this one works fine\n  async createUserRepository(user: User): Promise<User> {\n    const newUser = this.usersRepository.create(user); \n    return await this.usersRepository.save(newUser);\n  }\n\n  // Creating and inserting a new user into the database table using QueryBuilder and getConnection\n  // unit testing for this one does not work so well \n  async createUserQueryBuilder(user: User): Promise<User> {\n    await getConnection()\n    .createQueryBuilder()\n    .insert()\n    .into(User)\n    .values([\n        user, \n     ])\n    .execute();\n    return user;  \n  }\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { ServiceName } from './app_codes_rms_area.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from '../entities/user.entity';\nimport { Connection, Repository } from 'typeorm';\n\ndescribe('service tests', () => {\n\n    const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({ \n        create: jest.fn(),\n        save: jest.fn(),\n        // other functions\n    }));\n\n    const mockConnectionFactory = jest.fn(() => ({\n        getConnection: jest.fn().mockReturnValue({\n            createQueryBuilder: jest.fn().mockReturnThis(),\n            getMany: jest.fn().mockReturnValue(allUsers),\n            insert: jest.fn().mockReturnThis(),\n            into: jest.fn().mockReturnThis(),\n            values: jest.fn().mockReturnThis(),\n            execute: jest.fn().mockReturnValue(user),\n        })\n    }));\n \n    let service: ServiceName;\n    let mockRepository: MockType<Repository<User>>;\n    let mockConnection: Connection;\n\n    beforeEach(async () => {\n        const module: TestingModule = await Test.createTestingModule({\n            providers: [\n                ServiceName,\n                {\n                    provide: getRepositoryToken(User), // a User Repository is injected to the service \n                    useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test\n                },\n                {\n                    provide: Connection,\n                    useFactory: mockConnectionFactory,\n                }\n            ],\n        }).compile();\n\n        service = module.get<ServiceName>(ServiceName);\n        mockRepository = module.get(getRepositoryToken(User));\n        mockConnection = module.get<Connection>(Connection);\n    });\n        it('should create a new user and return it using Repository', async () => {\n            // some test that passes using mockRepository\n        });\n\n        it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () => {\n            expect(await service.createUserQueryBuilder(user)).toEqual(user);\n            expect(mockConnection.createQueryBuilder).toBeCalled();\n            expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();\n            expect(mockConnection.createQueryBuilder()['into']).toBeCalled();\n            expect(mockConnection.createQueryBuilder()['values']).toBeCalled();\n            expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();\n        })\n```\n\n```text\nโ— service tests โ€บ Service Functions โ€บ should create a new user and return it using QueryBuilder (with mocked Connection)\n\n    ConnectionNotFoundError: Connection \"default\" was not found.\n\n      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n      at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n      at Object.getConnection (index.ts:252:35)\n      at ServiceName.createUserQueryBuilder (somefile:19:11)\n      at Object.it (somefile:134:34)\n```\n\n```text\nRepository\n```\n\n```text\ngetConnection\n```\n\n```text\ngetConection()\n```\n\n```text\nnpm run test:watch\n```\n\n```text\nConnectionNotFoundError: Connection \"default\" was not found.\n```\n\n```text\nit('should create a new user and return it using QueryBuilder (with mocked Connection)'\n```\n\n```js\nasync createUserQueryBuilder(user: User): Promise<User> {\n  await this.usersRepository\n    .createQueryBuilder()\n    .insert()\n    .into(User)\n    .values([\n        user, \n     ])\n    .execute();\n  return user;  \n}\n```\n\n```js\nconst repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({ \n  create: jest.fn(),\n  save: jest.fn(),\n  createQueryBuilder: jest.fn().mockReturnThis(),\n  getMany: jest.fn().mockReturnValue(allUsers),\n  insert: jest.fn().mockReturnThis(),\n  into: jest.fn().mockReturnThis(),\n  values: jest.fn().mockReturnThis(),\n  execute: jest.fn().mockReturnValue(user),\n}));\n```\n\n```js\nimport * as typeorm from 'typeorm';\n\nconst getConnectionSpy = jest.spyOn(typeorm, 'getConnection');\ngetConnectionSpy.mockImplementation(() => ({\n  createQueryBuilder: jest.fn().mockReturnThis(),\n  getMany: jest.fn().mockReturnValue(allUsers),\n  insert: jest.fn().mockReturnThis(),\n  into: jest.fn().mockReturnThis(),\n  values: jest.fn().mockReturnThis(),\n  execute: jest.fn().mockReturnValue(user),\n}));\n```\n\n```text\ncreateUserQueryBuilder\n```\n\n```text\nrepositoryMockFactory\n```\n\n```text\nspec.ts\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm.Connection\n```\n\n========================================\n\nComments:\n- Thank you for your answer! Indeed, this seems to work; but I would really like to stick to using `getConnection()`. (Really, it is for practice; my new role involves NestJS). Do you have any suggestions for mocking getConnection? I've found a way where I use `@InjectConnection() private connection: Connection` in my service and combine it with `{provide: Connection, useFactory: mockConnectionFactory, }` in my spec.ts file (and it works), but here I'm mocking an injected connection, NOT the getConnection that is imported. It'd be really nice if I could mock the imported getConnection.\n- I updated my answer though I can not guarantee that it would work. Good luck with your new role! ๐Ÿป\n- Uhmm, still not; but thanks for the answer! I feel like I have some tweaking to do here and there, perhaps...\n- Edit: I adapted your approach to a simpler example where I'm using `getManager()` followed by `delete` a single function and it worked! I'm pretty sure that some further tweaking is necessary to make the chain of functions in `createQueryBuilder` to work (it's probably much more complicated...). Thanks again!\n- Wow, great. Glad I could help ๐Ÿป","metadata":{"transformedAt":"2026-08-18T18:33:02.583Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":328,"estimatedTokens":2863}}1176{"id":"stack-63207240","source":"stackoverflow","questionId":63207240,"title":"Nest can't resolve dependencies of the JwtStrategy","tags":["nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of the JwtStrategy\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am a newbie in NestJs world. As far as I know, I imported everything needed in the JwtStrategy. I don't know where it went wrong. Can somebody help me with this?\n\nAs far as I referred to documetation, Whenever we want to use any entity in a module, we should import that entity in the imports field in the @Module() decorator. I did it.\n\n**jwt.strategy.ts**\n\n```\nimport { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy, ExtractJwt } from \"passport-jwt\";\nimport { InjectRepository } from \"@nestjs/typeorm\";\nimport { Repository } from \"typeorm\";\nimport { UserEntity } from \"src/entities/user.entity\";\nimport { AuthPayload } from \"src/common/dtos/user.dto\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n @InjectRepository(UserEntity)\n private userRepo: Repository\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.SECRETKEY\n });\n }\n\n async validate(payload: AuthPayload): Promise {\n const { username } = payload;\n const user = this.userRepo.findOne({ where: { username: username } });\n if(!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\n**auth.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserEntity } from 'src/entities/user.entity';\nimport { JwtModule } from '@nestjs/jwt';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n JwtModule.register({\n secret: process.env.SECRETKEY,\n }),\n PassportModule.register({\n defaultStrategy: 'jwt'\n })\n ],\n providers: [AuthService, JwtStrategy],\n controllers: [AuthController],\n exports: [PassportModule, JwtStrategy]\n})\nexport class AuthModule {}\n```\n\n**user.entity.ts**\n\n```\nimport { Entity, Column, OneToMany, JoinTable, BeforeInsert } from \"typeorm\";\nimport { AbstractEntity } from \"./abstract-entity.abstract\";\nimport { IsEmail } from \"class-validator\";\nimport { Exclude, classToPlain } from \"class-transformer\";\nimport * as bcrypt from \"bcryptjs\";\nimport { CategoryEntity } from \"./category.entity\";\nimport { ArticleEntity } from \"./article.entity\";\n\n@Entity('User')\nexport class UserEntity extends AbstractEntity {\n @Column({\n type: \"varchar\",\n length: 80\n })\n fullName: string;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n @IsEmail()\n email: string;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n username: string;\n\n @Column({\n type: \"varchar\"\n })\n @Exclude()\n password: string;\n\n @Column({\n default: null,\n nullable: true\n })\n avatar: string | null;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n phoneNumber: string;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isAdmin: boolean;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isStaff: boolean;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isEmailVerified: boolean;\n\n @OneToMany(type => CategoryEntity, category => category.createdBy)\n @JoinTable()\n categories: CategoryEntity[];\n\n @OneToMany(type => ArticleEntity, article => article.createdBy)\n @JoinTable()\n articles: ArticleEntity[];\n\n @BeforeInsert()\n async hashPassword() {\n this.password = await bcrypt.hash(this.password, 10);\n }\n\n async comparePassword(attempt: string): Promise {\n return await bcrypt.compare(attempt, this.password);\n }\n\n toJSON(): any {\n return classToPlain(this);\n }\n}\n```\n\n**app.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from \"@nestjs/typeorm\";\nimport { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';\nimport { \n DatabaseConnectionService\n } from \"./utils/database-connection.service\";\nimport { AuthModule } from './auth/auth.module';\nimport { UsersModule } from './users/users.module';\nimport { ArticlesModule } from './articles/articles.module';\nimport { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';\nimport { ResponseInterceptor } from './common/interceptors/response.interceptor';\nimport { CategoryModule } from './category/category.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useClass: DatabaseConnectionService\n }),\n AuthModule,\n UsersModule,\n ArticlesModule,\n CategoryModule,\n ],\n controllers: [AppController],\n providers: [\n // {\n // provide: APP_INTERCEPTOR,\n // useClass: ResponseInterceptor\n // },\n {\n provide: APP_FILTER,\n useClass: HttpExceptionFilter\n },\n AppService\n ],\n})\nexport class AppModule {}\n```\n\n**database-connection.service.ts**\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { TypeOrmOptionsFactory, TypeOrmModuleOptions } from \"@nestjs/typeorm\";\nimport { truncate } from \"fs\";\n\n@Injectable()\nexport class DatabaseConnectionService implements TypeOrmOptionsFactory {\n createTypeOrmOptions(): TypeOrmModuleOptions {\n return {\n type: \"mysql\",\n host: process.env.HOST,\n port: parseInt(process.env.PORT),\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DATABASE, \n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n dropSchema: true,\n autoLoadEntities: true,\n logger: \"simple-console\"\n };\n }\n}\n```\n\nThe Error is as follows:\nhttps://i.sstatic.net/thZbI.jpg\n\n========================================\n\nTop Answer:\nConsider to move to Active Record pattern. All what you need to do is just to let your `AbstractEntity` extends `BaseEntity` of TypeOrm.\n\nYou can remove all typeorm features imports like:\n\n```\nTypeOrmModule.forFeature([UserEntity])\n```\n\nand all dependency injections for repository like:\n\n```\n@InjectRepository(UserEntity)\nprivate userRepo: Repository\n```\n\nJust use the entity class for querying:\n\n```\nconst user = await UserEntity.findOne({ where: { username } });\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy, ExtractJwt } from \"passport-jwt\";\nimport { InjectRepository } from \"@nestjs/typeorm\";\nimport { Repository } from \"typeorm\";\nimport { UserEntity } from \"src/entities/user.entity\";\nimport { AuthPayload } from \"src/common/dtos/user.dto\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n    constructor(\n        @InjectRepository(UserEntity)\n        private userRepo: Repository<UserEntity>\n    ) {\n        super({\n            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n            secretOrKey: process.env.SECRETKEY\n        });\n    }\n\n    async validate(payload: AuthPayload): Promise<UserEntity> {\n        const { username } = payload;\n        const user = this.userRepo.findOne({ where: { username: username } });\n        if(!user) {\n            throw new UnauthorizedException();\n        }\n        return user;\n    }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserEntity } from 'src/entities/user.entity';\nimport { JwtModule } from '@nestjs/jwt';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([UserEntity]),\n    JwtModule.register({\n      secret: process.env.SECRETKEY,\n    }),\n    PassportModule.register({\n      defaultStrategy: 'jwt'\n    })\n  ],\n  providers: [AuthService, JwtStrategy],\n  controllers: [AuthController],\n  exports: [PassportModule, JwtStrategy]\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Entity, Column, OneToMany, JoinTable, BeforeInsert } from \"typeorm\";\nimport { AbstractEntity } from \"./abstract-entity.abstract\";\nimport { IsEmail } from \"class-validator\";\nimport { Exclude, classToPlain } from \"class-transformer\";\nimport * as bcrypt from \"bcryptjs\";\nimport { CategoryEntity } from \"./category.entity\";\nimport { ArticleEntity } from \"./article.entity\";\n\n@Entity('User')\nexport class UserEntity extends AbstractEntity {\n    @Column({\n        type: \"varchar\",\n        length: 80\n    })\n    fullName: string;\n\n    @Column({\n        type: \"varchar\",\n        unique: true\n    })\n    @IsEmail()\n    email: string;\n\n    @Column({\n        type: \"varchar\",\n        unique: true\n    })\n    username: string;\n\n    @Column({\n        type: \"varchar\"\n    })\n    @Exclude()\n    password: string;\n\n    @Column({\n        default: null,\n        nullable: true\n    })\n    avatar: string | null;\n\n    @Column({\n        type: \"varchar\",\n        unique: true\n    })\n    phoneNumber: string;\n\n    @Column({\n        type: \"boolean\",\n        default: false\n    })\n    isAdmin: boolean;\n\n    @Column({\n        type: \"boolean\",\n        default: false\n    })\n    isStaff: boolean;\n\n    @Column({\n        type: \"boolean\",\n        default: false\n    })\n    isEmailVerified: boolean;\n\n    @OneToMany(type => CategoryEntity, category => category.createdBy)\n    @JoinTable()\n    categories: CategoryEntity[];\n\n    @OneToMany(type => ArticleEntity, article => article.createdBy)\n    @JoinTable()\n    articles: ArticleEntity[];\n\n    @BeforeInsert()\n    async hashPassword() {\n        this.password = await bcrypt.hash(this.password, 10);\n    }\n\n    async comparePassword(attempt: string): Promise<boolean> {\n        return await bcrypt.compare(attempt, this.password);\n    }\n\n    toJSON(): any {\n        return classToPlain(this);\n    }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from \"@nestjs/typeorm\";\nimport { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';\nimport { \n  DatabaseConnectionService\n } from \"./utils/database-connection.service\";\nimport { AuthModule } from './auth/auth.module';\nimport { UsersModule } from './users/users.module';\nimport { ArticlesModule } from './articles/articles.module';\nimport { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';\nimport { ResponseInterceptor } from './common/interceptors/response.interceptor';\nimport { CategoryModule } from './category/category.module';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRootAsync({\n      useClass: DatabaseConnectionService\n    }),\n    AuthModule,\n    UsersModule,\n    ArticlesModule,\n    CategoryModule,\n  ],\n  controllers: [AppController],\n  providers: [\n    // {\n    //   provide: APP_INTERCEPTOR,\n    //   useClass: ResponseInterceptor\n    // },\n    {\n      provide: APP_FILTER,\n      useClass: HttpExceptionFilter\n    },\n    AppService\n  ],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Injectable } from \"@nestjs/common\";\nimport { TypeOrmOptionsFactory, TypeOrmModuleOptions } from \"@nestjs/typeorm\";\nimport { truncate } from \"fs\";\n\n@Injectable()\nexport class DatabaseConnectionService implements TypeOrmOptionsFactory {\n    createTypeOrmOptions(): TypeOrmModuleOptions {\n        return {\n            type: \"mysql\",\n            host: process.env.HOST,\n            port: parseInt(process.env.PORT),\n            username: process.env.DB_USERNAME,\n            password: process.env.DB_PASSWORD,\n            database: process.env.DATABASE, \n            entities: [__dirname + '/**/*.entity{.ts,.js}'],\n            synchronize: true,\n            dropSchema: true,\n            autoLoadEntities: true,\n            logger: \"simple-console\"\n        };\n    }\n}\n```\n\n```text\nJwtStrategy\n```\n\n```text\nimports\n```\n\n```text\nJwtStrategy\n```\n\n```text\nAuthModule\n```\n\n```text\nproviders\n```\n\n```text\nimports\n```\n\n```js\nTypeOrmModule.forFeature([UserEntity])\n```\n\n```js\n@InjectRepository(UserEntity)\nprivate userRepo: Repository<UserEntity>\n```\n\n```js\nconst user = await UserEntity.findOne({ where: { username } });\n```\n\n```text\nAbstractEntity\n```\n\n```text\nBaseEntity\n```\n\n========================================\n\nComments:\n- where did you define `TypeOrmModule.forRoot` ? the `user` entity feature should be imported in your typeorm module root import\n- Did it in app.module.ts. It used to work before. But it doesn't now? I'll update app.module.ts.\n- Ok I can see your problem\n- Thank you @yash. I will be waiting for your answer.\n- can you add your UsersModule here as well?\n- UserModule has nothing to do with it. I just created UserModule and left it untouched for future uses.\n- Because from your architecture, i think `TypeOrmModule.forFeature([UserEntity])` should be in your UsersModule?\n- Consider there is no UsersModule.\n- actually it shouldnt be related your error.. i have a nestjs project very similar architecture with your app. using Typeorm with Passport module, but it;s working well\n- It used to work 2 days back. Suddenly after a commit this error is raised. I didn't change anything in the AuthModule. I just added a new column 'tags: string[]' in user.entity.ts. Does it have anything to do with this?\n- I don't think so. i used to get similar dependency injections errors before.. I switched to Active Record pattern. it doesnt require a dependency injection and dont need to make a repository instance, you can just use the entity class directly,\n- If we use active record pattern, It doesn't go well with the testing right?\n- no, it's even better with testing.\n- Okay, Thank you @yash. I'll try to implement it.\n- I'll definitely give it a try @yash. Thank you for the answer.","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":542,"estimatedTokens":3406}}1177{"id":"stack-66566006","source":"stackoverflow","questionId":66566006,"title":"Get application url from DI with Nest.js","tags":["nestjs"],"text":"Title: Get application url from DI with Nest.js\nTags: nestjs\nSource: Stack Overflow\n\nQuestion:\nIn the main.ts we can get the application url with app.getUrl().\n\nIs is possible to get it from a service via DI ?\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n console.log(`Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nasync function bootstrap() {\n    const app = await NestFactory.create(AppModule);\n    await app.listen(3000);\n    console.log(`Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n```js\nexport let app: INestApplication;\n    \nasync function bootstrap() {\n    app = await NestFactory.create(AppModule);\n    await app.listen(3000);\n    console.log(`Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n```text\napp\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":44,"estimatedTokens":229}}1178{"id":"stack-63887812","source":"stackoverflow","questionId":63887812,"title":"Set mongoose global options in @nestjs/mongoose","tags":["mongoose","nestjs"],"text":"Title: Set mongoose global options in @nestjs/mongoose\nTags: mongoose, nestjs\nSource: Stack Overflow\n\nQuestion:\nMongoose document says we can set global options like `mongoose.set('returnOriginal', false)`.\n\nNow I am using @nestjs/mongoose in nestjs, but I can't find a document describes how to do this global options setting.\n\nI do find a way to change the setting by `InjectConnection`\n\n```\nimport { Module } from '@nestjs/common';\nimport { MongooseModule, InjectConnection } from '@nestjs/mongoose';\nimport { Connection } from 'mongoose';\n...\n@Module({\n imports: [\n MongooseModule.forRootAsync({\n inject: [ConfigService],\n useFactory: (configService: ConfigService) => ({\n uri: configService.get('DB_URI'),\n useNewUrlParser: true,\n useUnifiedTopology: true,\n useFindAndModify: false,\n }),\n }),\n ...\n ],\n})\nexport class AppModule {\n constructor(@InjectConnection() private readonly connection: Connection) {\n connection.base.set('returnOriginal', false);\n }\n}\n```\n\nThis code works fine for me. However in `@types/mongoose`, there is no property `base.set` in type `Connection`. I have to omit the type definition for injected `connection`.\n\nMy question is whether this is a standard approach to set mongoose global options? If not, how can I do this?\n\n========================================\n\nCode:\n```js\nimport { Module } from '@nestjs/common';\nimport { MongooseModule, InjectConnection } from '@nestjs/mongoose';\nimport { Connection } from 'mongoose';\n...\n@Module({\n  imports: [\n    MongooseModule.forRootAsync({\n      inject: [ConfigService],\n      useFactory: (configService: ConfigService) => ({\n        uri: configService.get('DB_URI'),\n        useNewUrlParser: true,\n        useUnifiedTopology: true,\n        useFindAndModify: false,\n      }),\n    }),\n    ...\n  ],\n})\nexport class AppModule {\n  constructor(@InjectConnection() private readonly connection: Connection) {\n    connection.base.set('returnOriginal', false);\n  }\n}\n```\n\n```text\nmongoose.set('returnOriginal', false)\n```\n\n```text\nInjectConnection\n```\n\n```text\n@types/mongoose\n```\n\n```text\nbase.set\n```\n\n```text\nConnection\n```\n\n```text\nconnection\n```\n\n```js\n...\nimport * as mongoose from 'mongoose';\n...\nmongoose.set('returnOriginal', false);\n\n@Model({...})\nexport class AppModule {...}\n```\n\n```text\nmongoose\n```\n\n========================================\n\nComments:\n- Yes, def some documentation issues on NestJs' end.","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":112,"estimatedTokens":597}}1179{"id":"stack-61715052","source":"stackoverflow","questionId":61715052,"title":"NestJS TypeORM syntax error in migration file","tags":["postgresql","typescript","nestjs","typeorm"],"text":"Title: NestJS TypeORM syntax error in migration file\nTags: postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI was going through the NestJS official docs. I set up PostgreSQL on Heroku, connected with TypeORM, run a migration and after that my app started crushing. I tried different approaches and searched blogs/issues on github/questions here, but nothing helped.\n\nHere is an error:\n\n```\n[Nest] 46723 - 05/10/2020, 6:33:42 PM [InstanceLoader] TypeOrmModule dependencies initialized +84ms\n[Nest] 46723 - 05/10/2020, 6:33:43 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)... +493ms\n/Users/Shared/diploma/be/migration/1589119433066-AddUser.ts:1\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n ^\n\nSyntaxError: Unexpected token {\n at Module._compile (internal/modules/cjs/loader.js:721:23)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:690:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n at Function.PlatformTools.load (/***/PROJECT_ROOT/node_modules/typeorm/platform/PlatformTools.js:114:28)\n at /***/PROJECT_ROOT/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69\n at Array.map ()\n```\n\nHere is my `ormconfig.json`:\n\n```\n\"type\": \"postgres\",\n \"url\": \"postgres://***\",\n \"ssl\": true,\n \"extra\": {\n \"ssl\": {\n \"rejectUnauthorized\": false\n }\n },\n \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n \"migrationsTableName\": \"custom_migration_table\",\n \"migrations\": [\"migration/*{.ts,.js}\"],\n \"cli\": {\n \"migrationsDir\": \"migration\"\n }\n}\n```\n\nmigration was generated using `ts-node ./node_modules/.bin/typeorm migration:generate -n AddUser`\nI'm using `nest start --watch` command to start the app.\n\nMigration file `{TIMESTAMP}-AddUser.ts`:\n\n```\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class AddUser1589119433066 implements MigrationInterface {\n name = 'AddUser1589119433066'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`CREATE TABLE \"users\" (...)`, undefined);\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`DROP TABLE \"users\"`, undefined);\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\n[Nest] 46723   - 05/10/2020, 6:33:42 PM   [InstanceLoader] TypeOrmModule dependencies initialized +84ms\n[Nest] 46723   - 05/10/2020, 6:33:43 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +493ms\n/Users/Shared/diploma/be/migration/1589119433066-AddUser.ts:1\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n       ^\n\nSyntaxError: Unexpected token {\n    at Module._compile (internal/modules/cjs/loader.js:721:23)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n    at Module.load (internal/modules/cjs/loader.js:653:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n    at Module.require (internal/modules/cjs/loader.js:690:17)\n    at require (internal/modules/cjs/helpers.js:25:18)\n    at Function.PlatformTools.load (/***/PROJECT_ROOT/node_modules/typeorm/platform/PlatformTools.js:114:28)\n    at /***/PROJECT_ROOT/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69\n    at Array.map (<anonymous>)\n```\n\n```text\n\"type\": \"postgres\",\n  \"url\": \"postgres://***\",\n  \"ssl\": true,\n  \"extra\": {\n    \"ssl\": {\n      \"rejectUnauthorized\": false\n    }\n  },\n  \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n  \"migrationsTableName\": \"custom_migration_table\",\n  \"migrations\": [\"migration/*{.ts,.js}\"],\n  \"cli\": {\n    \"migrationsDir\": \"migration\"\n  }\n}\n```\n\n```text\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class AddUser1589119433066 implements MigrationInterface {\n    name = 'AddUser1589119433066'\n\n    public async up(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.query(`CREATE TABLE \"users\" (...)`, undefined);\n    }\n\n    public async down(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.query(`DROP TABLE \"users\"`, undefined);\n    }\n\n}\n```\n\n```text\normconfig.json\n```\n\n```text\nts-node ./node_modules/.bin/typeorm migration:generate -n AddUser\n```\n\n```text\nnest start --watch\n```\n\n```text\n{TIMESTAMP}-AddUser.ts\n```\n\n```text\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n\"migrations\": [\"dist/migration/*{.ts,.js}\"],\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- Have you tried removing javascript files from the migrations (or vice versa)? Sounds like it's trying to execute as JS and not TS, can you show your migration file or atleast a minimal version of it?\n- @Isolated I added migration file to the main message. TypeORM generates .ts migration and it should be ok (according to their docs). I run it with ts-node (also specified in typeorm docs) and it applied to the database without problems\n- I'm not at a PC so this is just basic debugging, my final thought would be set `entitiesDir:` to your TS entities in CLI, I'll be at my PC shortly so I'll see if I can reproduce it in my nest.js\n- It worked for me as well, although it looks like a bug for me. Nest start should look only for stuff on sourceRoot","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":161,"estimatedTokens":1347}}1180{"id":"stack-63078720","source":"stackoverflow","questionId":63078720,"title":"How can I define many to many columns with NestJS and TypeORM?","tags":["nestjs","typeorm"],"text":"Title: How can I define many to many columns with NestJS and TypeORM?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS/TypeORM so apologies and forgiveness please.\n\nI have a many to many relationship created; my table is created automatically with the correct columns.\n\nI have a location that can have many users, and a user can have many locations.\n\nMy route looks like this:\n\n```\nhttp://localhost:3000/locations/:location-id/users\n```\n\nMy `location.entity.ts` looks like this:\n\n```\n@ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable()\n users: User[];\n```\n\nMy `user.entity.ts` looks like this:\n\n```\n@ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\n`location_users_user` table is getting generated with these columns:\n\n```\nlocationId | userId\n```\n\nSo far, everything looks great! When I send a `GET` request to my route using Postman, I am seeing this error in the console:\n\n```\ncolumn location_users_user.locationid does not exist\n```\n\nI see that `locationid` is what it's looking for, when my column name is `locationId`. Is there somewhere I need to set the case of the column names?\n\nI have also worked through this SO thread to set additional params in the `JoinTable` decorator.\n\nThat leaves me with this:\n\n```\n// location.entitiy.ts\n@ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable({\n name: 'location_user',\n joinColumn: {\n name: 'locationId',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'userId',\n referencedColumnName: 'id',\n },\n })\n users: User[];\n```\n\nHowever, I'm still getting this error:\n\n```\ncolumn location_users_user.locationid does not exist\n```\n\nI don't think I'm setting the correct `Join` or something. I only have that decorator on my location entity.\n\nThank you for any suggestions!\n\n**EDIT**\n\nI have updated my `user.repository.ts` file as follows:\n\n```\nasync getLocationUsers(locationId: number): Promise {\n const query = this.createQueryBuilder('location_user')\n .where('location_user.locationId = :locationId', { locationId });\n```\n\nThe error still thinks I am looking for a `locationid` column. I've changed it to `foo` to just see if I was even in the correct spot and I am. I'm not sure why it's missing the case of `locationId`.\n\n**EDIT2**\n\nI've found that it could be a possible Postgres thing? Using double quotes, I'm now seeing the correct table/column name in my error:\n\n```\nconst query = this.createQueryBuilder('location_user')\n .where('location_user.\"locationId\" = :locationId', { locationId });\n```\n\nResults in: `column location_user.locationId does not exist`\nWhich is still odd, because that table does exist and so does the column.\n\n**Edit**\n\nHere is the `location.entity.ts` file:\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable()\n users: User[];\n```\n\nHere is the `user.entity.ts` file:\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n email: string;\n\n @ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\nI'm able to see the users' relationship when I get a specific location, so I know that's working properly. I am trying to just get all users that belong to the location; here is what my `user.repository.ts` file looks like:\n\n```\nasync getLocationUsers(locationId: number): Promise {\n const query = this.createQueryBuilder('user')\n .where('location_users_user.\"locationId\" = :locationId', { locationId });\n});\n\n try {\n return await query.getMany();\n } catch (e) {\n console.log('error: ', e);\n }\n }\n```\n\n========================================\n\nTop Answer:\nMight be a little late to a party but here's an interesting article on the subject.\n\n========================================\n\nCode:\n```js\nhttp://localhost:3000/locations/:location-id/users\n```\n\n```js\n@ManyToMany(type => User, user => user.locations, { eager: true })\n  @JoinTable()\n  users: User[];\n```\n\n```js\n@ManyToMany(type => Location, location => location.users, { eager: false })\n  locations: Location[];\n```\n\n```js\nlocationId | userId\n```\n\n```text\ncolumn location_users_user.locationid does not exist\n```\n\n```js\n// location.entitiy.ts\n@ManyToMany(type => User, user => user.locations, { eager: true })\n  @JoinTable({\n    name: 'location_user',\n    joinColumn: {\n      name: 'locationId',\n      referencedColumnName: 'id',\n    },\n    inverseJoinColumn: {\n      name: 'userId',\n      referencedColumnName: 'id',\n    },\n  })\n  users: User[];\n```\n\n```text\ncolumn location_users_user.locationid does not exist\n```\n\n```js\nasync getLocationUsers(locationId: number): Promise<User[]> {\n    const query = this.createQueryBuilder('location_user')\n      .where('location_user.locationId = :locationId', { locationId });\n```\n\n```js\nconst query = this.createQueryBuilder('location_user')\n      .where('location_user.\"locationId\" = :locationId', { locationId });\n```\n\n```js\n@PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  name: string;\n\n  @ManyToMany(type => User, user => user.locations, { eager: true })\n  @JoinTable()\n  users: User[];\n```\n\n```js\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n email: string;\n\n @ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\n```js\nasync getLocationUsers(locationId: number): Promise<User[]> {\n    const query = this.createQueryBuilder('user')\n      .where('location_users_user.\"locationId\" = :locationId', { locationId });\n});\n\n    try {\n      return await query.getMany();\n    } catch (e) {\n      console.log('error: ', e);\n    }\n  }\n```\n\n```text\nlocation.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nlocation_users_user\n```\n\n```text\nGET\n```\n\n```text\nlocationid\n```\n\n```text\nlocationId\n```\n\n```text\nJoinTable\n```\n\n```text\nJoin\n```\n\n```text\nuser.repository.ts\n```\n\n```text\nlocationid\n```\n\n```text\nfoo\n```\n\n```text\nlocationId\n```\n\n```text\ncolumn location_user.locationId does not exist\n```\n\n```text\nlocation.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.repository.ts\n```\n\n```js\nasync getLocationUsers(locationId: number): Promise<User[]> {\n    const query = this.createQueryBuilder('user')\n      .leftJoin('user.locations', 'location')\n      .where('location.id = :locationId', { locationId });\n});\n\n    try {\n      return await query.getMany();\n    } catch (e) {\n      console.log('error: ', e);\n    }\n  }\n```\n\n```js\n@ManyToMany(type => Location, location => location.users, { eager: false })\n```\n\n```js\n@ManyToMany(() => Location, (location) => location.users, { eager: false })\n```\n\n```text\n@ManyToMany\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nleftJoin\n```\n\n```text\ngetLocationUsers\n```\n\n```text\nuser.repository.ts\n```\n\n```text\ntype =>\n```\n\n```text\n() =>\n```\n\n========================================\n\nComments:\n- can you please add full code of the two entities?\n- Hi @yash I've just updated my question at the bottom to include the relationships and my repository method. Thank you!\n- This is really interesting. I had to use the double quote otherwise I wasn't getting the correct case for `locationId`. It seems this was the part that I was clearly not doing correctly: `.leftJoin('user.locations', 'location')`. Thank you so much for your time. It helped get me back on the right track!","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":367,"estimatedTokens":1835}}1181{"id":"stack-60204284","source":"stackoverflow","questionId":60204284,"title":"Mocking Date.Now jest toHaveBeenCalledWith in nestJs","tags":["node.js","typescript","unit-testing","jestjs","nestjs"],"text":"Title: Mocking Date.Now jest toHaveBeenCalledWith in nestJs\nTags: node.js, typescript, unit-testing, jestjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to figure out how to mock a call to Date.now with jest in my nestjs application.\n\nI have a repository method that soft deletes a resource\n\n```\nasync destroy(uuid: string): Promise {\n await this.userRepository.update({ userUUID: uuid }, { deletedDate: Date.now() });\n return true;\n}\n```\n\nto soft delete we just add a timestamp of when it was requested to be deleted\n\nFollowing some discussions on here and other sites I came up with this test.\n\n```\ndescribe('destroy', () => {\n it('should delete a user schemas in the user data store', async () => {\n const getNow = () => Date.now();\n jest\n .spyOn(global.Date, 'now')\n .mockImplementationOnce(() =>\n Date.now().valueOf()\n );\n const targetResource = 'some-uuid';\n const result = await service.destroy(targetResource);\n expect(result).toBeTruthy();\n expect(userRepositoryMock.update).toHaveBeenCalledWith({ userUUID: targetResource }, { deletedDate: getNow() });\n });\n });\n```\n\nI assumed that .spyOn(global.Date) mocked the entire global dat function , but the Date.now() in my repository is still returning the actual date rather than the mock.\n\nMy question is, is there a way to provide the mock return value of Date.now called in the repository from the test or should I just DI inject a DateProvider to the repository class which I can then mock from my test?\n\n========================================\n\nCode:\n```text\nasync destroy(uuid: string): Promise<boolean> {\n  await this.userRepository.update({ userUUID: uuid }, { deletedDate: Date.now() });\n  return true;\n}\n```\n\n```text\ndescribe('destroy', () => {\n    it('should delete a user schemas in the user data store', async () => {\n      const getNow = () => Date.now();\n      jest\n        .spyOn(global.Date, 'now')\n        .mockImplementationOnce(() =>\n          Date.now().valueOf()\n        );\n      const targetResource = 'some-uuid';\n      const result = await service.destroy(targetResource);\n      expect(result).toBeTruthy();\n      expect(userRepositoryMock.update).toHaveBeenCalledWith({ userUUID: targetResource }, { deletedDate: getNow() });\n    });\n  });\n```\n\n```js\nimport UserRepository from './userRepository';\n\nclass UserService {\n  private userRepository: UserRepository;\n  constructor(userRepository: UserRepository) {\n    this.userRepository = userRepository;\n  }\n  public async destroy(uuid: string): Promise<boolean> {\n    await this.userRepository.update({ userUUID: uuid }, { deletedDate: Date.now() });\n    return true;\n  }\n}\n\nexport default UserService;\n```\n\n```js\nclass UserRepository {\n  public async update(where, updater) {\n    return 'real update';\n  }\n}\n\nexport default UserRepository;\n```\n\n```js\nimport UserService from './userService';\n\ndescribe('60204284', () => {\n  describe('#UserService', () => {\n    describe('#destroy', () => {\n      it('should soft delete user', async () => {\n        const mUserRepository = { update: jest.fn() };\n        const userService = new UserService(mUserRepository);\n        jest.spyOn(Date, 'now').mockReturnValueOnce(1000);\n        const actual = await userService.destroy('uuid-xxx');\n        expect(actual).toBeTruthy();\n        expect(mUserRepository.update).toBeCalledWith({ userUUID: 'uuid-xxx' }, { deletedDate: 1000 });\n      });\n    });\n  });\n});\n```\n\n```sh\nPASS  stackoverflow/60204284/userService.test.ts\n  60204284\n    #UserService\n      #destroy\n        โœ“ should soft delete user (9ms)\n\n----------------|---------|----------|---------|---------|-------------------\nFile            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n----------------|---------|----------|---------|---------|-------------------\nAll files       |     100 |      100 |     100 |     100 |                   \n userService.ts |     100 |      100 |     100 |     100 |                   \n----------------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        5.572s, estimated 11s\n```\n\n```text\njest.spyOn(Date, 'now')\n```\n\n```text\nuserService.ts\n```\n\n```text\nuserRepository.ts\n```\n\n```text\nuserService.test.ts\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":148,"estimatedTokens":1063}}1182{"id":"stack-60511072","source":"stackoverflow","questionId":60511072,"title":"Is it possible to ignore class-validator on the client side?","tags":["typescript","nestjs","class-validator","typescript-decorator","class-transformer"],"text":"Title: Is it possible to ignore class-validator on the client side?\nTags: typescript, nestjs, class-validator, typescript-decorator, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have an app with NestJs with separated server and client. In server side, I use `ValidationPipe` and use decorators on DTO classes, for example:\n\n```\nexport class SearchDto {\n @IsOptional()\n readonly offset?: string;\n\n @IsString()\n readonly value: string;\n\n @IsNumber()\n readonly limit: number;\n}\n```\n\nEverything works, but on the client side, I can't use classes with decorators (it's strict rule) and I simply need to use it like `type`, - `const search: SearchDto = await...`\n\nHow `class-validator` (`class-transformer`) works when there is no `ValidationPipe` over it? Is it wrapped as in server side or fully ignored? Does it call `__decorate` and put it inside js bundle?\n\nOtherwise I need to write interfaces like this :\n\n```\nexport class SearchDto implements ISearchDto {\n @IsOptional()\n readonly offset?: string;\n\n @IsString()\n readonly value: string;\n\n @IsNumber()\n readonly limit: number;\n}\n\nexport interface ISearchDto {\n offset?: string;\n value: string;\n limit: number;\n}\n\nlet decorated: SearchDto;\nlet nonDecorated: ISearchDto;\n```\n\nThanks for your help.\n\n========================================\n\nCode:\n```text\nexport class SearchDto {\n   @IsOptional()\n   readonly offset?: string;\n\n   @IsString()\n   readonly value: string;\n\n   @IsNumber()\n   readonly limit: number;\n}\n```\n\n```text\nexport class SearchDto implements ISearchDto {\n   @IsOptional()\n   readonly offset?: string;\n\n   @IsString()\n   readonly value: string;\n\n   @IsNumber()\n   readonly limit: number;\n}\n\nexport interface ISearchDto {\n  offset?: string;\n  value: string;\n  limit: number;\n}\n\nlet decorated: SearchDto;\nlet nonDecorated: ISearchDto;\n```\n\n```text\nValidationPipe\n```\n\n```text\ntype\n```\n\n```text\nconst search: SearchDto = await...\n```\n\n```text\nclass-validator\n```\n\n```text\nclass-transformer\n```\n\n```text\nValidationPipe\n```\n\n```text\n__decorate\n```\n\n```text\nValidationPipe\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\ntransform: true\n```\n\n========================================\n\nComments:\n- Thanks, im not allowed to use decorators only in client code, in server its ok. Want to use the same dto on client - server","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":136,"estimatedTokens":579}}1183{"id":"stack-60099285","source":"stackoverflow","questionId":60099285,"title":"How to update NestJS Swagger module but use OpenAPI 2.0(Swagger)?","tags":["javascript","node.js","nestjs","openapi"],"text":"Title: How to update NestJS Swagger module but use OpenAPI 2.0(Swagger)?\nTags: javascript, node.js, nestjs, openapi\nSource: Stack Overflow\n\nQuestion:\nWe are making an API in Node.js/Typescript with NestJS framework. We use `@nestjs/swagger` package to make it conform to OpenAPI(formerly known as Swagger). It is inteneded to be used with `Azure/autorest` to generate client code.\n\nAutorest supports OpenAPI 2.0 and not 3.0 yet. `@nestjs/swagger 3.*.*` implemented OpenAPI 2.0. When we update `@nestjs/swagger` to `4.*.*` it turns into OpenAPI 3.0. This doesn't fit our needs because we can't use Autorest anymore. On the other hand not updating the package means we might miss out security updates or not even be able to update the entire NestJS framework.\n\nIs there any way to update `@nestjs/swagger` and stay with OpenAPI 2.0?\n\n========================================\n\nTop Answer:\nMaybe you can use the library\n\napi-spec-converter enter link description here\n\n```\nconst apiConverter = require('api-spec-converter');\nconst yaml = require('yaml');\nconst fs = require('fs');\n\napiConverter.convert(\n {\n sintax: 'yaml',\n order: 'openapi',\n from: 'openapi_3',\n to: 'swagger_2',\n source: './swagger-v3.json',\n },\n function(err, converted) {\n if (err) {\n console.log(err);\n console.log('Error converting file');\n return;\n }\n const yamlString = yaml.stringify(converted.spec);\n fs.writeFileSync('./swagger-v2.yaml', yamlString);\n\n console.log('Done!');\n },\n);\n```\n\nAdd a call script in the **package.json**:\n\n**\"convert:swagger\": \"node ./swagger-converter.js\"**\n\nPlease note that the source path is the one generated by NestJS.\n\nAnother point is that I'm generating the output in .**yaml**, but you can generate it in .**json** by just removing the syntax options and using **converter.stringify()** option\n\n========================================\n\nCode:\n```text\n@nestjs/swagger\n```\n\n```text\nAzure/autorest\n```\n\n```text\n@nestjs/swagger 3.*.*\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\n4.*.*\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nOpenAPI 3.0 specification\n```\n\n```text\nautorest 3\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nupdate the entire NestJS\nframework\n```\n\n```text\n@nestjs/swagger\n```\n\n```text\nautorest 3.beta\n```\n\n```js\nconst apiConverter = require('api-spec-converter');\nconst yaml = require('yaml');\nconst fs = require('fs');\n\napiConverter.convert(\n  {\n    sintax: 'yaml',\n    order: 'openapi',\n    from: 'openapi_3',\n    to: 'swagger_2',\n    source: './swagger-v3.json',\n  },\n  function(err, converted) {\n    if (err) {\n      console.log(err);\n      console.log('Error converting file');\n      return;\n    }\n    const yamlString = yaml.stringify(converted.spec);\n    fs.writeFileSync('./swagger-v2.yaml', yamlString);\n\n    console.log('Done!');\n  },\n);\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":135,"estimatedTokens":699}}1184{"id":"stack-59638438","source":"stackoverflow","questionId":59638438,"title":"NestJS/TypeORM - connecting to multiple databases - ConnectionNotFoundError","tags":["nestjs","typeorm"],"text":"Title: NestJS/TypeORM - connecting to multiple databases - ConnectionNotFoundError\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nConnecting to **two databases** using TypeORM and NestJS throws a **ConnectionNotFoundError** when a custom repository is registered using the connection **(UserConnection & PhotoConnection)** one for each database. I have created a minimal repo here https://github.com/masonridge/connissuewithndb. The TypeOrm registration is done in the AppModule of NestJS \n\n**(app.module.ts)**\n\n```\n@Module({\n imports: [\n\n TypeOrmModule.forRootAsync({\n name: 'PhotoConnection',\n useFactory: async () => {\n return {\n type: 'sqlite',\n synchronize: true,\n database: 'TestPhoto.sqlite',\n entities: [Photo],\n } as SqliteConnectionOptions;\n },\n }),\n TypeOrmModule.forRootAsync({\n name: 'UserConnection',\n useFactory: async () => {\n return {\n type: 'sqlite',\n synchronize: true,\n database: 'TestUser.sqlite',\n entities: [User],\n } as SqliteConnectionOptions;\n },\n }),\n // TypeOrmModule.forFeature([User, UserRepository], 'UserConnection'),\n // TypeOrmModule.forFeature([Photo, PhotoRepository], 'PhotoConnection'),\n PhotoModule, UserModule,\n ],\n```\n\n**(photo.module.ts) DB connection1 - PhotoConnection is registered here**\n\n```\n@Module({\n imports: [ \n TypeOrmModule.forFeature([PhotoRepository], 'PhotoConnection'),\n ],\n providers: [\n PhotoService,\n ],\n controllers: [PhotoController],\n exports: [TypeOrmModule],\n})\nexport class PhotoModule {}\n```\n\n**(user.module.ts) DB connection2 - UserConnection is registered here**\n\n```\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserRepository], 'UserConnection'),\n ],\n providers: [\n UserService,\n ],\n exports: [TypeOrmModule],\n controllers: [UserController],\n})\nexport class UserModule {}\n```\n\n**(user.repository.ts) Custom repository**\n\n```\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n async createUser(name: string): Promise {\n const user = this.create();\n user.username = name;\n user.salt = 'salt';\n user.password = 'xxkdkdk';\n user.save();\n return name;\n }\n}\n```\n\n**(photo.repository.ts)**\n\n```\n@EntityRepository(Photo)\nexport class PhotoRepository extends Repository {\n async createPhoto(name: string): Promise {\n const photo = this.create();\n photo.name = name;\n photo.save();\n return name;\n }\n}\n```\n\nThe repo is injected into the service using the connection (PhotoConnection)\n**(photo.service.ts)**\n\n```\nexport class PhotoService {\n constructor(\n @InjectRepository(Photo, 'PhotoConnection')\n private readonly photoRepository: PhotoRepository,\n ) {}\n```\n\nand here using **UserConnection (user.service.ts)**\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User, 'UserConnection')\n private readonly userRepository: UserRepository,\n ) {}\n```\n\nThe application starts fine but on a POST request it throws a ConnectionNotFoundError error \n\n (node:190812) UnhandledPromiseRejectionWarning: ConnectionNotFoundError: Connection \"default\" was not found.\n at new ConnectionNotFoundError (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\error\\ConnectionNotFoundError.js:10:28)\n at ConnectionManager.get (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\connection\\ConnectionManager.js:38:19)\n at Object.getConnection (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\index.js:244:35)\n at Function.BaseEntity.getRepository (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\repository\\BaseEntity.js:67:57)\n at Photo.BaseEntity.save (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\repository\\BaseEntity.js:27:33)\n at PhotoRepository.createPhoto (C:\\nestjs\\type-orm-dbscratch\\dist\\db\\photo\\photo.repository.js:15:15)\n at PhotoService.createPhoto (C:\\nestjs\\type-orm-dbscratch\\dist\\db\\photo\\photo.service.js:24:43)\n at PhotoController.addSetting (C:\\nestjs\\type-orm-dbscratch\\dist\\db\\photo\\photo.controller.js:22:27)\n at C:\\nestjs\\type-orm-dbscratch\\node_modules@nestjs\\core\\router\\router-execution-context.js:37:29\n at process._tickCallback (internal/process/next_tick.js:68:7)\n\nI would like to know if there is an issue with the registration. Any help would be appreciated.\n\n========================================\n\nCode:\n```text\n@Module({\n  imports: [\n\n    TypeOrmModule.forRootAsync({\n      name: 'PhotoConnection',\n      useFactory: async () => {\n        return {\n          type: 'sqlite',\n          synchronize: true,\n          database: 'TestPhoto.sqlite',\n          entities: [Photo],\n        } as SqliteConnectionOptions;\n      },\n    }),\n    TypeOrmModule.forRootAsync({\n      name: 'UserConnection',\n      useFactory: async () => {\n        return {\n          type: 'sqlite',\n          synchronize: true,\n          database: 'TestUser.sqlite',\n          entities: [User],\n        } as SqliteConnectionOptions;\n      },\n    }),\n    // TypeOrmModule.forFeature([User, UserRepository], 'UserConnection'),\n    // TypeOrmModule.forFeature([Photo, PhotoRepository], 'PhotoConnection'),\n    PhotoModule, UserModule,\n  ],\n```\n\n```text\n@Module({\n  imports: [    \n    TypeOrmModule.forFeature([PhotoRepository], 'PhotoConnection'),\n  ],\n  providers: [\n    PhotoService,\n  ],\n  controllers: [PhotoController],\n  exports: [TypeOrmModule],\n})\nexport class PhotoModule {}\n```\n\n```text\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([UserRepository], 'UserConnection'),\n  ],\n  providers: [\n    UserService,\n  ],\n  exports: [TypeOrmModule],\n  controllers: [UserController],\n})\nexport class UserModule {}\n```\n\n```text\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n  async createUser(name: string): Promise<string> {\n    const user = this.create();\n    user.username = name;\n    user.salt = 'salt';\n    user.password = 'xxkdkdk';\n    user.save();\n    return name;\n  }\n}\n```\n\n```text\n@EntityRepository(Photo)\nexport class PhotoRepository extends Repository<Photo> {\n  async createPhoto(name: string): Promise<string> {\n    const photo = this.create();\n    photo.name = name;\n    photo.save();\n    return name;\n  }\n}\n```\n\n```text\nexport class PhotoService {\n  constructor(\n    @InjectRepository(Photo, 'PhotoConnection')\n        private readonly photoRepository: PhotoRepository,\n  ) {}\n```\n\n```text\n@Injectable()\nexport class UserService {\n  constructor(\n    @InjectRepository(User, 'UserConnection')\n    private readonly userRepository: UserRepository,\n  ) {}\n```\n\n```text\nActiveRecord\n```\n\n```text\n'default'\n```\n\n```text\nextends BaseEntity\n```\n\n```text\nthis.save(user)\n```\n\n```text\nuser.save()\n```\n\n```text\nActiveRecord\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":270,"estimatedTokens":1620}}1185{"id":"stack-61510569","source":"stackoverflow","questionId":61510569,"title":"TypeORM. Two Foreign Keys referencing the same Primary Key in one table","tags":["node.js","typescript","nestjs","typeorm"],"text":"Title: TypeORM. Two Foreign Keys referencing the same Primary Key in one table\nTags: node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn my project I would like to have bi-directional ManyToOne - OneToMany relations with two foreign keys referencing to the same primary key. In my case it would be a table 'match' which contains two players from table 'player' (player1Id and player2Id are FK). I want to be able to get all matches where a particular player played as well as assign a player to the match. In Match entity I guess it should be something like this: \n\n```\n@Entity()\nexport class Match {\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player1Id\", referencedColumnName: \"id\" })\nplayer1: Player;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player2Id\", referencedColumnName: \"id\" })\nplayer2: Player;\n//some other properties...\n```\n\nbut since I have to indicate one inverse-side entity in @OneToMany() decorator then how should it look like in Player entity? Is there any way to map such an association in TypeORM and is it a good and common practice to have two FK in one table referencing to the same primary key in another table? I'm new in NodeJS and webdev in general. Thanks for any help.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Match {\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player1Id\", referencedColumnName: \"id\" })\nplayer1: Player;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player2Id\", referencedColumnName: \"id\" })\nplayer2: Player;\n//some other properties...\n```\n\n```text\n@Entity()\nexport class Match {\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToMany((type) => Player, (player) => player.matches)\nplayers: Player[];\n\n//some other properties...\n```\n\n```text\n@Entity()\nexport class Player{\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToMany((type) => Match, (match) => match.players)\n@JoinTable()\nmatches: Match[];\n\n//some other properties...\n```\n\n```text\n@JoinTable()\n```\n\n========================================\n\nComments:\n- One player can have many matches? Could you please attach the Player Entity code?\n- Thanks! It's a great idea I was so focused on the idea of having two players so I couldn't come up with that :) That solves my issue, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":82,"estimatedTokens":588}}1186{"id":"stack-60512682","source":"stackoverflow","questionId":60512682,"title":"How do I apply fastify rate limiter to a single route in Nest JS?","tags":["nestjs","rate-limiting","fastify"],"text":"Title: How do I apply fastify rate limiter to a single route in Nest JS?\nTags: nestjs, rate-limiting, fastify\nSource: Stack Overflow\n\nQuestion:\nI am able to apply a rate limiter to my nest app globally using code similar to the answer of this question. On the fastify rate limiter readme, it is shown that you can apply a rate limiter to a specific route via a config property with the rateLimit object with options. Nest's documentation does not explain how to do this; is it possible in the framework or am I out of luck?\n\n========================================\n\nCode:\n```js\napp.use(rateLimit({\n  whitelist: (req, key) => {\n    return !limitProtectedRoutes.includes(req.url);\n  }),\n}));\n```\n\n```text\nwhitelist\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Why not add your code examples instead of sending people off to multiple links? Your question would be more clearly understood that way.\n- A little hacky but if I really can't do it the \"proper\" way this looks good to me! Will accept after giving a little time for other answers.\n- Yeah, there's no real way to drop down to the fastify instance to register a middleware directly, so this is about as good as you'll get","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":32,"estimatedTokens":303}}1187{"id":"stack-61360247","source":"stackoverflow","questionId":61360247,"title":"NestJS > TypeORM Mapping complex entities to complex DTOs","tags":["node.js","typescript","nestjs","typeorm","class-transformer"],"text":"Title: NestJS > TypeORM Mapping complex entities to complex DTOs\nTags: node.js, typescript, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nIm using class-transformer > `plainToClass`(entity, DTO) to map entities to DTO's\n\nI've also implemented the associated transform.interceptor pattern described here.\n\nThen I use `@Expose()` on members of my DTO's. This works great but I have a limitation, I need to map member DTO's in my parent DTO and this isn't happening, see simple example below\n\n```\n@Exclude()\nexport class ParentDTO{\n\n @Expose()\n pMember2 : string;\n\n @Expose()\n pMember2 : ChildDto[];\n}\n\n@Exclude()\nexport class ChildDTO{\n\n @Expose()\n cMember2 : string;\n}\n\nexport class ParentEntity{\n pMember1 : number;\n pMember2 : string;\n pMember3 : string;\n pMember4\n : Child[];\n}\n\nexport class ChildEntity{\n cMember1 : number;\n cMember2 : string;\n cMember3 : string;\n}\n```\n\nNow if I run `plainToClass(parentEntityFromDB, ParentDTO)` I was hoping to get the following\n\n```\nParentDTO{\n pMember2 : string;\n pMember2 : ChildDto[];\n}\n```\n\nHowever, what I am getting is\n\n```\nParentDTO{\n pMember2 : string;\n pMember2 : Child[]; //Including all original members\n}\n```\n\nBasically plainToClass(entity, DTO) is not automatically mapping members to match the given DTO type.\n\nIs there a way to do this or is this a limitation of the method??\n\nThanks\n\n========================================\n\nCode:\n```text\n@Exclude()\nexport class ParentDTO{\n\n  @Expose()\n  pMember2 : string;\n\n  @Expose()\n  pMember2 : ChildDto[];\n}\n\n@Exclude()\nexport class ChildDTO{\n\n  @Expose()\n  cMember2 : string;\n}\n\nexport class ParentEntity{\n  pMember1 : number;\n  pMember2 : string;\n  pMember3 : string;\n  pMember4\n : Child[];\n}\n\nexport class ChildEntity{\n  cMember1 : number;\n  cMember2 : string;\n  cMember3 : string;\n}\n```\n\n```text\nParentDTO{\n  pMember2 : string;\n  pMember2 : ChildDto[];\n}\n```\n\n```text\nParentDTO{\n  pMember2 : string;\n  pMember2 : Child[]; //Including all original members\n}\n```\n\n```text\nplainToClass\n```\n\n```text\n@Expose()\n```\n\n```text\nplainToClass(parentEntityFromDB, ParentDTO)\n```\n\n```text\n@Exclude()\nexport class ParentDTO{\n\n  @Expose()\n  pMember2 : string;\n\n  @Expose()\n  @Type(() => ChildDto)\n  pMember2 : ChildDto[];\n}\n```\n\n```text\n@Type\n```\n\n```text\n@Type\n```\n\n```text\nplainToClass\n```\n\n```text\n@Exclude\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":158,"estimatedTokens":581}}1188{"id":"stack-76933674","source":"stackoverflow","questionId":76933674,"title":"NestJS does importing module to AppModule will make it available to other modules?","tags":["javascript","dependency-injection","nestjs"],"text":"Title: NestJS does importing module to AppModule will make it available to other modules?\nTags: javascript, dependency-injection, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am learning NestJS and I was reading the documentation but couldn't find an answer for this question.\n\nI have my infrastructure module:\n\n```\n@Module({\n imports: [DatabaseModule],\n controllers: [],\n providers: [\n ConfigService,\n {\n provide: 'RequestClient',\n useClass: AxiosRequestClient\n },\n {\n provide: 'FileStorage',\n useClass: S3FileStorage\n }\n ],\n exports: ['RequestClient', 'FileStorage', DatabaseModule]\n})\nexport class InfrastructureModule {}\n```\n\nI import this into my `AppModule`:\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({\n load: [filesystemConfig, awsConfig, databaseConfig],\n isGlobal: true,\n cache: true\n }),\n InfrastructureModule,\n PhysicianModule,\n PatientModule,\n RemsModule\n ],\n controllers: [],\n providers: [ApiResponseInterceptor]\n})\nexport class AppModule {}\n```\n\nWill the `InfrastructureModule` exports be available to `PatientModule` or do I need to import the `InfrastructureModule` to `PatientModule`?\n\nCurrently when I am trying to inject like this:\n\n```\nexport default class PatientMedicalRecordFileRepository implements IPatientMedicalRecordFileRepository {\nprivate readonly tempPath: string\nprivate readonly s3Path: string = 'private/patients'\nprivate readonly cloudfrontBaseUrl: string\n\nconstructor(\n private readonly configService: ConfigService,\n @Inject('FileStorage') private readonly fileStorage: IFileStorageService\n) {\n```\n\nI get the error:\n\nERROR [ExceptionHandler] Nest can't resolve dependencies of the PatientMedicalRecordFileRepository (ConfigService, ?). Please make sure that the argument FileStorage at index [1] is available in the RemsModule context.\n\n========================================\n\nTop Answer:\nIf you wish to import the Module only on the AppModule level and have it available across the other modules, you can always annotate your Module with @Global() decorator. More info can be found in official NestJS DOCS\n\n========================================\n\nCode:\n```text\n@Module({\n    imports: [DatabaseModule],\n    controllers: [],\n    providers: [\n        ConfigService,\n        {\n            provide: 'RequestClient',\n            useClass: AxiosRequestClient\n        },\n        {\n            provide: 'FileStorage',\n            useClass: S3FileStorage\n        }\n    ],\n    exports: ['RequestClient', 'FileStorage', DatabaseModule]\n})\nexport class InfrastructureModule {}\n```\n\n```text\n@Module({\n    imports: [\n        ConfigModule.forRoot({\n            load: [filesystemConfig, awsConfig, databaseConfig],\n            isGlobal: true,\n            cache: true\n        }),\n        InfrastructureModule,\n        PhysicianModule,\n        PatientModule,\n        RemsModule\n    ],\n    controllers: [],\n    providers: [ApiResponseInterceptor]\n})\nexport class AppModule {}\n```\n\n```text\nexport default class PatientMedicalRecordFileRepository implements IPatientMedicalRecordFileRepository {\nprivate readonly tempPath: string\nprivate readonly s3Path: string = 'private/patients'\nprivate readonly cloudfrontBaseUrl: string\n\nconstructor(\n    private readonly configService: ConfigService,\n    @Inject('FileStorage') private readonly fileStorage: IFileStorageService\n) {\n```\n\n```text\nAppModule\n```\n\n```text\nInfrastructureModule\n```\n\n```text\nPatientModule\n```\n\n```text\nInfrastructureModule\n```\n\n```text\nPatientModule\n```\n\n```text\n@Module({\n    imports: [\n        InfrastructureModule,  \n    ],\n    ...\n})\nexport class PatientModule {}\n```\n\n```text\nexports: ['RequestClient', 'FileStorage', DatabaseModule]\n```\n\n```text\nAppModule\n```\n\n```text\nHttpModule\n```\n\n```text\nInfrastructureModule\n```\n\n```text\nAppModule\n```\n\n```text\nInfrastructureModule\n```\n\n```text\nPatientModule\n```\n\n```text\nPatientModule\n```\n\n```text\nPatientModule\n```\n\n```text\nInfrastructureModule\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":198,"estimatedTokens":972}}1189{"id":"stack-60759337","source":"stackoverflow","questionId":60759337,"title":"Nestjs run on lambda function without creating an actual server to combine with AWS API Gateway?","tags":["node.js","amazon-web-services","http","model-view-controller","nestjs"],"text":"Title: Nestjs run on lambda function without creating an actual server to combine with AWS API Gateway?\nTags: node.js, amazon-web-services, http, model-view-controller, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have 5 HTTP microservices written with NestJS. I have to convert them into lambda function where each service will have its own lambda function. The purpose of this is to completely turn my service to serverless. \n\nI am using API Gateway to map requests to the right lambda by the given request path.\n\nNow creating an MVC pattern from scratch that receives an URL path and resolves and controller & function needed (including url params, and such) is something that has already been done by both express and nestjs.\n\nIs there a way to implement nesstjs's abstraction functionality without the actual server listening? So I can simply pass nestjs the URI and request data and it will work upon it?\n\nAny other solutions for running an MVC serverless process on lambda?\n\n========================================\n\nTop Answer:\nYou must provide more info about your architecture.\n Have you used `Blueprint` with `microservice`?\n Then choose `microservice-http-endpoint`.\n\nTake a look at [microservice-http-endpoint] example.\n1\n\n========================================\n\nCode:\n```text\nfunctions:\n  index:\n    handler: dist/index.handler\n    \n    events:\n    - http:\n        cors: true\n        path: '/'\n        method: any\n    - http:\n        cors: true\n        path: '{proxy+}'\n        method: any\n```\n\n```text\nserverless.yml\n```\n\n```text\nsls deploy\n```\n\n```text\nsls config credentials\n```\n\n```text\nBlueprint\n```\n\n```text\nmicroservice\n```\n\n```text\nmicroservice-http-endpoint\n```\n\n========================================\n\nComments:\n- is it possible to deploy without serverless. ?","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":72,"estimatedTokens":447}}1190{"id":"stack-56242848","source":"stackoverflow","questionId":56242848,"title":"Kill nestjs - node.js process while lost redis connection (microservice)","tags":["javascript","node.js","typescript","redis","nestjs"],"text":"Title: Kill nestjs - node.js process while lost redis connection (microservice)\nTags: javascript, node.js, typescript, redis, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\napp.connectMicroservice({\n transport: Transport.REDIS,\n options: {\n url: redis://ip:6379,\n retryAttempts: 5,\n retryDelay: 5000,\n }\n});\n```\n\nThis is how I connect to microservice in nestjs, simple and basic in Windows.\n\nDuring the process the connection to redis could be gone but I can't catch it.\n\nIt means that the app will be still alive and nothing happen if the redis connection will be restored, I won't be able to subscribe new events.\n\nHow can I handle it or add a timeout or catch issue like that. \nThe fix for now is only restart the service manually. I want to kill the process with `exit(1)` in that case\n\n========================================\n\nCode:\n```text\napp.connectMicroservice({\n  transport: Transport.REDIS,\n  options: {\n    url: redis://ip:6379,\n    retryAttempts: 5,\n    retryDelay: 5000,\n  }\n});\n```\n\n```text\nexit(1)\n```\n\n```text\nimports: [ClientsModule.register([\n  { name: 'REDIS_CLIENT', transport: Transport.REDIS },\n])],\n```\n\n```text\nconstructor(@Inject('REDIS_CLIENT') private readonly client: ClientProxy) {\n}\n\nasync onModuleInit() {\n  await this.client.connect();\n  setInterval(async () => {\n    try {\n      await this.client.emit('healthcheck', 'healthcheck').toPromise();\n    } catch (e) {\n      // Sending the message has failed, start recovery\n      console.error(e);\n      process.exit(1);\n    }\n  }, 1000);\n}\n```\n\n========================================\n\nComments:\n- Thanks , it out, is it possible to reconnect to the microservice with retries mechanism, instead kill the process.\n- In my case, an error with no additional data except for the name `CONNECTION_BROKEN` was raised by the ClientProxy. No way to catch that, the only strategy working is this one. I suggest to wrap the whole application within a Docker container and set **restart policy** to **always** so when the `process.exit(1)` is called, Docker will automatically restart your app","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":72,"estimatedTokens":516}}1191{"id":"stack-55900854","source":"stackoverflow","questionId":55900854,"title":"Creating Mutations In Nestjs Using The Code First approach","tags":["typescript","nestjs"],"text":"Title: Creating Mutations In Nestjs Using The Code First approach\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am in the process of creating a graphql api that is built on Nestjs (code first approach) and prisma for the database management. I have followed nestjs' official page and have successfully created the resolver for housing my queries, subscriptions and mutations. My first Query is working correctly without any problems. However after creating a mutation, the created mutation don't prompt for any parameters and the graphql playground does not indicate errors in my mutation request. \nThis mutation is responsible for creating a user and is supposed to take two parameters for the successful completion of the operation. \n\ni have tried re-creating the mutation using the schema first approach but the app crashes during start up. I also tried adding a name property to the mutation but still nothing happens.\n\nThis is my mutation\n\n```\n@Mutation(returns => User, { name: 'createUser' })\n async createUser(args) {\n return await this.userService.createUser(args);\n }\n```\n\nand in the user service \n\n```\nasync create(args) {\n return await this.prismah.mutation.createUser({\n name: args.name,\n email: args.email,\n });\n }\n```\n\nthe mutation should prompt for two parameters before submision and after submision it should create a user instance in the db\n\n========================================\n\nCode:\n```text\n@Mutation(returns => User, { name: 'createUser' })\n  async createUser(args) {\n    return await this.userService.createUser(args);\n  }\n```\n\n```text\nasync create(args) {\n    return await this.prismah.mutation.createUser({\n      name: args.name,\n      email: args.email,\n    });\n  }\n```\n\n```text\nimport { InputType, Field } from 'type-graphql';\n\n@InputType()\nexport class UserInput {\n  @Field() name: string;\n  @Field() email: string;\n}\n```\n\n```text\nimport {Args} from '@nestjs/graphql';\nimport {UserInput} from './path-to-the-user-input-class-created';\n\n\n@Mutation(returns => User, { name: 'createUser' })\n  async createUser(@Args('data') user: UserInput) {\n    return await this.userService.createUser(user);\n  }\n```\n\n========================================\n\nComments:\n- What is the \"User\" variable?","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":76,"estimatedTokens":558}}1192{"id":"stack-53172524","source":"stackoverflow","questionId":53172524,"title":"Handling Nest.js app on Redis cache store disconnection","tags":["caching","redis","nestjs"],"text":"Title: Handling Nest.js app on Redis cache store disconnection\nTags: caching, redis, nestjs\nSource: Stack Overflow\n\nQuestion:\nWhen I setup Redis as cache store like:\n\n```\nimport { Module, CacheModule } from '@nestjs/common';\nimport * as redisStore from 'cache-manager-redis-store';\n\n@Module({\n imports: [\n CacheModule.register({\n store: redisStore,\n host: 'localhost',\n port: 6379,\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nIt works as expected. However, if for some reason the connection to Redis goes down, the whole application will crash:\n\n```\nError: Redis connection to localhost:6379 failed - connect ECONNREFUSED \n127.0.0.1:6379\n at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)\n```\n\nHow can I gracefully handle these errors or even try to reconnect?\n\n========================================\n\nTop Answer:\nyou can handle or you can check connections whether is connected or not. you can also use nestjs/bull module Click here\n\nRedis Service Ready = queue.clients[0].status === 'ready'\n\nRedis Service Disconnect = queue.clients[0].status === 'reconnecting'\n\n\r\n\r\n\n```\nimport { InjectQueue } from '@nestjs/bull';\nimport { BadRequestException, HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';\nimport { Queue } from 'bull';\nimport CONFIG from 'src/config/config';\nimport { CreateEmailServiceDto } from './dto/create-email-service.dto';\n@Injectable()\nexport class EmailServiceService {\n private readonly logger = new Logger(this.constructor.name);\n constructor(\n @InjectQueue(CONFIG.REDIS_QUEUE_NAME)\n private mailQueue: Queue,\n ) {\n }\n async sendConfirmationEmail(user: CreateEmailServiceDto): Promise {\n try {\n const queue: any = this.mailQueue;\n\n if (queue.clients[0].status === 'reconnecting') {\n throw new HttpException(\"Redis Service is unavailable!\", \n HttpStatus.SERVICE_UNAVAILABLE);\n }\n\n await this.mailQueue\n .add('confirmation', {\n user,\n });\n\n return {\n message: 'Email Sent Successfully!',\n status: 201,\n };\n } catch (error) {\n console.log(error);\n this.logger.error(`Error queueing confirmation email to user \n ${user.to}`);\n if (error?.response && error?.status)\n throw new HttpException(error.response, error.status);\n\n throw new BadRequestException(error);\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Module, CacheModule } from '@nestjs/common';\nimport * as redisStore from 'cache-manager-redis-store';\n\n@Module({\n    imports: [\n        CacheModule.register({\n            store: redisStore,\n            host: 'localhost',\n            port: 6379,\n        }),\n    ],\n    controllers: [],\n    providers: [],\n})\nexport class AppModule {}\n```\n\n```text\nError: Redis connection to localhost:6379 failed - connect ECONNREFUSED \n127.0.0.1:6379\n    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)\n```\n\n```text\nimport { CACHE_MANAGER, Inject } from '@nestjs/common';\n\n...\n\nexport class AppModule {\n    constructor(@Inject(CACHE_MANAGER) cacheManager) {\n        const client = cacheManager.store.getClient();\n\n        client.on('error', (error) =>  {\n            console.info(error);\n        });\n    }\n}\n```\n\n```text\nCACHE_MANAGER\n```\n\n```text\nredisCache.set('foo', 'bar', { ttl: ttl }, (err) => {\n  if (err) {\n    throw err;\n  }\n\n  redisCache.get('foo', (err, result) => {\n    console.log(result);\n    // >> 'bar'\n    redisCache.del('foo', (err) => {\n    });\n  });\n});\n```\n\n```js\nimport { InjectQueue } from '@nestjs/bull';\nimport { BadRequestException, HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';\nimport { Queue } from 'bull';\nimport CONFIG from 'src/config/config';\nimport { CreateEmailServiceDto } from './dto/create-email-service.dto';\n@Injectable()\nexport class EmailServiceService {\n  private readonly logger = new Logger(this.constructor.name);\n  constructor(\n    @InjectQueue(CONFIG.REDIS_QUEUE_NAME)\n    private mailQueue: Queue,\n  ) {\n  }\n  async sendConfirmationEmail(user: CreateEmailServiceDto): Promise<any> {\n    try {\n      const queue: any = this.mailQueue;\n\n      if (queue.clients[0].status === 'reconnecting') {\n        throw new HttpException(\"Redis Service is unavailable!\", \n         HttpStatus.SERVICE_UNAVAILABLE);\n      }\n\n      await this.mailQueue\n        .add('confirmation', {\n          user,\n        });\n\n      return {\n        message: 'Email Sent Successfully!',\n        status: 201,\n      };\n    } catch (error) {\n      console.log(error);\n      this.logger.error(`Error queueing confirmation email to user \n          ${user.to}`);\n      if (error?.response && error?.status)\n        throw new HttpException(error.response, error.status);\n\n      throw new BadRequestException(error);\n    }\n  }\n}\n```\n\n========================================\n\nComments:\n- that logs the error, but NestJS is still crashed / not responding ... did you manage to fix this beyond just this logging?","metadata":{"transformedAt":"2026-08-18T18:33:02.584Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":203,"estimatedTokens":1217}}1193{"id":"stack-76667883","source":"stackoverflow","questionId":76667883,"title":"Inferring types from string literals in unions","tags":["typescript","nestjs"],"text":"Title: Inferring types from string literals in unions\nTags: typescript, nestjs\nSource: Stack Overflow\n\nQuestion:\nLet's say I want to manage services from different modules in a project within a single function, and depending on the type of data I get, I call a different service.\n\nFor example, I've got these two DTOs:\n\n```\nclass UserDto {\n constructor (name: string) {\n this.name = name\n }\n public name: string;\n}\n\nclass CarDto {\n constructor (brand: string) {\n this.brand = brand\n }\n public brand: string;\n}\n```\n\nAnd these two Services:\n\n```\nclass UserService {\n create(val: UserDto) {\n // Create the user\n return 'foo';\n }\n}\n\nclass CarService {\n create(val: CarDto) {\n // Create the car\n return 'bar';\n }\n}\n```\n\nPretty basic stuff. Then I can get a service that can manage the calls depending on what type of data I get. For that, I create a union type that is supposed to figure out what kind of data I'm getting and what service I should call, let's say something like this:\n\n```\ntype DataType =\n | {\n data: 'user';\n dto: UserDto;\n service: 'userService'\n }\n | {\n data: 'car';\n dto: CarDto;\n service: 'carService'\n }\n```\n\nFinally I want to put this all together in a function within the service that manages these two sub-services, like this:\n\n```\nclass MainService {\n constructor (\n private userService: UserService,\n private carService: CarService,\n ) {}\n\n serviceManager(val: DataType) {\n // Call the right service here!\n }\n}\n```\n\nWhat I don't want to do is checking for every property if that's the one I want. **This is what I'd like to avoid**:\n\n```\nserviceManager(val: DataType) {\n const name = val.data;\n if (name === 'user') this.userService.create(val.dto);\n }\n```\n\nInstead, I would prefer an approach in which TypeScript would infer what service I get and what information I'm passing to said service. So this is what *I thought* should work (spoiler, it doesn't):\n\n```\nserviceManager(val: DataType) {\n const func = this[val.service];\n func.create(val.dto);\n // Argument of type 'UserDto | CarDto' is not assignable to parameter of type 'UserDto & CarDto'.\n // Type 'UserDto' is not assignable to type 'UserDto & CarDto'.\n // Property 'brand' is missing in type 'UserDto' but required in type 'CarDto'.\n }\n```\n\nFinally, I decided to go for another route and don't even use subservices. But I have been trying to find a workaround to this problem even if it's not relevant for the project I'm working on anymore.\n\nWould it be possible to make something like this with TypeScript with some different way of declaring the type DataType or is it just plain impossible? Maybe I should have used generics when declaring the functions within the subservices?\n\n========================================\n\nCode:\n```text\nclass UserDto {\n  constructor (name: string) {\n      this.name = name\n  }\n  public name: string;\n}\n\nclass CarDto {\n  constructor (brand: string) {\n      this.brand = brand\n  }\n  public brand: string;\n}\n```\n\n```text\nclass UserService {\n  create(val: UserDto) {\n    // Create the user\n    return 'foo';\n  }\n}\n\nclass CarService {\n  create(val: CarDto) {\n    // Create the car\n    return 'bar';\n  }\n}\n```\n\n```text\ntype DataType =\n  | {\n      data: 'user';\n      dto: UserDto;\n      service: 'userService'\n    }\n  | {\n      data: 'car';\n      dto: CarDto;\n      service: 'carService'\n    }\n```\n\n```text\nclass MainService {\n  constructor (\n    private userService: UserService,\n    private carService: CarService,\n  ) {}\n\n  serviceManager(val: DataType) {\n   // Call the right service here!\n  }\n}\n```\n\n```text\nserviceManager(val: DataType) {\n   const name = val.data;\n    if (name === 'user') this.userService.create(val.dto);\n  }\n```\n\n```text\nserviceManager(val: DataType) {\n   const func = this[val.service];\n    func.create(val.dto);\n    // Argument of type 'UserDto | CarDto' is not assignable to parameter of type 'UserDto & CarDto'.\n    // Type 'UserDto' is not assignable to type 'UserDto & CarDto'.\n    // Property 'brand' is missing in type 'UserDto' but required in type 'CarDto'.\n  }\n```\n\n```text\ninterface DtoMap {\n  user: UserDto,\n  car: CarDto\n}\n\ntype ServiceMap =\n  { [K in keyof DtoMap]: { create(val: DtoMap[K]): string } }\n\ntype DataType<K extends keyof DtoMap> = { [P in K]:\n  { data: P, dto: DtoMap[P] }\n}[K]\n```\n\n```text\nserviceManager<K extends keyof DtoMap>(val: DataType<K>) {\n  const services: ServiceMap = {\n    car: this.carService,\n    user: this.userService\n  }\n  const func = services[val.data];\n  func.create(val.dto);\n}\n```\n\n```text\nserviceManager()\n```\n\n```text\nval\n```\n\n```text\nDataType\n```\n\n```text\nthis[val.service]\n```\n\n```text\nval.dto\n```\n\n```text\nUserService | CarService\n```\n\n```text\nUserDto | CarDto\n```\n\n```text\nthis[val.service]\n```\n\n```text\nUserService\n```\n\n```text\nval.dto\n```\n\n```text\nUserDto\n```\n\n```text\nthis[val.service]\n```\n\n```text\nUserService\n```\n\n```text\nval.dto\n```\n\n```text\nCarDto\n```\n\n```text\nDtoMap\n```\n\n```text\ndata\n```\n\n```text\nDataType\n```\n\n```text\nServiceMap\n```\n\n```text\nDataType<K>\n```\n\n```text\nDataType<keyof DtoMap>\n```\n\n```text\nDataType\n```\n\n```text\nservice\n```\n\n```text\nservices\n```\n\n```text\nServiceMap\n```\n\n```text\nK\n```\n\n```text\nDataType\n```\n\n```text\nserviceManager()\n```\n\n```text\nK\n```\n\n```text\nDtoMap\n```\n\n```text\nval\n```\n\n```text\nDataType<K>\n```\n\n```text\nval.data\n```\n\n```text\nservices\n```\n\n```text\nServiceMap\n```\n\n```text\nconst func = services[val.data]\n```\n\n```text\n{ create(val: DtoMap[K]): string }\n```\n\n```text\nfunc.create\n```\n\n```text\n(val: DtoMap[K]) => string\n```\n\n```text\nval.dto\n```\n\n```text\nDtoMap[K]\n```\n\n```text\nfunc.create(val.dto)\n```\n\n========================================\n\nComments:\n- Does this approach meet your needs? If so I'll write up an answer explaining; if not, what am I missing?\n- @jcalz I beileive it does, although I'm not quite used to generics, so I'm having a little bit of trouble when trying to call the serviceManager function, so if you could also add it to your answer, I'd be really glad. Otherwise, I'm still very thankful!\n- Like this? I will write up an answer either way, but let me know if that does or does not resolve the trouble with calling the `serviceManager()` method.","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":50,"totalLines":377,"estimatedTokens":1529}}1194{"id":"stack-75534963","source":"stackoverflow","questionId":75534963,"title":"Using NestJS and Mongoose, why isn't my updateOne method working to update a user's name by ID?","tags":["typescript","mongodb","mongoose","nestjs","crud"],"text":"Title: Using NestJS and Mongoose, why isn't my updateOne method working to update a user's name by ID?\nTags: typescript, mongodb, mongoose, nestjs, crud\nSource: Stack Overflow\n\nQuestion:\nIn the `update` method of my NestJS `UserService`, I'm using `updateOne` to update a user's name by their ID. However, the update doesn't seem to be working properly. What am I doing wrong?\n\nHere's the relevant code:\n\n```\nasync update(id: ObjectId, updateUserDto: UpdateUserDto) {\n return await this.userModel.updateOne({\n _id: id,\n name: {\n firstName: updateUserDto.name.firstName,\n lastName: updateUserDto.name.lastName,\n },\n });\n}\n```\n\nThanks for helping me out!\n\nWhen I call this method and pass in a user ID and a UpdateUserDto object containing a new first name and/or last name, I expect the user's name to be updated in the database. However, when I check the database after calling the update method, the name hasn't changed.\n\n========================================\n\nCode:\n```text\nasync update(id: ObjectId, updateUserDto: UpdateUserDto) {\n  return await this.userModel.updateOne({\n    _id: id,\n    name: {\n      firstName: updateUserDto.name.firstName,\n      lastName: updateUserDto.name.lastName,\n    },\n  });\n}\n```\n\n```text\nupdate\n```\n\n```text\nUserService\n```\n\n```text\nupdateOne\n```\n\n```text\nasync update(id: ObjectId, updateUserDto: UpdateUserDto) {\n  return await this.userModel.updateOne({_id: id,}, {\n    name: {\n      firstName: updateUserDto.name.firstName,\n      lastName: updateUserDto.name.lastName,\n    },\n  });\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":382}}1195{"id":"stack-57518718","source":"stackoverflow","questionId":57518718,"title":"how to extract JWT when authorize in Nestjs","tags":["node.js","nestjs"],"text":"Title: how to extract JWT when authorize in Nestjs\nTags: node.js, nestjs\nSource: Stack Overflow\n\nQuestion:\nMy purpose is make a role guard to verify the permission of user. I trying to extract authorization header to get the role information which is include on JWT. I implemented ***canActivate*** interface to check role of use but i don't know how to get the role info from JWT to verify it.\n\n```\nexport class RolesGuard implements CanActivate {\n constructor(private readonly _reflector: Reflector) {\n }\n\n canActivate(context: ExecutionContext): boolean {\n const roles = this._reflector.get(\n 'roles',\n context.getHandler(),\n );\n\n if (!roles || roles.length === 0) {\n return true;\n }\n\n const request = context.switchToHttp().getRequest();\n const user: InstanceType = request.headers.role;\n\n // i want to get the role from JWT in here\n\n const hasRole = () => roles.indexOf(user.role) >= 0;\n\n if (user && user.role && hasRole()) {\n return true;\n }\n\n throw new HttpException(\n 'You do not have permission (Roles)',\n HttpStatus.UNAUTHORIZED,\n );\n }\n}\n```\n\nI tried extends ***PassportStrategy***, but it can't work together with ***CanActive***\n\n========================================\n\nCode:\n```text\nexport class RolesGuard implements CanActivate {\n  constructor(private readonly _reflector: Reflector) {\n  }\n\n  canActivate(context: ExecutionContext): boolean {\n    const roles = this._reflector.get<UserRole[]>(\n      'roles',\n      context.getHandler(),\n    );\n\n    if (!roles || roles.length === 0) {\n      return true;\n    }\n\n    const request = context.switchToHttp().getRequest();\n    const user: InstanceType<User> = request.headers.role;\n\n    // i want to get the role from JWT in here\n\n    const hasRole = () => roles.indexOf(user.role) >= 0;\n\n    if (user && user.role && hasRole()) {\n      return true;\n    }\n\n    throw new HttpException(\n      'You do not have permission (Roles)',\n      HttpStatus.UNAUTHORIZED,\n    );\n  }\n}\n```\n\n```js\n// the mention of jwt in the AuthGuard is only needed if not working with defaultStrategy\nexport class RolesGuard extends AuthGuard('jwt') {\n  constructor(private readonly _reflector: Reflector) {\n    super()\n  }\n\n  canActivate(context: ExecutionContext): boolean {\n    const passportActive = super.canActivate(context);\n    if (!passportActivate) {\n      throw new HttpException(\n        'You do not have permission (Roles)',\n        HttpStatus.UNAUTHORIZED,\n      );\n    }\n    const roles = this._reflector.get<UserRole[]>(\n      'roles',\n      context.getHandler(),\n    );\n\n    if (!roles || roles.length === 0) {\n      return true;\n    }\n\n    const request = context.switchToHttp().getRequest();\n    // this should come from passport\n    const user: InstanceType<User> = request.user;\n\n    // i want to get the role from JWT in here\n\n    const hasRole = () => roles.indexOf(user.role) >= 0;\n\n    if (user && user.role && hasRole()) {\n      return true;\n    }\n\n    throw new HttpException(\n      'You do not have permission (Roles)',\n      HttpStatus.UNAUTHORIZED,\n    );\n  }\n}\n```\n\n```text\nJwtService\n```\n\n```text\nJwtModule\n```\n\n```text\njwtService.decode(myJwt)\n```\n\n```text\nAuthGuard\n```\n\n```text\nsuper.canActivate(context)\n```\n\n========================================\n\nComments:\n- Thank you, i used first suggest, inject JwtService to handle. It worked for me.","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":148,"estimatedTokens":829}}1196{"id":"stack-74320998","source":"stackoverflow","questionId":74320998,"title":"How do I serve static files in NestJS using fastify?","tags":["nestjs","static-files","fastify","nestjs-fastify"],"text":"Title: How do I serve static files in NestJS using fastify?\nTags: nestjs, static-files, fastify, nestjs-fastify\nSource: Stack Overflow\n\nQuestion:\nHow does one serve static files in NestJS using fastify? I can't seem to find any recent examples of setting this up properly. I have my **main.ts** set up like this:\n\n**main.ts**\n\n```\n// This must be the first thing imported in the app\nimport 'src/tracing';\n\nimport * as winston from 'winston';\nimport fastifyStatic, { FastifyStaticOptions } from '@fastify/static';\nimport { NestFactory } from '@nestjs/core';\nimport {\n FastifyAdapter,\n NestFastifyApplication,\n} from '@nestjs/platform-fastify';\nimport { path } from 'app-root-path';\nimport { WinstonModule } from 'nest-winston';\nimport { doc } from 'prettier';\n\nimport { AppModule } from 'src/app.module';\n\nimport join = doc.builders.join;\n\nasync function bootstrap() {\n const app = await NestFactory.create(\n AppModule,\n new FastifyAdapter(),\n {\n logger: WinstonModule.createLogger({\n format: winston.format.combine(\n winston.format.timestamp(),\n winston.format.json(),\n ),\n transports: [new winston.transports.Console()],\n }),\n rawBody: true,\n },\n );\n\n await app.register(require('@fastify/static'), {\n root: require('app-root-path').resolve('/client'),\n prefix: '/client/', // optional: default '/'\n });\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n app.get('/another/path', function (req, reply) {\n reply.sendFile('index.html');\n });\n\n app.enableShutdownHooks(); // terminus needs this to listen for SIGTERM/SIGKILL\n await app.listen(3002, '0.0.0.0');\n console.log(`Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\nThe static file I'm attempting to serve is `client/index.html`.\n\nHowever, when I run my app I get the following error: `Nest could not find /another/path element (this provider does not exist in the current context)`.\n\nI've also tried setting up my **app.module.ts** Modules like this:\n\n**app.module.ts**\n\n```\n@Module({\n imports: [\n ...configModules,\n ...domainModules,\n ...libraryModules,\n ServeStaticModule.forRoot({\n rootPath: require('app-root-path').resolve('/client'),\n renderPath: '/client/*',\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\nThis leads to the following error:\n\n```\n/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:286\n throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url)\n ^\nFastifyError: Method 'HEAD' already declared for route '/'\n at Object.addNewRoute (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:286:19)\n at Object.route (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:211:19)\n at Object.prepareRoute (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:144:18)\n at Object._head [as head] (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/fastify.js:247:34)\n at fastifyStatic (/Users/ewu/Desktop/Projects/janus/node_modules/@fastify/static/index.js:370:17)\n```\n\nHere are the relevant packages and their versions:\n\n```\n\"@nestjs/serve-static\": \"^3.0.0\",\n\"fastify-static\": \"^4.7.0\",\n\"fastify\": \"^4.8.1\",\n\"@nestjs/platform-fastify\": \"^9.1.2\",\n\"@fastify/static\": \"^6.0.0\",\n```\n\nI'm using version 9.0.0 of Nest and v16.15.0 of Node.\n\n========================================\n\nCode:\n```text\n// This must be the first thing imported in the app\nimport 'src/tracing';\n\nimport * as winston from 'winston';\nimport fastifyStatic, { FastifyStaticOptions } from '@fastify/static';\nimport { NestFactory } from '@nestjs/core';\nimport {\n  FastifyAdapter,\n  NestFastifyApplication,\n} from '@nestjs/platform-fastify';\nimport { path } from 'app-root-path';\nimport { WinstonModule } from 'nest-winston';\nimport { doc } from 'prettier';\n\nimport { AppModule } from 'src/app.module';\n\nimport join = doc.builders.join;\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter(),\n    {\n      logger: WinstonModule.createLogger({\n        format: winston.format.combine(\n          winston.format.timestamp(),\n          winston.format.json(),\n        ),\n        transports: [new winston.transports.Console()],\n      }),\n      rawBody: true,\n    },\n  );\n\n  await app.register(require('@fastify/static'), {\n    root: require('app-root-path').resolve('/client'),\n    prefix: '/client/', // optional: default '/'\n  });\n\n  // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n  // @ts-ignore\n  app.get('/another/path', function (req, reply) {\n    reply.sendFile('index.html');\n  });\n\n  app.enableShutdownHooks(); // terminus needs this to listen for SIGTERM/SIGKILL\n  await app.listen(3002, '0.0.0.0');\n  console.log(`Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n```\n\n```text\n@Module({\n  imports: [\n    ...configModules,\n    ...domainModules,\n    ...libraryModules,\n    ServeStaticModule.forRoot({\n      rootPath: require('app-root-path').resolve('/client'),\n      renderPath: '/client/*',\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n```\n\n```text\n/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:286\n            throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url)\n                  ^\nFastifyError: Method 'HEAD' already declared for route '/'\n    at Object.addNewRoute (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:286:19)\n    at Object.route (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:211:19)\n    at Object.prepareRoute (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/lib/route.js:144:18)\n    at Object._head [as head] (/Users/ewu/Desktop/Projects/janus/node_modules/@nestjs/platform-fastify/node_modules/fastify/fastify.js:247:34)\n    at fastifyStatic (/Users/ewu/Desktop/Projects/janus/node_modules/@fastify/static/index.js:370:17)\n```\n\n```text\n\"@nestjs/serve-static\": \"^3.0.0\",\n\"fastify-static\": \"^4.7.0\",\n\"fastify\": \"^4.8.1\",\n\"@nestjs/platform-fastify\": \"^9.1.2\",\n\"@fastify/static\": \"^6.0.0\",\n```\n\n```text\nclient/index.html\n```\n\n```text\nNest could not find /another/path element (this provider does not exist in the current context)\n```\n\n```text\n@Get()\n```\n\n```text\n@Controller()\n```\n\n```text\nAppController\n```\n\n```text\nGET /\n```\n\n```text\n@Get()\n```\n\n```text\nServeStaticModule\n```\n\n========================================\n\nComments:\n- That fixed it for me! To clarify for other people, with this solution I no longer needed to do any of the fastify static stuff in `main.ts`; just having the `ServeStaticModule` set up in `app.module.ts` was sufficient.","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":240,"estimatedTokens":1727}}1197{"id":"stack-74160018","source":"stackoverflow","questionId":74160018,"title":"How to get headers from AxiosResponse-Observable?","tags":["axios","rxjs","nestjs"],"text":"Title: How to get headers from AxiosResponse-Observable?\nTags: axios, rxjs, nestjs\nSource: Stack Overflow\n\nQuestion:\nUsing NestJS, Axios returns an `Observable`.\n\nHow can I get the headers of a GET- or HEAD-Request?\n\nLets say I make a HEAD-request:\n\n```\nimport { HttpService } from '@nestjs/axios';\n\nconst observable = this.httpService.head(uri);\n```\n\nHow can I get the headers from the result?\n\n**Update:**\n\nI found a nice workaround that just works with a single line of code.\n\nThere is another library called `https` with is more powerful:\n\n```\nimport http from \"https\";\n\nawait http.request(uri, { method: 'HEAD' }, (res) => {\n console.log(res.headers);\n}).on('error', (err) => {\n console.error(err);\n}).end();\n```\n\n========================================\n\nTop Answer:\nAccording to https://github.com/axios/axios#request-config:\n\nFor request headers you should use something like this:\n\n```\nthis.httpService.axiosRef.interceptors.request.use(function (config) {\n // Do something before request is sent\nconsole.log(config);\n return config;\n }, function (error) {\n // Do something with request error\n return Promise.reject(error);\n });\n```\n\nYou should use it onModuleInit (to prevent working a few interceptors in a time)\n\nAlso you can make own module like in this answer: https://stackoverflow.com/a/72543771/4546382\n\nFor the response headers you can just use response.headers\n\n========================================\n\nCode:\n```text\nimport { HttpService } from '@nestjs/axios';\n\nconst observable = this.httpService.head(uri);\n```\n\n```text\nimport http from \"https\";\n\nawait http.request(uri, { method: 'HEAD' }, (res) => {\n  console.log(res.headers);\n}).on('error', (err) => {\n  console.error(err);\n}).end();\n```\n\n```text\nObservable<AxiosResponse>\n```\n\n```text\nhttps\n```\n\n```js\nthis.httpService.head(uri).subscribe(res => {\n    console.log(res.headers)\n});\n```\n\n```text\nsubscribe\n```\n\n```text\nheaders\n```\n\n```text\nthis.httpService.axiosRef.interceptors.request.use(function (config) {\n    // Do something before request is sent\nconsole.log(config);\n    return config;\n  }, function (error) {\n    // Do something with request error\n    return Promise.reject(error);\n  });\n```","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":110,"estimatedTokens":544}}1198{"id":"stack-72568484","source":"stackoverflow","questionId":72568484,"title":"How to test nestjs with graphql by end to end?","tags":["graphql","nestjs","e2e-testing","supertest"],"text":"Title: How to test nestjs with graphql by end to end?\nTags: graphql, nestjs, e2e-testing, supertest\nSource: Stack Overflow\n\nQuestion:\nIn the test/posts/posts.e2e-spec.ts file\n\n```\nimport { INestApplication } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport request = require('supertest');\nimport { PostsModule } from '../../src/posts/posts.module';\n\ndescribe('Posts (e2e)', () => {\n const posts = {\n id: 1,\n name: 'FirstPost #1',\n };\n\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n ...\n }),\n PostModule,\n ],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await app.close();\n });\n\n describe('post', () => {\n it('should retrieve all post data', async () => {\n request(app.getHttpServer())\n .post('/graphql')\n .send({\n query:\n `{findPosts() {\n name\n }}`,\n })\n .expect(200)\n .expect((res) => {\n console.log(res.body.data)\n expect(res.body.data.post.length).toEqual(posts.length)\n })\n })\n })\n});\n```\n\nI created migration and inserted data into database first, then run this test, it can't go to the `expect` items. Even set console log I can't see anything in the output.\n\nSo maybe the `/graphql` can't be access in this way? I can access the endpoint from browser as http://localhost:3000/graphql.\n\nIf import supertest as\n\n```\nimport * as request from 'supertest';\n```\n\nIn the line request it showed:\n\nThis expression is not callable. Type โ€˜typeof supertestโ€™ has no call signatures.\n\nThe version of them:\n\n- supertest: 6.1.3\n\n- @types/supertest: 2.0.11\n\n========================================\n\nCode:\n```text\nimport { INestApplication } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport request = require('supertest');\nimport { PostsModule } from '../../src/posts/posts.module';\n\ndescribe('Posts (e2e)', () => {\n  const posts = {\n    id: 1,\n    name: 'FirstPost #1',\n  };\n\n  let app: INestApplication;\n\n  beforeAll(async () => {\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [\n        TypeOrmModule.forRoot({\n          type: 'mysql',\n          ...\n        }),\n        PostModule,\n      ],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n\n  describe('post', () => {\n    it('should retrieve all post data', async () => {\n      request(app.getHttpServer())\n      .post('/graphql')\n      .send({\n        query:\n          `{findPosts() {\n            name\n          }}`,\n      })\n      .expect(200)\n      .expect((res) => {\n        console.log(res.body.data)\n        expect(res.body.data.post.length).toEqual(posts.length)\n      })\n    })\n  })\n});\n```\n\n```text\nimport * as request from 'supertest';\n```\n\n```text\nexpect\n```\n\n```text\n/graphql\n```\n\n========================================\n\nComments:\n- so path `&#47;graphql` should be a constant. previously it can be found at `m._graphQlAdapter._apolloServer.graphqlPath`, but the latest version apolloServer has no property `graphqlPath`","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":154,"estimatedTokens":823}}1199{"id":"stack-73219017","source":"stackoverflow","questionId":73219017,"title":"NestJS: Unable to connect to MongoDB using MongooseModule.forRootAsync","tags":["nestjs","nestjs-mongoose"],"text":"Title: NestJS: Unable to connect to MongoDB using MongooseModule.forRootAsync\nTags: nestjs, nestjs-mongoose\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect to local mongoDB in the `AppModule` by doing the following but it won't connect:\n\n```\nimports: [\n MongooseModule.forRootAsync({\n useFactory: async () => {\n return {\n uri: 'mongodb://localhost:27017/client',\n useNewUrlParser: true,\n useCreateIndex: true,\n };\n },\n }),\n ],\n```\n\nError from NestJS:\n`[MongooseModule] Unable to connect to the database. Retrying (1)...`\n\nThe MongoDB is running fine. I can connect to it through MongoDB Compass with the same uri.\n\nWhat is done wrong causing the connection not being established?\n\n========================================\n\nTop Answer:\n**This works with async and logging options**\n\n```\nMongooseModule.forRootAsync({\n useFactory: async () => {\n const connection = await ConnectToMongodb.getConnectionString();\n return {\n connectionFactory: (connection) => {\n if (connection.readyState === 1) {\n console.log('Database Connected successfully');\n }\n connection.on('disconnected', () => {\n console.log('Database disconnected');\n });\n connection.on('error', (error) => {\n console.log('Database connection failed! for error: ', error);\n });\n\n return connection;\n },\n uri: connection,\n };\n },\n })\n```\n\n========================================\n\nCode:\n```text\nimports: [\n    MongooseModule.forRootAsync({\n      useFactory: async () => {\n        return {\n          uri: 'mongodb://localhost:27017/client',\n          useNewUrlParser: true,\n          useCreateIndex: true,\n        };\n      },\n    }),\n  ],\n```\n\n```text\nAppModule\n```\n\n```text\n[MongooseModule] Unable to connect to the database. Retrying (1)...\n```\n\n```text\nMongooseModule.forRootAsync({\n      useFactory: async () => ({\n        uri: 'mongodb://localhost:27017/client',\n      }),\n    }),\n```\n\n```text\nMongooseModule.forRootAsync({\n      useFactory: async () => {\n        const connection = await ConnectToMongodb.getConnectionString();\n        return {\n          connectionFactory: (connection) => {\n            if (connection.readyState === 1) {\n              console.log('Database Connected successfully');\n            }\n            connection.on('disconnected', () => {\n              console.log('Database disconnected');\n            });\n            connection.on('error', (error) => {\n              console.log('Database connection failed! for error: ', error);\n            });\n\n            return connection;\n          },\n          uri: connection,\n        };\n      },\n    })\n```\n\n```text\nMongooseModule.forRootAsync({\n      useFactory: async () => {\n\n        const port = process.env.MONGODB_PORT;\n        const host = process.env.MONGODB_HOST;\n        const password = process.env.MONGODB_PASSWORD;\n        const user = process.env.MONGODB_USER;\n\n        const connection = `mongodb://${user}:${password}@${host}:${port}`;\n        return {\n          connectionFactory: connection => {\n            if (connection.readyState === 1) {\n               console.log('Database Connected successfully');\n            }\n            connection.on('disconnected', () => {\n               console.error('Database disconnected');\n            });\n            connection.on('error', error => {\n               console.error('Database connection failed! for error: ', error);\n            });\n            return connection;\n          },\n          uri: connection,\n        };\n      },\n    }),\n```\n\n========================================\n\nComments:\n- Removing the options works like a charm! Thank you so much!","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":147,"estimatedTokens":890}}1200{"id":"stack-73665875","source":"stackoverflow","questionId":73665875,"title":"Dependency injection into nestjs mixin","tags":["typescript","nestjs","mixins"],"text":"Title: Dependency injection into nestjs mixin\nTags: typescript, nestjs, mixins\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a guard that takes parameters and also uses a global service (`prismaService`).\n\nThe dependency injection works as expected for a normal guard, but to create a guard that accepts parameters I'm using mixins.\n\n```\nexport const UserGuard = (table: Prisma.ModelName, field: string) => {\n class RoleGuardMixin implements CanActivate {\n constructor(prismaService: PrismaService) {}\n\n async canActivate(context: ExecutionContext) {\n const subject = await this.prismaService[table];\n return true;\n }\n }\n\n const guard = mixin(RoleGuardMixin);\n return guard;\n};\n```\n\nIn this case the PrismaService isn't found (I believe because the mixin is a pure function that returns a class). Is there a way to get nestjs to inject PrismaService after the guard is called? Can services be injected into classes?\n\n========================================\n\nTop Answer:\nThanks to @Micael for the answer.\n\nWhat is needed is to decorate the `RoleGuardMixin` with the `@Injectable` decorator.\n\n```\nexport const UserGuard = (table: any, field: string) => {\n @Injectable()\n class RoleGuardMixin implements CanActivate {\n constructor(public prismaService: PrismaService) {}\n\n async canActivate(context: ExecutionContext): Promise {\n const request = context.switchToHttp().getRequest();\n const subject = this.prismaService[table].findUnique({\n where: { id: request.params.id }\n });\n return request.user.id === subject[field];\n }\n\n const guard = mixin(RoleGuardMixin);\n return guard;\n};\n```\n\n========================================\n\nCode:\n```text\nexport const UserGuard = (table: Prisma.ModelName, field: string) => {\n  class RoleGuardMixin implements CanActivate {\n    constructor(prismaService: PrismaService) {}\n\n    async canActivate(context: ExecutionContext) {\n      const subject = await this.prismaService[table];\n      return true;\n    }\n  }\n\n  const guard = mixin(RoleGuardMixin);\n  return guard;\n};\n```\n\n```text\nprismaService\n```\n\n```text\nexport const UserGuard = (table: Prisma.ModelName, field: string) => {\n  @Injectable() // <<<<<<<\n  class RoleGuardMixin implements CanActivate {\n    constructor(private prismaService: PrismaService) {}\n    //          ^ or 'public' or 'protected'\n\n    async canActivate(context: ExecutionContext) {\n      const subject = await this.prismaService[table];\n      return true;\n    }\n  }\n\n  const guard = mixin(RoleGuardMixin);\n  return guard;\n};\n```\n\n```text\nexport const UserGuard = (table: Prisma.ModelName, field: string) => {\n  class RoleGuardMixin implements CanActivate {\n    constructor(@Inject(PrismaService) private prismaService: PrismaService) {}\n\n    async canActivate(context: ExecutionContext) {\n      const subject = await this.prismaService[table];\n      return true;\n    }\n  }\n\n  const guard = mixin(RoleGuardMixin);\n  return guard;\n};\n```\n\n```text\n@Injectable()\n```\n\n```text\n@Inject()\n```\n\n```text\nexport const UserGuard = (table: any, field: string) => {\n  @Injectable()\n  class RoleGuardMixin implements CanActivate {\n    constructor(public prismaService: PrismaService) {}\n\n    async canActivate(context: ExecutionContext): Promise<boolean> {\n      const request = context.switchToHttp().getRequest();\n      const subject = this.prismaService[table].findUnique({\n        where: { id: request.params.id }\n        });\n      return request.user.id === subject[field];\n  }\n\n  const guard = mixin(RoleGuardMixin);\n  return guard;\n};\n```\n\n```text\nRoleGuardMixin\n```\n\n```text\n@Injectable\n```\n\n========================================\n\nComments:\n- You just need to make sure that the module that uses that guard has access to the `PrismaService` provider. Also, add `@Injectable()` to `RoleGuardMixin`\n- This worked! The Injectable did the trick. I also had to add \"private\" to the constructor to declare the prismaService. I misunderstood the Injectable decorator. If you want to post as answer I'll accept it! Otherwise I'll post my code.","metadata":{"transformedAt":"2026-08-18T18:33:02.585Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":150,"estimatedTokens":1001}}

Showing the first 1,200 of 1334 lines. Download the file for the rest.