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,816
questions
156
votes
10
answers
153k
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 } ...
144
votes
30
answers
151k
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';
^^^^^^
...
140
votes
4
answers
66k
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
112
votes
5
answers
279k
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://...
104
votes
11
answers
168k
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
55k
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 ...
91
votes
3
answers
45k
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 ...
86
votes
6
answers
165k
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 } ...
86
votes
5
answers
127k
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 ...
85
votes
22
answers
49k
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 ...
83
votes
9
answers
85k
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 [...
79
votes
10
answers
83k
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 ...
77
votes
15
answers
188k
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 ...
76
votes
3
answers
153k
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 ...
76
votes
13
answers
182k
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'
| ...
75
votes
8
answers
124k
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 ...
69
votes
17
answers
181k
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 './...
69
votes
6
answers
129k
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 ...
69
votes
9
answers
101k
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 ...
69
votes
12
answers
77k
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:
"@...
67
votes
9
answers
101k
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 ...
66
votes
15
answers
80k
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(...
64
votes
15
answers
31k
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
13
answers
75k
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';
...
62
votes
5
answers
55k
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,
...
59
votes
2
answers
97k
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 ...
53
votes
12
answers
141k
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 ...
52
votes
16
answers
102k
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 ...
51
votes
4
answers
56k
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/:...
49
votes
6
answers
139k
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.
47
votes
12
answers
105k
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 ...
47
votes
3
answers
82k
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())
...
46
votes
4
answers
28k
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
11
answers
32k
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 ...
44
votes
6
answers
77k
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 ...
43
votes
5
answers
41k
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 ...
42
votes
11
answers
52k
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 ...
41
votes
5
answers
92k
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
@...
41
votes
5
answers
34k
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 ...
40
votes
6
answers
42k
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/...
40
votes
3
answers
25k
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
11
answers
70k
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 ...
38
votes
9
answers
23k
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.
...
38
votes
2
answers
71k
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, ...
37
votes
9
answers
28k
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"). ...
37
votes
9
answers
54k
views
Boolean parameter in request body is always true in NestJS api
Consider this endpoint in my API:
@Post('/convert')
@UseInterceptors(FileInterceptor('image'))
convert(
@UploadedFile() image: any,
@Body(
new ValidationPipe({
...
36
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 ...
36
votes
3
answers
19k
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)...
35
votes
5
answers
40k
views
Unable to import ESM .ts module in node
I have been trying to import an ESM module written in typescript in nodejs. But I am getting the following error:
An import path cannot end with a '.ts' extension.
Util.ts
export class Util {
...
35
votes
17
answers
90k
views
nest Command not found
I followed the documentation to create my first NestJS project.
Installing the Nest CLI with the command npm i -g @nestjs/cli was successful.
The output was:
+ @nestjs/[email protected]
updated 1 package ...