Questions tagged [nestjs]
Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript.
nestjs
12,510
questions
150
votes
9
answers
144k
views
Inject nestjs service from another module
I've got a PlayersModule and an ItemsModule.
I want to use the ItemsService in the PlayersService.
When I add it by injection:
import { Injectable } from '@nestjs/common';
import { InjectModel } ...
136
votes
29
answers
143k
views
TypeORM Entity in NESTJS - Cannot use import statement outside a module
Started new project with 'nest new' command. Works fine until I add entity file to it.
Got following error:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^
...
134
votes
4
answers
61k
views
What's the difference between Interceptor vs Middleware vs Filter in Nest.js?
What'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?
Thanks
104
votes
5
answers
263k
views
How to use query parameters in Nest.js?
I am a freshman in Nest.js.
And my code as below
@Get('findByFilter/:params')
async findByFilter(@Query() query): Promise<Article[]> {
}
I have used postman to test this router
http://...
98
votes
9
answers
156k
views
NestJS - How to use .env variables in main app module file for database connection
I am working on my first NestJS application, which was working fine with hardcoded database connecting string in app.module.ts.
But then as per our requirements, I had to pick the database config ...
97
votes
1
answer
54k
views
nestjs vs plain express performance
I've just tested performance on a simple nest's controller, that returns text on a get request (no database).
And the same simple GET controller (middleware) with express.
I used WRK tool to test ...
87
votes
3
answers
42k
views
What's the difference between tsc (TypeScript compiler) and ts-node?
I'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.
Now, I'm approaching nestjs framework, and I see ...
84
votes
21
answers
45k
views
Why do we need DTOs and interfaces both in NestJS
The NestJS documentation showcases how to add DTOs to use in Controllers to validate request objects by using class-validator package. DTOs described there are TypeScript classes. Now, while ...
84
votes
5
answers
122k
views
What is the nestjs error handling approach (business logic error vs. http error)?
While using NestJS to create API's I was wondering which is the best way to handle errors/exception.
I have found two different approaches :
Have individual services and validation pipes throw new ...
80
votes
6
answers
153k
views
Class-validator - validate array of objects
I 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:
So far I have:
import { IsString, IsNumber } ...
79
votes
9
answers
77k
views
Nest.js - request entity too large PayloadTooLargeError: request entity too large
I'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:
[Nest] 1976 - 2018-10-12 09:52:04 [...
75
votes
14
answers
177k
views
Environment variable with dotenv and TypeScript
I create this .env file:
TYPE=xxx
HOST=xxx,
PORT=xxx,
USERNAME=xxx,
PASSWORD=xxx,
DATABASE=xxx,
in my file I use in this way:
import * as dotenv from "dotenv";
dotenv.config();
export const ...
75
votes
10
answers
76k
views
How to copy non-ts files to dist when building typescript?
I have Mail module in folder with this structure:
- Mail
- templates
- <Handlebars files>
- mail.module.ts
When I build (compile) TypeScript project, my template folder is not ...
73
votes
3
answers
142k
views
Validate nested objects using class validator and nestjs
I'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 ...
72
votes
7
answers
118k
views
How to use nestjs Logging service
I tried to use the internal Logger of nestjs (described on https://docs.nestjs.com/techniques/logger -> but with no description of how to use it)
But I had problems (tried to inject LoggerService and ...
71
votes
14
answers
168k
views
TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest'
I 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.
--> starting at object with constructor 'ClientRequest'
| ...
67
votes
17
answers
168k
views
NestJS enable cors in production
I've enabled CORS in my NestJS app following the official tutorial, so my main.ts looks like the following:
import { FastifyAdapter, NestFactory } from '@nestjs/core';
import { AppModule } from './...
67
votes
8
answers
95k
views
Inject TypeORM repository into NestJS service for mock data testing
There's a longish discussion about how to do this in this issue.
I've experimented with a number of the proposed solutions but I'm not having much luck.
Could anyone provide a concrete example of ...
67
votes
12
answers
72k
views
Is there a recommended way to update NestJS?
I'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?
Current dependencies are:
"@...
66
votes
6
answers
124k
views
How to implement pagination in NestJS with TypeORM
Is there any way to get the total count and records with a single query, instead of running it as 2 separate queries?
If it's not possible, is there any way to reuse the where condition in both ...
66
votes
9
answers
94k
views
Logging request/response in Nest.js
New to Nest.js,
I am trying to implement a simple logger for tracing HTTP requests like :
:method :url :status :res[content-length] - :response-time ms
From my understanding the best place for that ...
64
votes
15
answers
30k
views
UnhandledPromiseRejectionWarning: Error: You must `await server.start()` before calling `server.applyMiddleware()` at ApolloServer
I am trying to start my nestJs server and It keeps giving me this error:
UnhandledPromiseRejectionWarning: Error: You must await server.start() before calling server.applyMiddleware()
at ApolloServer
...
62
votes
15
answers
74k
views
Is it possible to add Authentication to access to NestJS' Swagger Explorer
I'm currently using Swagger in my NestJS project, and I have the explorer enabled:
in main.js
const options = new DocumentBuilder()
.setTitle('My App')
.setSchemes('https')
.setDescription(...
61
votes
13
answers
72k
views
Error while running nestjs in production mode, cannot find module
I have implemented a generic class as below which might be causing the problem,
import { Logger } from '@nestjs/common';
import { PaginationOptionsInterface, Pagination } from './paginate';
...
59
votes
2
answers
91k
views
How to use Nest.js's @Headers properly?
According 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 ...
59
votes
5
answers
51k
views
In Nest.js, how to get a service instance inside a decorator?
In CustomDecorator, how to access a service instance defined in Nest.js?
export const CustomDecorator = (): MethodDecorator => {
return (
target: Object,
propertyKey: string | symbol,
...
52
votes
16
answers
100k
views
Connection "default" was not found with TypeORM
I use TypeORM with NestJS and I am not able to save properly an entity.
The connection creation works, postgres is running on 5432 port. Credentials are OK too.
However when I need to save a ...
50
votes
4
answers
53k
views
How to create nested routes with parameters using NestJS
I need to build an API where most of the routes are prefixed with a common URL part which also has a parameter.
In my specific case, my routes need to look like:
/accounts/:account/resource1/:...
48
votes
6
answers
131k
views
How can I create columns with type Date and type DateTime in nestjs with typeORM?
I am new with nestjs. How can I set columns that accepts Date format and dateTime format?
Not in both cases, the columns are two differents column, one accept Date and other dateTime.
46
votes
10
answers
131k
views
Nest can't resolve dependencies of the ItemsService (?). Please make sure that the argument at index [0] is available in the AppModule context
I follwed Nest JS Crash tutorial, Youtube Link,
I followed this, but when i import interface in service it shows error
Nest can't resolve dependencies of the ItemsService (?). Please make sure that ...
45
votes
12
answers
99k
views
How to exclude entity field from returned by controller JSON. NestJS + Typeorm
I want to exclude password field from returned JSON.
I am using NestJS and Typeorm.
The solution provided on this question doesn't work for me or in NestJS. I can post my code if needed.
Any other ...
45
votes
4
answers
27k
views
TypeError: rxjs_1.lastValueFrom is not a function
I 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.
import { Module } from '@nestjs/common';...
45
votes
3
answers
77k
views
Howto get req.user in services in Nest JS
In 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.
@Controller()
@UseGuards(AuthGuard())
...
43
votes
11
answers
30k
views
Access raw body of Stripe webhook in Nest.js
I need to access the raw body of the webhook request from Stripe in my Nest.js application.
Following this example, I added the below to the module which has a controller method that is needing the ...
43
votes
6
answers
38k
views
NestJS - Test suite failed to run Cannot find module 'src/article/article.entity' from 'comment/comment.entity.ts'
i need help with nestjs and jest testing. I am new to NestJS and i got stuck on Cannot find module error when i run tests.
I am trying to test my service and when i run tests i have received error ...
41
votes
6
answers
72k
views
Nest can't resolve dependencies of the PhotoService (?)
I'm starting with Nest.js and I'm getting an error after I create a service:
Nest can't resolve dependencies of the PhotoService (?). Please verify whether [0] argument is available in the current ...
40
votes
5
answers
85k
views
Validation on optional Parameter using class-validator in nestjs?
I 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()
I tried something like this
@...
40
votes
3
answers
24k
views
Mongoose Subdocuments in Nest.js
I'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({...}).
Let's use ...
39
votes
6
answers
39k
views
GraphQLError: Query root type must be provided
I'm using NestJS, TypeORM and GraphQL for my backend API. I'm getting the following error:
GraphQLError [Object]: Query root type must be provided.
at SchemaValidationContext.reportError (/home/...
39
votes
10
answers
49k
views
Password confirmation in TypeScript with `class-validator`
Today, 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 ...
39
votes
5
answers
32k
views
Nestjs Dependency Injection and DDD / Clean Architecture
I'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.
Please note that the ...
37
votes
2
answers
68k
views
Is it possible to set default values for a DTO?
Is there some way to use default values when a query is empty?
If I have the following DTO for a query:
export class MyQuery {
readonly myQueryItem: string;
}
And my request contains no query, ...
36
votes
10
answers
64k
views
Jest has detected the following 1 open handle potentially keeping Jest from exiting: TCPSERVERWRAP
I 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.
Ran all test suites.
Jest has detected the following 1 open handle potentially ...
35
votes
9
answers
25k
views
Circular Dependency with Nestjs Swagger 4
When I updated the @nest/swagger library to version 4, this error happened:
(node:16134) UnhandledPromiseRejectionWarning: Error: A circular dependency has been detected (property key: "customer"). ...
35
votes
9
answers
21k
views
Test functions cannot both take a 'done' callback
I'm trying to create a simple test with nestjs, and I'm getting this error
Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.
...
35
votes
3
answers
18k
views
How to print stack trace with reference to typescript source in Nest.js
I 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)...
34
votes
8
answers
43k
views
Decorator to return a 404 in a Nest controller
I'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.
@Controller('user')
export class ...
34
votes
1
answer
7k
views
Optional authentication in Nest.js with @nestjs/passport
I 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 ...
34
votes
2
answers
50k
views
What is the right way of production deployment of nestjs application
I've developed simple nestjs rest services. Now I am planning to deploy my app. Please help me with efficient way of production deployment of nestjs app.
33
votes
2
answers
51k
views
validate nested objects using class-validator in nest.js controller
I want to validate body payload using class-validator in a nest.js controller. My currency.dto.ts file is like this:
import {
IsNotEmpty,
IsString,
ValidateNested,
IsNumber,
...