-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestJs.txt
More file actions
1223 lines (913 loc) · 31.1 KB
/
Copy pathNestJs.txt
File metadata and controls
1223 lines (913 loc) · 31.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Nest JS
.....................................................................................
What is Nest.js?
Nest.js is a framework for building efficient,scalable Node.js server-side applications.
Server side apps Types:
1.Monolith - Old of way building distributed apps
2.Microservices -Modern way of building distributed apps.
Nest.js can be used to build both applications.
Our focus mostly is Microservice based apps.
Micro service is collection of independant apps talks each other for exchaning data.
Apps are collection of apis.
In Genernal we can create different types "api"
API means Application programming interface.
API is implemented in many ways.
API is implmented via object oriented models like classes or via functional programming.
Objects encapsulate apis.
API are used to carry out biz logic like "fetching data,saving,updating,deleting,sorting,filtering,"
Objects are hosted on runtimes, the other applications like other apis or userinterface apps like browsers,mobile apps may try to communicate those objects.
Based on Communications(Communication Protocals) apis are classified:
There are many protocals.
HTTP
HTTP2
TCP
UDP
HTTP based APIS(App)
..................
1.Web Services
1.1.XML based- HTTP With SOAP - SOAP Web Services
1.2. Data Independant based - Direct HTTP with various data formates like json,xml,html,pdf.... : RestFull Webservices.
1.3.Data Independant based - Direct HTTP with JSON based
...GraphQL
GraphQL is alternate to RESTFull WebServices.
2.2.RPC Based API
Remote Procedure call.
APIS are communicated via "TCP" Protocal at low and high level.
RPC based in java
=>RMI,EJB...
RPC language independant
=>gRPC is most popular framework for building TCP based apps at low level
=>gPRC uses a protocal called "protobuff" Which is HTTP 2 Based.
Nest.js supports "REST api,GraphQl api, gRPC api" style development.
...................................................................................
Nest.js Development Arch
Nest apps can be written in plain js or with object oriented js via Typescript.
Nest App
|
-------------------------------
| |
Javascript Typescript
Note: Nest with Typescript is highly recommended.
Popular Server side(Micro/monolithic) frameworks
1.express
2.hapi
3.fastify
4.moleculer
5.loopback
etc....
There are lot of frameworks available in the market but lacks common problems like
popular design patterns like MVC,Dependency,Decorator based,Class Based object oriented
You can see all best features and design patterns available in the front frameworks
like angular,react,vue
if you take angular is the best framework which incorporates all industry standard design patterns like MVC,dependency injection,class and interface based,decorators based,modularity
What if i want the angular like framework in server side , there was no frame work but now we have that is "Birth of NEST.js"
Nest.js is replica of Angular in the Server side
Nest inspired from "Angular"
Features of Nest.js:
1.Nest is MVC Framework
2.Nest is Dependency Injection framework
3.Nest is Modular framework - ES 6 based modularity and Logical Modularity.
4.NEST is pure class and interface based
5.Nest supports Decortors
6.Nest supports all typescript features
7.Nest provides infrastructure to build any type of apis
8.Nest supports "reactive programming" via rxjs for advanced async stream based programming
....................................................................................
Project Setup- Nest app creations
...................................................................................
Nest CLI
It is command line interface tool that helps to
=>initialize /create new project
=>dev features like hot reloading, bundling for testing
=>schematic features to create artifacts - code generation.
=>To create production builds
=>To test apps including unit testing,etoe testing..
How to install nest cli?
npm install -g @nestjs/cli
like angular cli
npm install -g @angular/cli
How to verify?
>nest --help
nest --help
Usage: nest <command> [options]
Options:
-v, --version Output the current version.
-h, --help Output usage information.
Commands:
new|n [options] [name] Generate Nest application.
build [options] [app] Build Nest application.
start [options] [app] Run Nest application.
info|i Display Nest project details.
add [options] <library> Adds support for an external library to your project.
generate|g [options] <schematic> [name] [path] Generate a Nest element.
Schematics available on @nestjs/schematics collection:
┌───────────────┬─────────────┬──────────────────────────────────────────────┐
│ name │ alias │ description │
│ application │ application │ Generate a new application workspace │
│ class │ cl │ Generate a new class │
│ configuration │ config │ Generate a CLI configuration file │
│ controller │ co │ Generate a controller declaration │
│ decorator │ d │ Generate a custom decorator │
│ filter │ f │ Generate a filter declaration │
│ gateway │ ga │ Generate a gateway declaration │
│ guard │ gu │ Generate a guard declaration │
│ interceptor │ itc │ Generate an interceptor declaration │
│ interface │ itf │ Generate an interface │
│ middleware │ mi │ Generate a middleware declaration │
│ module │ mo │ Generate a module declaration │
│ pipe │ pi │ Generate a pipe declaration │
│ provider │ pr │ Generate a provider declaration │
│ resolver │ r │ Generate a GraphQL resolver declaration │
│ service │ s │ Generate a service declaration │
│ library │ lib │ Generate a new library within a monorepo │
│ sub-app │ app │ Generate a new application within a monorepo │
│ resource │ res │ Generate a new CRUD resource │
└───────────────┴─────────────┴──────────────────────────────────────────────┘
How to create new Project?
By default nest creates "REST api" - Web Services
nest new myfirst-app
my-nest-app> code .
Project Structure:
It has lot of files and folders.
readMe.md
How to use this project
package.json
gives information about this project like
-basic scripts - run,build,test
-Dependency - basic default dependency for the project.
Basic nest dependency:
dev + prod
@nest/common
@nest/core
@nestjs/platform-express
rxjs
What is @?
private package
what is nest?
nest folder
what is common or core
subfolder
nest-cli.json
provides information /configuration about the project.
node_modules
-provides all basic libs and apis
src
->root application folder
files
-main.ts
-app.module.ts
-app.controller.ts
-app.contoller.spec.ts
-app.service.ts
test
-contains etoe test configurations
....................................................................................
How to start app?
There are three mode
1.dev mode
2.dev mode with watch
3.prod mode
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
....................................................................................
Nest js Application Arch
....................................................................................
Nest Core Concepts:
1.Modularity:
...........
There are two types of modularity
=>Physical Modularity - files and folders along with "ES 6 module keywords
"export,export default and import"
=>Logical Modularity
Code is organized into object called module.
Any distributed apps/user interface apps.
App is collection of features like customers,products,payments.
Each feature is classfied as layers.
Basic Layers in Server side apps:
................................
In case if it is WebService(REST Api).
1.Controller
Where We expose apis which to be communicated by other apps like front end or other apis
2.Service
Where we have biz logic like save,findAll,delete,remove,filtering,sorting
Services are communicated by controller.
3.Repository(DAO)
This is optional layer now a days, which directly communicates the Datasources
like databases via ORM frameworks.
How to organize the features in code?
for eg : order Feature - controllers,services,orm(entities),utilities......
each layer of code is organized phsyically "files and folders" -This is called phsyical modularity.
order
|
controllers
OrderController.ts
services
OrderService.ts
utilites
OrderUtility.ts
According to Nest code style guide
feature based
src
|
order
order.controller.ts
order.service.ts
order.utility.ts
order.entity.ts
order.controller.spec.ts
...+other files
product
product.controller.ts
product.service.ts
product.utility.ts
product.entity.ts
product.controller.spec.ts
eg:
src
|
orders
|
order.service.ts
export class OrderService {
...apis
}
src
|
orders
|
order.controller.ts
import {OrderService} from './order.service'
export class OrderController {
constructor(private orderService:OrderService){}
}
.....................................................................................
2.Nest is Object oriented
Nest has been built Typescript rich features like strong typing,class based...
In Nest every thing is Object.
In Nest objects are classified into two category.
1.Nest infra structure object
2.Domain objects
1.Infrastructure object
The object which makes up applications..
-Module -Logical Modularity
-Controllers
-Services and Providers
-Pipes
-Guards
2.Domain objects
Objects which represents data called as models/entity.
Domain objects are mostly javascript literal objects /class objects
Module Object:
Nest application is encasulated into one single Big Object called "Root Module/App Module".
How to create object?
we need to declare class?
export class OrderController{}
we need to create object
let orderCtrl = new OrderController()
Are we going to create objects like above in Nest?
"No"
Nest framework /Nest Runtime (nest ioc engine/container) takes care of "creating Objects and linking objects with objects automatically" which is called "IOC"
Refer
https://www.martinfowler.com/articles/injection.html
How nest understands that this class is infrastructure class?
export class OrderController{}
export class Greeting {}
We can tell to the nest ioc container via "Decorators"
Nest provides lot of built in Decorators
@Controller('order')
export class OrderController{}
when ever nest sees this code, which creates object/initalizes all dependencies.
We will see lot of decorators later
Basic Decorators
1.@Controller -controller
2.@Injectable - service
3.@Module-Module Object
....................................................................................
Primary Objects
and
Nest BootStrap Process
.....................................................................................
Nest Application Object:
Every Nest app is encapsulated inside Nest Application.
Every Nest app has entry point called "main" program.
How to create Application object?
By calling NestFactory is class having method called "create" method.
NestFactory.create => className.method
Here "create" method is static method
static methods are called without creating instances
How to create object?
new ClassName() =>constructor pattern
className.createInstance() =>Factory Pattern /Builder Pattern
create methods take "AppModule" as parameter.
AppModule is object which encapuslate other objects
Every NestJs application "must have one single Root /App Module"
Every AppModule must have one single Controller called "Main Controller/App Controller"
.....................................................................................
Nest Web Service
By default nest app is encapulsted with "RESTAPI".
if you want to run web service(restapi), you need web server and container.
Nest application also need web container.
By default nest nest applications are running on the top of "express"
Express provides low level web container features
express:
const express =require('express')
const app = express()
app.listen(3000,()=>{});
'Nest application can be executed on even in another container too "Fastify" '
....................................................................................
How to write module?
Module is logical contaniner which encasulates other objects like controllers,services...other submodules
Whether you create main module or submodule , the syntax remains same.
In nest every thing is object including module,
in order to create object we need class.
Step 1: Declare class and you have share the class so that other class or program can use (You have to use es 6 export or export default keyword).
export class AppModule {
}
Step 2:
we need to create object for the class.
you need to say what type of object you create? (domain or infra)
In case of infra object we never create object using new Constructor().
Nest provides a feature called "IOC container" Which is program , responsiable for
creating objects
How to tell to the IOC Container that go and create object?
Via "Decorators"
in order to create module object "@Module" decorator is used.
import { Module } from "@nestjs/common";
//in order to qualify this is Module object
@Module()
export class AppModule {}
Decorator Meta Data:
.....................
The Decorator may or may not take parameters.
Parameter value can any type like primtives or object or array.
@Module parameter:
It takes object as parameter.
"Ioc container not only create objects but also properly link all dependencies"
Decorator Meta Data takes configuration which is information for "Nest" IoC container.
//parameters are used to link objects
@Module({
imports: [],
controllers: [],
providers: []
})
imports:[]
-All submodules like usermodule,product module
controllers:
-List of controllers part of this module
providers:
-List of services to be created
....................................................................................
Controllers
....................................................................................
Controller is also object which is created by Nest IOC container
Step 1: Declare class and export
export class AppController {
}
Step 2: Decorate as controller
@Controller()
export class AppController {
}
parameter is empty which means root "/" without route.
Step 3: Write http based apis.
Nest provides to mark api which to be communicated by http clients using HTTP verbs
"GET,POST,DELETE,PUT"
import { Controller, Get } from "@nestjs/common";
@Controller()
export class AppController {
constructor() { }
//apis
@Get() // http get method
public hello(): string {
return 'Hello Nest App!'
}
}
....................................................................................
Service Object
....................................................................................
Service is layer where we write biz logic.
Service is object , created by Nest ioc container.
Steps:
1.declare class and export
export class AppService {
}
2.Decorate the service with @Injectable
import { Injectable } from "@nestjs/common";
@Injectable()
export class AppService {
constructor() { }
//biz logic
public sayHello(): string {
return "Hello Nest App!";
}
}
3.Configure the service inside module -AppModule
providers:[AppService]
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
constructor() {}
//biz logic
public sayHello(): string {
return 'Hello Nest App!!';
}
}
...................................................................................
How to structure Nest Application
(Nest style guide)
....................................................................................
Nest Application must be modularizied.
Every Nest application is created based on "features/domain"
A feature module simply organizes the code relevant for a sepcific feature, keeping
code organized and establilishing clear boundaries.
This helps us manage complexity and develop with "SOLID" principles, as the size of the project/app team grows..
products,customers,payments,....
common/util
You have to create sub folder which represents domain /feature
src
|
heroes
|
hero.controller
hero.service
hero.module
villains
villain.controller
villain.service
villain.module
shared
shared.module.ts
filter-text.service.ts
2.plan Logical modularity
=>For each domain, we must have logical modularity - sub module
heroes
hero
hero-list
shared
heroes.module.ts
All controllers and services related to that domain, must be injected into that submodule only, not inside main/app module.
rootFolder - src
Must contain only root module and root Controller
File structure conventions:
...........................
->file must follow the domain model.
greet
user
product
customer
->file name must follow like
domainname.infraname.ts
greet.module | service |controller |guard | pipe .ts | spec.ts
greet.module.ts
greet.controller.ts
greet.service.ts
greet.controller.spec.ts
->class Names
->Noun Customer,Product,Greeter
Customer|Module|Service|Controller
->It has to end With infra Objects
CustomerModule
CustomerController
CustomerService
->root files
app.controller|module|service
if you have any dto/models/entities and interfaces
src
|
heroes
|
dto
|
hero.dto.ts
interfaces
hero.interface.ts
Eg:
...
Greeter :Domain
Step: 0 : create folder
src/greeter
Step: 1 Create SubModule
src/greeter/greeter.module.ts
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [],
providers: [],
})
export class GreeterModule {}
Step 2:create Service layer
import { Injectable } from "@nestjs/common/decorators";
@Injectable()
export class GreeterService {
constructor() { }
//apis
public sayGreet(): string {
return 'Greet to Nest App'
}
}
Dependency Configuration:
src/greeter/greeter.module.ts
import { Module } from '@nestjs/common';
import { GreeterService } from './greeter.service';
@Module({
imports: [],
controllers: [],
providers: [GreeterService],
})
export class GreeterModule {}
Step 3: write controller
import { Controller, Get } from "@nestjs/common";
import { GreeterService } from "./greeter.service";
@Controller('api/greeter')
export class GreeterController {
constructor(private greeterService: GreeterService) { }
//HTTP apis
@Get()
public sayGreet(): string {
return this.greeterService.sayGreet();
}
}
Dependency Configuration:
import { Module } from '@nestjs/common';
import { GreeterController } from './greeter.controller';
import { GreeterService } from './greeter.service';
@Module({
imports: [],
controllers: [GreeterController],
providers: [GreeterService],
})
export class GreeterModule { }
Step 4:
Configure GreeterModule inside AppModule.
import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { GreeterModule } from "./greeter/greeter.module";
//in order to qualify this is Module object
@Module({
imports: [GreeterModule], // if AppModule has any submodules as dependency
controllers: [AppController], // if AppModule has controller as dependency
providers: [AppService] // if AppModule has Service as Dependency.
})
export class AppModule { }
.....................................................................................
.....................................................................................
Automation-Code Generation
.....................................................................................
Steps we have followed:
1.created folder
2.created files like modules/controllers/services
3.depedency injection and configuration
It is complex step, in order to avoid this steps manually nest offers a cli command
nest generate
generate|g [options] <schematic> [name] [path] Generate a Nest element.
options:
-d, --dry-run Report actions that would be taken without writing out results.
-p, --project [project] Project in which to generate files.
--flat Enforce flat structure of generated element.
--no-flat Enforce that directories are generated.
--spec Enforce spec files generation. (default: true)
--skip-import Skip importing (default: false)
--no-spec Disable spec files generation.
-c, --collection [collectionName] Schematics collection to use.
-h, --help Output usage information.
eg:
nest g mo users
CREATE src/users/users.module.ts (82 bytes)
UPDATE src/app.module.ts (313 bytes)
src/users/users.module.ts
import { Module } from '@nestjs/common';
@Module({})
export class UsersModule {}
src/app.module.tsimport { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { GreeterModule } from "./greeter/greeter.module";
import { UsersModule } from './users/users.module';
@Module({
imports: [GreeterModule, UsersModule],
controllers: [AppController]
})
export class AppModule { }
...........
Service:
nest g s users/user --flat
CREATE src/users/user.service.ts (88 bytes)
CREATE src/users/user.service.spec.ts (446 bytes)
UPDATE src/users/users.module.ts (241 bytes)
....................................................................................
Building REST API
...................................................................................
Controllers
Routing
Request Objects
Resources
Status and Headers
Request Parameters
Request Payload
..
Controllers:
Controllers are responsible for handling client request and generate responses..
Routing:
The Routing is mechanism controls which controller receives which requests.
Generally a Controller can have more than one Route , different route can perfrom different actions.
Decorators:
@Controller() => without parameter
@Controller('users') => root route
HTTP method decorators
@Get => get req => GET /rootRoute eg ; GET /users
@Post=> POST req
@Put => Update req
@Delete => Delete Req.
All these operations are called "CURD" operations
Eg:
user/user.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserService {
constructor() {}
//users api
//CURD operations
public findAll(): string {
return 'users';
}
public save(): string {
return 'save';
}
public update(): string {
return 'update';
}
public remove(): string {
return 'remove';
}
}
user/user.controller.ts
import { Controller, Delete, Get, Post, Put } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('users')
export class UserController {
constructor(private userService: UserService) { }
// Get /users
@Get()
findAll(): string {
return this.userService.findAll()
}
@Post()
save(): string {
return this.userService.save()
}
@Delete()
remove(): string {
return this.userService.remove()
}
@Put()
update(): string {
return this.userService.update()
}
}
.....................................................................................
Nest CURD Generator
...................................................................................
Resource:
In RestFull web services, apis are defined or structured as resources.
Resource represents domain eg: "UserResource,ProduceResource,CustomerResource"
Why CURD Generator?
Without Curd generator for a domain/resource,you have to write so many steps
=> Generate module -> nest g mo
=> Generate a controller -> nest g co
=> Generate a service -> nest g s
=> Generate a generate entity
With Curd generator you can do every thing with single command.
Generate a new Resource
nest g resource
=>creates a module,controller,service,entity class,DTO ,spec files...
eg
nest g resource products
? What transport layer do you use? REST API
? Would you like to generate CRUD entry points? Yes
CREATE src/products/products.controller.ts (957 bytes)
CREATE src/products/products.controller.spec.ts (596 bytes)
CREATE src/products/products.module.ts (268 bytes)
CREATE src/products/products.service.ts (651 bytes)
CREATE src/products/products.service.spec.ts (474 bytes)
CREATE src/products/dto/create-product.dto.ts (33 bytes)
CREATE src/products/dto/update-product.dto.ts (181 bytes)
CREATE src/products/entities/product.entity.ts (24 bytes)
UPDATE package.json (1975 bytes)
UPDATE src/app.module.ts (707 bytes)
√ Packages installed successfully.
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Data base integration
Mongo db Integration
NestJS project setup
MongoDB connection
Mongoose schema
DTOs
CRUD APIs
Validation
Service layer
Controller layer
Environment configuration
Steps:
1.nest new mongoapp
2.install dependencies
npm install @nestjs/mongoose mongoose
npm install class-validator class-transformer
npm install @nestjs/config
3.CURD RESOURCE generation
nest g resource users
src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
//TO read ".env files"
ConfigModule.forRoot({
isGlobal: true,
}),