Afrikaans
Akan
Albanian
Amharic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
learn the fundamentals of nestjs by
building the back end of a Spotify clone
nestjs is a framework for building
efficient scalable node.js web
applications you'll learn how to design
a database create rest apis and deploy
the apis to production how did Alie
develop this
course welcome to my course
nestjs let's talk about what is
nestjs nestjs is used to build server
side application in node.js it is built
on the top of node.js
expressjs and
typescript the major difference between
nestjs and other nodejs framework is
this framework is using
typescript and it is using the angular
architecture angular Concepts on the
pack if you familiar with angular
concept you can work with nestjs is very
easily why they are using the angular
concept because if you use the angular
architecture Concept in the back end you
can organize your project in a easy way
the development would be
easy the contribution for other
developers would be easy in
sjs look at the
documentation you will find the
controllers providers modules middleware
exception filter pipes guards inter
interceptors and custom decorators all
of these are Concepts in
angular why they created nests if you
have worked with Express you don't have
any structure like you don't have any
best practice to organize the backend
project so they created the structure
architecture level they designed the
architecture to build server side
applications in nodejs and
typescript under the it is using
expressjs and
typescript so they are just solving the
architecture problem when you build the
large application in nodejs we backend
web application in
nodejs when your code base is increasing
day by day it's hard to follow specific
architecture that's why they have
created the
nestjs if you follow the nests you will
see hey we need a controller we need a
provider we need modules we can break
application into multiple modules we
need a middleware we need exception
filters so this is how you can architect
your backend
application this is exciting project I'm
going to share you all of these Concepts
in this course
let's create a new project in
njs first of all you need to install ljs
globally on your machine I'm going to
install nestjs CLI this this command
will help us to generate nests
project my CLI has installed now we need
to create a new project you can use this
command Nest new the name of the project
you can choose any name
here I just use in fundamentals dpro I'm
going to use
[Music]
npm now it is going to it's going to
install all of these packages for
me now my project has created
successfully so I'm going to navigate to
my project
directory this is end fundamentals Das
Pro now I'm going to open that into my
code editor I'm going to use vs
code so when you open the package.json
file you can run your project in
development mode by using this command
npm start
Dev npm Run
start
D
you can see my project has started
successfully uh by default njs uses 3000
Port you can verify that from the main.
file I'm going to go to the Local Host
call in
3000 let's see what will
happen you can see Hello
World so our project is running fine now
in the app controller you will have a
simple message the simple controller
method it's a route get
hello and you will see the hello world
here hello world or you can say hello
I'm learning
nestjs I saved the application it has
reloaded
successfully let me send the request
again you will see hello I'm learning
njs
so this is our source folder you will
place all of your Source folder source
code inside the source folder this is
our main.ts file when you run this
command npm run Start Da njs is going to
call this bootstrap function and inside
the bootstrap we have a factory function
and we are initializing the app module
this is our root module in here we have
set the port we have the service we have
module controller and the test file for
a controller this is our module remember
this is the angular structure and each
module is consist each module consist of
controllers services and providers you
can import multiple modules here we have
the
[Music]
service and uh you will place all of
your spec file inside the test end to
end test should be uh saved here and
unit testing you unit testing files will
be located here this is eslint RC rules
for eslint prettier
n if you want to customize the nest C
nestjs project you will do inside the
nest CLI we have package.json file we
have TS config and TS config build this
is used for typescript configurations
let's talk about the concept of module
in
njs in njs each module is consist of
providers controllers imports and
exports so this is the building block of
nestjs application you can read my notes
I have provided you the PDF
documentation nest in providers nestjs
are classes that act as a Services
factories or
repositories if you have worked with
angular you know the
providers so you can encapsulate your
business logic and it can be injected
into controller or other
services so controller serve as the
function of handling HTTP request
whenever you create a new endpoint you
will register it inside the
controller I'll teach you more about
controllers in the next video Imports is
an array specify the external modules
needed for the current module you can
import other module let's say you have
break down your application e-commerce
application into multiple modules you
have post module you have products
module you have ERS module you have
users module let's say a user module can
use
the product module this is how you think
in terms of modules if you want to
export you can also export controllers
and services from the current
modules so each nestjs application will
have a root module just like in angular
root module serve as the entry point and
is responsible for instantiating
controllers providers and other core
elements
nextjs follow the module isolation
principle ensuring that application is
organized into distinct functional or
feature based modules so you will have
root module app module let me check the
application you will have the app module
you can see that you have Imports array
this module has app controller and app
service let's say we're going to build a
back end of Spotify application we can
divide our application into multiple
modules you will have a root module and
I'll have the artist which is feature
module and we will have songs module to
handle the songs functionality we have o
module to handle authentication these
three are all the feature
modules SS modules are a functional
organizational unit that follow the
modularization principle it helps to do
code free usability and separation of
concerns principle under the hood they
have implemented the principle design
pattern to organize your code that's it
let's create a new module I'm going to
create a song
module you can use CLI Nest G4 generate
in the name of the module which is the
module keyword I want to generate the SS
module here you can provide any name I'm
I'm interested in the songs module so
you can see in the app. module it has
added the entry automatically for you in
the Imports array and you can see you
have a songs module that's it so this
songs module will have controllers
providers and imports and exports
array controllers are responsible for
handling incoming request and sending
response back to the client we are
building the Spotify clone
application let's imagine or let's say
you want to fetch all the songs or you
want to see all the songs of Martin gck
artist your browser will send the find
all songs request to the nestjs
application inside the nestjs
application you will have songs
controller inside the songs controller
you can see we have find all
method the find all method will be
called and this method will fetch the
songs record from the
database and send respon response back
to the
client similarly you can send the same
request from your mobile application so
controller will be responsible for
handling request and sending response
back to the
client you can create a controller very
easily all you need to do is
controller
decorator and inside The Decorator you
can provide the prefix route prefix
if you want to define the request
Handler inside the controller you have
to use the HTTP get decorator if you
want to create the post endpoint you
have to use the post
decorator it's just returning a simple
string message fetch all the songs and
this method will be converted into this
API
endpoint Local Host callon 3000 /
songs
we are going to build these API
endpoints to fetch all the
songs to fetch a single song I created
these routes to create a new song to
update a song on the based on ID and
delete a song on the based on
[Music]
ID I'm using the rest client extension
to send the API calls it is similar to
The Post
men if you don't have rest client you
can find from the vs code extensions and
find the rest client the rest client
package is saying You must have a file
with
HTTP I created the HTTP
extension now my application is running
at Port 3000 my development project is
running at 30001 you should not aware
you should not care about this project
we are building project on Port
3000 if I send the request to fetch all
the songs we don't have any rout yet it
is giving me the warning message or
error 44 you don't have all these end
points I want you to accept the
challenge and start building these end
points we don't have any
controller let's stop the
application and I'm going to create a
controller
songs you can see that songs controller
has created inside the songs
folder we have spec file testing file
and controller. TS file this is the
controller decorator this is the
prefix one more thing it has added the
end entry in the controllers
array now let's create the request
Handler first of all I'm going to
implement the
get find
all it is going to return a simple
message find all
songs
let's restart or run the
application you can see that our
application is running
now let's fetch all the songs I got find
all the
songs find all songs endpoint it means
we successfully created the route to
fetch all the
songs now now I can send the
request to fetch the songs watch all
songs end
point let's create a
single
song endp
point you have to use the ID as a
dynamic
parameter I can say find
one
here I can
say fetch song on the based on
ID similarly we
need update put for update I'm going to
use the put HTTP
verb
update update song on the based on ID we
also need
delete
I can get the delete from
here let me replace the update to
delete delete song on the based on ID
and finally we need a post
endpoint to create a new
song I can say the
post
create create a new
song so we created the CED API end
points now it's time to send all the
request it's working fine now create a
new song endpoint update song on the
based on ID delete song on the based on
ID
now you got the basic understanding of
controller and how to create route in
njs
application let's talk about Services
services are providers it means you can
inject into another class it will be
treated as a
dependency we will have a
service and the service is responsible
for fetching data from the database and
saving data to the
database if you have to interact with
database you have to write the source
code inside the service you will create
a method to interact with
database we will use repositories don't
worry and this service can be injected
into controllers if you have multiple
controllers into module you can inject
the same service into that controller or
multiple controllers you can also export
the service from a current module and
you can use that service into another
module we will have the song service
it's nothing more it's just a class and
all you need to do is to injectable
decorator it means you can inject as a
dependency into another class
this is how you will inject the service
into controller or into a class you have
to inject it in the Constructor it will
be treated as a dependency for the songs
controller now the songs controller is
dependent on song controller is
dependent on the song
service let's create a new service
I'm going to use n CLI to generate a
service let's write the name which is
songs it will create a class and it will
inject into our songs
module you can see
that we have the song service spec file
which is testing file and we have the
surver
we we have used the injectable
decorator one more
thing it has registered as a provider
inside the songs module I told you
services are provider providers could be
factories helper
function you will learn more about
dependency injection in more details in
the later
mod so I told you service services are
responsible to interact with database
right now we are not going to interact
with database we'll use the postris SQL
postris database in the later videos for
that here I'm going to create a local DB
which it should be array local
array saving saving record in the
disk private read only songs array I'm
going to create the empty array let's
define a new method to create a new song
and it is going to
return
let's push the song make sure you get
the song from the create method there is
a method push and I we need we need to
provide a new
song and let's create another method
find all and and it is going to return a
simple array this. songs and I can
return this. songs
array so we have created two method now
it's time to inject this
service into the controller I want you
to do it accept the challenge and do
it all right I'm going to do it for you
song
service now inside the create I can use
the song service by using the this this
do song service please create a new song
I'm going to provide a dumy
name Animals by
[Music]
Martin you can choose any name don't
worry we will create a separate song
model and separate interface for the
song let's call the
return and for the find all I am going
to use this do song service.
findall let's run the
application
our application is running let's send
the API request to create a new
song you can see I got a new
song if you sent all the songs
request I got all the songs
let's save another
song you can see I got five songs let's
fetch all the songs I got all the
songs so our service is working now in
the real world
application we will write the database
code code here here save the song in the
database and here what we will do fetch
the
songs from the
DB but we will implement this feature in
later
videos in this video I'm going to teach
you how to validate the request
body when you send request to the Local
Host call in 3000 3000 SL song we are
trying to create a new
song but let's say if I miss the title
field it is going to give me the
validation
message the title should not be empty
and title must be
string let me REM know the artist
now you can see title should not be
empty and artist should not be empty so
I would like to add this
validation to our create new song API
endpoint when you go to the
Spotify if I click on any
[Music]
song this is the title of the song and
this is the published date or release
date and this is the duration so we're
going to pick title duration and the
date of the
song let's do
it this time I'm going to use class
validator let's install the class
validator
package and we also need class
Transformer
you can see both packages have
installed nexts provide validation pipe
you can use validation pipe for specific
controller method you can use it here or
you can use it here it's your choice but
but I'm going to create a global I'm
going to register it as a global so I
can use in any
controller so you can call use
method there is a method which is use
Global
pipes nexts already created the
validation
pipe you don't need to create it
again I have imported the validation P
from next sjs common
package and now if you don't have dto
which is data transfer object you have
to specify the network data transfer
object properties let's create a new
song create a new file create song
d. now we need to add decorator paste
very
adds let's create a new
class and I'm going to name it to create
song
dto the first property is title I'm
going to make it read
only and we have the second property
which is artist
array and we have another property which
is release
dat
or you can specify the type which is
string and the type of part is it's an
array and we have the
DAT there is another
property which
is
duration
we need to store the duration in the
time
format now I'm going to use the
decorator from class validator the type
of title should be string and it's a
required property so you can say it's
not an
empty we can follow the same stuff for
artist not empty
it's an
array it's an
array and you can say type
string let's add decoration decorator
for release
date type should be string and
class validator provides a
decorator is date
string now we have for if you want to
store the time or add the validation for
the time there is a there is a decorator
which is military
time and it's also required property so
I'm going to add is not empty
so is date string if you want to apply
that you have to add the date in this
format and you have to add the time in
this
format now we're going to apply we have
already
registered validation pipe here and we
created the data transfer object which
is create song dto now I would like to
apply this create song dto in the create
endpoint
you can register it or you can apply it
by using the body parameter please apply
it on the request
body and I can say create
song create
song dto the type is create song
dto and this time I'm going to push
create
song
dto let's try to test it out and we need
to run the
application so we have to send the
request or add the Json body in the
response let me open the rest c. HTTP
file and we need to add the Chason body
let's send the
request you can see title should not be
empty title must be string artist should
not be empty and artist must be an array
so validations have applied
successfully I can say let's say lasting
lover the
title and we need the
artists
s
let's now we're going to test it
out so we have this
record if you will add the date in
different
format you can see dat should be valid
ISO 860 date string for date string
format if I do in this way you will get
the error dur must be valid
representation of military time which is
hours and minutes so it's working fine
now let's talk about the
middleware a middleware function runs
before executing the route
Handler inside the controller songs
controller I have the find all route
Handler and the create route Handler if
you if you want to run any function
before executing the route Handler you
can write your code inside the
middleware it's a
function a browser wants to fetch the
songs before fetching the songs would
you like to call any method would you
like to run your logic would you like to
execute any type of
code middleware can have request object
response object and next
function it means you can customize the
request object if you want to add header
if you want to log the request time you
can do
that a middleware can execute any type
of
code you can modify the request object
if you want to add the request header
authentication token to the request you
can do in the
middleware you can end the request and
response cycle you can call the next
middleware function by calling the next
method we're going to build the logger
middleware let's
imagine you want to send request from
your browser to
server before executing the route
Handler I would like to log the request
message or the DAT
time let's implement the logger
middleware it's a class we're going to
build a class based
middleware and to create a middleware
you need to implement the nextest
middleware
interface it provides a use method and
use method will have the request
response and the next function
here I'm just logging the request dat
time and at the end I'm also calling the
next
function it will if you will not call
the next function it will not go to the
next
step one more thing middleware it's is
like a
dependency you can inject into module
it will act as a
dependency here we are injecting the
middleware as a
dependency to inject the middleware as a
dependency we need to implement the nest
module interface it will provide the
configure method and the consumer will
be middleware consumer and we just need
to call the apply method from the
consumer
object and you need to provide the
logger
middleware here you need to specify
where do you want to implement the
logger middleware I would like to
implement for songs
API let's implement the locker
middleware before creating a middleware
I'm going to use Nest
CLI please give me the help for nest
generate command
you can see that I got all the commands
related to Nest
generate you can generate class
controller decorator filter
guard middleware pipe
provider we also have other options like
no flat please do not create directory
or no spec please do not create testing
file let's create a new folder
common I'm going to place all my middle
Wares inside the common
directory next generate
Mi common
SL
middleware
and the name of the middleware which is
logger and I don't want a spec
file please do not create the
directory let's try with no flat and
dash dash dry run
let's see what will happen dry run it
will not
create the actual file but got the steps
you will get the understanding how it
will
run it's working fine now no files
return to dis but when you EX cute this
code it will create the logger
middleware file inside the middleware
directory that looks good so I'm going
to remove the dry run let's write the
file
perfect we have created the logger
middleware you can see that it has
already implemented the nest mid
middleware
interface and I got the use method with
these three arguments request response
and the next function here you can
customize the request object if you want
to add your custom logic you can do it
here I can say request dot dot
dot new date whatever you want to do do
to dat
string so we created the
middleware
now I told you or I taught you how to
apply the middleware I want you to do it
in the app
modle we need to implement the nest
module you can see that I got the
configure
method and we need to call consumer.
apply the name of our middleware which
is logger
middleware and we have the four
roots or
routes I can say the
songs now we need to test it out let's
run the
application
my application is running now we need to
send the API
request if you will send the request to
the root URL which is Local Host colum
3000 our middleware function will not
run because we applied the logic to
songs
route fetch all the songs and I
got the the log here request log send
the post request I got the request log
send the put request or send the delete
request I got the
log there are two other options to
implement the or to apply logger
middleware I can say option number
one consumer. apply logger
middleware for
routes
please run for only
songs path
and for only
run request method.
poost it could be option number
two if you send request
get request to fetch all the songs it
will not run if you will send the post
request for the songs I got the request
if you send the put you will not see the
request
log another option we
have let's do
it
consumer zor dot apply logger middleware
for
routes you just need to provide the
controller it could be option number
three it depends on what use case you
like to
use now I can fetch all the songs and I
got the request
log which create a new song I got the
request
log update a new song and I got the
request
log this is how you will create a
middleware did you think about the error
handling in
njs if error comes from your application
code nestjs provide builtin HTTP ex
exception so let's say error comes
while
fetching the data from DB but we did we
did not add any logic to handle the
errors
gracefully let's
imagine we got the error while fetching
the data from the
DB error in
DB while fetching record let's imagine
that when error will happen nestjs will
send this error to http exception this
is the built-in exception in
nestjs let me let me send the request to
fetch all the
songs you will see the server error with
500 status
code next s has sent this message from
HTTP
exception but you can use the
exception in your controller
functions let's say I can
say
or did you think about how can you catch
the
errors you have to use the try catch
block I can log a simple
message I am in
the catch
block and this is my
error
let's try to fetch all the
songs you can see that I got the error
message I'm in the catch block and this
is the
error it means we successfully got
caught the
exception but we want to send the useful
method in the useful status code in the
response I can not see anything
here for that we need to use the HTTP
exception I can say through new HTTP
exception it's a
class and we need to provide the
message can say server error or whatever
you want to say I can say server
error and we have to provide the status
code
HTTP status provides a lot of status
codes you can use
anything whatever you want to do for me
server
error internal server
error if you want to send the message or
cause which should be the error this
one let's try to fetch all the songs
you can see that I got the message
server error with 500 status code which
successfully caught the
exception but if you want to use
different error message you can do that
you can use forbidden status
code it will
work let's restart the
application now I got it
so we have the status code 403 instead
of
500 I'm going to replace forbidden to
internal server
error this is how you will cach the
exception in your source
code if error will come from this
service this this method
TR cach block will cat the
eror got
it let's talk about the pipes in
njs there are two use cases to use the
pipes the first one is to transform the
value here in our example application we
have the find one method
we are expecting the ID as a input
parameter by default it is going to give
me the string so I can use the parse int
pipe to transform the string value to
number here you will see the type of ID
it should be
number another use case for pipes are to
validate the input parameter
in the create method we will accept the
input argument like song title song
artist we will validate the all the
input arguments by using the validation
pipe let's implement this transform
value in our demo application
so I'm going to remove
it let's start it
again it is giving me this
response in nestjs you get you can get
the dynamic parameter by using the ram
decorator Ram decorator and the name of
our argument which is
ID I'm expecting the
ID
and I use the template
string let's define the type of
ID I'm going to send the request you can
see the type of the ID is
string we were expecting the number
type but nestjs got us the string
type you can convert this string into
integer or the number by using the pipe
Pars in pipe that's
it let's send the request to fetch the
song on the based on ID you can see I
got the number ID number type if I
provide the string value
here you will get the validation error
validation failed numeric string is
expected bad request
error if you want to customize the error
message you can instantiate
it eror status codee HTTP status dot not
acceptable now I got not acceptable if I
provide
the numeric string I got the ID which is
number type of the ID is
number we successfully transformed the
string value to number value in the next
video we will implement the input
validation using pipe we will create the
custom validation
pipe you have learned how to inject
dependency by using the Constructor
based dependency injection
pattern we have injected the song
service into the song
controller what what will happen when
songs controller will inject or
instantiate the song service let me open
that songs
controller here we are injecting the
dependency song
service and we have provided as a
dependency
here this one this song
service when Nest container instantiate
the songs controller it first looks for
any dependencies in our case we have the
song
service when it finds the song service
dependency Nest will create the instance
of the song service and cach it and it
will return
it if already created the cache then it
will return from from the cache it will
not create the new
instance let's imagine you are using the
song service inside the multiple
controllers the first controller let's
say we have the songs controller I'm
using it first time
here if I use song service inside the
song service dos back file it would be
treated as a second time now the second
time it will not create any instance it
will get the instance of the song
service from the cache this is the
Singleton pattern applied here next
under the hood created a Singleton
single instance of the song service and
it is going to share the same same
single instance throughout our songs
module but you're going to learn
multiple scope if you want to use the
scop scope strategy if you want to
instantiate a new instance after for
after every incoming request you can use
the scops but I'll talk about the scops
later there are many techniques to use
the providers some of them are standard
providers value Prov providers known
class based provider
tokens class providers we use that class
providers Factory providers used Factory
providers and nonn service providers
we're going to play around with all
these six
techniques let me explain with the help
of
examples this is the standard provider
inside the S module we are using it as a
standard provider but you can convert
the above
syntax into this one let's use
it I need to open my
project we need to create a new
Branch model 3 lesson number
one
open the socks
module so we are using the standard
provider technique but you can write the
above syntax or above
code by using this syntax I can say this
is
provider just this
it
now we have the song service and the
song service please use it as a class
when you inject it into another
class we are using inside the class in
injecting as a
dependency
now you can test the
application
I'm going to send request to any
URL let's create a new song artist must
be
[Music]
stream this is this
true why artist I
think so I got the
issue in the create song d
I did add the H should be true I'm
telling to class
validator the elements of the array type
should be string each element of the
array should be
[Music]
string now it will it will be working
fine if we have three articles or three
artist Martin
and
John you can see that it's working fine
now
so we also tested this syntax this is
the standard
provider but if you like this syntax you
can keep this syntax but I just want to
show
you I'm going to this out uncomment this
one now I got the song
service now I'm going to talk about the
value
providers if you want to create the
moing service instead of the original
service
you can do that with the help of use
value the use value syntax is useful for
injecting a constant value or you want
to put an external Library into Nest
container or replacing a real
implementation with more
object we are using this
one we are replacing a real
implementation of song service with Mo
object
so when you need this use case you have
to use the use value or if you want to
inject a constant value you can use the
use value or if you want to inject
external Library into the nest container
you can use the use
value let's do
[Music]
it
I'm going to create a mocking object
here we have a find all method inside
the song
service when you open the song
service you will see the find all
method but we have to return the songs
I'm not going to throw the
arrow
would be song
service and use
value which is songs moing object Mo
song
service that is it
now
now we need to test
it I'm going to fetch all the
songs and this time you are getting the
response from the mo object not original
song
service so we have the find all method
and it is returning this
one if I will app add the
artist I'm going to fetch all the songs
from the mo service object mock
service and you can see I got the record
from the mock service instead of
original song service find all
method we have learned how to use the
use
value
now if you want to inject the known
class based provider you can do that
let's say I want to inject an object
with
connection we have three
properties connection
string if you would like to inject any
object object as a dependency you can do
it well with use value I told you you
can inject constant by using use value
you can object an you can inject an
object or you can inject the working
object let's create a new file with
connection.
file and I'm going to specify some
connection
properties you have to create an new
constant. file inside the common folder
and I'm going to add the constants
directory here you will have constant.
TS
[Music]
file I can say
connection. and I'm going to copy the
code I just defined three variables and
I have Define the type which is
connection now I would like to register
it as a
provider you can register inside the
songs module or you want to register it
to app module it depends on you provide
this is the name or the token
value this is
how I will
inject in the class when I will inject
in the class I'll use this token
[Music]
key use value let me
provide which is
[Music]
connection so we have to inject it
inside the
song service I can use the add inject
decorator so
songs
controller I think I injected inside the
song
service so I'm going to inject here
inside the song
service or let me inject in the
Constructor
function
here I would like to
inject I can
say
inject let's provide the
key
private
connection here we need to provide the
type I have defined the type this is the
type so I can
log the
connection this.
connection if you will not add the
private so you can add directly without
adding the this keyword I did not add
the provider so I access the connection
string without adding the
this so let's say this is I can
say I'm going to use the template
string this
is connection
[Music]
string when songs controller will be
instantiated this Constructor function
will be called so it will log this
message you can see we have this is the
connection string so I can get the
connection
string now I can see this is connection
string and I can say the connection
[Music]
string or you can
say my SQL dot
dot col do
dot 1 2 3 6 or maybe
Port I created the fake or dummy
connection
stren you have learned how to inject the
object as a
provider and used it as a
dependency
now we're going to talk about class
based provider we have already used the
class based provider here this
one not this one this one used Class so
I'm going to
create a
new
service this this will be called da
config
service inside the dep config service
I'll have one property and a one
function DB host and get DB
host remember it's an injectable
service so you can register it as a
provider inside the app module by using
the use class syntax and you have to
provide the name of your service in our
case we have the da config
service and and then and then I can use
the dev config service inside the app
service
so I can
create a
providers hold up let's
rename
providers let's create a new
class def
config
service.ts
and we
have these properties we have TB host in
the get TB
host so let me register inside the app
module
we have provider and I can say please
provide Dev
config service in the use
class Dev confli
service and and now I can inject inside
the app
module let me inject it
here I can say
private
Dev
config
service and I can say def config
service and I can call the method from
the D config let me convert into the
template
string da config
service. DB
host so
we have to send the request to the root
URL to test
it
rest let me send the
request hello I'm learning NS
fundamental and this is the DB host
which is St config which is Local Host
DB
host
so if you want to inject the known
service provider like a simple
object and you want
to inject Dynamic
value you have added the check or if
condition if node development equals to
development then you you have to inject
the dev config otherwise you have to
inject the pro config if if you have two
objects and you want to inject on the
based on condition this is the known
service provider it means these will not
be
classes if you have this type of use
case you can inject by using the use
Factory so I'm going to
call inside the app module let me let me
show the
demo I just created the two
object and in the
provider we have used the key which is
config and I use the used Factory and we
have to provide the arrow function it's
just returning a value Dev config and
the pro config if you want to in inject
dependency or inject provider only based
on condition then you can use the US
Factory and now the same way you can
inject config
value in the app
service here we have to inject
it by using the
inject decorator provide the key which
is
config in
private
config we have Port value and type a
[Music]
string and you can say Port should
be this do config do
Port so we have to test it to send
request to the root
URL now I got
the host which is Local Host and the
port which is
400 so we have to add
4,000 you have learned how to inject
provider as in the standard way you have
learned the use value you have learned
how to add non class based provider you
have learned how to use use class
provider how to use the dynamic how to
in how to register the dynamic
provider and finally you have learned
how to how to register known service
providers
the previous video you have learned
multiple techniques to register a
providers when you register a provider
by default nestjs use this scope default
it means a single instance will be
created which is called the Singleton
pattern and this single instance of the
provider is is shared across the entire
application nextest cach the instance
when application request for the second
time it will not create a new instance
second time it will return from the
cash another injection scope technique
which is
request a new instance of the provider
is created exclusively for each incoming
request and we have the third technique
injection scope technique transient
providers are not shared across consumer
each consumer that inject a transer
provider will provide a new dedicated
instance most of the time you need
default scope because single turn
instance is recommended to improve the
performance of your
[Music]
application when you get the instance
from the C
it will give you the instance in the
more faster way instead of creating the
complete object it just give you the
copy of the already created
object so you can play around with
injection
Scopes let's
say if you want to use it inside the
song service I didn't I could not find
how to debug the dependency injection
so you have to use
here
[Music]
scope injection
scope what we have to say
scope scope
to
transient the performance of your
application will be
hard it will decrease the performance
but but it depends on your use case what
are your
requirements similarly when every
incoming
request if you have use case you want to
create a new
instance you can use it well for the
requesting purpose for testing
purpose I'm going to open the songs
controller
and here we have to
[Music]
say
it's an
object let's import this
scope I'm going to send the API request
it's working fine
one thing you did not
notice when I will create a new song it
should add the song in the array
so I have created three
objects three songs object in the songs
array when I will send the request to
fetch a single song or all
songs it should give me the empty
response because on every
request it will delete it the complete
data complete
songs
because it will also re instantiate the
song service inside the song service we
we have the
are we have the songs
are you can see I created the song now
when I try to fix all the songs it
should give me the first song or all
songs you can see the empty
response in this video I'm going to
teach you how to add one to many or many
to one relationship between two entities
where a contains multiple instances of B
entity and B entity contains only one
instance of a
entity we have two use
cases we are building this Spotify
clone if you are using or you use
Spotify each user has its own playlist
and each
playlist can have multiple songs so you
as a user can store multiple songs or
save multiple songs in the playlist so
there is a one to one one to many
relationship between playlist entity and
the songs entity see similarly we have
each user can have multiple playlist
many playlist can belong to a single
user so this is also a many to one
relationship between playlist and the
users let's create the playlist entity
and add
relationship we don't have any
playlist entity go ahead and create a
playlist
entity I have created a new folder
playlist. entity. TS
file so I'm going to copy couple of the
code from
my
notes we have created the playlist
entity
now we have to make make a relationship
between songs and the
users
similarly type orm provides one to many
decorator and this represents the target
entity relation entity we are making a
relationship with song entity this
representing the inverse side of the
relation in the song model we have a
playlist
property and we have the array of the
songs I'm going to copy this code and
I'm going to paste it
here we don't have song.
playlist open the song
entity here we can add a
relationship but we also going to add a
relationship between user so I'm going
to copy this code and paste it
here now we have to add many to one
relationship in the song
entity so many songs can belong to a
playlist for each unique
user we have to import the playlist
import many to one
relation and finally we have to add one
to many relation in inside the song
inside the users user
entity so I'm going to copy that
code inside the user
model and I'm going to paste it
here
now everything is fine
now I have added many to one relation in
the song it means it will have the
primary key of the playlist entity and
save it as a reference key or the
foreign
key now we need to create the clip
playlist
module I also want
[Music]
to create a new playlist I'm going to
create a new
endpoint but first of but first we need
to register our new entity I'm saying to
type orm please convert or make relation
between playlist and the user playlist
and the
song
every everything is fine now when you go
to the pg
admin refresh your
tables you will see playlist
table this is the playlist
table and we have the user
ID when you open
playlist entity we have added the many
to one relation it means it will have
the user ID as a foreign key and inside
this song entity we have added many to
one relationship as for the playlist so
this song will have
the primary key as a foreign key of the
playlist entity let me show
you inside these
songs we have a playlist
ID relations have created successfully
we created one to many and many to one
now I want to show you how can you save
a record with relation
entities
go ahead and create a playlist module
you can use with n CLI to create a
playlist module but I'm going to use my
not
notes
playlists
module. and I'm going to paste my
playlist module we don't have playlist
service and we don't have playlist
controller I can create these two files
controller. let's
create playlist
dot
service.
file I'm going to copy
my playlist
service we have to import couple of tip
dependencies inject
dependency and we need
playlist we need a
user
we we need a song that is good right
now also need to get the
injectable we also need to import report
osit
Tre I don't have any user so import the
user we have service right now and we
going to create
controller
or we can
build create playlist
function I'm going to create a new
method you can see that we don't have
create playlist
dto we are just creating the instance of
playlist I'm providing the name of the
playlist when you go to the playlist
entity you have the name
property each playlist can have multiple
songs so I will get IDs of the songs
from the request
body we are using the same logic in the
previous video we
used here I'm setting the relation with
songs
entity I am creating the playlist when
you are when you need to create a
playlist you have to provide the
name and you can set the relation for
the
songs and you can set the
relationship for the
user when we will implement the
authentication I will not find the user
directly from the database I'll get it
from the logged in
user we have set the relationship with
user and finally we are saving the
playlist we don't have create playlist
D go ahead and create a playlist
D we have used that
logic I'm going to create a new file
playlist
dot or you can
say it should be new
folder dto inside the
dto playlist create playlist
dto create
playlist do
D.S we are expecting the name type
should be string and I'm getting the IDS
of the song from the request body that's
why I specified the number type the
array of the numbers and we have the
user it should be a number it should be
the
ID and finally we have to use the create
playlist
dto we have to import
it and now we have to build our
controller function and the
endpoint do we have a controller yes we
have a
controller everything is good to go I've
have specified the playlist with this
endpoint we injected the playlist
service we have used that logic and I'm
returning a simple playlist in the
response we have to register the
playlist module inside the app module
and it will also be treated as a feature
module just like we did with songs
module we have playlist
module now I have to test the
application you can test it by sending
the
request do we have a user I already
created the user in the previous
video I can double check check it my
users you can see that we have three
users I would like to save the record
for the second user with ID number
two rest
client we have to create a new playlist
I can say create new
playlist we have to send the post
request Local Host column 3000 playlists
content type is equals to
Json
application
Json let's provide the
data I'm going to create a new playlist
with Feelgood now I would like to save
the song with ID number six do we have
the song with ID number six let me
double check it
yes we have the song with ID number
six and this is our user let's say I'm
going to say I'm going to create with
user ID number
two it's not a
valid
request
now it looks fine we need to add a space
here we have a playlist feel good now
and we have a one song with ID number
six and we have this user so this user
has playlist feel good now and it has
only one
song you can double check it from the
playlist
this is the playlist
record in this video I'm going to teach
you how to connect nestjs application
with type orm and
post nestjs provide multiple drivers to
connect with database if you want to use
mongod DB you can also do that if you
want to use my
if you want to use post you can do that
in this video I'm going to implement the
post with
nestjs uh typ orm is a object relational
mapper you will write the code in
JavaScript objects and these objects or
classes will be converted into database
tables if you want to write SQL queries
you don't need to write plain SQL cury
you can write queries in the form of
objects
first of all you have to install a
couple of dependencies we need nestjs
typ orm package and post driver and type
orm uh open the package tojson file and
you have to install these dependencies
I'm going to add them
here let me install all of these
dependencies
we also need typing for
nestjs we have to install this
package I'm going to install as a def
dependency we
already have this package types at
node
we installed these packages njs type orm
post and type
orm so now we need to import the type
orm module into our root module in our
case root module is our app
module so we have to call this method
from type or a module and you have to
provide the connection strings or
connection properties like type host
Port username password database entities
and
synchronize whenever you will create a
new entity you have to register it here
for synchronize means whenever I will
run the application please delete the
data from all the all the tables
synchronize please delete everything
from the table but do not use
synchronize in production otherwise you
will lose the production
data whenever you have to create a new
entity you have to add it here inside
the entities array so the for root
method Sports all the configuration
properties exposed by the data source
Constructor from the type or a
package I have installed PG admin if you
don't have you can install the post
admin I'm using PG admin 4 you have to
provide your password let's connect with
server we have to create a new database
right
now I'm going to create a new database
Spotify
clone this is my
user go to the app module
and we have to import the type type or
module
here we have have to install manually
it's not giving me
suggestion
from
Nest JS type
orm and we need to get type omm
module so I'm going to call a method
type orm
module do for root with we have to
provide the
options database which
is Spotify
clone host which should be Local
Host and we need to specify the port for
post gr I think 4
5432 by
default username for me it's postcript
add you have to provide your password
for me I think it's
root I specified the database name and
we have empty entities right now I don't
have any
entity and synchronize set to
true it will create the database
tables
po
it should be usern name not a
user so how can you verify we have
successfully connected to type
orm you can use data source object in
the app
module now you can inject
it and I can
log let's add
private you can log anything
from DB name let's
say and I can get it from the data
source
dot data
source. database
this do I have that property let me
check
it dat source. driver dot
database Let's test it
out I'm getting the
error wrong
driver so I think I did not provide the
type let's add the
type the type of the driver which is
post
now we have made the connection
successfully you can see DB name which
is Spotify
clone you can also
check the songs table inside the Spotify
Let me refresh it and I would like to
look at the
tables we have the
tables I don't have any song because we
did not create any entity right
now but we have successfully
connected to the postris
database in this lesson I'm going to
teach you how to create an entity entity
is a class that maps to database table
or collection when us using
mongodb you can create entity by
defining a new class and Mark it with an
entity
metadata and inside the metadata you can
provide the name of the table in our
case I'm going to provide the songs
table
name an ID which is the primary
generated column the ID will be
generated automatically it's an auto
increment and we have the title I use
the column
decorator for artist array postris also
Sports error data type you have to
provide the column and I'm using the V
character you have to say this column is
an array type you have to specify the
array should be
true and we have a release dat property
or release dat field in the database
table I'm specifying the call colum
decorator and we have and we are seeing
this the type of this field which is
State we also have time type in the
post you can say we have the duration I
specified the date data type in the post
Cas you can Define the time I don't want
to save extra date field here I only
need Time Properties time related
metadata and lyrics lyrics could be the
long text that that's why Post sports
text type if you want a long if you want
to store a string with long content or
long long
length entity songs which is the name of
the
table and you can say I spec I
have I I have specified the description
for each
field
when you will create the entity you also
need to update the lyrics in the create
song datto we did not we did not add
lyrics property in the previous videos
that's why I use the lyrics it's an
optional property it depends on the user
does user want to add lyrics or
not and finally we need to register the
entity to the app module and then you
can can test the
application let's try to implement
it go ahead and create an entity I can
say
songs or song.
entity songs. entity or song whatever
you want to call let me say what I
called song.
entity
dots let's specify the
class I can say
song I can provide the
entity the name of the table which is
songs now we
need primary generated
column ID the type should be
number and we have the title
field let's specify the title
[Music]
column
title type should be
string and we have another column this
time we have the artist
array you have to specify it as a string
array here I I can say the V
character V character and
the type should be
aray and we
have release date duration release
date
let's it should be
date release date type should be
date and we have
duration type should be
time
duration and the
date and finally we have the
lyrics type should be
text
lyrics type should be
string
now we need to test this
entity you have to
add register the entity in the song in
the entities
array now it should create the songs
table for
us let me test it out from the PG
admin refresh the tables I got the songs
table
with these columns
ID title artist release date and the
duration we don't have any
[Music]
record so
let's
update the create song dto and I'm going
to copy
it and I'm going to paste it
here create song dto let's add another
field the optional which is
lyrics everything is fine
now we have tested
it in the next video you are going to
learn how to perform C
operation we're going to fill these
methods update delete find one find all
and the create this time we going to
fetch and save data to the
database let's perform cred operations
type orm Sports repository
pattern for each entity type orm
provides repository and this repository
has CR features like create create
record update record find record and
delete record repository provides the
method first of all you have to register
the type or a module as a feature into
the songs
module
we providing the
entity like these entities I would like
to use inside the songs
module and it it will provide the
repository songs repository here then
you can inject the songs
repository to use songs repository you
need to import the type or a module into
songs module just like we did it here
this this module uses the four feature
method to Define which repositories are
registered in the current scope we only
need song entity that's why we use the
we have imported or added the song
entity now we can inject the songs
repository into the song service just
like we did we did it as a dependency
injection please inject the song's
repository and the type of the entity
which is song and you can in you can
import repository from nestjs type or M
package now I told you songs repository
provides scrud method to create delete
update here you can look at
that create delete fetch records from
the songs
table let's implement this create song
method this time we don't need to add a
record in the local DB you're going to
save the new song by using the song
repository. save
method let's Implement
here in the songs
module we have to
import type orm module as a
feature provide the song entity I would
like to use this entity into the songs
model in songs
module now you you are able to inject
songs repository into the song
service so I want you to inject this
songs
repository Constructor
pattern songs
Repository
repository and I can provide the song
type which is
entity now you have the exess of crud
methods so song repository provides this
safe method just like you learned here
it provides this safe method for first
of
all we have to create a new
song and it should
return a
promise with
song so I just
created should say
create song
dto the type should be
create Song
D so I just created the instance from a
song class I specified the title I got
the title from D I got the artist from
dto duration lyrics and release date
from the dto and finally you can
call Safe method this. songs
repository and I will would like to call
this safe method and provide a newly
created song and it should return the
object get rid of the songs array I
don't want to use
it we also need to remove everything
from
here now it's time to test this G
method make sure you have
called
yeah it should use the up
expression
here
in the controller let's look
at
issue here it
should promise and the
song inject the
repository inject
repository and we we have to provide the
entity which is
song so everything is fine you can test
without a sync V by default it should
return the
promise
HTTP let's create a new
song we also need
lyrics
I'm going to send the
request
amazing we have a song you can verify
from the
database you can see that that I got the
first record this is the lyrics duration
and the release
date now it's time to implement find
all it's easy to implement the find all
all you need to
do is provide the return type
promise with song
array return this do songs
repository do find that's all you
[Music]
need
and in the
controller songs
controller
you can also add
promise with song
aray
let's fetch all the songs from the DB I
got the array right now we have only one
record now we need to implement the find
one find by ID you can create a new
method inside the song
service and it is taking the ID as a
parameter and returning the promise with
song you can
use song repository. point1
method and in the
controller we need we need to pass the
ID as a integer
and return the
song in the
response let me open the songs
controller we already did
it I'm getting the
ID all you need to
do is return
this. song.
find1 here I can
say promise with
song Let's test it out by sending the
request only the based on ID you can see
I got the first record if I try to fetch
the second record I don't have any
record that's why I got the
empty let's implement the remove
method I'm going to create a new method
inside the song
service it's just returning
nothing
or you can say delete
result you can use
that and
return
here and we need
to use this method into the songs
control
ER we have to call
it this Do song service.
remot and we have to provide the
ID we did not pass the ID or get the ID
as a
Prem I'm going to use Prem
decorator and get it here
ID
and it's returning
promise with delayed
result we need to test it out first of
all let's create a new
song
to we have a
song lasting lever
two the ID of the song which is two now
you can perform the delete operation I
would like to delete this
record so I got the delete result we
have successfully
deleted if I try to fetch all the
songs
[Music]
no I think I deleted with ID number one
so first record has
deleted and we need to use the
update let's perform the update
record so we
need update method I'm going to create a
new
method inside the song service we don't
have update DTU data transfer object you
need a tip you need a new data transfer
object for update the
record because when you update the
record all the fields are optional but I
can get update result from type
orm we don't have update song dto we
have to create it
I'm going to create in the
dto update
song Das
d. so this time we have to copy
everything all the fields are optional
all I did I copied the create Song D and
put the optional for every title for
every
field
is title should be optional so I can say
instead of empty it should be
optional it should also cre it
here is
optional is
optional now it looks good
so we have to use the updates s
video now we need to implement the
controller
function songs.
controller that we need to get the Prem
and we need to get the
body need to get the pram and update
song dto and I'm going to call this do
song service.
update the first one is ID and the
second argument is update song
tto you have to import
it the return type should be promise
with update result that's
it I have found the
issue which is this space content
type let's try to send the update
request duration must be valid
presentation now it looks good so you
can double check it from the
database this is the record with
id2 we have successfully
updated the
record we have tested the
application in the next next lesson you
will learn how how to implement the
pagination now we're going to implement
the
pagination I'm going to use external
package to implement pagination in
nestjs uh first of all you have to
install this
package
I'm going to register it
here and we have to install
it and now I'm going to add a new method
inside the song service this time I'm
going to call it
paginate and I'll use paginate
method from nestjs type or M paginate
and it will accept the pagination
options like page metadata when you will
fetch the record on the pation it should
give me the items array and we have this
metadata total items item count items
per page total pages and current page
these are all the options
inside the options object and finally it
will return the pation and we have to
provide our model which is
song and we have to call the page unit
with song
entity we have to provide the songs
repository and the options if you need
to add a cury builder like filtering or
sorting you can also do
that but here is our control rer
function we use the Prem now we're going
to use security decorator and it should
name of the field which is Page you can
add a by default default value which is
one and I applied the pars int and I
have added the default
value
and we have another field or another
property and I'm getting it from the
cury prams this is the limit and default
limit which is 10 and I applyed the pars
into pipe operator and finally it should
return the pagination with song entity
if limit is greater than 100 please do
it 100 otherwise we have to specify the
limit or tell or add the
limit there is a page unit method we
created inside the song service and you
have to provide the page and the limit
we're getting the page and limit from
the
cury so you have to test it by sending
the cury parameter page which is two and
the limit whiches to I want to see two
records per
page and I want to see the page number
two if you want to add the Sorting you
can also do that by using the query
Builder
please apply sorting on release date I
want to see the latest song on the based
on date let's implement it or you can
Implement by your
own first step we have to
create a new method
paginate and we need these
options I can import all of these from
the
method so we have the pagate
method now we have to call it inside the
songs
controller you can it depends on your
use case but I I'm going to call the
paginate method in the find
all so I'm going to replace my find all
method to this find
all we also need cury
Prem
it's just getting the es lint warning
messages we also need
default value
pipe we need pagination from
nestjs that looks good
we can test
it this time I'm going to send the
request to fetch all the
songs it has applied the limit 10 and
default value which is page which is one
over the first
page total items item count items per
page 10 and total Pages we have one and
current page which is one let's add
another
record new song
to let's add another record new song
3 let's add another record new song four
now we have four
songs
you can
say I want to see the page number one
this
time I want to set the limit to two I
want to see only two records per
page we have the items array you can see
we have only two
records there are total two pages we are
on the first page and items per page two
item count two total items we have the
four I told you if you want to add
sorting you can also do
that by using the query
Builder inside the song
service I'm going to add curil fer
here and we have to provide cury Builder
not songs repository we have to fix
it cury
Builder let's provide the cury
Builder
please
create a new song
with let's say a new Five song latest
date it should should give this record
first let's create it created a new
song I got a latest song Only the based
on release date it means it's working
fine
now in this video I'm going to teach you
how to build one toone relationship
between two
models one to one relation where a
entity contains only one instance of B
and B contains only one instance of a
let's take an example a user can become
an artist or an artist can have only
single user profile so there is a one
toone relationship between user and the
artist we don't have an artist model or
artist
entity first of all you got to create
artist entity with primary
key and then you have to create the user
entity because we're going to make one
to one relationship between artist and
the
user I'm going to have ID field or First
Column first name column last name
column email column and the password
column for user
entity now we're going to add one to one
relationship type or provides one to one
decorator to add relationship between
two two
entities uh in the first argument you
specify the relation type I'm telling
type orm I would like to make a
relationship with with user
enti this is the type of the relation
you specify the relation entity type by
following this syntax AR
function and this join column will rep
will
create the reference key or a foreign
key of the user entity inside the artist
entity so we have so we will have a user
ID as a foreign key inside the
artist and finally you have to register
the user and artist entity in the app
module now we're going to implement
these
steps let's create the first a new
Branch
so I'm going to create a new artist
entity if you like you can use CLI
command to generate a new entity so I'm
going to say artist do
entity. file I'm going to copy my
code there is nothing here you already
learned how to create an
entity and next we have to create a user
model a user entity go ahead and create
a new folder with
user or
users let's keep it to
artist so I'm going to create a new
entity user.
entity. P the code we have ID field
first name last name email and the
password and now we're going to make a
one to one relationship I would like to
store the user ID inside the artist
model if you want to store artist ID
inside the user you can also do that it
depends on your use
case like I want to make a relationship
here let me do it
here we
need one to one
decorator
specify the type of relationship by
following the syntax we would like to
make a relationship with
user and here we will have the user and
the user and I also need a join
column that's it for
now cannot find a module user. .ts
file so we have to import it
manually now it looks
good and now we have to register these
entities inside the app module we
created couple of new
entities please convert these entities
into tables I can say
artist and we have
user our last step is to test the
application and I have to run my PG
admin let me connect with post this
database
so it has successfully let me check my
schema which is 45
clone I have to connect
it inside the tables we have the artist
and the users
table we have have the user ID inside
the
artist and inside the
users we have for columns or ID first
name last name email and the
password our application is running fine
now this is how you will make one toone
relationship between two
entities now we're going to talk about
how to implement many to many
relationship
ship many to many relationship is a
relation where a contains multiple
instances of B entity and B entity
contains multiple instances of
a let's take an example many artists can
publish many songs and multiple artist
can belong to one song or multiple
artist can publish multiple
songs we have a multiple many to many
relationship inside the artist nestjs or
type orm provides many to many
decorator this will specify the target
relation
entity and this is the inverse side of
the
relationship and it will have the songs
array and on the song we will have the
artist array we have a many to many
decorator the target entity in the song
we have Target entity which is
artist and the second argument
specify the inverse side of the
relationship inside the artist we have
songs property that's why I can access
the artist. songs and inside the
artist entity we have song. artist
that's why I can access the artist from
this song entity song. artist that is
the inverse side of the relation when
you set the casc to
true it means you can create or update
the record while creating a new song or
an artist I'll teach you the benefits of
ask
getting when you implement the many to
many relationship you you need a joint
table many to many imple uh relationship
always work with third table which
should be joint table and I rename it to
songs artist and this songs artist will
have primary key of the song and the
primary key of the Artist as a foreign
key
and we also need to refactor some create
song dto instead of using EST string EST
string we going to we are going to get
IDs from the request parameter IDs of
the artist and IDs of the artist in the
update song video and then you have to
register the artist entity in the songs
module that's because I want to the
artist repository inside the songs
modle and finally you need to refactor
the create method we're going to get
artist here the first
step we are going to get this artist IDs
from the request object or request
parameter or the request
body and then we will find all the
artist only based on IDs and finally
here we are going to set the song do
artist equals to artist if you have set
the casket to true just like we have
done it done it here cascading we set to
true now it will set the relationship
between songs and the artist it will
automatically create the record with
third table which is the joint table
here here it will create a record it
create records in the songs artist table
by by setting the relation with this one
songs. song do artist should be artist
and finally we're going to save the song
in the using song
repository and you can test the
application now um let's implement it
first so we have many to many
relationship I'm going to add this
relationship in inser the
artist I'm going to do it
here this specify the target relation
type and we don't have we we did not
create the song. artist inside the song
entity now we have the songs array let's
import many to many
I'm also going to implement it
here many to many
decorator the target entity in our case
it's an
artist and it's going to take the
artist let's specify the inverse side of
the relation artist dot
songs and we will have join
table I'm going to name it
to songs artist or artist song let's
take it the songs
artist and finally I'm going to specify
the artist
array
duplicate
identify yeah I don't need this type
because I'm not getting the string array
from the artist instead of I'm getting
the array of the artist from the request
parameter
we added many to many relationship
inside the song model or song
entity and we forgot to set the
cascading to
True here you can do it inside
here G SC to
true
now we need to refactor the create song
dto I have to
refactor
from it should be
number and the
first argument is an
empty and and it looks
good similarly we have to refactor the
update song
dtoo it should be number array of
numbers the first argument is
empty looks good now we need to register
the artist entity inside the songs
module so we can access the artist
repository inside the song service
I I'm saying to type orm I would like to
access the artist repository inside the
songs module or the song
service that's why I have to register it
here and finally we need to refactor
create
song I can say create uh inside the song
service so you can do it too if you want
here we have
to find all the
artists on The based on
ID then we have to set the
relation with artist and
songs so you can do it but first of all
we have to
inject the Repository which is
artist I can say
private artist
repository and
repository I can say
artist let's get all the artist
you have to add a Sync
here this do song artist
repository find by IDs I can use that
method provide the artist ID from the
song
dto
artist now I can set the relation
with song. artist it should be artist so
we have set the cascading it will create
a relation many to many relation with
songs and the
artist now it's time to test our
application rest
client here we have to send the post
instead of artist we need to send the
IDS of the artist
a user can become the artist so we don't
have any record in the artist and the
user model you have to create it
manually so I'm going to
refresh you can see we have the third
table which is songs
artsts is
not artist we have to fix
it
inside
this inside the
songs
entity here we have to fix
it
this
I'm going to refresh the
table get it off this table you can drop
it delete or drop yes now we have song
artist with song ID as a foreign key of
the song
model artist
ID we don't have any user right now I
want you to create it manually let me do
that
I'm going to add a new record with ID
one it should be
Jane or
saga
Saga
gmail.com I'm going to add anything here
pass password let's add another
user I can say
Jane and I can say
do Jan at
gmail.com password 1 2 3 4
5 now you can save the record so we have
two users right now
if you want you can also add another
user or artist I can say
Martin
gar
Martin at
gmail.com 1 2 3 4
5 let me save the record so these two
users are the artists but we need to
make a relation inside the
artist
table let's add a new record with ID and
here we have to add a artist
ID let me double check
it yes one and the three
one we have to add
another artist one the ID should be
three so these two are the
artist ID should be here we have to set
the ID should be
two now it looks
good so what I'm saying
that a user with ID3 is an artist a user
with ID one is also an
artist so one Martin and seag are an
artist and Jane is a just a simple
user so when you create a new record I
can
say let's add a
new song so these two are all the artist
they are going to create they have
created a new song
I can say you for
me that is it right now I'm going to
send the
request sounds good we have a new record
title this is the artist
ID this is the complete
artist so we have an art ID
one and we
have the relationship
let me double check it from the artist
and the
songs it just created a single record it
did not get the ID 1 and three I don't
know what is wrong with
it
let's do it here one and three you for
me
to again I am getting the ID only
one let's log
the song
d.
artist 1 and three then what
why 1 and three it looks
good maybe the issue
with
here
console.log
so when you look at the artist
record oh we have one and the
two so one and the two instead of 1 and
three
let's provide the
two you and for me
three
now I got the artist ID one and the
two it will also addit a relationship
here inside the songs and the artist I'm
going to
find now you can see
that a song ID with 10 has two
artist these two
users user ID number three and user ID
number
one in this video you're going to learn
how to implement this signup
functionality a user can create an
account in our application and we need
to save the user in the
database first of all we have to install
dependencies I'm going to use bcrypt JS
password bcrypt JS package to save the
user
password in encrypted format I don't
want to save the password in plain text
like 1 2 3 4 5 we have to save the
password in encrypted format that's why
you have to install this
dependencies let me open my package.json
file I'm going to add a new entry let me
copy
it and I'm going to paste paste it
here we also needed to install the
typing for
typescript I have to add the typing in
the dep
dependency I'm going to put it
here so I'm going to run npm install
please install dependencies for
me you can see two packages have
installed added new two
packages now we have to create a user
module and the Au module we don't have a
user module and Au module inside our
application I'm going to use nest
CLI to generate a new module I can say
o we have created a new o
module you can see
that we also need to generate the ser
service for
art you can see that Au service has
generated we also need
controller I can say
AU
an au controller has created it has also
added the entry inside the controller's
part we have it has automatically
imported Au module inside my app
module here is the O module
now we have to
create the users module one more thing
we did not export the odd service
yet here I I can say I would like to
export the Au
service it means whenever you will
import the Au module into another module
like we have imported the Au module into
app module it means
I can inject the OD service inside the
app
module that is why I exported the OD
service let's create the user
module I'm going to create
manually
users. module.
TS I paste
it we don't have user service
yet
we have to create the user
service let's use the
nli a user service has
created we have to import the users
module inside the app
module
so we have the user service and we have
the user
module I've also added the type or a
module and registered the user entity
because I would like to use the users
repository inside my users module I
would like to inject the user users
repository into the user
service now we have to register a new
route inside the O
controller we're going to register the
signup and the login route inside the O
controller we don't have a user dto yet
but we do not we also don't have a user
service do create
method I want you to create the user D
you
first I can say I would like to add my
DS inside the dto
folder
create user. dto
file I'm going to paste my code we are
expecting the first name last name email
and the
password from Network
request this is the network data request
object now we got to create the create
function inside the user service it is
saving the user inside the database
do we have a user
entity now we got to do
it inside the user
service here we have to add the
logic we need to inject the user
repository I've already told you how can
you do
it
I have created the create
method what this create method is doing
remember we have installed bcrypt JS
package let's import it
first
I don't want to copy the code inside the
Constructor
function now it looks
good we have to import it first create
BPT
package here we are just injecting the
user
repository we are generating Assa it is
nothing more it's just a
number we need a salt to encrypt the
user password there is a hash method
inside the bcrypt library and we are
using this hash
method it is going to return the promise
first you first argument would be PL
text password we are getting the plain
text password from the network request
and this is our salt and finally we are
just saving the user depository user
inside the
repository and we are deleting the
password it's an extra remove
them I don't want to send the user
password in the response that's why I
have deleted deleted the user password
and finally we are returning the user
from the response in the in the
response we have called the user
service. create method here now it's
time to test the application one more
thing we have to refactor a little bit
our users
entity I'm going to make it to
Unique should be true because because
email should be unique for each
user and I don't want to save the pass I
I don't want to send the
password in the in the
response it is saying that when working
with type orm there might be cases where
you want to exclude one or multiple
columns field from being
selected that's why we have used the
exlode
now let's run our
application and we have to save the
user we're going to send this
request
HTTP we have to send request to this
route because we created this odd /up
route
we have to provide first name last name
email and the password now we're going
to test it
out I have caught the
error if user service is a
provider
if user service is a provider it is is
it the part of au
module you should learn from the error
inside the Au
module we have to import the user module
because I am using the user service
inside my o
controller or inside the a
service let say user
module here we are injecting the user
service inside the O
controller everything is good to go
right
now we have to test our
application what I would like to send
the signup
request let's create a
new
account I got the error 500 internal
error duplicate key value
Violet unique
key do we have a
user inside our database can say John
one
two still we are getting the same value
same
error cury
failed error duplicate Cube value viate
constraint we have changed a data entity
and the table we have
to we have changed the database Act I
have added two new entries unique
constraint and the
exclude so we need to drop our
schema and let me do
it I cannot
drop we did not use
migrations at the end of this module
I'll show you how to use the migration
whenever you need to update a database
you have to create a new
migration what I want to
[Music]
do I want to disconnect from the
database Spotify
clone now I would like to
delete it is used by some
other let's use
another database I can say
one
I found this is the shortcut to handle
this error because we did not use
migration so I can say that now I got
the data from
scratch where application is running
fine now
let's sign
up you can see that it has resolved the
issue the issue was with database update
I got a
user when you go to the Spotify clone
one get rid of this
one Spotify clone
one and we have to go to the
tables inside the
users
we have a de
cord email john1 12@gmail.com and this
is the password in encrypted
format in this lesson you are going to
learn how to perform login request when
user sent the login request we have to
verify the user from our database we
have to decrypt the user password and
compare the user password we're going to
implement Json web token
authentication a user provides the
credential like username and password to
the
server then our server will generate the
Json web token and send back to the user
it will have the header payload and
signature don't worry I'll teach you
everything when client reive the Json
web
token if you are building front-end web
application you can save the Json web
token in the local
storage when user want to receive or
user wants to receive protected rout he
must need to provide JWT token in the
request
header and server will receive the JWT
to token from the request
header and it will verify or validate
the token if token validated
successfully it will allow you to access
the protected route you will learn how
we are going to implement Json web token
authentication we're going to use
passport passport
strategy or passwort package you have to
install these two
packages I'm going to install it in my
dependencies we have to run npm let
me hold on we did not create a separate
Branch module number
six lesson number two
[Music]
now we have
it npm
install we have installed two
packages the next step we have to create
a login
route I can create inside my o
controller let's create a new login
route we don't have a login D yet we
also don't have a login function inside
the OD service
yet let's create a login
function inside the OD
service au. service here we have to
create the log
function and we
also need to get user service as a
dependency let's create a new
method first of all we are trying to
find the
user on the based on
email if user found it should give me
this
user let's complete this step first we
have to find the
user we did not create the find one
method I can say that inside the user
service let's create a find one
method it is going to take the partial
as a user
and we're getting the email or we can
let's try to use the login
dto login
dto if it did not find the user it
should return the unauthorized access we
have to find the user only based on
email we don't have login dto let's
create a login
dto inside the AU
dtos I can create
login. D.S
file so we have the login
dto I got the
email we also need to import login
dto we also need to import user
entity and it should return the user
that's
it now the second step is we have to
compare the user
password inside the OD service the
second step we have to compare the user
password I have to import the
bcrypt import Star as bcrypt from bcrypt
now I can compare the password with
plain text password and user encrypted
password if password
matched then we have to return the
user and delete the user password if
password did not match we have to send
unauthorized
exception that is it right
now
we did not inject private Au
service now I have called the
dto login method and provided the login
dto
let's try to send the login
request rest
client.
HTTP we have created a user with John
12 John 12 run the
application
let's send the API request to login
user it should be 3,000 not a 3,000
one we successfully got the user back in
the response let's say I'm going to
provide the invalid email I got error
cannot find user if I provide the
invalid
password I got password did not match
and unauthorized it's working fine
now but our goal is to send the Json web
token when user made successfully login
request it should send the Json web
token in the response in the next lesson
I'll teach you how to create Json web
token and how to send the Json web token
in the
response we have found the user on the
based on email and we have encrypted the
user
password if user has logged in
successfully we need to send the Json
web
token and when you will apply
authentication on protected
route you have to send the Json web
token in the
header we're going to use nestjs JWT
package and passport JWT
package and then we will import Port jwd
module you have to provide a unique
key you have learned how to create the
login function and
we you have to refactor it right now you
have to send the access
token you can create Json web token by
using JWT
service this is the provider you can
inject it here as a service provider
then I will move my constants into a
separate file au. constants
does and you have to register the JWT
module and update o constant Secrets I
also updated the expiry date of Json web
token it will be expired after 1
day we going to have JWT service we are
extending it from the passport
strategy remember I'm using the nestjs
passport
package and we have passport jwd
strategy here it is just extracting the
token from the
header we are checking the Json web
token expiry
date or expiry validation or expire
duration here you have to provide your
secret key which we have
saved and then finally we're going to
have validate method it is returning the
user ID and the
email when you apply the
oard oard JWT oard will call this
validate
function you have to register the JWT as
a provider then this is how you will
Implement authentication you got to
create a guard it's like a middleware in
expressjs if you want to implement role
based authentication you need
guards we have jwd odard it is extending
oard from the
passport if you want to add your own
custom logic you can do it
here this is how you will make your
route
protected by using the gwd O card and
finally you have to apply you have to
send the authentication request like
first of all you got a
login login route will give you the Json
web
token then you can access your protected
route like this is the protected route
profile is the protected route
only authenticated user can access this
profile route so you have to provide the
validation token which is this one Json
web token in the authorization barrier
it's a
scheme and it will allow you to access
the
route so let's implement it first first
of all we have to install a couple of
dependencies
here passport
JWT nestjs JWT and passport JWT strategy
I also need dep dependency which is
typing of
typescript let's do it
here and we have to install the
dependencies
these packages have
installed now you are able to use JWT
module let's use inside the app
module we have to register
it we will move this constant into
separate file but right now I'm going to
do it in this
way JWT module. register and this is the
secret
key and finally we have to refactor our
OD
service
if everything is
fine then we can use Au or JWT
service you have to add this return type
return
type
if password mashed generate adjacent web
token or create a pad
object I'm going to create a payload
object now we are just adding email
and the user ID inside the payload and
it is generating the Json web
token let's create a separate file for
the
constants can say o/c
constants
do let me refactor it
here
one more thing you got to register the
JWT module in the Au module instead
of app module that was a
mistake so this is our authentication
[Music]
module we have to register it
here out constants do
Secret and you have to
provide sign in
options
options we have expiry date which is one
day so we have registered the jwd
module now you have to create jwd
strategy I can
say JWT
strategy dos it's nothing more it's a
service or provider you can inject
it
injectable export class JWT
strategy passport strategy it is going
to provide the
strategy passport
JWT
now we have to call Super
Constructor and you can
extract the
header from Au header as a barrier
token and we have to provide the ignore
expiration check the expiry
date secret which is our secret key
ke and we will have the validate
function whenever you apply at the O
card this validate method will be
called
our next step is to register GWT
strategy in the O
module I have to register it here JWT
strategy now you have to create the
guard which is
JWT guard
dos
export class JWT
guard it is also a class or service
provider that's why I I'm using the
injectable and we have to extend it from
the
passport from the odard which is from
the the njs passport
package make sure you say this is the
JWT if you want to extend this JWT guard
you can do
this our final step is to apply the O
card to the public public route let's
say I want to protect this route I did
not create it
yet let's say get
profile and it is going to take
request return request.
user
should be
decorator now we have
to let's do it without
card npm Run start
f
our application is running now let's
send the login request you will receive
the access
token I'm going to copy
it and I going to paste it
here access
token now let's access the
profile
slash profile because we created the
profile route in app
controller I'm going to send the request
cannot access the
profile
I do not add the
route I can access the profile route I
got the 200 status
code it means route is working fine if I
apply the authentication
guard I can say use roles
or use
roles use guards
yep I can mention my guard which is or
guard if you have what in Express JS
it's nothing more it's like a
middleware this oard function will run
before executing the get profile
function this function runs before
request Handler which is get
profile oh it should be jwd o guard jwd
guard not and this not this one o
card
let's rename it to JWT o guard not a JWT
guard JWT oard it looks
good
let's try to access the profile
route status 401 which means you did not
provide the access token please provide
the access token if you want to access
this private route so you can provide
the exess token by using this format I
pasted the
token awesome I got the user ID and the
email I have applied the OD card and
this JWT
strategy method will be called first
they are going to run the Constructor
and then they are going to use the
validate
function in this lesson I'm going to
teach you how to implement role-based
authentication what is role-based
authentication if your application has
multiple roles like artist manager user
accountant CFO person you can have a
different functionalities for each role
in Spotify clone when you look at the
Spotify clone only artist can upload a
song If you are a user like let me show
you you with the help of
Spotify
web.
Spotify
like if I go to my
profile I don't have any feature to
upload a
song Only approved artic can upload the
song or delete the
song in this way you can divide your
application into multiple
roles we have create songs
endpoint I would like to restrict this
endpoint for other users only artists
should access this create song
endpoint we don't have artist module we
have to create artist module then we're
going to implement the artist module
into import the artist module into app
module we have to write a method find
artist on the B on user ID then we got
to add a logic here inside the login
method we will save the artist ID in the
payload object and then you have to
create a new payload
type and finally you need JWT artist
card we will have a separate card for
artist we are extending the jw2 remember
I told you if you want to customize or
add a logic in the guard you can do that
it's just returning a super
Constructor and here we are using the
handle request method this function will
check if you have art artist if you are
an artist then it is going to return the
user otherwise it will throw the
exception we have to refactor the
validate method in GWT strategy we need
an artist
ID then here you will have to apply JWT
artist guard on the create song
endpoint you can do that as well or you
can follow me let me implement
it
let's create the artist
module here we have the artist module it
has already imported into my app
module this one the artist
module we also need R service
next generate service and I can say
artist you have to import type orm
artist
entity module. for feature because I
would like to use
repository here artist repository we
have to provide the Artist as an
entity so we have the artist
service and we also need artist
controller
artist I can use a nest generate
controller
artist
now we have the artist
controller now we're going to create the
find artist
method I'm going to copy my
code inside the artist
service let's do it
here we need to import couple of
dependencies
we have to find the artist on the based
on user
ID our next step is to refactor the
login
method inside the art
service we have to add R
service
injected we need to add a artist
ID inside the payload type inside the
payload if password
matched find if user is an
artist then we need to add the artist ID
into the
payload what I can
say because course I can save the artist
ID in the payload
object user do p. artist
ID should be it is saying that you don't
have artist ID in the
payload you can create a payload type
inside the types p.
type
I can say types.
yes now I can access it I can Define the
P
type it should be user
ID we have mentioned the artist ID is an
optional
property now we need to have JWT oard I
told you how can you implement it we
already implemented the O
card let's say I'm going to create a new
guard inside the
O I can say
artist JWT
godts export class
artist JWT
guard extends o guard
JWT it's a Pur it's a service that's why
I have to use the injectable it's a
service
provider
if I will write the can
activate you can see that I got the code
all I need to call the super
Constructor super do can activate and
provide the
context yep everything is fine you also
have handle
request now you can write your logic
here if there is an error or there is a
no user then you have to throw the
unauthorized
[Music]
exception if everything is good to go
you have
to return the
user if there is an artist ID then we
should return the
user get rid of the extra arguments I'm
not using
them when you apply the artist JWT card
it should call the handle request and it
will extract the user and try to check
the artist ID from the
user if you want to log the user you can
also do that I will show you what will
happen inside the user
we created the JWT AR
card JWT o
card jwd arst
card then we have to refactor a little
bit validate method in the JWT
strategy we can add the
artist it should be P
type
now it looks good we have the user ID p.
email and p. artist
ID and
finally we have to apply the jwd artist
card on your protected endpoint in our
case we have the songs create endpoint
we have to protect it for other
users all you need to apply JWT artist
card
and inside the songs
controller I can restrict this endpoint
from other
users I can say that
jwd artist JWT
C
if you want to log in the request you
can do
that let's try to do it
here request decorator and
request
I think it should be
request it's not a requ request this
one
request nexts commment and then we have
to access the
request why it's giving me the
error
I have to do it
here and
request now it looks
good I can log request.
user
let's start the
application I got the
error the O JWT
strategy JWT strategy what I did wrong
oops forgot to
add I forgot to add closing
parenthesis
if you go to the artist table you will
not see any record because we don't have
any artist record it's an
empty if you go to the
users how many users we
have I have only single user now I would
like to make the
artist what I can say what is wrong
is au module is a valid njs
module Artist Artist
service I think we have to
import the artist module here inside
the are we
using
the rst
service yes we are using the RT
service that is why I need to
import the artist
module and inside the artist
module I can say I have to export artist
service I want to teach you how to
handle errors you must know you must
familiar with error
handling
our application is running
now first of
all we have to create a new
artist I can say let's sign up a new
user or I can say that sign up artist
let's say
that it should be let's say c
Martin
Garrick Martin
Garrick we have registered a user which
which should be which could be an artist
so if you want to make this user Martin
Garrick to artist you have to update it
manually but I did not create the
endpoint but you can do that I taught
you how to do
it let's first of all the ID is
to I'm going to open all the
artist and we have to add the
entry this is user number two and
finally you have to save
it now Martin is an artist
so I have to log in as in Martin
gar I can say sign up artist
or login
artist get rid of first name and the
last name let's send the login
request it should be
[Music]
login I got the
token
now if you check the
profile it should have the artist ID you
can see that this is the artist
ID this is the user
ID this is the artist ID from the artist
table this
one so it's working fine now when you
have to
create I for I got I I have to get the
token
again let's save the
[Music]
token the token will be deleted after
one day I can say that arst token
temporary if I try to create create a
new song it should give me the
unauthorized because you are not an
artist and you did not provide the
authorization
token
authorization b e a
r a r e
r now I can say we have artist which is
one Mart Martin Garrick has an animal
song let's say they want to publish this
song
I have the
artist now it's working fine this is the
user ID email and the artist ID user ID
email and the artist ID so we got this
one artist and the ID colon
one
we have successfully created the
endpoint I can say request.
user
let's create a new song from Martin
Garrick say love
again so this is the request. user user
ID email and the artist
ID in this lesson I'm going to teach you
how to use or how to enable how to
create two Factor
authentication you're going to learn how
to implement two Factor
authentication if you don't know about
two Factor authentication you can read
this text a user enters the username and
password on a login page page after
successful initi initial
authentication the system sends you the
onetime password or onetime
token for the verification a user may
provide the onetime code generated by
the authenticator
app and send to the system then system
validate this token if token has
validated then you are able to
authenticate then you are able to access
the route
we're going to use third party package
to implement two Factor authentication
Speak Easy and we need a typing first of
all I would like to show you the demo
how two Factor authentication works I
already implemented in my development
project I can show you the demo first of
all you got to log to the user I got the
access token we're going to create a new
endpoint to enable the
authentication this endpoint will enable
the authentication for the user and it
will create a secret key let me show you
I'm going to provide this text I
provided the
token now I got this secret key and I
got this response from the Speak Easy
package base 32 I saved this base 32
string to my database table for the user
is for the user
table a user has this
record now I I I got this secret key if
you have authenticator app Google
Authenticator you
can you can place the secret
key I have enabled the Google Chrome
extension I want you to do it when you
look at Chrome Google Authenticator you
have to enable this
extension now I
got this authenticator if you have
Google Authenticator on your phone or
you can install it all you need to do is
to add a new app you can also generate
the QR
code with this OTP path Ot Ot paath OTP
o URL you can generate QR Code by using
this this
URL but you can add manual entry for T
testing Sam profile this is the same
user the name of the user this is the
secret key now I started getting a
unique onetime
password so I have to copy this
password let me do it again it's going
to be removed after 1 minute I copied
it it's going to be
removed yep now I have to provide this
token to validate the user I have Pro
I'm going to provide it here we also
need to have updated token so copy this
one
and
I have to validate the
[Music]
token yes we have to add a new token
because it will be
expired now you can see you are
verified the token has
validated now this user has enabled the
two Factor
authentication if you send the login
request
you see this message hey you have
enabled two Factor
authentication you can implement this
Logic on your front end application
please send the token at this URL please
send the onetime password token from
your Google Authenticator app on the
front end side you can send request to
this endpoint and provide the token
that's a complete flow of two Factor
Authentication
let's start implementing two Factor
authentication we have to install couple
of
packages we need a Speak Easy
package we will use this package to
generate secret key or validate the
token onetime password we also need
typing add it as a def
dependency let's run npm install
packages have installed the first step
you have to add two new columns inside
the user
entity do
entity I'm going to add them here by
default two factor string should be null
and it's a Boolean property by default I
have set to default to
false two Factor secret could be empty
and this is the Boolean
value when you run the
application it should create two new
columns for the user property for the
user
table
our application is running
now let's refresh the user
table I have the 2 FAA secret and enable
2 FAA which is a Boolean
column now we're going to create a new
method inside the O service to enable
the two Factor
authentication first of all we need
maybe we need a
type I can add my type here enable to F
type or you can create an interface
we have to type and then we need a
method you have to create a new method
to find the user on the based on user
ID if user has already enabled to factor
authentication we have to return the
secret key if user did not enable the 2
FAA
authentication then we have to generate
the secret key this is we use the secret
key and we're going to use the base 32
secret key and finally we have to update
the 2fa secret 2fa key for the specific
user and then you have to write the do
you have to return the secret key in the
response we got to find the user if user
already enabled the secret two Factor
authentication we have to return the
saved to to f secret otherwise we have
to generate a new secret and then you
have to set this secret for the user
user and finally you have to update the
user I'm going to copy the
code let's do
[Music]
everything inside the OD
service
I have to create a new
method import Speak
Easy we also need to import Toof enable
type we don't have a method find by ID
do we have a
method find by ID inside the user
service
not we have to create the find by ID
method
you can also do the secret key or unable
to factor authentication here use user
dot let me first add a new method inside
the user
service let's go to our next
step user
service here we need this
method I'm going to copy this method now
we have
defin by ID
it is going to accept the
ID so we have to provide the user
ID you can
enable two Factor
Authentication to
true and finally you can call user. Save
method or no we need a
repository to save
it we also need another method it will
update the secret key and enable the
authentication you can create a new
method
inside the user
service let me import the update
results we have completed the enable to
factor
authentication now it's time to test
it let's create an O endpoint inside the
O
controller
I I'm going to use the guard JWT o
guard if you if you don't
need anybody you can create it as a get
end
point I can say that JW the O
card
[Music]
I just imported missing
Imports
we have a login user sign up user sign
up artist login user here I can
say
enable two Factor
authentication
profile
Au enable two Factor
authentication let me double check that
enable to fa we also need to provide the
authorization token so we need to get
get the
token I got the the access
token provide it
here let's send the request I got the
secret key that's
amazing what is the name of the user
which is
John if you have Google Authenticator on
your phone you can install it manually
I'm going to add a new
profiles which is John
user add your secret
key it is generating onetime password
for 1 minute
only we have also saved the key into the
user users
table let's fetch all the US
[Music]
users here we have the secret key and it
has enabled two Factor
authentication our next step is to
validate the onetime password
token let me open
it we have created a new user or
registered a new user in the Google
authenticator it is generating onetime
password we have to take this token or
onetime password and try to validate
with our
application we're going to implement
this logic first of all you may you may
need another
endpoint validate to fa we are also
using a JWT o card we are getting the
request here we will have a method
validated to f a token it is going to
provide the user ID the logged in user
ID and we also need to get the token
valid validate token dto we will create
validate token
dto I'm going to create a new
endpoint inside the O
controller I created the post because we
need to get the token you can also use
the get and get the token
prams JWT
oard let's create the validate token
dto inside the
dto I can
have validate
token.
D.S
now we have
to create a new method to validate to fa
token here we need to create this method
it is going to accept the user ID the
token the onetime password like this
one this one this
one and we will find the user on the
based on
ID and then we have
to get this secret key which we saved
earlier and then you have to provide the
token and we have to mention encoding
which is based
32 if token is
verified where is
that if token is verified then we have
to return verified to True otherwise we
have to return verified to false you can
also rapar code inside the TR catch
block I'm going to copy my complete
code and I'm going to paste it here
inside the OD
service
the code is complete
self-explanatory now we have to test it
we already created the
route inside the rest
client
I can use
that and I'm going to paste it
here I can say
validate to a
token validate to
fa let me double check my controller
validate to
fa it's a post end point
point and we have to app content
type application
Json let's provide the
token let me get the
token John
user amazing we got got the verifi to
true if I provide the invalid
token I got the verifi to
false I got the verified false
because because token has expired there
is a new
token we successfully enabled two Factor
authentication validated with
token you can
add you can also add disabled
authentication logic or you can have
this
feature let's implement it by creating a
new function inside the OD
service it's nothing more just disable
the authentication and or set this
value we need to have that function
inside the user service because we have
repository inside the user
service I can say
that so we have this method disabled to
fa now it's time to create a new route
to disable the
authentication inside the O
controller I'm going to create a new
Endo
here
JWT o
there is a typo here spelling issue for
the O
guard J WD o
guard
e
everything is fixed
now
let's try to send disable authentication
request inside the Au controller this is
the get
endpoint I can have
that let me paste it here
disable authentication disable to
fa it should be disable not an enable
so it has disabled authentication you
can double check it by
login I got the
token and let me check it from my
DB you can see that it has dis enable
false set the
false
one more thing you can do if you
disabled the authentication you can
delete the secret key or you can use the
existing secret key let me let me do
it yeah we have to disable or deleted
the
key
inside the
disable validate
token
disabled I can
say to FS secret to set to
false
or you can set the null
value let's try to do the null
value let's enable the authentication I
got the
secret double check it from the DB we
have enabled and we have a different
secret
key I don't want to save the I don't
want to change the secret
key you should not change the secret
key maybe it depends on your use
case if client disabl
this to fa maybe he has to scan the QR
code
again let's disable it it looks
good we have empty to fa and it has set
to
false
I also have to add this property into my
notes
if user has enabled to factor
authentication we have to customize a
little bit Logic for the login
method we have to send the
link to user this one validate to F
token this
one if user has enabled to fa and have
the secret
key then you have to return this
type go to the
login or
service go to the login
method here I can add a
logic we have to add return type new
return type
this
[Music]
one let's try to access the login
function by sending the login
request we have enable two Factor
authentication it should give you the
link not an access
token we have to log in the
user where is the login
user here we
[Music]
have
let's double check
it we have empty2 FAA that's why I got
the access
token let's enable
it we enabled the two Factor
authentication let's send the
login
now I got the link validate to fa please
send the one onetime password or token
from your Google Authenticator app you
can implement this Logic on the front
end on front end you can send the
request to this URL and you have to
provide the token a user user has to
provide the
token so we have completed the two
Factor
Authentication
in this lesson you're going to learn how
to implement API key
authentication each user will have its
own API Keys when he wants to access
authenticated route or protected route
he has to provide the API
Keys when you need to control the number
of calls made to your API you can check
from your API Keys how many times API
Keys has
hit if you want to identify the usage
patterns in your API traffic you can do
with the help of API
Keys API key authentication is typically
used in scenarios where multiple users
or application need to access an
API you can read this text you can read
the complete
flow we're going to use this step we're
going to generate API Keys we can create
and store API key for each user we have
to create an API key
strategy strategy service just like we
did for the JWT
strategy and we have to register API key
strategy in a
module and the step number five validate
the user by API key and apply API key
authentication on protected route I have
to use external package which is uu ID
to generate API
key and we will have API key column in
the user
entity and then when we have to create a
new
user what you have to do you got to set
the API key which is U ID by calling
this method it will generate a unique
key when you send the when you create a
new account it should give you this API
key and Next Step you have to create API
key
strategy when you provide the API key it
is going to call this method the
validate function and inside the
validate you have to call validate user
by API key and you have to provide your
API
key if user is validated this is how you
will provide the API key authorization
barrier this is my API key we're going
to use external package passport HTTP
barrier to apply this strategy to
validate API Keys finally you have to
register as a provider API key strategy
this is our method to validate the user
on the based on API
key if user validated with the help of
API
key this is our Endo here I'm I can say
I want to access the
profile on the based on API key or you
can create in the O controller use guard
o guard you have to provide the
barrier it means I want to apply API key
valid ation or API key authentication on
this
route and I don't want to set the send
the user back password back in the
response that's why I deleted the user
password and you can send the message
authenticated with API key this is the
user this is how you will provide the
API key when you make the authenticated
request I want you to implement this
complete flow if you stuck you can
follow my
video Let's install the package
first
let's run the
application you will get the error
because we have two to three records in
users table but it will find null value
for API key we did not set the
constraint API key should be null if
user has signed up we can have the API
key or if if you set the null Lael to
true you can have a separate function to
create the API key for the user it
depends on your use case your company or
your business
logic I'm expecting the null value error
from the type
orm we are using this
database
we have all the
[Music]
users you can see I got the eror
relation user contains null value which
is API
key you can fix two or three
ways you can set API key value manually
but I don't have API key
column there is a concept we didn't use
the
migration but I found the hack to use to
resolve this
issue I can say Spotify clone 2 let's
change the database
Run start
there it will take some time to create
all the
tables database does not exist let's
create a
DB
restart the
application the application is running
fine
now
[Music]
we have this database Spotify clone
2
so we have the API
key now we need to add the API key when
you create a new
account I can do it inside the
user service or odd
service do we have the sign up function
[Music]
here I think inside the
users yes we have the create
[Music]
function
I have to change a little bit logic I
did not create a new user so I'm going
to do it
here we have to import this
package we are getting the
user.
password delete this
one we got it we got the API
key yeah I can say saved
password
I have updated user D to user password
and we have saved the
password and we have deleted the saved
password now we can we have to test it
by sending this sign up request
open the r
client I'm going to send the request
sign up request sign up
user so it has generated the API key it
looks
good we have encrypted password it's
fine
now our next step is to create API key
[Music]
strategy we have to install this
package I'm going to copy the same code
and create a new file API key strategy
inside the
O API Das
key
Dash
strategy. DS strategy.
DS going to copy the
code
we are using the passport strategy and
we are providing this passport HTTP
barrier OD
strategy we have to import or
provide API key strategy inside the O
module register it API key
strategy and we have to validate the
user on the based on API
key I can create a new
method I also need to find user on the
based on API key let's add a new method
inside the user
service now it looks good let's create a
new controller
function into the O
controller it means I'm telling to a or
nests application I would like to
validate this route on the based
on API
Key njs
password everything is good to go right
now we have to test the application
run the
[Music]
application first of all we have to
create a new
account I change the email John 13 we
got the API
key I'm going to store the API
key key John
13
now we have to provide this API key to
access the profile
route access
profile we have a get end
point get
http or/
profile authorization
basic here we have to provide the API
[Music]
key it's not a basic we are using this
[Music]
scheme barrier
scheme b e a r e
r now I got the user back in the
response and it has authenticated with
API
key in this lesson I'm going to teach
you how to debug nestjs application
using VSS
code if you don't have launch. Json file
in vs code folder you can create
it let's create the launch. jsn file if
you go to the
debug I'm going to create a new folder
vs
code and you can have launch. Json file
let me copy these
configurations so I have to start the
application in debug mode nestjs has a
script in package Chon
file now you can start the application
by running npm start Run start
debug you can see that our debugger has
started now I want you
to attach a process when you go to the
debug now you have to attach
it you can put break points let me
to here the O
[Music]
controller I'm going to put
breakpoint let's try to send the API
request it has stopped at this break
point so I can see what is inside the
request
I have request
body request
client request. user you can also watch
on a specific property the request.
user you can see that I got the API key
email enable to fa to fa secret this is
a great way to debug the application you
can find errors very easily by using
debugging if you want to debug the
complete flow you can do that into the
app
strategy what I was API API key strategy
or API
strategy yep we have the API key
strategy I'm going to put break point
here let me put the break point here and
I would like to put the break point here
let's send the request you you can see
that it has first called this validate
method it is going to find the user on
the based on API key it has found the
user now it is going to return execute
this line return
user it
has now it has added the request. user
you have returned API user from the API
key strategy like this one
nestjs has
stored user inside the request object
like request.
user like this
one and finally we have deleted it you
can step over
it go to the next line
if you need to step into a specific
function you have to use this one step
in if you want to go out from this
function you can press step
out in this lesson I'm going to teach
you the concept of
migration migrations is like a Version
Control for your database
you can manage your database
changes by using migrations migration is
a file that contains a set of
instructions for creating modifying or
deleting database
tables whenever you make changes in your
entity you have to create a new
migration if you want to go back to the
previous changes there is a command for
revert you can use that
command once you get into the
production right now we are building our
application in development environment
when we push the application into
production you will set the synchronize
to
false so you have to
manually update the changes to for your
entities that's why I have set the
synchronized to
false in production you will not set the
synchronized property to
True migration is just a file with SQL
queries to update database and apply new
changes to an existing
database I got the simple definition of
migration it's called it's like a
Version Control for your database you
will keep keep track of your changes
toward your
schema first of all you have to move
type orm configuration into a separate
file these are all my type type orm
configurations now you don't need to
write your entities
manually when you have to create a new
entity you add a new entry for the
entity now you don't need
that I have added the regular expression
for this path we also using the
JavaScript because we're going to use
migration I found it's easier to work
with JavaScript when you are working
with with
migrations when you build the project
nestjs will generate the disc
folder this disc folder I can provide
that path this is the JS
file we're going to provide this type of
file I have set this synchronized to
false
we have created a new data
source when you write the script to
migrate in package or Json file you have
to provide the data source file this
this data source and this data source
has a data source object this data
source
object step number
two you have to refactor type or M
config into app module you got to
provide data source options this dat
data source
options and then you have to write the
script for type or M generate run and
revert we're going to use all these
scripts we will add a new column in the
user
entity and then we will run run the
generate the migration based on this
column this is the name of the migration
at user phone where we have St about the
migration here we have specified the
path there is a DB folder and inside the
DB we have migrations
directory and finally you will run the
migration when after creating the file
you have to run the migration if you
want you can implement this complete
steps or you can follow
me
I'm going to create a new file inside
the DB create a new folder inside the
root
directory
DB data
source. TS I'm going to paste this
code my database is which is Spotify
clone Spotify clone
2
so I have to delete
everything here we have to
provide a data source
options this options
object I have completed this step number
two now we need to add couple of scripts
there is no logic logic here
specifically you can copy the
scripts first of all please build the
project generate the JavaScript files
then and then we are using the type orm
npx and
dashd I'm telling to type orm I have
stored my database configuration inside
this
file if if you have to go back or revert
the changes you will run this
command I'm going to copy this script
and paste it here inside the
scripts now let's try to add a new
column user.
entity I'm going to add a new column
here
here type A
String now finally we have to run the
migrations npm run migration generate
I'm using this script here you are
specifying I have I want to store
migration in this file migrations and
this is the name of the file it will
also add the
timestamp first it is going to build the
project then it is going to execute this
command meanwhile I have to start it
from the scratch I don't want existing
database so I would like to delete
Del my
database I'm also going to delete this
one because we have set this
synchronized to false we have to add
changes manually that's why we are using
migrations and new file has created
inside the DB inside the
migrations we have this file this is a
Tim stamp and the name of the file add
user
phone. so we have to create a new
database I can say Spotify
clone now I want to
add all this stuff
like inside the data source Spotify
clone let's generate the migrations I
can say
that my migrations you can choose any
name or in
it
it is going to take all these entities
and creating creating the SQL
files SQL queries for all these entities
because right now our database is
empty
in we don't have
tables
now you can see my
migrations if you check the database you
will not see any table because we did
not run the migration yet now we going
to run the
migration npm run
migration
run now it is going to execute these
queries
these creating all the tables and all
the
relationships we have the
migrations
there is no record inside the
migrations I'm going to
delete this
migrations and this migration file
let's create it from
scratch
it has created all the migration now we
have to run
it everything is good right
now it has executed the queries and now
if I refresh my tables you will see all
the tables we have songs users but if I
go to the
users I will have font property I don't
want font
property let's edit a user entity I'm
going to remove
phone now let's generate the
migration I can say removed phone
you can see that it has created the
migration file removed phone it is going
to drop this
column now we need to run this
migration to update changes in the
database
let's try to check the
column there is no phone column here
this is how the migrations
work this lesson I'm going to teach you
the concept of data
seeding data seting is a process of
populating a database with an initial
set of
data when you create a new
column inside
here
when you create a new column in the user
entity let's say I would like to add a
new
column and here I can say this is this
could be the phone
number
but when you run the
migrations the phone number will be
empty in the
database so you can load your initial
data by running the
seeds applying CED data to database
refers to the process of inserting
initial data into the database usually
when the database is first created let
me show you the demo of
cing
you are going to learn how to create the
seed service and we have a seed method
inside the seed
service we
are
running type orm queries by using
transaction here we have placed all my C
data when my application bootstrap
loads it will create a new user a fake
user and it will save into the database
and then it will create the artist and
save artist into the user into the
database we also have a c data for
playlist first of all we're going to
create a new user then we're going to
create a new playlist and we have
assigned a relation between playlist and
the user so we're going to save couple
of
data when you run the application when
application will be completed
you can verify from your
database let me show
you in your users table you will see a
new user will be created so these are
all the
users these are all the users I created
with fake data by using the
seaing I also have a
playlist it is going to pick the random
name for a
playlist Rap
playlist World playlist or country
playlist I've also have a seed for
artist you can see that now my
application is is running
now when you look at the
users you will see another users couple
of another
users if you look at the playlist you
will find one more
playlist you can also look at the
artist you will have more artist this is
how you can increase your development
workflow or testing
workflow now I want you to implement it
by looking at the documentation I
created for
you
here I don't want a new
column first of all we have to
install another package to generate the
fake
data and next step we have to create a
seeds folder inside the
DB
seeds I can data seed. TS
file I have created a new file while
here we're going
to do initial
seaing you can create a separate
function for each entity like you can
create a separate function for seed
songs I did not create this seed songs
method here you can create
that if you want to look up more
documentation of of Faker package you
can find from your from the official
documentation
page it is giving me the
error entities Source
playlist here I can find the
entity
now our next step is to create a new
seed
module I'm going to use type orm to
create a new seed
module and
then what we are doing here we are
generating the encrypted password I use
the same password for each user here we
are creating the user I got uu ID from
API key and I got repository from the
manager we will call the seed data in
main.ts
file seed module has
created we also need a seed service what
I can do I'm going to copy this
code and create a new service inside the
seed
module see do
service if you want you can use CLI to
generate service we also have to import
or register as a
provider seed
service cannot find um oh it should be
SE data seat should
be I can say this seat data seat
data and it should be gone
we are making connection with our
database here I got the manager from the
quy manager and I called this C data and
finally we are we have started the
transaction if transaction if any query
has failed it is going to roll back the
transaction
so our final step you can read this text
if you want to learn more about what is
cury Runner what is
transaction here you have to boot you
have to call the seed method here
whenever you want to save a data in the
database if you don't want to save a new
fake data you can just disable these two
lines but let me show you the demo I'm
going to start the
application it is going to run these
methods seed user it is going to create
a new fake user seed artist and Seed
playlist let me show you the current
look of my
schema I'm using spotify clone on
database Let me refresh my
tables uh I would like to see all the
users there is nothing here I don't have
any
user you can create many users if you
want you can use fake
package to generate 20 15 50 55 records
and you can and then you can provide
into the repository user repository it
will create all these records but I use
a single record I just want to show you
the process you can manipulate with your
own use
case one more thing I could not find the
official package or official
documentation or in typ orm seeding I
got I have implemented my own
strategy now my application is
running you can see I have couple of new
users you can see I have couple of new
artist I think I will have only single
artist yes but if you look at the
users it has picked a random first name
random random last name random last name
and the email and the password and the
API key it has generated one more thing
if you want to look at the playlist I
will also have a one
playlist electronic music
song that's how the seeding work
works whenever you create a new entity I
would recommend you to create a seed
function whenever you run the
application it is it is going to create
a new data but I'm going to comment this
code you can
enable
the
seaing
here if you want to make it more Super
productive you can create a console
command in
njs I'll teach you in the advanced
Concept in this lesson I'm going to
teach you the concept of
configurations we're going to create
custom configur ation file with the help
of nestjs
config if you see our main. file I have
mentioned the port number
manually if you want to have a separate
port for development project or for
production environment you can specify
in the environment variable we don't
have any EnV file in if you have worked
with
nodejs you will have separate EnV
environment file. EnV file for
development and you you will have
separate. EnV file for
production one more thing if you look at
our type orm
configurations here we have type orm
configurations I have specified a
username
manually password manually database
manually I also specify the host
manually what if you want a different
environment variables for production
let's say you want to deply the project
to AWS or Hoku you need a separate en
andv environment variables for
production level but we did not
Implement that logic now we need to do
it if want to read what is configuration
you can read this complete text I have
explained
configurations you may need a database
setting for in for development and
production you may have different API
keys for production and API keys for
development you can have multiple
environment files for production
production and testing
nestjs provide provide config module
we're going to use this package I'm
going to copy
it and I'm going to paste in my
dependency section or if you want to
install manually you can do that I have
to do npm
install in The Next Step you have to
import config module in the app module
this config module will have config
service and we're going to use the
config service to access the environment
variables let me show you how can we do
it package has
installed now we need to import config
module into the app
module geted of these extra
dependencies
we have to import it here let's import
config
module so here we have config
[Music]
module after importing config module you
have to provide the path of your EnV
file here you have to provide the
path we don't have any EnV file go to
your root directory and create two files
the first one for env.
development for production
level I can say en EnV for
production this one is for development
and this one is for
production if you want to have a
separate port for different environment
you can do that but I'm going to keep
with
3,000 for production you can place it
here so we have created the EnV file so
how can you load this EnV file we have
to set the path in the app
module here I have to provide the
options configurations I can say EnV
file path it can access the array the
first one is do env.
development and do
EnV do
production one more thing I would like
to mention we have used the config
module inside the config module config
module is using do EnV
package if you Google the
envv this package is used to define
environment variables for different
environments for development and per for
production but by default nestjs config
package is using the
EnV we have used this load ENB
property so what you have to make it
Global let's say I would like to import
EnV module into my Au module into the
artist module let's say I want to use
API keys from env. development file to
artist module you don't need to import
config module you can use config service
automatically but if you use if you make
a
global when you want to use config
module in other modules you will need to
import it as it standard with any Nest
module or you can make it Global I have
set it to Global
so I can use config service without
importing the config
module now we have to create the custom
configuration
file you have to create a new folder
inside the source folder I can say
config let's create the
configurations here you have to place
all your
configuration you have to define
configuration inside the EnV
file and this configuration dots file is
is going to fetch or add
validations for environment variables
inside the
configuration so config module is going
to use this configuration .s file it is
going to to extract all these values
from config does let me show you
how we have to load our configuration
file custom configuration file I can say
load you can have multiple configuration
file you can have different
configuration file for database you can
have different configuration file for
app settings or user profile settings
something like that but I'm going to
keep it simple let's use a simple
configuration
file we have to import the
configuration now our next
step is to test the EnV
variable we have created the port and we
have defined or getting the port
from uhv and here now let's say if you
want to access this port variable I'm
going to do it for testing purpose don't
do it in
production inside the O service let's
say I can define a new Vari new function
get EnV
variable you can call any function
here here how can you use
the configuration dots file while how
can you get the this
port into your a
service like we have to inject the
config service we have to inject the con
config
service config
service remember I did not import the
config module into the Au module because
we have set it to Global in the app
module so we can use config
service config service.
get pass it into as a integer you have
to provide the name of your key which is
Port when you open the configuration. ES
file we have specified the key which is
Port so how can you use this function
let's say I'm going to create
a controller function for testing don't
do it in production I just want to show
you the demo I can say
test get
EnV or you can say
test EnV
variable it is going to return this do
out
service calling the get EnV variable
that's it do not do any fancy stuff here
let's start the application and we have
to test this
route now we need to test
it I have to send the request to this
URL this
endpoint we have to send the get
request can say test
EnV 3000 sl/ test
amazing I got the Port Port value which
is 3,000 it's working fine
now now if you check the main.ts
file we have defined the port into
configuration we are using the port
value manually I would like to use the
config service here I want to get the
Value Port value from the config service
and I would like to use it here this is
how you can do it you can get the config
service instance from the by calling the
app.get method and providing the
instance providing the config service
class it is going to give me the
instance config service
then I can use the method
here so you can do it
here config service you can import
it now I
can get the port
value service.
getet let's pass it as a
number here I can say the port which is
key get rid off this no I'm not using
seed service we
have our application is running fine now
let's send the test test request test I
got the port 3000 we successfully
configured the port in the main.ts
file now we also need to add our secret
key inside the EnV
file we are using getting the value from
the Au constants but I don't want to get
it from the Au constants I would like to
add secret key inside my EnV file
I have to place it here secret now I
would like to use this
secret we are using this secret inser
the app
module inser the Au module not app
module here we are using the O constant.
secret but I want to get it from the
config
service I want you to think about it how
can you add or how can you get the value
from config
service we also need to add a property
in the
configuration I'm going to do it
here and this is
how you will get the
value from config service we have to
register this module as a
async and and it is going to return the
dynamic
module so you have to follow this
pattern if you want to configure Dynamic
module Dynamic module is a feature that
allows you to dynamically configure and
register modules at runtime based on
Dynamic
conditions so we have this Dynamic
value so what I want you also have to
inject the config service you have to
import the config module this use
Factory is used to inject the config
service and we are getting the value
here so I'm going to copy
that I'm going to replace my Au module
with this
code import config service and config
module Imports I don't want to use the O
constant get rid of the
Hat we have to import config
module we also need to import config
service that is it
now we have specified The Secret inside
the
configuration did I Define the secret in
the production I think I did
not if you want you can do it
env.
production let's restart the
server our application is running
successfully it means we successfully
configured the secret key you can test
it by sending the API
request I have to open it
here rest
client I can send this signup
request
it's oh I got I sent the login request
we have to send the signup request user
has created successfully
it's working fine now now our next step
is to configure the DB configurations
database
configuration I'm going to add the
configurations inside the my EnV file
development
file if you want to add a
separate EnV file separate configuration
for database you can do it can say that
DB
configuration my database is end
test now we have to define the values
inside the configuration. ES
file I'm going to copy the same code
or I need these
values now we have to update or refactor
the manual
values with configuration config
service so I I'm going to
create a new type orm async config
object and then we're going to use
inside our type orm
module let's refactor it you have to
create it this is the same process you
have to create this module or register
this module as a
dynamic I'm going to use the same
configuration when defining the type or
a
module I'm going to do it
here you can import type orm config
options we also need to get config
module and config
service
type or module
options I got the DB host DB Port
username DB name password entities and
synchronize set to
false here we are going to get it from
the process.env
I'm going to copy
that code and I'm going to paste or you
can
say replace this text
host inside the app module we have to
register
it type orm module this
time type
orm ASN
config get rid of data
source
wrong driver I think something is
[Music]
missing
postgress
we have to use the for root async in the
app module I think that is why it is
showing me the
error
you can see that application is running
fine now it means we have successfully
configured the
database we have successfully configured
the
settings it's working fine
now in the previous video we have
created the environment variables
we have set up the DB configuration DB
Port username password and database
name we if you want to add the
validation if you want to validate these
environment variables you can also do
that with the help of class validator
package to implement the validation you
have to create the env. env. validation.
TS
file we did not add node EnV inside the
development or production.
EnV I have set the Isam which
is
enum here I have defined the validation
for Port DB host username password DB
name and the
secret we're going to use class based
validator class validator package that's
why I created the
class and we will have the validate
method it is going to accept the config
object with record key value
pair first of all we're going to use
plane to instance from class Transformer
package plain instance converts a plain
literal object to class based
Constructor object you can learn more
about class Transformer by looking at
the doc so class Transformer allows you
to transform plain object to some
instance of a class you can look at the
documentation of class Transformer if
you want to learn more about
it
and you have to enable this property to
true and we have to provide the
environment variable which we have
created the class this one environment
variables and we have the config SE
config
object you I'll teach you I'll show you
what is inside the validated
config now it should be the instance of
a
class
if error comes you can send the error
back
otherwise you have to return the
validated config and then you have to
provide this validate method inside the
config
module we don't have node EnV you can
create inside the environment variable
let me do that
first
env. environment I'm going to copy
that in the production I'm going to copy
here now you have to create a new
file inside the root
directory env. validation. TS file
file we will have the enum for
development
environment it could be development
production test and
provision now you have to create a
class to validate the environment
variables we have Port dbhost username
password and the secret now we have to
implement the logic for validate
function it should return the validated
object validated
config so I got the instance of the
class we provided the environment
variables here let's say if I would like
to
log the config I can say please log the
config and here I would like to
say
please log validated
config now we have to perform the
validation
there is a validate sync method you can
use
it let me import
them I'm going to import them
here
if error comes we need to throw the
error otherwise we need to return the
validated object validated config
object so we created the validate
function now it's time to register it
inside the app
module I'm going to register it in the
config module here there is a
validate we have to import the
validate you have to import it manually
it's not giving me the
suggestions can say
validate
from
it should not be
EnV it should
[Music]
be env. validation that's why I'm not
getting the
suggestion because this is a typescript
file it's not an environment
file now I should get the suggestion for
validate
let me import it from env. validation do
not import it from the class validator
package I would like to test this
application you can see that we have I
have the config object inside the the
config object I have the property Port
secret node EnV DB host we Define these
properties inside the environment file.
env. development I got the DB name all
these couple of things now you have
environment variable which is the
instance of a Class A Class based
object in environment variables I got
all this port all this
stuff I'm going to comment this
out what if I set the wrong value in the
development file let's let me test
it if I set the DB Port should be string
let's say
that it should give me the
error I have to restart the application
because I have made changes in theb do
development
file I did not set the validation for DB
Port that's why I did not get the
error let's say I'm going to do it here
DB
Port I can say the type should be
number I have saved the
application I have to restart
it
you can see that I got the
error property DB Port has filed the
following constraints is
number let's replace the DB
Port we have successfully implemented
the validations for environment
variables in this lesson I'm going to
teach you how to increase the speed of
module reloading what do I mean by
module hot reloading if I change
anything here in any file it will take
too much time time to reload the
application if I'm going to log
something
here now my application is running first
time it will take some time let me show
you the problem and what problem we're
going to solve and how we going to solve
that
problem
e
for
in this lesson I'm going to teach you
how to increase the speed of nestjs
project
reloading if I make changes in any file
let's say I'm going to delete this code
it will take some time to reload the
application I would like to increase
this speed with the help of web
pack you can see that it's taking too
much time to reload
application nestjs provides a way to
increase the speed of your hot
reloading you can see that it's still
calculating the
changes it's still calculating waiting
for the file
changes I think it has took 30 seconds
to load the application let's increase
the speed with the help of
weback first of all you have to create a
new file web H hot modu reloading doc
config you have to create this file
inside the root
directory and I'm going to copy this
code because I'm not not going to teach
you weac in this
course and step number two we have to
make some changes in bootstrap function
I can open the bootstrap function in the
main. file we have to add the code here
if module. H then you going to do this
process
it is asking me which module I going to
talk about let me check it from my
project yes I need to declare module as
a
variable
I can I would like to declare it here I
can also add that
part into my
documentation now our third step is to
add a script to use web pack instead of
default configuration to run the project
in development
mode we have to refactor the start dep
script I would like to change it and
let's do
it this time we're going to run the
project with web
pack
e
cannot find run script weback
plug-in do we need to install
it oh yeah we need to install
it
e
make sure you installed it as a Dev
dependency so I need to uninstall
it now we need to install it as a dep
dependency
let's run the
project
weback is building your
sources
project is
completed let's try to send the API
request but it's still
running
first time it will take some time to
initiate the
project now project has completed it's
time to send the API request I'm going
to send API request to root URL
let's say I would like to make some
changes I can
say hello world I saved the
application now you can see that it took
2 to 3 seconds to reload the
application updated modules you can see
that it also loged the message updated
modules so I'm going to move this
line application has started again I
found it's very helpful when you are
building a project in development
environment we're going to use Swagger
package to document the
apis if you don't know about Swagger
it's an OP Source software Frameworks
that enables developer to document and
design the restful web
services it provides a set of tools and
specification for defining the structure
end points and data models of an
API we will have Swagger specification
Swagger editor and Swagger
UI if you haven't looked at the Swagger
let me show you the
demo
this is the example of swagger
documentation you will have all the end
points what these end points are doing
you can look
at as you can see that we have profile
route we have all these routes available
you can also create a section for each
each route I'll teach you how to do that
so I just want to show you this is the
overall view of swagger
documentation so we have to implement it
first of all you have to install a third
party package which is nestjs
Swagger uh Swagger Nest has created this
package
let's install this
package or I can add into my
package.json
file let's install
it
Swagger package has installed now we
need to configure this Swagger module in
bootstrap function you have to do it
here you can use document Builder from a
Swagger
module you can have to set the title
title should be Spotify GL the name of
your
application and you can write the
description for your
application you can set the version and
finally you got to call the build
function and then we will create the
document with the help of swagger module
and you have to provide your application
instance and this config module this
config
setting and here we're going to mount
the Swagger document at/ API route and
you have to provide the application
instance and your document
I'm going to copy the same code and I'm
going to place it here inside the
bootstrap
function you got to do it
here let's import Swagger
module
I'm not getting the hints for Swagger
module and
document let's import
manually cannot find a module nestjs
worker
why
I think I have to install it
manually and install next just
swager now the error is going
now we have a Swagger
dependency
here we have the nest F
package you can write the name of your
title
application and you have to write the
description version and finally we got a
call the build and we are creating the
document and we have set up the Swagger
module it's time to run the
application oh there is an
issue it was an extra
parenthesis
application is running now let's try to
test
it I can go to the Local Host colon 3000
SL
API now we have the title of the
document and the
description we have all these routes but
we did not add the
tags I'll show you tags
in the next
video let's try to send the request to
the root
URL so I got this response hello I am
learning nests
fundamentals if I execute this endpoint
I got the
port the 200 status
code in this lesson I'm going to teach
you how to document this signup
route if you look at this signup
route I don't have any schema yet it's
not displaying the schema what type of
parameters do we need do we need first
name do we need last
name I also want to show the description
or the purpose of this signup
route
first of all you have to add the API tag
to the O controller let's convert all
these routes into o
section we're going to place the login
route into OD section enable to fa and
validate to fa let's do it first I'm
going to open the O
controller
here I can
say API
tags I can use the
Au my application is running
now you can see all the routes are
placed inside the O section
one more thing I would like to add in
the O
controller we have to decorate the sign
up route the next step we have to add
the API operation and the
response I'm going to use the API
operation we need to get it from this
Swagger
module
it will return the user in the response
with 2011 status code this is called
please register a new
user make sure it's running
now let's
refresh
I cannot see the sign up rout I think it
is taking too much
time oh I found the
error API
response we need to get the API response
yes we have the API
response let's restart the
[Music]
application
now you can see that we have the
register
user we have specified it
here somebody which is registered new
user and you can see the
response it should it will return a user
in the
response let's try to test it
if I if I provide first
name NH last
[Music]
name
shsf and we have to provide
email SN
gmail.com let's provide the
password 1 2 3 4 5 let's try to test it
out internal server
error because let me look at the error
entity metadata note found no metadata
for a user was
found I found there is an issue with
type orm and a web pack if you use vbac
hot reloading like we have used weac
package to reload the application fast
type orm does not work with this
configuration like this one we have to
replace it and you have to register all
the entities manually but it can work
with migrations there is no problem with
migrations but you have to replace it
here
we have to import couple of
entities application is broke
now I think I have to restart
it application is running fine let's
test it out I'm going to create a new
user a user has created successfully you
can see that with 2011 status
code when you look at the sign up
route if you check schema it is not
displaying me in the schema what do I
mean by
schema here I cannot see the login dto I
don't have create song dto I don't have
create user
dto it should display me the schema let
me run the
application
my application is running
now if you look at the schema in the
signup route you will see the empty
create user
dto you can fix it with the help of API
property you have to tell Swagger hey
this is the API property I want to I
want to see in this Swagger
document let's add API property in the
user
entity we have to do it here please
provide the first name of the user first
name of the user let me import API
property you have to do the same thing
for last name you can also add example
like what could be the data type look
like
I'm also going to add API property for
email let's do it for the
password my application is running
now but I cannot see this schema value I
cannot see properties here for my
schema you have to register nestjs
Swagger plugin you can do it in the nest
CLI I'm going to copy the
plugins open
nli and I'm going to do it
here let's restart the application
because we have modified
nli let's refresh the
application I cannot
see my
schema
I have to register the plug-in inside
the compiler
options that was the
mistake restart the
application now you can see the schema
value first name last name email and the
password it will also show you the
schema value for login
dto
here we have the user example value
email ID API key
playlist in this lesson I'm going to
teach you how to test Authentication in
Swagger
document we have to enable barer o it's
a
scheme you can do it in main.ts file you
have to add this function Nest Swagger
module provides this function add
barrier
o this is the type HTTP scheme is
barrier format should be
JWT name is
JWT you can add you can add the
description jwd token and I would like
to provide in the
header this is the name when you need to
use or apply on the controller
function one more thing we also need to
update the secret key in the JWT
strategy I don't want to use o constant.
secret I I have to get it from the
process.env
secret this get profile is our protected
route if you want to apply
authentication or app if you want to
protect or apply authentication of
swagger document you have to use the API
barrier a and this is the name we use
jw/ here this one
like create songs endpoint is also a
protected route you can also apply
authentication on that in the songs
controller these are all the protected
routes only
artist can access update endpoint delete
endpoint and create endpoint so you can
apply Authentication
on these routes as
well but I just want to show you the
demo in the app controller we have this
protected route get profile
endpoint let me show you in
our Swagger document SL
API here we have login
route we don't have any authentication
section let's implement it first of all
let me write documentation for login
route inside the O
controller it looks
good now we have to enable the
authentication I'm going to copy the
code and paste it
here now we have to apply JWT
authentication we also need to update
the secret key in the JWT
strategy
I don't want to use o secret from the O
constants let's get it from the
environment
variable and this is we have to
use I'm telling to Swagger hey Swagger
this is the protected
route application is broken now restart
the application I found an issue when
you are working with we hod module
reloading do not save the application if
your application is in error
format if there is an error in the file
do not save the application otherwise it
will break the V hod module reloading
now it it will take some time
to restart the app
application application is running
now I have to refresh my
page now you can see the
authorize if I try to access the profile
route from
here it should give me the error unauth
red so you can you have to log in to get
the access
token I'm going to send the login
request password does not match what was
the password 1 2 3 4 5
6 I have got the access token
now I can use this
token and I'm going to provide it here
this is the name JWT o you can see that
authorize
Now by enabling this JWT o
here this Swagger will use this token
just like we saved
here
let's access the protected
route you can see that I got the user ID
and the email it has already
attached authorization barrier and the
token if you have all protected routes
in the controller you can also add API
barrier or
here for all controller routes but I
have only single route is protected
protected this is the public right route
that is why I did not use the API or o
barrier or inside root inside the
controller for a
controller so I applied separately API
or API barrier OD
you can also Define the tags for songs
controller I want you to do
it you can apply High authentication on
songs controller protected
route like create is a protected route
you have to add API or o barrier
decorator
here it did not create the aay tax
because my application has broken now by
using this code restart the
application my application is running
now I can see all the songs related
route you can also do it for the
playlist API
TX
you can see the playlist
section in this lesson I'm going to
teach you how to install mango DB using
docket
compose if you don't have installed
mongod DB on your machine you can
install it manually or you can install
with Docker compose I have already
installed Docker on my machine my Docker
is
running you can see that here is my
Docker is running
now but we don't have any project right
now to use with
mongodb I don't want to install mongodb
in my previous project we're going to
create a new project to play around with
mongod DP
database I want you to create a new
project
I can say Nest
new and we need to provide the name of
your project I can
say n
production nestjs
project with mongod DB and I want to
ship it on production level you have to
choose your package manager I'm going to
use
npm it will take some time to install
the
dependencies my project has created
successfully all the dependencies have
installed I'm going to go to my
project I'm going to open the project
into my vs
code
let me run the project by using npm Run
start
Dev let's commit in
it and I would like to create a new
Branch I'll store this code into this
branch
[Music]
to connect with mongodb we will install
this dependency or this package in the
next video or you can install it
here we need NCS mango package and we
need mango separate
package this is the magic we need to
implement we're going to use docket
compose to start mang DB
driver I'm going to create a new file in
the root directory I can say Docker
compose
EML you have to Define your
version I can say one you have to define
the
services here we need to define the
service mongod DB or mango
mongodb the name of the
service you have to provide the
environment I can
say mongod DP
database and we need to provide the name
of the database which is
test we also need to provide the image
we need to get the local uh latest image
from the docker
repository Docker Hub or you can say
let's define the port I'm going to copy
the same code I don't want to make
mistake that's it or you can change your
database I can say
Spotify
clone now you have to start MB
driver you have to execute this command
do compose
up my project I'm going to open my
project into R directory and let's
execute this
command I
think already allocated I think my
already project is running
on 2701 docket compos let me stop that
project
project here we need to stop
it let's try it
[Music]
again now it is going to start the
mongod
DB I'm also going to use external tool
it's a graphical user
interface mango DP Compass you can
install it you can play around with GUI
with mongodb database this is the GUI
mongodb mongodb
Compass you have to have a new
[Music]
connection you can have a new
connection it is going to ask me the
host and the port I can say Local Host
and this is the port
2701 because my mango DB is running on
this port 27017 so I'm going to connect
it and you can create a new database
Spotify clone and you can have the
collection which is
songs you can see
that I have interacted with mongodb
database and I created a new
database
so our mongod DP driver is running
successfully in the next video I'll
teach you how to connect nestjs
application with mangos or mongod
DP in the previous video we have
installed these two packages
mangos and nestjs
mangos if you would like to connect
nestjs application with mango or mango
DB
you have to create a new module in the
app module you have to create it by
calling the for root method this for
root method is similar to mango. connect
from the mango package you can read the
connect package from the official
documentation what I want you to make
sure your mongodb is
running my mango mongod DB driver mongod
DB is running with the help of Docker I
use Docker compose
up here it is running Docker compose
up now we have to call this method
mongos module. forward in the app
module make sure you have this database
Spotify clone if I run the application
let's see what will
happen
npm runs start
def mango module because we did not
import it let's import it with the help
of VSS code I'm going to save the
application
you can see that Mango's package has
installed it has also initialize the
mango score module
dependencies it means we have
successfully connected to mongod
DP if I will write the invalid Port
let's see what will
happen
I'm getting the error mangos module
unable to connect the
database so it means we have configured
the mango DB with
nestjs but if you look at mango
Compass I think I don't have Spotify
clone
database it can work without creating
the database if I create the database
it will
work I can create the name of the
collection now we have Spotify
clone it looks
good now we're going to create schema
using mongos
model in mongos everything starts with
schema each schema maps to mongodb
collection and different finds the shape
of the document within the
collection schemas are used to define
the models and models are responsible
for creating and reading documents from
the mongodb
database so we're going to create the
first
schema you have to create a new folder
songs here you have to create the
schemas folder and you have to have a
schema which is songs. TS file but we
will use this song document when we will
inject the model into song
service you can use the decorator schema
nestjs mango module provides schema
decorator this prop represents the
property in the
collection we will have songs collection
and inside the song collection we will
have these Fields Title release date
duration
and the
lyrics Yep this schema decorator marks a
class as a schema definition it Maps Our
Song class to mongod DP collection of
the same name but it will add S at the
end of the final mango collection name
will be
songs and prop decorator defines a
property in the document and finally we
will have schema Factory
it will return the raw definition of
schema I logged on song schema and I got
this result schema object we have these
properties title release date and
duration and couple of metadata for each
field this is how you will create a
schema I want you to implement
it
so I'm going to implement
here by creating a new
folder inside these
songs we will have
schemas here I'm going to create a song
schema or song. TS
file
I just pasted my
code we have defined four Fields I got
all these properties from our previous
project which we worked with tym and
post I got title release date duration
and lyrics I set this data type for dur
string I couldn't find a Time Field Time
data type in mangos so you can validate
manually duration by using third party
date
plug-in so we created the schema
successfully this lesson I'm going to
teach you how to save record in mongodb
database we're going to save record card
in mongod DP
collection right now we don't have a
songs module we don't have songs
controller we don't have song surveys
we're going to create all these stuff
and then we're going to create post end
point inside the songs controller you
have learned how to create the post
endpoint how to create network request
object or data transfer object
dto and then I'm going to use song song
service song service has create method
to save the record in mongodb collection
and finally we will create create song
dto object inside the create song d.
file and here I would like to inject the
model remember schema will act as a
model you can use schema to generate a
model so I'm telling please give me the
model
the name of the model which is songs and
I would like to use here I would like to
inject it as a dependency I remember I
have created the type in the song schema
file I got the song
document and this song model provides
crud operation create read update and
delete it is similar to type orm
repository it will be treat treated as a
type RM
Repository and finally we have a safe
method in the song model and I am going
to call the method here it is going to
return the
promise and finally we have created the
songs
module we have to inject the song model
just like we did with type orm
repository if you will not do that part
you will not be able to inject song
module here that's why you have to
register it as a here I'm telling to njs
I would like to use song model in the
service or in my
provider and then you can send the
request to this
URL to to create a new song in the
mongod TB collection I want you to
implement
it let me implement it for
you let's
generate let's generate controller
songs let
generate so
service
songs it has created the songs
module it has also updated the entry in
the app
module you can also see the songs
controller it has also updated Creed the
songs controller inside the app module
you can see
that now we have songs
module inside the songs module we have
songs controller and the song
service now it's time to create a new
endpoint I'm going to copy the code
inside the songs
controller we just injected the song
service right now this create method
does not exist in the song
service we also don't have create song
dto Let's create let's create create
song
dto I'm going to create a new folder
dtos and I'm going to create a new file
file create song hd.s
file that's
it I already taught you how to create a
method in the
service let's refactor the song service
add a new
method we have injected the song model
make sure you provide the name of the
song model here we are injecting the
song model and I called called create
method from song
model and finally we have to tell njs I
want to use this song model in the songs
module so please make it
injectable and now we have to run the
application
I have to import
song dependency
song
it looks
good we have to test
it I'm going to create a new file to
make API request I can say api.
HTTP let's send the API
request
you can see that a song has created we
can verify from
Compass here is the record inside the
songs
collection let's add another
song
so we have another
song it should display the second song
but I cannot find
out no I can see the second
song we have two records in mongodb
collection this is the
document if I don't set the title what
will happen you will see internal server
error because we have set the
validations inside the song
schema these properties are required
title is required release date is
required and duration is required
in this lesson you're going to learn how
to implement find and delete method we
will create two endpoints to handle
find and
delete
request let's start implement it I have
already taught you how to implement crud
or rest based API end
points let's create a method find to
fetch all the records from mango DP
collection it is going to give me all
the
documents now we have to create a route
to handle the
request
our application is running now let's
send the API
request to fetch all the
songs we have to send the get API
request we don't have any record yet
let's create a new song I have I've
created a new song I'm going to create
another
song now we have two songs let's fetch
all these
songs we have successfully implemented
the find all
method now it's time to implement the
find by
ID
I'm going to create a new method find by
ID in the song service and there is a
method find by ID in the song model you
have to provide the ID we're going to
get the ID from the request
parameter let's create a new
route
now we are going to send the request to
fetch song Only based on
ID find one
song we have to get the ID I'm going to
send the request to fetch all the
songs now I'm going to copy the ID and
we need to provide the ID
here so I got the single record on the
based on
ID you can also implement the delete
endpoint I'm going to create a delete
function inside the song service
song model provides delete one method
and you have to provide the ID mango
work works with underscore ID if you
have worked with mongodb the ID
stored ID stores in this underscore ID
format if you if you are using or have
used postgress or MySQL in my SQL or
postgress you say the primary key or
primary ID with this ID without
underscore now we have to create a
delete endpoint in the songs
controller we have to get the delete
method that is
it
let's create a new
song because we're going to delete that
song I'm going to get the ID and now we
have to delete the song to send the
delete API
request delete
song you can see deleted count is one
acknowledged true it means we have
successfully deleted the song you can
double check it by sending the API
request to fetch all the songs and you
can see new song does not exist
here you can also implement the update
functionality I already taught you when
you were learning type or mcard
operations similarly you can implement
the update operation you can have you
first of all you have you have to Define
update function Here song model provide
the update method you can use that
method and then you got to create a
controller to handle the update
request in this lesson I'm going to
teach you the concept of
populate if you want to make a relation
or a reference between two document
between two collections remember in
mongodb
collection collection will have
documents in my SQL or post you will
have tables and
columns so if you want to make the
reference or relation between two
collection you can do with the help of
poate you have to implement the concept
of
poate I have this use case or scenario
each song must have must belong to one
album and each each album can have many
songs I want you to implement it if you
want to do that you can Google Mongo's
relation or check the official
[Music]
documentation this is our
album schema we did not create the album
schema yet I'm going to teach you how to
do that or you going to create or you
can create the album schema just like we
did the song schema scha it is going to
take the array of the songs because each
album can have many songs that's why I
created the array of songs and you can
have multiple
types it's an array I got the types from
mango package here you will see type
from the mangos and I'm telling that the
reference is
songs because when you create the song
when you created the song schema you
have defined a class for class song by
default the collection will be songs you
can also double check it from mongod DB
Compass let me show
you I'm telling you I would like to make
a reference with songs
[Music]
collection let me do that
inside the Spotify clone we have the
collection name which is songs I have
added the reference
here and finally you also have to add a
relation for this for the album in the
song schema I'm creating a property and
type should be Mango's object ID or
mongodb object ID here I'm I'm getting
the or defining the reference album.
name it should be
albums and we have the album and finally
you got to create album module just like
we did the song module and I'm saying I
want to use the album model in the album
service or we we will be able to inject
the album model to perform crud
operations and here I have injected the
album model in the album service just
like we did songs model inside the song
service and I created a new method we
will have a create album dto and here we
will have find
albums this is how you will implement
the populate let's say you want to
display all the songs on the front end
against each album then you need this
query you got to I'm telling to mongod
DB please give me all the albums please
give me all the albums for each Album
please also give me all the songs this
is how you going to do
it and create when you are trying to
create a new album you got to provide
the title and the songs it should be the
IDS and we have create method to create
a new album
and uh find all albums and you also have
to refactor create Song D you can
implement it I want you to do it I
already taught you all of these steps to
do
that first of all we have to
create album nextest
generate nextest generate module
albums or I can say
albums and next gener at
controller
album and Nest generate service
albums Nest generate
module albums
Nest generate
controller
albums Nest generate
service
albums
I don't need spec files I'm going to
delete
them now you have albums module albums
controller and album service it has also
added the entry in the app
module let's create a new folder
schemas I have to create create a new
schema I can name it to album
schema. we will also need a
dtos now we're going to I'm going to
copy album
schema and I'm going to paste it here
that's
it
and I can
use I also have to refactor the song
schema we have to add another property
one thing I forgot to add it should be a
mongodb property that's I forgot to
add add prop decorator for the lyrics
property we need to get the types from
object
ID from
mango we also have to import the
album from album
schema everything is good right now
let's
create we have to
update album
module actually we
need we need this line I'm going to copy
[Music]
everything
e
we don't have dto let's create
that create Alum
dto now we have to
define a
controller we already created the
controller I can
say should be albums
controller album
service and we also need to refactor the
create song
dto
I have found the error in the album
service get rid of the song Let's import
it
here if I save the
[Music]
application we also have to
refactor in the song
schema
everything is good
now what we what I want to do I would
like to create the album
first create
album we have to send the post
request by providing the
data it is going
to get give it is going to asking me the
name of the
album title title of the
album let's say
dance and I would like to provide the
array of the
songs I want to save let's
say these two
collections
these two
collections inside the dance inside the
dance
[Music]
album I'm also going to save this
document or save the song inside this
album let's create a new
album
I got the
eror song validation
failed duration duration is required
OMG I forgot to add the albums
here now you can see that I got the
dance album with these two
songs now we have to fetch all the songs
I'm going to test the popular method
popular
functionality find all
[Music]
albums with
songs this time we have to send the get
request let's fetch all the
albums you can see that I got the albums
array this is the first album and we
have all the songs against each album
this is how you can make a relation or
reference with document with
collections or with
models in this lesson we're going to
prepare our application for
deployment I'm going to teach you how to
deploy nestjs application at
Railway you will also deploy your
postgress
database at Railway we're going to
deploy our application this one the
Spotify clone which we were
building our application is using postp
database with type orm I'm going to
teach you how to deploy the complete
application at
sailway
first of all you got to create a new
project make sure you deploy your
project at GitHub
repository I did not deploy the project
yet first of all we have to do a do a
little bit
configuration we have to set our
environment variable when I will run the
application in production it should run
this production. EnV file if I'll be
working at development environment I
want to work with local post database I
don't want to change in production
level so we got to configure a couple of
settings we already created the env.
development. env. production but it is
not configur configurable when my
project is running in production mode it
should pick this production
file I've already written down the
validation in EnV validation for node
environment but I did not set in the
configuration
let me do
it I can say node
EnV and I can get the value
from process
dot process. env. node
EnV now this variable is available for
the config
service I've already provided you the
nests deployment raway started kit BR
started kit project you have to open it
and run npm install to install all the
dependencies now we have to configure
the EnV file path in app module
get rid of this
stuff I don't want to do
it
configure get it off this
middleware get rid of this data source
here we have to update our
path what I can
say please get the value
from process do
do
EnV do node
EnV or you can say get the path from the
current working directory and you can
provide the name of your
file current working
directory and
Slash
dot here we need to do EnV dot
development or
production we have to remove this
one
please get the working
directory and find the env. production
file or env. development
file we have to set the script or we
have to set the development environment
in our package.json file for the dev I
can say I want to mention node EnV to
development we have to do
it here we have to set the production
value when you run the application with
production how can I test
it in the main.ts file maybe I can use
that or what can I do yeah I have the
access to config
service I can say console
DOT
log
config
service
doget I can provide the name which is
not
EnV
let me part it to
string let's see what will
happen you can see that it's working
fine now my application is running in
the development
environment if I run the application in
produ prodction
environment when you see the production.
environment I don't set the I didn't set
the database configuration so it will
not work my application will be crashed
let me show
you you can see that my application has
crashed
an instance of environment variable has
failed
yeah it is showing me the validation
error dbport does not exist DB host does
not exist if I copy this
configuration what will
happen now it should run the
application you can see that my
application is working fine
now but we will replace these
configurations with Railway post
configuration I have everything in the
master
Branch let's create the GitHub
repository because Railway will be
asking for GitHub
repository let's create a new repository
I can give any
name nextjs deploy to
railway
if you want you can create private
repository I'm going to make it
public we have to add
origin it is asking me to create push as
a main
branch let's do
that so I got the main branch everything
inside the main
branch let's try to check it
out so I have everything in the main
branch now we
have we have EnV doev development we
have env.
production you should not push your env.
development or env. production to the
GitHub
repository because we wanted to set it
to the kit
ignore do not add
Dov
files if I add.
EnV update get
ignore
we have to push the
code I try to add do EnV in the G ignore
edit I try to
add EnV in the
ignore and it was not not
working I also removed the cache for
env. development and env. production
file
removed
envs now we have to push
it
oops envs
let's push the
code
let me delete this file
manually I'm also going to delete env.
[Music]
production
now we got to pull the
code everything is up to date right now
if I try to
push you should not
see env. production and EnV do
development
file so we have pushed the source code
to our GitHub repository you going to
say deply from the GitHub
repository here we have to configure
our repository I can say deploy njs app
to I can say now it is going to deploy
the code
it is
building and running env. production no
it is trying to building the
project
now you can see that our project has
deployed if you want you can see the log
what is going on
here I got this
error instance of environment variables
has failed in the valid
validation that's an issue we have to
configure our environment variables
our application has crashed now we have
to set the environment
variables first of all I have
to create a new database it's very easy
to create a database in real
way just right click and find the
database I'm going to have
post now you can have the
post when you see the connect here you
can find your database
option I can say this is
post and you can up create your EnV
production file
EnV
[Music]
production oops I deleted that
files we need to get back our
development. EnV
file do env.
development and I also need to get
production EnV
file now I'm going to copy my
database in the
production let's do it
here
[Music]
database this
[Music]
one and we need PG
Host this
one and we need password I want you to
use your own password do not copy my
password
username it should be post it's working
fine you also need a
port everything is good to go
now
now I want you to copy these EnV file
the your production EnV
file and open the N nestjs deploy to
raway
project and in the in in the variables
you have to set your environment
variables that's it I'm going to update
my variables now it is going to redeploy
the app
application now redeployment is in
progress It's Time to it's it will take
some
time my application has deplo
deployed now it is going to start let's
look at the deployment
logs amazing I I was logging the
production in the app module or I think
I was doing in the main.ts file you
should not do
that it's working fine it means we
successfully deployed our
application so how can you test it maybe
you had thinking about it how can I test
this application right now we don't have
any domain let's generate domain to test
the
application uh if you want to refactor
you can change that I can say Spotify
clone
production now we have this domain name
I'm going to open
it it is going to give me the nothing
here don't worry when you try to access
the API
routes it will take some time because we
have set the domain
name it is going to take some
time now it's working I think fine
now after 30 seconds my project has
Reloaded
now we're going to figure it out I'm
going to send the API request to test
the application it is working fine now
but what will happen if I try to create
a new user let's say I want to perform
database operation I'm sure it is going
to give me the
error let's create a new
user
Jane
Don Jan
gmail.com 1
2 3 4
56 I'm going to send the
request I got internal server
error you can check the log what what is
going
on users does not
exist because my database is empty now
we did not implement the migration
remember you have seen in the data
source we have set this synchronized to
false but do not use synchronize to true
in
production what we have to do we have to
run our migrations to perform changes we
have to add relations because I done
that I've done
it I think I don't want phone migration
you can delete
that
now I have to execute these queries
these queries will create table
in our postrest database here
here what we have to do we got to run
the
migrations I got this issue we have to
migrate the database in the production
so we have to use a
migration make sure you are using the
password process. env. password not a DB
password because we have defined the
password in our environment
file we have to run the migration I'm
going
to run the script npm run migration I
would like to create all my tables
that's why I just provided the name in
it so I got the
undefined
process. I'm doing the log for node
environment I'm also doing the log for
DB DB host I'm also doing the log for DB
password you can see that I got the
development value it is working fine but
when you look at the env. development
I'm using the database for the Local
Host like post gra local instance here
I'm using the railway postra
instance so I have to tell to nestjs
build
command under the they are using
generate command is using njs build
command this one type orm but I want to
say please run the produ run the project
in the production let if you want to run
the de in migration in production you
have to Pro tell njs project you can
create a separate script for build for
production or separate SCP for separate
script for build in the development
environment but you can do quickly by
using say that
export node EnV here I want to set the
node environment variable to production
now you can see development environment
should be in the
production I'm going to run the
migration I've also logged the node
environment it should give me the
production by default
it if it if it logs
production it means it is going to run
the production EnV
this
one you can see node environment is
production but I got DB host is empty
undefined and password I figured it out
the issue I have to
install do EnV
package and here we have to use the EnV
package it is not getting variables from
EnV because we were using the config
module for config
configuration after installing config
module do EnV
package you have to import it
here do en/ config now you should be
able to access these variables
so I'm going to run the
migration
before running the build you have to set
the node envirment do you want to run it
for production or do you want to run it
for development but if you want you can
create a separate script SE separate
build script for production and
development I still got the
eror production
it's not getting the
value I think it is not finding the env.
development
file so there was an issue it is not
loading the EnV from the env.
development. env.
production if we will have simple. EnV
then EnV package can get variables from
the file but right now it is not getting
it so you have to provide the custom
path I just did a little bit
configuration we have to import the
path we have import the
part so we have to
use this
syntax
require this
one all I have to do is provide the EnV
path
now it should work it should get the
values so I'm going to create the
migration cannot read
property
PA is equals to
path
but I got still
undefined let's log EnV
path oh it is getting the value
from
DB but my file is located
at root folder so it is not here inside
the
DB if I try this
one I tried to work with this env.
production with custom path but it is
not
working all I did if I
change EnV it is it will work let's let
me show
you get rid of
[Music]
everything now if I copy that and
create EnV file in the root directory it
will
work I found there is an issue with type
orm now I'm going to paste my
code for production
you you have
to adjust nestjs build when you try to
run the migration you have to update the
changes here I found this is the way you
can implement it but there was an issue
with custom file path so now it will
work I'm going to run the
migration now I can see production and
the my container name which is my DB
host and my password now migrations has
been generated
successfully it's time to run the
migration we got to run this
command npm
run
migration
run should be
run you can see that it is running all
the queries creating tables in the
railway postris
database now you can understand you can
use this EnV for type orm
build use it for type or RM
migrations because in the app module we
are using the configuration of config
module we are not loading this EnV file
we are loading envir environment
development env. production file but you
can use this EnV for
migrations now we need to double check
it
we have to deply our
code now it will take some time to
redeploy the
application the application is running
now I got this secret key the database
host and the
password now we're going to run
it/ API open this Swagger
tool you can also double check it from
postris
database I have only migration table it
should give me all the tables but
something went wrong
here inside the
migration the record is empty table is
empty unique key primary key what is
going
on oh I have two migr
ations get rid of this
file get rid of all these
migrations let's generate the migrations
from the
scratch I'm going to name it to in
it now migration has R it
successfully I'm going to comment this
code now you have to run the
migration everything is good to go all
the ques has have
executed now you should see the data in
the data datase you can see I got artist
playlist songs and users
table we have these
columns if you want you can run the
seed from App module I think we we were
doing seeding in main.ts
file you can enable this
code application is running
now let's create a new user
amazing we have created the record
successfully you can also double check
it from the post
database you will have the user
here but I created this user
from the this one from seeding because I
think my seeds are running
constantly I think I enable that seed in
the app module we got to disable
it otherwise it will generate more
users I'm going to remove them now you
have to see constantly a new
data I can say disabled
seats now it is going to redeploy the
application so this is how you can
deploy nestjs application to
railway in this module I'm going to
teach you how to do unit testing
integration testing and end to end
testing for nestjs
application before getting started on
testing I want to teach you some of the
basics of just because we're going to
write a lot of mock functions we're
going to write we're going to write a
lot of spying spy
functions you will learn how to create
Mo implementation of service of a
controller of a
repository if you know the basics of
justest if you know mo functions if you
know spy function then you can skip
these three
lessons if you want to refresh the
knowledge of just you can continue this
video just as you if you don't know
about just just is a popular JavaScript
framework it is developed by
Facebook you can use for testing
JavaScript
application you can use just with react
view angular and
nodejs these are all the function alties
of the Gest asynchronous testing code
coverage snapshot testing moing and
spying we're going to use a lot of
moking and spine with nestjs that's why
I want to teach you these two concepts
in more
details you will learn how to do matches
and test suits and test running and
assertion uh before creating the just
project I want you to open an empty
folder we're going to start it from the
scratch and you got to create
package.json
file I can say npm in it d-s please
create the package.json file for
me I got the package.json file now I'm
going to copy
that and let me replace
that here what I want to
say we we need to install the typing of
the justest we need to install the
justest app a Dev dependency and I
created the script to test the justest
if you want to run the justest in watch
mode I'll teach you how to do that you
got to run you got to run this
script so uh please install these two
dependencies I'm going to install
them it's going to install the
dependencies let's create a new file I
I'm going to name it to some .js file
we're going to test this function we're
going to write test cases to test this
function in the third step we have to
create some.
test.js file I'm not using typescript
here I just want to show you the basics
that's why I want to keep it more
simple we have to import the sum
function from the sum. JS file
I have to write the test case at 1 + 2 =
3 now we're going to write the test case
you can use the
test it should give me the
result 1 + 2 =
3 so we're going to call this
function it's going to take the call
back
function I can
say
expect it's not giving me suggestion
because it is taking too much time to
install the
dependencies because I think my internet
connection is slow right now
so we need a
[Music]
function sum. 2 B 3 we have to call that
function it is going to take two
arguments if you look at the sum. JS
file you will see two arguments A and B
the first argument I'm going to provide
one and the second argument I'm going to
provide two let's try to test it
out it's still
working npmi minus
TJ my both packages have installed just
in the typing of the
just now you can write the test case
I've written the test case you can run
it npm run test I would like to run it
in the watch
mode dash dash watch is not
sported so you have to write the watch
all now you can see that I have to
update the script for the watch
all now we have to select the pattern I
would like to run this s test.ts file
right now we have only single
file it's going to execute this file the
test has passed now if I write the
invalid value I save the
changes it has started automatically and
I got the
error expected four but received
three you can play you can play around
with multiple matches function let's
say 1 +
4
or to have been
called to have property to have
returned to have returned with let's say
five you can play around with multiple
watches received have as type
number so this is not a right matcher
function so I can say it should be
five this is how you will write your
first test
case now I'm going to teach you the
concept of
mocking we're going to play around with
mock functions Auto mocking inest refers
to the automatic creation of mock
implementation for imported modules or
dependencies during
testing let's create the mock
functions you can use the mock function
to track the function calls
if you want to remove the dependencies
we're going to do in njs testing we're
going to remove maybe the implementation
of service implementation of the service
then we will have more implementation we
can simplify the testing and control
behavior when you do the unit test your
code let's say if your code is dependent
on five dependencies let's say if your
class is dependent on on Class
B Class
B Class
C or class D let's
say and you want to do the unit testing
let's say this is the class A now Class
A is dependent on let's suppose Class B
Class C and class
D now Class A let's suppose we has two
function or one function if you if I
want to test the one function from the
class A when you do the unit testing you
test the individual Parts you test the
individual functions to test the
individual function maybe the individual
function of Class A is dependent on the
function of Class B function of Class C
and the function of Class D then we have
to write the mock implementation for the
class B Class C and the class D
I'll teach you in the later
videos now we're going to create mock
function this is how you will describe
or you can group all your test cases
into a
group describe I want to write all the
mo function examples in this
section it is similar to the test you
can Define the it or the test it is
referring as a test so it should create
the basic mock function let's create a
new file Mo function. spc. TS file I
have created the test.js file but you
can also create the
spec. JS
file the concept is same
now now we have to write the mo
function here I can
say
I will provide the
mo write Mo function
examples here this this this section
will have the mo function
examples let's write our first test case
it should create a basic Mo
function should create a
basic mock
function
you can create a mock function by using
the just. function I can say this is the
mock
function just provide is a
FN now we have the empty Mo function if
you log the mo function you will see
this is the empty function let's try to
do it run the script again to run the
Tex test in the watch
mode this time I'm going to add the
pattern for the more Dash function. spc.
file it is going to ask me the pattern I
can say mock now it's going to run this
file if you see the log you
have a function a mo function if I call
that you will see there is nothing here
we have undefined
function if you pass the argument it is
going to still it is going to still give
me the
undefined this is the empty mooch
function if you want to return the value
from the mock function you can also do
that
return
value Mo return value now let's say I I
would like to return the
four now if I call that function it
should give me the value of four I can
write the match functions on it mock I
call the
function to be the value should be
four you can see our test has passed now
if I add the invalid value which is
three it's going to give me the error
expected three but received
four if you want to remember I told you
you can also keep track the calls of the
function with the help of Mo how many
times this function has cost
called mo. calls.
length to be we have called
only one time so it should give me the
length is
one if I call the function two
[Music]
times Mo
function
dot to
have been
called
been
[Music]
called let's say I want to call that
function and I'm expecting the four
it should give me the error you can see
that the save to expected is one here we
have the
error it should give me the two because
we have called this function two times
if you want to keep track of the calls
of the function how many function have
how many times you have called the
function you can also do measure on
that here I can say expect
mock function to have been
called it is checking that did you call
the function yes we already called two
times this is how you you can return the
value from the mock function you can
create you have learned how to create
the basic mock
function
now you're going to learn how to create
a basic Mo function with
arguments we did not create a function
with
argument we just created a basic mock
function then we have returned the
value here I can
say it should create a mock
function with an
argument
let's create a function con
mock song function you can say song
mock just.
function it can have create song dto
let's say
that
mock create
song and this
function will have this
argument but I also want to write the
implementation you can do that as well
well right now we did not return the
value if you want to return the value
you can
do this stuff it is going to return a
song
title animals and
ID or you can oh
animals and ID which is one let's say
that
that if I am expecting on
that it should give me the same
object
animals ID which is
two or ID which is one if you want to
test the object you can use this two
equal
expression make sure you have called
that function with
argument create D is not
defined title should be
animals create D is not
defined I think it will not not work we
have to write the implementation here I
just want to show you the another
alternative path it's a call back
function it's going to it's going to
return the create song
dto now you
can look
at this
one
now my test has passed now if I will
write the ID it should give me the false
it should give me the false value or it
has failed because I am just returning
the ID but you can pass this
test if I create if I return the
object use the spread operator and ID
which is
one let's try to check it out
out now my function has my test has
passed
now if I provide the another value
lower in our application this function
like create song function does not exist
here we don't have a create song
function we don't have njs project we
don't have repository we don't have
service controller that's why this is
how you can create the mock
implementation you can also create a
mock function with mock
implementation we used callback function
here here but if you want to
use this Mo implementation you can do
that as
well it should create a mock
function with an
argument with Mo
implementation this
one I don't have preer
file R
see single C to
true because I use this prettier
formatter now my code has formatted
now we're going to use the same
approach const mock create
song just.
function I have defined the
function mock create song do
mock
implementation create song
dto it's going to return the object
create song dto and the ID which is
one now I'm going to ex run the mat to
test the
code my code has passed now my test has
passed now you can approach you can
implement the same stuff by using the
call back function here or if you prefer
the mug implementation you can do in
this
way now I'm going to teach you how to
create a mo function and it function
this function should return the
promise all you need to do is call the
mo result value we use the mo return
value you can do that with the help of
Mo resolved
value let's say I would like to create a
new
function
let's create a new test case it
should create a mo function with
promise ultimately it it is ultimately
it is going to return the
promise fetch song data or you can say
that fetch all the songs from the DB or
you can say the network
request now we got a
return Mo return or Mo resolved
value let's say fetch songs I got the
array ID
one title
Lover now I will like to call that fetch
[Music]
songs Doc do
results dot to
equal if you want to apply assertion on
promises you can call the results
property and then I can apply this
Expressions to equal this
one make sure you could to call that
function now my test has passed if I
write fetch I'm going to call the fetch
functions do
resolves dot to have
length it should have
one my test has passed if I write the
two it should give me the error because
we have only one property in the songs
array I got the
error I'm going to call it with
one this is how you will do the
mocking you have learned the feature
Auto moing which is mock
functions but we did not talk about the
spank and you can control the
behavior
and you can assert on their usage during
testing you can create the function
spying on spy you can spy on a function
by using the just. spy
on it allows you to create a spy or a
mock function for an existing object
method if you want to spy on existing
object you can do that if you want to
spy on existing class you can do
that now we're going to spy on an
object we have an object spy on a method
on the
object we going to Let's imagine we will
have the song repository and we have the
create method what I want to do I want
to spy on the create method I don't want
to use this implementation I want to use
my fake implementation in under the
hood just will tell you you I called
this function but I have used your
implementation this implementation this
one instead of instead of using this
original
implementation let's spy
on I want to I want you to create a new
file since by on demo dopc
dots let's create a song
repository and we have a create function
let's imagine we have a find
function let's imagine we have the find
one
function I want you to add the add this
Pi on this find find and find one but
first let me do that find one will
accept the ID let's
imagine the
ID now let's create a
[Music]
function so I created the test case it
should spy on the
existing method
function object
method so you can create a function on
this py
on
so this is how you will spy on the
function it should also give me
the toll tip
create if I log this piy function let me
show you what is inside
that I have to run this file
P I want to spy
on it's going to run this
file my test has passed but this is a mo
function if I call
that it should give me nothing because
it's an
[Music]
undefined what what if I call the
function SP and I'm going to call
it not an ID let's provide the
title or let's say if I call the
function
[Music]
function of this song
repository you will see the
magic I have called this function now my
function this function is pying on this
function what will
happen if I log
spy do
mock do
calls it should say I have been
called with this argument
array it's an array mo. length which
should be
[Music]
one it is saying I've been called only
one time by using this one if I call
song repository. create let's
say
title new
song now the length should be
two you can see
that if you want you can spy on the
function spy do to have been
called now my function has been
called expect
spy you can also say that to have been
called called
with called
with title should be
lower it is fine now if I say lovers it
should give me the
error you can see I got the
error you can also track the how many
times this function has called to have
been being call times it's going to give
me the
one I'm spying on this function song
repository. create similarly you can spy
on the find and the find
one you can also spy on a class I'm
going to create a new
class we
have let's say I'm going to place the
Clause here we have safe method in the
artist repository I want to spy on this
function but you can also write the
implementation just like we did it we
can have our own custom
implementation I call this
method now you can see
that to have been called times to have
been called with at the end you can also
restore the
mo but I would like to do this one after
each please restore all the mocks this
is a hook after
each it is going to run after all the
test in this section in describe
section now we're going to copy
that test case and paste it
here
we have created a new instance from the
artist
repository and I call just. spy on I
want to spy on the save function but I
also want to add my
implementation it is going to return the
create artist dto or it is going to
return you can say
that I would like to return the
object create artist dto and I want to
add the
ID now you can see that spy it is going
to call this function artist. save what
is here I called spy name and it has
returned Martin Garrick and with ID
which is one and how many times to have
been called yes expector to have been
called with name we provided the Martin
garx
spy and I don't need to do that because
we are doing it
here
expect
spym do calls. length how many times
have you been
called I think I did it one time
rt. everything is to have been
[Music]
hold with two
times also called artist. save and I
also called it
manually now it looks
good in this lesson I'm going to teach
you the concept of unit testing in
nestjs when you do unit testing you test
the individual component of your
application individual component means
individual function of a controller of a
repository of a
service we have song song service I have
attached this started kit project you
have to open it and run npm install you
got to install all the
dependencies we have uh we have this
song
controller when I'll be talking about
unit testing I mean I have to test
individually this function get song get
songs create song and update song and
delete
song but you notice the song controller
is dependent on song
service here we need more implementation
of song
service
because I want to test individually this
song controller but when we will do end
to end or integration testing when you
will test the end to end you will
integrate all of your services all of
your classes all of your
dependencies you can verify your unit of
code such as fun s methods or
classes with the help of unit test you
can find the bugs earlier you can
improve the code quality you can do
faster debugging you can refactor all
refactor code very
easily now when you run the source code
when you run the test for song control
dopc file nestjs already created this
spec file for us if you run that it is
going to say hey when I look at the song
controller I saw dependency There song
service but when you are creating the
testing module here we are creating the
testing module on the Fly n sjs will
compile it when it will comp compile it
will instantiate all the dependencies
for the testing module here it is saying
I'm depending I'm dependent on song
service but you are not providing any
song service here you not providing any
provider let's
say you are not any provider song
service so it will give me the
error because we are doing unit testing
I don't want to include song service
here I want to test individually these
components but I'll teach you how to
fake how to create the fake
implementation of song service here we
are getting the controller from this
module and it should be defined this is
the first test NP you can run the test
they have created the script for testing
I'm going to use this one npm run
test watch
let me provide the pattern for song
controller
dopc now it is going to watch this spec
file you can see that test has failed
now
here have you included song service in
the
provider
no we no we did
not if I will add the song
service but still getting the error now
the song service is dependent on the
song
repository but we will include all these
dependencies in integration testing but
I want to test the individual components
so get rid of the song
service I got the error so we need a
fake implementation we got to create the
mo service for the
song Here is how you can
register a mock service with the help of
Mo
implementation you have to register the
song service and you going to provide
the song service
provider here you have to use the use
value property to create the fake
implementation object or the
service you will have the get songs
method inside the song service here I
created the mo function and it is going
to return the promise with this
record let's try to check it
out when I will open the song service
we H we will have these methods get song
is returning a promise get song is also
you have to write the fake
implementation or Mo implementation of
the song
service we
need
providers song
service
song
service here we have to write the fake
implementation get
songs you can create a mock
function all you need to do is return a
promise with a value let's
say ID is
[Music]
one title
title let me check the song
model or song entity we have one
property which
is
title dancing
feed now I
have the mock implementation of get
songs now you can write the test
case make sure you get the
service if you need I think I don't need
that you can see that now my test has
past now I'm going to write another test
case it
should it should fetch all the
songs
or you can wrap your code inside the
describe fetch all the
songs here I have to write this one or
you can say if you need to write
multiple test
cases for get songs functionality you
have to do it in this
block
now we have to call the
function
songs v
controller. get
songs it's going to call this method get
songs you have to use the async
keyword
now we have to write the
matcher it is going to give me the array
of the songs to
equal now we're going to copy this
one a test has passed now get
song should fetch all the
songs
now I'm going to
copy all of the code for mock
implementation for the methods of
controllers it should add the create
song dto it should have the update song
dto what we have done so far I created
the mo
function with Mo implementation remember
it is get it is getting the idea is an
argument now it's going to return the
promise here for the create song it is
accepting the create song
dto I create the ID which is a unique
key and I have separate the separate the
create Song D it's returning a promise
similarly we have done for the update
song we created the mock function with
an argument update song dto returning
the
promise in song service for the update
it is returning the update result so
make sure you have this affected one and
delete song what is an
error oh I have to restart
the
project
now we have a fake implementation of
delete
song now let's test this
[Music]
function get song by ID I'm going to
copy
that get song by
ID you can provide an ID which should be
anything get song Yes ID could be
anything or I I can provide
a unique
key a uu
ID you can see the test has pass now for
get song
ID now I'm going to copy the create song
Let's test
it we have created the new new song by
using Create song
dto we have to provide this create song
dto and song. title should be run away
because we are giving this argument here
create function is giving me the create
song dto with
ID or you can also write
another matcher to
equal ID should be a uu ID
ID and
title should
be
Runway run
away you can see that my test has passed
now similarly we have to do the same
thing for update
song we are creating the update song
dtoo by using the update song dto object
I would like to update the
title it should be defined and affected
should be
one update
song
you can see update song has passed
now now we have to
perform testing for delete
song I just provided the ID you can
provide any
ID you can see that delete song has also
passed now this is how you will test
your controller unit testing for
controller in this lesson we're going to
test our service we're going to write
unit test for
service when you run this service you
will get the same error because in this
song service we have a one dependency
which is repository the song Repository
we have these so repository will
have this we have to write the mo
implementation for find method find one
or fail save method and create method
update and the delete because our
service is using these methods from the
song repository so if you write the if
you run the test for song service. speec
you will get the same issue this is the
default implementation from nestjs
Project they are using the provider
right now we don't need any controller
here we are doing unit testing we are
doing individual testing for each
function let's run the song
service it is going to find the song
service. spc. TS
file the test has failed
now it is dependent on the song
repository but I did not provide here I
did not register it so we have to create
the fake or Mo implementation for song
Repository
what I'm going to do I'm going to copy
this code we
need
these get
repository and get
song I have created a two objects song
array song one song song and the song
array this is how you will create the mo
implementation for the repository we
have to get the repository
token here I can do
that one thing make sure you provide the
song service
I forgot to do that in the controller
Let's test
it so everything is working fine now now
we're going to test the
service we have to import it get
repository
token I'm telling to nestjs this is my
fake or Mo implementation for the
repository song
service for the find it is going to
return the array we use promise. resolve
Mo
implementation for the just I'm getting
the options as a find one options you
can import it from the type orm we also
need to
import create song
dto it is returning a promise with one
song it is going to return the promise
with a song newly created song and save
method is just a simple Mo function it's
not doing
anything in update we need to get update
song
dto we have return the mo
implementation and it is returning a
promise with one
song for the delete it is returning a
promise with
affected but maybe for the update you
can give this response affected
one now we have to test
it if you need a repo you can get the
repo yes we may need a repo I can get
the repository by using get repository
token let's
test the method from the song
service it should give me this song by
ID we're going to test this method this
[Music]
one this
one get song by ID this
one it is using find one or fail and is
using fetching the song on the based on
ID so what I have I have done I created
a new
song I I got the song on the based on ID
it should be Yu
ID Yu
ID so I'm going to spy on this find one
or fail
what I have
done I called this method get song in
under the
hood this Pi this method this Pi just Pi
will be spy on find one or fail it is
saying hey you have called find one or
fail from the original repository
method and it has been called with this
one this is how you can write the unit
test
now we're going to write the test
case to create song I created this
song and I'm going to expect it with one
song called one
time and you can say called with title
lover let's copy the
update let's copy the
delete everything is passed
now for update I think inside the song
service what we have done update
result so we have to fix
it more repository it should give me the
affected and the
one
result
result do affected equals
to
affected
one test has passed now if you want to
spy on delete method how many times I
have call delete method if you want to
track the calls you can spy on that by
using the Spy repository on delete
method I've have been called this one
time and it is affected one time I got
the it means affected means one record
has deleted
successfully and it has been called with
uid that's all for unit testing with
service
now you're going to learn the concept of
end to end testing we're going to do end
to end testing for our nextjs project
end to end testing is a software testing
methodology that focus on testing the
entire application flow from start to
finish now we're going to integrate all
the song controller repository song
service
everything you can do
API testing in end to endend
testing validation of the user flow
improved user
experience now we're going to start
doing the end to end testing first step
we have to add the script in our
package.json
file they have written the script for
end to endend testing but they did not
add add the
watch that's why I just addit the watch
or detect open handle
I I have written this line or keyword
for to handle the
errors if you will not at this line This
one this
word it will give you some type of
warning
messages the first step we have to
register it the type or a
module in the song and to end test here
we have the end to end
test this
one this is the end to endend test for
our generic application let's run
it npm run
test find the
script test E2
e and the watch
mode
let's provide the pattern
app it is going to run this spec file
this is end to endend testing for app
module going to create nests application
and initialize it here it is going to
test our root
URL under the hood they are using the
Super
Test request from the Super Test making
the API request by using calling the
server this is the end point and it is
expecting the 200 status
code test has
failed got expected 200 but got 4
44 but I would like to add the test
case into to end testing for our song
controller for song
module
let's create a new
file here inside the test I'm going to
name it to
songs I can call it
songs do E2
do- spec. DS file
it is just an initial code you can copy
that from the app do e2e
testing I got this
one describe it should be
songs import couple of
dependencies type or module
make sure you have created the database
for testing I created that with the test
F and syn synchronize set to true you
have to register entity manually it will
not work with regular
expression at the end of each or at the
end of all test when all the test will
be finished it is going to drop the
schema we will have the song Mar
is not getting the path I think
so we have to do in This
Way song Find song
entity same thing
here
there
is I got the testing
modu that's
it now we have to run
it here you have to provide
your
username
password and the Local Host Post Port in
the name of your
TP it is going to run this
file I got the error you your test Suite
must contain at least one test all right
now we're going to test the
code first
step after each test we have to clear
the repository because we're going to
interact with
database in the
describe this will be run before all and
we will have after each we have to clear
everything from the song table or song
repository this clear method will delete
the records from the table but it will
keep the schema schema
this function or this hook will run
after every
test make sure you import the super
test I'm going to write the test case
for
delete or not not a delete for
create
I just created a new method create song
we have the song song. title song.
repository and it is going to save the
song in the real database right now we
don't have more implementation for the
song repository or the song service it
is going to save the record in our real
database we are using the test
def if you don't have test def you can
create it
I have set the title get the repository
instance from the app.get and called the
safe
method maybe you need to
add a weight
expression because we are returning a
song
with
promise you can do in this
way it will automatically get this
promise with
song let's write the test
case before fetching these songs make
sure you have the record in the database
that is why that is why I created a new
song with create song first you got to
save the song in the in the postest
database with title
animals and then you have to send the
API request to this URL
doget and here I'm checking the status
code should be 200 and the request body
or the results body should have length
one which should be have one record it
is an array it is going to give me the
array in results. party and I'm I have
created a one song
so it should be there there should be
one song in our database so that's why I
converted into an
array after then when this test will be
completed it is going to call this
method clear the
repository you can see our test has
passed now if I write let's say 20 1 or
maybe 400 it is going to give me the
error hey I'm expecting
200 you can see I got the
error so get song endpoints has tested
successfully
now we're going to get test get song by
ID first we have to create a new song
then I have to I have to send the API
request make sure you have to send the
ID I created this song because after
each test it is going to clear the
repository it is going to delete all the
records from the songs
table create a
song then it's going to you have to
provide the ID first I have created the
song then we have to test it make sure
the body should equal to this
song I'm going to save the
application it should
pass two test has passed
now now we're going to test update songs
endpoint make sure you have to import
it it should be
it create a new
song and you have update song dto I
would like to update the animals to
wonderful sending the API
request this is how you will send the
data to if you want to send the Json op
object into the request body you can
call the send method I want to send it
as a update song
dto this one I want to update the title
which is wonderful status code should be
200 and affected should be one it means
our record has updated
successfully and
let's do this for
post
we have this is our create song dto we
did not
create we did not create the song right
now I'm going to use the create song dto
provide it as a request
body the status code should be 2011 and
the title should be
animals for test has passed now we have
to test the delete song
endpoint let's create the song first and
then we have to provide the ID which
record you want to
delete status should be
200 and the affected body should be
affected should be one it means record
has deleted
successfully this is how you will write
the end to endend or integration testing
with database or the nestjs
application nestjs version 10 has
released
now I'm going to show you how to create
new projects with nestjs version 10
version 10 is very fast they have
integrated the rest rust compiler they
have integrate the rest to compile the
source code
sjs if you Google the version 10 you
will find the blog post from the owner
of the
nestjs they have
released version 10 in the version
10 you you can compile the code in a
faster way like it will also improve the
hot
reloading you
can you can do development in the more
fast
way to start a project you have to add
this
command we we're going to use this
[Music]
options this one we will add these
options into Nest
CLI they have also introduced a new
feature this time you can Mo the entire
module instead of provider and
controller
these are all the new features in the
nestjs version 10 but the main feature
is improving the compile code speed of
the
compiler but let's create a new project
first of all you have
to
remove or uninstall nest
jli because you will have have the older
version of n
CLI I'm using Mac so we need to add the
sudo keyword instead of install first we
need to
uninstall the
nli I have already installed
nli can I check the version of this
package I don't know let's try to look
at that
I have
8.1.0 I have I have the latest version
but it will generate the nestjs 10
project Nest
new and we have to provide the name of
our project I can
say web
socket
implementation
nextest let's do it again nextest new
the name of the project
websocket
implementation I would like to use the
npm
it will take some time to install these
dependencies my project has
created I can look at by going to this
directory I would like to open this
project into my vs code
editor if you check the package. jsn
file you can see we have the nest
version
10 now what I have to
what I have to
do we have to compile the code
faster let's first we have to run the
project without this command This
One S swc Speedy web compiler first we
have to run it
without Speedy web
compiler
you can look at the time for running the
project when you will have multiple
modules you will have multiple
controllers and you added the testing
functionality your application speed
time will be slower your development
time will will be
slow so let's make it
faster with the help
of these two options I want you to add
these
options into package into
nli n c.
Json I'm going to add these two options
to my
compiler these two
options Builder I would like to use the
S swc and type
check let's run the
project you can see that I got the issue
fail to load fail to load s swc CLI and
S swc core we got to install these two
packages let me execute this
[Music]
command install it as a def dependency
because I want to improve the project
running
time increase the
development
time
so packages have
installed now we need to run the
project now it can take the S
swc it can use this Builder and type
check our project is running
the project running time has increased
now if I save something in our
application let's
say in the app
controller in the app
[Music]
service
hello world from nestjs version 10 I
want to save the
application successfully
compiled this is how this is how you can
improve this implement or in improve the
development time the project running
time in development
environment in this module we're going
to work with web
sockets when you want to implement real
to real time application like chat web
application real time web
analytics live streaming online gaming
then you need web
socket which we have worked with HTTP
server in
HTTP where client sends the request in
the server
response but if you if you're using web
sockets web sockets establish a
persistent connection between client and
the
server and you can have ongoing
communication the best example is
Facebook Messenger you send a message to
your friend and your friend rep replies
and you reply to your friend and your
friend reply this is how the bir
directional communication Works in under
the hood they have implemented the
websocket protocol they are using the
websocket
technology if you need to make
persistant connection then you need
websocket you want to implement a
realtime feature like live updates live
score live streaming then you need
websocket
here is chat application can be built
with web socket collaborative editing
tools real time analytics online gaming
and the live streaming nestjs also
provides websocket module you can use
that but it also provide two approaches
you want to do you want to work with
socket iio or you want to use the web
socket you can get the details from
their official
documentation but in this video I'm
going to implement the socket
IO you got to install these two
packages I'm going to open my
package.json file let me add my
dependencies I think I already installed
these two dependencies I don't need to
do it again you can do it manually by
running npm install and first install
this
dependency and then you have have to
install these
dependencies our next step is to create
the events module we will have the
Gateway a Gateway will be responsible
for handling the events you will have
the events module a Gateway is nothing
more it's a class with provider you can
inject it as a
provider here we we need this Gateway
we're going to create the event Gateway
it's nothing more it's a class
here you have to decorate with websocket
Gateway I'm allowing any origin you can
use any specific origin if you
want here I'm trying to implement the
own module in
it when any client connected to my
application this event will be
triggered this is how you will register
the event by using the own own
function I can also get the socket ID I
can also log that have has it connected
or
not this is how you will create or
register a new event subscribe message
and we will have a function new message
you will have the message body you will
get the
data if someone sends message or filed
an event from the client side
application like react angular view or
any kind of front- end
application this function will be called
but make sure they have called this
event with message key this key and it
is going to lock the data you can read
this text here for every
detail let's create events
module
we have created the events module now
let's create the
Gateway you can see we have the events
module Gateway will be registered as a
provider you can see in the events
module we have websocket Gateway by
using this decorator and we have one
event if you want you can add the
CES and we also need to establish a
connection I need to check make sure you
imported server from socket IO
Library you have to import it manually
otherwise it will not
work websocket G websocket
server now we have this handle
message subscribe
message when you need to register an
event in backend application or the
nestjs application you will use the
Subscribe message
decorator
and what I would like to do I want to
get the data or you can have client but
I like the data I don't have any payload
option but I'll use the message body
decorator instead of use this one
message
body data should be type
any I'm not going to return any thing
right now all I want to log the
message I can say message received from
the
client and this is my
message or I can log the
data so far we have registered the event
when any web application like any
front-end application has connected to
our websocket server
first they need to connect on the our
host here we have provided but right now
we're going to run the project on Local
Host so any front end application should
connect with Local Host colon 3000 and
then he can establish a connection
between with with this application when
when any front end application establish
the connection it's going to call the
own module in it but right now I don't
have any own module in it right now it
will log
this
message
implements on module in it that's it
after module loaded or this file is this
class is loaded successfully then we can
log the
message when connection established this
event will be triggered and it is going
to call with socket I ID and the
connected its Boolean
value now we have set of the websocket
server and we created our first event
which is message you can have multiple
events here you can also perform the DB
operation like if someone sends a
message you can save the message into
database in the next video in the next
lesson we're going to consume this event
from our frontend application we will
have a simple basic front end
application with index.html and there
would be JavaScript in the index.html
file now it's time to consume the
application consume the event or send
message from the frontend application
when you run your server let's say npm
Run start
def now my server is it's ready to
listen this message event it's waiting
for someone to send a message by using
this event
key so all you need to do you got to
create a
basic
index.html file you can copy that code
or you can create manually I can say
client here I will have
index.html file one more thing you will
see events Gateway subscribed to the
message event to this
message so it means we successfully
created the event I'm going to copy the
code I'm using the socket IO Library
where we are creating the socket IO
instance by providing our application
path in our case we have nest's
application is running on Port
3000 we have registered a event
it's trying to connect with our
application with nestjs application when
it when it will be connected it is going
to log this message and emit this
message to the server here I'm going to
open the
server this one events
Gateway we have registered the message
event this is how you can emit the event
I'm telling to socket IO please call
this function that's it and we also
registered couple of events if someone
if if server sends data back to the
client we have to register it we have to
catch the data here that's why I use the
on
listener if exception event trigger it
is going to call this method if if our
backend application disconnected or
stopped it is going to call this event
it is going to trigger this event now we
right now we're not returning anything
here let's try to test
it uh I'm going to use open Live server
go live when you open the index.html you
will
see this it is going to open my project
into live server please check the
console for message
reply inside the console you will
see you have connected
successfully when you open your backend
application this message is received
from the
client so client has sent this message
or you can
say I am the
client I'm going to reload the
application it has automatically reload
reloaded you can see I'm the client
so it has also connected one more thing
you will also see this socket ID and it
has it means connected successfully
first it is going to log this message
console. ID Lo connected we have emitted
this message event it's going to call
this
function now we we are not returning
anything that's why this event is not
triggered let's try to return from
return something I'm going to return
some value let's
say some value from server let's see
what will
happen our application
reloaded let's try to test it out
message received from the
client but I did not log what message
have you received
you can see message received from the
client on the client side we sent this
message I'm the client it has
received but it is not triggering this
event I cannot see anything here let's
say if I if I'll try to log
something
hello I cannot see this Hello message in
my
console it's not
triggering so that is why you need
observable websocket also provides the
observable you can
say I would like to return this
observable
websocket response and I can have any
type here we have
to convert the object to observable
that's why I'm going to use the off
operator from
rxjs I can say
event you got to provide the name of the
event which is message and the
data here you can return anything from
the server
message
returned from
server
hello you should see this message here
because we are listening on the client
side you can see event message received
from the server if I will refresh our
application you will
see this
one message returned from the server
hello if I stopped my application it is
going to F this or trigger this
disconnect event you should see the
disconnected this is how you will create
wi directional or realtime chat
application with web
socket in this lesson I'm going to teach
you how to set up graphql server we're
going to use Apollo server nestjs Apollo
package nestjs graphql package graphql
and TS
Mor you can read the documentation of
these
packages I'm assuming you must know the
basics of graph ql I'm not going to
teach you the basics of graphql what is
graphql and why do we need graph Q
I have attached a started kit project
you have to open it and run npm
install I have already I have already
installed all these dependencies I don't
need to install them
again all I need to do is to install
graphql packages I'm going to copy all
of these
packages
the packages have installed
successfully and now the next step we
have to register the graphql
module I'm going to open my app
module and we I would like to import
graph module
here we need to import couple of
dependencies Apollo driver config
I'm telling graphql hey I want to use
Apollo
driver and I will have do graphql
file where I will place all my schema
definitions in the graphql
file this file will have the typescript
typings of
graphql and output as a class don't
worry I'll Teach You How can you
generate the typings
we are using for RO to register the
graphql
module the Apollo driver config specify
the type of the configuration options
being
provided so driver AP poo driver this
property sets the driver used by the
graphql module in this case we are
telling graph Nest chairs hey I want to
use a polo
driver
we will place all of our graphql schema
in graphql file the extension should be
do
graphql uh if you want to generate
typescript definition from your graphql
schema you have to specify these
definitions I'll teach you how to do
that and we are just combining the
path we will have so graph. TS file
inside the source
directory this property specified that
the generated type script definition
should be outputed as a class this means
that the generated code will be
representing represent the types as
typescript
classes now our next step is to create a
schema
file
inside the song folder I'm going to
create a new file song.
graphql here I will place all of my
schema file we're going to have a
query let's define a song
type we will have ID and the type of ID
is required this means it is a required
property it should not be
null and I'm going to add a string
variable or string type field which is
title the type of the title is string
and I'm also going to add a new query
type here I can say I want to fetch all
the
songs and you can say the type should be
song and it is going to return all the
songs our next step is to generate the
typings which is typescript definition
file
we need a graphql definition
Factory
class here we are trying to in we are
instantiating or creating a new object
from graph definition Factory there is a
generate method to generate the typing
you have to specify the type which is
I'm using the regular expression here I
will have all of my schema file in the
cql that's why I use the type definition
path and I would like to I would like to
create all the type typescript
definition in the graphql dots file it
will save it as a class let's create a
new
file generate typings dots file inside
the root
directory typings
dots
now all you need to do is to execute
this
command NPS npx DS node generate
typings it is going to generate the
graphql dots file with this
definition you can see that a graphql
dots file has
created we have a class which is song
and we have a abstract type which is I
query and we have this
type so we will use this type definition
when we will creating disolver functions
when we will resolve queries against
your schema
files now I would like to run the
application is everything fine now let's
test it
my application is running
now let's send the request to Local Host
colon
3000 and you will have playground at
this graph quel
Endo when you go to the Local Host colon
3000 you will see the playground this is
how you will perform
graphql apis you will test graphql apis
by using this
playground let's
say I'm going to send the API request
graphical API request I want to fetch
all the songs I want to see the ID and
the title but it is going to give me the
error hey you don't you are not
resolving this
query because it's returning
n it's getting the validation eror
because we don't have any resolver to
resolve this query this
one in the next video I'll teach you how
to create mutations and how to create
queries we're going to we're going to
fill our song
schema let's complete our
schema let's create a new
query to fetch a single
song when you try to fetch a single song
you must need to provide the ID so ID
should not be
null and it should return this
song in the
response let's write a new
query it should give me the
song and I would like to fetch the the
song on the based on
id id should not be
null now we're going to write uh venue
query in the playground you got to
follow the structure song and you have
to provide the ID in this case I'm
providing the 1 2 3 as an
ID now we're going to Define mutations
we learned how to fetch data with the
help of query but I want to write the
data so to to mutate the data you need a
mutation so let's define an mut
mutation
mutation I'm going to have create
song it will accept the create song
input
or create song
input and I don't have any type so
that's why I'm going to define the
input create song
input I will have the title field and
the type should be string it should not
be null so I can say the type of create
song
input it should be create song input and
it should not be null and it should give
me the song in the
response
now I want to write the mutation for
delete song or you can say update
song I would like to update the song
Only the based on ID the first argument
it should be ID and the update song
input we will have update song
input it should give me the update
result this is not an empty
field that's why I use this exclamation
mark and
input
update song
input title should be string but I did
not mention it to required property if
you will have multiple song multiple
fields in song let's say a user will
have let's say a song can have
date or you can
say date release date or publish date or
artist something like that but I cannot
set date required in the artist required
field because it depends on the user a
user can update the title or whatever he
wants to upate
update now I don't have any type for
update
result let's define a new type update
result it will have
affected and type should be
number do we have int yes
int similarly we will have a type for
delete
result delete
result and typ should be int now we're
going to Define mutation for delete
song I can delete on the based on
ID here I can say delete
song I don't need to put anything and it
should give me the delete result that's
it so we did not resolve these queries
in mutations in the next video we're
going to write resolver functions to
resolve these query and mutations Let's
test it out by generating the
type one more thing I want to show you
can create a script to run the typings I
can say in the package.json
file let's define a new
script we here you need to define the
script generate slash colon typings TS
node generate typings this njs project
all already installed TS node as a def
dependency you don't need to install it
again npm
run I can say generate
typings it will generate the typings or
types in the graphql dots
file
I found an
error unknown type create song input did
you mean create song input or update
song
input oops I have to fix
that everything is fine now let me see
my graphql dots file we have type for
create song input type for update song
input we have types for mutations and
update result and delete
result when you see your
playground you have to look at the
queries in mutations we have queries and
mutation when you try to
fetch let's say I want a query for
songs ID let's say I'm going to provide
invalid
ID let's try to fetch the title and the
ID I'm going to send the request it
should give me the error hey you are not
resolving that's why we need resolver I
can use n CLI to generate a new resolver
I can say
song it's going to create a new resolver
resolver is nothing more it's a provider
like a service you can inject it as a
dependency here you can see
that inside the providers we have a song
resolver and it is it also created the
song resolver dopc file and song
resolver we have resolver
Tator now I'm going to resolve these
queries I'm going to open song do
graphql let's resolve this
query I also need song
service so Constructor
private song service song
service let's import
it
I have this I need a query
decorator here I would like to resolve
this query
songs I can say get
[Music]
songs return this
do song service dot get songs
and you can also mention your return
type I can get it from the song entity
or song graphql type this
one make sure you are using the Asing
here what is saying unable to resolve
the signature of method decorator when
called as an
expression
oh we need to get the query from nestjs
Craft
ql now it looks
good let's try to test it
out let's try to resolve this query
I would like to fetch all the
songs you can see
that we have a song I already created a
song If you don't want to see the title
you can say I only want to see the
ID but I have single song in my
database now let's resolve the query to
fetch a sing single song I Can Say
song
async Get
song it should give me the song with
promise this do song service
dot get
song you need to provide the ID but I
can get the ID
here
I can use the arcs from the N graphql I
can say the
id id is
string let's provide the ID
here I have saved my
application let's try to resolve this
query I want to copy this
ID and let's fetch a
song ID should be this one and I'm
expecting the title in the response fail
to fetch please check your connection I
think my application did not start it
now I have to send the request I got my
record which is song on the based on ID
if I provide the invalid ID let's
say you will see the error invalid input
Syntax for the type
the ID does not exist as same
here now I'm going to provide the
correct ID I got the
record you have learned how to resolve
queries in the next video I'll teach you
how to resolve
mutations now you're going to learn how
to resolve mutations in the previous
video we resolved our queries let's
resolve
these mutations create song update song
and delete
song now you need mutation instead of
query we also need create song dto as An
arcs or you can say create song
input you can also do that you can also
get this typing from from graphql
file and I just called this
function it's not finding source. cql we
have to do it
manually now it looks
good
it is taking some time to in restart the
server let's create a new
song I'm going to write mutation create
song create song input we have to
provide
title the name of the song which is
follow me
I want to see ID and title in the
response you can see a new song has
created I can fetch all the songs and
you can see follow
me it means we successfully created this
we have successfully resolved this
create song
mutation now it's time to resolve update
song
mutation I'm going to copy this
[Music]
one update song we need to Res solve we
need to get update song
input update song
dto or you can use update song input
from graphql file I also need to get
update result from
graphql it is
saying I'm getting the
error
update
song If I get this
from from typ orm let's see what will
happen now it looks
good because this start update
song it's returning the update result
from type
orm when you look at the update song you
will see the Promise with update result
I imported update result from
typm let's try to update the
song I'm going to write
mutation update song we need the
ID I'm going to copy this
ID let's place it
here and we we also need to provide
update song
input I would like to update the title
update
song Let's fetch all the songs and you
can see the updated
song similarly we need delete mutation
let's resolve it I'm going to copy it
here delete song we have to get it from
the type orm
let's try to delete this song
mutation delete
song we need to provide the ID I'm going
to copy this
ID let's see
affected delete
song successfully executed it should
delete the song
let's try to fetch the song on the based
on this
ID you will see there is no song here
you can see there is no
song in this lesson I'm going to teach
you how to handle errors in
graphql let's say I want to fetch all
the songs but instead of returning all
the songs I have to return the
error you can do simp simply by using
throwing the error or you can say let me
do this in this way I'm going to comment
this line through new
error I can say unable to fetch
songs let's try to send the graphical
request it's still
working my application did not reload
yet let's wait
now it has
reloaded you can see unable to fetch the
songs I got the error internal server
error uh if you check the Apollo
documentation we are using Apollo driver
Apollo driver is saying you can use the
graphql error class and you can provide
your own
message Apollo Apollo Apollo
documentation is saying
they also provide buil-in error codes
like Parts field graphql validation
field Pat user
input bad request we're going to use
this error bad
request all you need to do is to throw
the error and you going to provide your
message in the code so let's use the
throw the
error new graphql error
I got this graphql error class from
graphql package here you can see that
now first I have to say unable to fetch
the
songs you have to provide the options
you can provide the
code you can say server error or what
what type of message you want to use it
depends on your use
case
I can say internal server
error let's try to test it out I saved
the
application it will take some time to in
reload the
[Music]
application application has reloaded
let's send the request and I got the
error unable to f F the songs and I got
internal server error this time you can
see graphql error unable to fetch the
songs you can also see the message I got
the error at song resolver doget songs
you can also check the error
stack get song song song resolver doget
song we have the error at this function
get songs this is how you can send the
error in
graphql
if you want to use your own custom
message you can also do that you can
provide your custom message your custom
code and your custom
extension you can also set the HTTP
status if you're working with HTTP API
you can also set your HTTP status code
and some type of
headers in this module you're going to
learn how to apply authentication in
graphic
SQL we have implemented authentication
with rest
API now I would like to implement
authenticate graph cuel
apis in the previous module you learned
how to create graphel apis with
nestjs I'm going to pick the same
example project just like we did with
authentication in rest API
I have provided the starter kit code you
have to open it and run npm
install when you install all these
dependencies you can run the project and
you will get this
error let me run the
project because there is no graphql file
there is no graphql extension file
when you open the app
module you will see the graphql
setup we have a graphql module I'm
creating a graphql module by using the
Apollo driver just like we did with in
the previous module I'm using the
context I'm just returning a simple
request mapping the request into request
it's nothing more I'll teach you more
about when we will protect
resolvers so I've already taught you all
of these stuff like we created the OD
service we have a login
method here we have a JWT guard I taught
you how can you do that what type of
implementation we have done we have
passport strategy with JWT it's
validating the
user and we have dto login dto
everything
everything I have taught to
you if you don't know about all of these
functionalities you can go back to the
module number six on
authentication you can watch the first
four lessons on authentication or first
three lessons on authenticating nestjs
apis you will get the
error no definition found no type
definition word found because we don't
have any graphql file I just did the
graphql setup first of all we're going
to set up our we're going to define the
schema we don't have we don't have any
schema what I want to do I want to do
schema in O folder let's create o.
graphql what we are going to do we're
going to create the user type and we're
going to Define query
and we will have mutation for sign up
mutation and we will have login
mutation first of all let's define a
user
type the first argument is ID it should
be required not null first name the type
should be
string I can get this value from the
user entity
you can open the user entity on the
right hand side right
side first name is required last name is
also
required and email is also
required and password is also required
so we need these properties these five
properties I'm not going to play around
with playlist something like
that let's make it more simple we
defined a user
type now I'm going to define a
mutation sign
up it is going to take the signup input
and the type should be signup input we
did not create it
yet it should be required and it is
going to turn a user back in the
response or sign up
response we not we did not create this
we did not create this signup response
type now let's define a new type with
signup
input when you when you sign up we are
telling you need to provide hey client
you need to provide the first name you
need to provide the last name you need
to provide the
email email is also required password is
also
required now let's define the sign up
response sign up
response what you want to send in this
signup response you can send a simple
email it depends on you I'm going to
send a simple email
now we're going to Define
query we have a mutation let's
define login
query I can say
login it is going to take login
input inside the login
input and it is going to return a login
response we did not not have these type
yet it's are
required let's define an
input I'm going to Define input here
login
input we need
email type should be string we need
password type should be
string and we also need to Define login
resp
response I want to send the access token
you can double check it from your OD
service or user service we have a login
in the login we are just returning the
access token here you can see that
access token the type is string we're
going to follow the same convention the
type is string it should be
required we created the login mutation
that that's
it let's try to test it out by running
the mutation or running the typing
command npm run
generate
[Music]
typings it is going to generate the
typescript definition
file typescript definition file has
created you can see graphql do s
file we have all of these
typings we have created or defined our
schema in the next video I'll teach you
how to resolve queries and mutation
we're going to work on sign up mutation
first in the previous video we have
created this sign up
mutation now we need to resolve this
signup
mutation we don't have resolver inside
the O module let's create a new
resolver we have to provide the name
which is
O Au resolver has created you can check
inside the Au
module we have Au resolver we have spec
file and we have Au
resolver we have to resolve our signup
[Music]
mutation
mutation which is sign up I'm going to
open the autra ql
here I want you to do it should be sign
up
user I'm going to define a new function
and it is going to return a sign up
response you can get the
typing from graphql dots
file and one more thing we need to
inject
service user service and OD service we
need both of
them user service and we need OD
service we have a create
method let's get the argument I can use
the
arcs we need to get sign up
input and I can say sign up
input you can also also get the type
sign up
input and I'm going to provide sign up
input everything is fine now let's try
to test this signup
mutation I'm going to run my
application my application has started
and I got the
error
sign up defined in resolver but not in
the
schema oops there is a type typo Here
sign
up we have to generate the typing
again npm run generate
[Music]
typings
everything is up to
date it is taking too much time because
I'm using no nestjs Version 9 because I
built this project in module number six
by using the nestjs version 9 that is
why it's very slow
I have to oh let's restart it
again my application has
started I'm going to send request to the
Local Host callon 3000 and/
graphql if you check the docs we have a
sign up
mutation let's create a new
user first name make sure you have
database in your
postgress let's provide the last
name let's provide the
email let's provide the
password I got the
error because I did did not select any
field here I would like to select the
email because I can only access the
email I think I already created a
user with
this email let's use new
one there is an
issue reading
password
let's try to check the
error password
is
invalid
why let's try to log sign up input what
it is
getting
or do we have sign up function
here inside the OD service do no we got
to use
the user service.
create let me check in the Au controller
what we are calling what we are
using user service. create that is
it I'm getting the
undefined maybe there is an issue
in autra Q let's check it
out oh syn sying up
input my God sign up
input sync
input sign up
input let's run the project let's update
the fix it sign up input we also need to
update it here sign up
input
run the
project Let's test it out by sending the
request to create a new
user sign up input we also need to
update
that
we have created a new
user a user has created
successfully you can see that we got the
object let's log in I want you to
implement it I'm going to copy
that we need to get the
query from nestjs graphql
package we also need to get login input
and the login
response we have a typo here
aouc I need to run the typing
again
let's run the
project let's try to send the login
request I'm going to copy use email and
the
password I need to get the access
token we have successfully logged
in because I got the access
token in the next video I'll teach you
how to protect
resolver we're going to create a new
protected field which is
profile only authenticate user can
access this
profile we have created all
card this one JWT o card we have to use
this o card into our resolver I'll teach
you how to do that but I want you to
think about how can we implement or how
can we apply JWT off
card we have completed the sign up
and the login
functionality let's say I want to
protect
resolvers when we were building the rest
apis if you look at the app
controller I can say this is the
protected route only authenticated user
can access the
profile and here we also getting the
user from the request
object but you are thinking about how
can we protect the resolver let's say I
want to write a query
profile and type should be profile we
don't have any profile type let's create
the profile
type the type should be string the field
should be
string and here we have the user
ID let's generate the
typing when we resolve this
query only authenticated user can access
this
profile we should not allow anyone to
see other person or other people
profile how can you do
it when we were building the rest apis
we use the JWT
guard we have created this guard and we
apply when we applied this JWT o card on
our protected route just like we did in
the app
controller this is my protected route
the profile route and I have applied the
O card by using the use card JWT oard
maybe you thinking how can we do into
graph
well I'm telling you I'm you you also
need God you also need JWT o guard I
want you to implement it you don't need
to change anything in the JWT strategy
because we were using the passport
strategy if you are not sure if you
don't know about how did I implement the
passport
strategy you can look up the
Authentication section I think it's
section number six or module number six
or
seven and then you can get the
lesson for passport or jwd
authentication it has generated the
typings in the graphql dots we have the
profile
class now when we resolve this query I
have to say hey this is protected
route let's let me show you I'm going to
run the
project to access the protected
route a user or client should or client
must need to provide authentication
token the user can get authentication
token by executing or sending the login
request
and this login request gives the access
token in the
response let's wait for the
application my application is running
now let's send the request to the Local
Host col 3000
/ql here you can provide the
authorization HTTP
header I'm going to send the login
request I got the access
token here you can access the profile
route you have to provide the token
here we did not write the resolver for
the profile
query let's resolve
it inside the Au
resolver let's resolve Au query or
profile
query get
profile it is going to give
the
promise
with
profile and here is the
question
how can you access the profile or how
can you access the current logged in
user like we need to send current logged
in user
actually we need to send the user ID the
current logged in user
ID and his
email we are returning the
promise that is why I caught this
issue let's return new
promise and
resolve return
resolve this
object I just created the fake
promise to pass this
test oh I have written the profile in
the
mutation let's change it to
query restart the
[Music]
application now we're going to send the
request it's still
running now we're going to access the
profile I caught the profile
but only authenticated user can access
this
profile so we need to apply the O guard
how can you do it let's create a new
guard I'm going to copy that guard and
create a new guard and I'm going to say
gql
oards
here instead of JWT I can say graph o
card and now we need to do a little bit
logic we need to use the can activate
function because in graph ql we need to
get the execution
context and we need handle request it is
going to
return a
user and you can import authentication
error when you look when you look at app
module you will see this
request I'm just mapping
the request from req request here I got
the request from the context here you
can see
that and I call the super Constructor by
calling this execution context
host because in graphel you need to get
the request object from the
context when you have if you have worked
with graphql before each resolver will
have four argument
here you will have for
argument
parent I think
root context value and info you can get
the documentation from
Apollo server
resolver here you can see
each resolver has four arguments parent
ARS context value and
info ARS you can see
ARs and I'm going to log
everything
parent console. log ARS
console. log context
value and we also need to log the info
let's see what is inside this this stuff
but make sure you apply the
guard use guards I can say graphql or
guard now this route this resolver is
protected it is secure
now don't worry I'll teach you
everything what is going on
here let's send the
request
here you can see the log
console there are a lot of stuff
here parent is undefined there is no
parent for this query ARS is an object
but is but there is nothing inside the
ARs there's a context value this is
there is the request
object and inside the request object you
can find your
user here is the user I found the
user this is
the this is the
user this is the this object is current
logged in user
if you look at the jwd passport
strategy here we are
saving user ID and the
email that's why I got the user ID and
email what I can
say I can only
return context
value do request.
user
I don't need to use the promise
here it's just returning a simple
profile I'm going to send the request
this time I got the original user ID and
the email let's sign up up a new
user I'm going to create a new
user
Linda let's save the
email now I got the user we have
successfully sign up let's log
in I got the access
token now I can use this access token
here I want to access the profile of
this route or user wants to see this his
profile I got this
user now let's debug the application I'm
going to put couple of break points here
what is going on here let's look
at I have already set up the VS code
folder inside you have launch. Json file
if you don't know how to debug the
application let me teach you I've
already taught you there is a script in
the package. s file for the debug the
application you can
say npm
start please start the project in debug
mode my application is running in the
debug
mode
now I can start the debugging by
pressing on this attach
button I've put couple of break points
here now it has
started I can debug my applic
a I can also put breako
here or
here now we're going to send the
request it has stopped at this o
card and first of all it is going to run
the can activate function we are using
getting the graphql
context by calling the
create and here I got the context
object and inside the context you can
see we have the Handler function we have
the
ARs ARS
property the first one is object and we
have a request we have this request and
we have field name which is
graphql field which is
profile you you can see the field
noes this is how graph run under the
H this is my string or the query graph
request and here is the name something
like that profile which is
profile let's step over the code you
will see the
context inside the context we have OD
context type
graphql now I'm extracting the request
object by calling the get
context so I got the
request inside the
request you can see
that this is the request we have this
endpoint SLG graph
ql this is the body we have the
query and we have the
variables let's jump to the next break
point there is no
error and there is a user you can see
that and it is going to return the
user now you can access the user
inside the
context parent is null which is
undefined we don't have anything in the
ARs now you have the context value you
can also do debugging here context value
dot request.
user you can see I got the
user and we have the info
info is related to information related
to query if you need to access the path
parent type field name something like
that
schema then you can use the info
validation error we have directives
include skip
deicated query type graphical object
type we have the fields login
profile all this information related to
graphql schema and the query inside the
info
object now we are going to just return
the current logged in
user that's how the authentication Works
under the hood in
graphql if you need to implement
realtime application you have to build a
realtime functionality like chat
application or notification type
application
then you use graphql subscription if you
have worked with API rest
apis we used websocket and socket iio
for realtime
application but we are building graph
apis if you need realtime functionality
then you need graphql
subscription I'm going to build or
Implement graphql subscriptions with
nestjs Pro project first of all you have
to install dependency graphql
subscriptions and then we will install
the subscription
Handler just like query and mutation you
need to define a new type
subscription I have created this song
created field it means when a new song
is published to Spotify
application this Spotify application
will send the notification to all users
we want to implement this
feature when you define the type
subscription we defined it
here you have to write the resolver to
resolve this field we need a pops up
module from graphql subscriptions the
package we have installed
earlier here it is going to listen
for song created event this
resolver is listen for song created
event here we are resolving this field
song
created when you run the application you
should go to the Local Host colon 3000
/g
graphql I'm going to run the
subscription song created we have ID
title I have started the subscription
you will see the subscription is
listening it's in the listening mode our
next step is to publish this
event when we will publish the event you
have to send the payload which is a new
song and I have created a new song Here
we are publishing an
event
here it is going
to now the subscription is already
running here you can see and now it can
receive it has received a new
song if you want implement this
subscription you can do
it otherwise you can follow me I'm going
to implement it you have to install
package graphql
subscription and we have to install the
Handler in the app
module install subscription Handler
let's define a new type subscription in
the song
graphql I'm going to Define It Here song
created it is going to return a new
song now we need to resolve it
resolve the song created field inside
the song
resolver we need to import psup at the
top of our
resolver you can import it from graphql
subscriptions
package now we're going to resolve this
subscription song
created I can do it here at the
bottom we need to get
subscription from nestjs graphql
package let's try to import manually
from cql
subscriptions we need pups
up
let me run the application and then I
will be able to start the subscription
in the listening mode the pups sub Asing
iterator we are telling to pups sub
module or the ppup module is saying I'm
listening for the song created event
with this label this is an event I'm
listening for an event with this label
song
created my application is running
now let's run the
subscription when you check the docs you
will see subscription with song
created I'm going to start the
subscription song created when a new
song will be published it is going to
give me this record the song object now
it is in the listening
mode
when we will
create a new
song it means when artist in real world
Spotify application has published a new
song Spotify application will send the
notification of this song to all
users new song I can say new
song
I need to get ID and the
title a new song has created but I
cannot see anything here because we did
not publish the event when we will
create when we will be creating a new
song Here we have to
publish this event this one song creat
event so you can do it as well I'm going
to copy my
code and let's do it
here this is how you
can sent message to the event by using
the song created label and we have
provided the payload make sure you use
the song
created Property name otherwise it will
not not
work let's create a new
song I have created a new song and it is
saying I cannot could not connect to
websocket
endpoint please check if the endpoint
URL is
correct now it's in the listening mode
mod created a new song now I have got a
new
song because we are publishing a new
song and it has received it
here let's say I can say new the name of
the
song you can choose any
name I have created a new song or artist
has published a new song at Spotify web
application now the Spotify application
has has sent the notification to all
users who are subscribing to song
created
event that's it the concept of
subscription in this module you're going
to learn how to test graph
apis we have already tested our rest
apis we're going to use the same logic
to test graphql
apis we're going to do Mocking the same
way just we did in the previous
module when you see song resolver dopc
file you will see this default
code when you run the test by using this
command npm run test you will get this
error hey you are using a song resolver
but your song resolver is dependent on
song
service you have to import it but we are
doing unit testing so when you are doing
unit testing you have to test individual
parts of your code you have to test
individual
functions if this function is depend
dependent on some other functions or
some other dependency or some other
classes or some other services you will
create a Moog implementation of the
dependency I've already taught you the
Moog implementation when we will when we
will be testing song
controller this is how you will create
the mo implementation of song
service you we will have have these
methods inside the song
service in get song create song we are
just creating the mo
implementation I just copied this code
from the song Ser song controller song
controller spec file and I have updated
the create song dto to create song input
and update song dto to update song
input and then you will test your
functions
if you want to test your get fet song
Get song function inside the song
resolver you can do
that I'm applying the await expression
on get song and I got the song here I'm
doing
expectation checking asserting or
expecting value it will pass this is how
you will test create
song create song will be passed update
song and the delete
song Let's execute it or you want to
execute by yourself I want you to do
it let's select the song
resolver it's going to run the song
resolver dopc
file
you can see the
error hey your resolver is dependent on
the song service but you did not import
the song service let's fix it by mocking
the
service I'm going to copy the same
code
and paste paste it
here we don't have song service let's
import
it
it's not giving me the suggestion I have
to import
manually I got the song service we also
need to get the create song input and
update song
input
I think it will not get this path Source
do/ graphql
let's add the complete
path you can see our test has passed
now
now we're going to write the test unit
test for a song's
query it should fetch a song first of
all I need to apply a weight expression
on get songs it is going to give
me this song because we are using our Mo
implementation inside the get songs it
is going to return this object or this
array with a promise here we are just
resolving
it unable to fetch songs I got the
error let me check my song resolver what
is inside the song
resolver I think I'm throwing the error
that's why I got this error let's
comment this code and I would like to
return this song
service with get songs array it is going
to give me the array of the songs we are
just
using this get song method
but we are using this
implementation this one it will call the
get songs but it is it will use our own
implementation this
one this is how you can fix the bugs
with the help of unit
testing
our test has
passed now we need to test a single song
query we have created this
song actually we need to yeah we need to
test this one we need to create test
create new song
resolver we're just creating a new song
and we are expecting
it because create song will give me the
ID and whatever we
passed
here the object it is going to return
the same object
here
the test has passed now we need to test
update and
delete it is giving me the error update
song a unique
ID we are not expecting the ID in the
update
song there is an issue I
think it is going to give me the
ID
let's look at the update song
[Music]
resolver song
resolver let's look at the update
song update
song
I think I have to change the order first
I need to get the ID I need to place the
ID and then I need to get the update
song input you have to rearrange the
order now it should
work
let me look at the song
service ID it's giving you are not using
the update song
tto title
but let's restart the application
the error is gone
now everything is fine our update test
has passed and our delet delete the song
test has also
passed it is returning the affected
that's why I use the affected
here in the next video I'll teach you
how to do end to end
testing graphql
apis this lesson I'm going to teach you
how to do end to endend testing with
graphql apis in the previous lecture we
tested unit tested we tested the
individual function of resolver now
we're going to do integration or end to
endend testing we're going to test
exactly the API by sending the HTTP
request or queries from the HTTP
module this is how you will test the
songs
query and it is going to give me the
result I'm using the
request request package to send the HTTP
request if you are working with graphql
there is only single endpoint which is/
graphql it will be same for each query
and
mutation now I'm trying to fetch all the
songs and I got all the songs this is
how you will test the end to end testing
I already taught you how to set up the
end to end testing
file when we were building when we were
testing the rest API in the previous
previous
module so
before each we're going to create
testing module this is a
same before
all we're going to
create new database I have the test
database it will drop after completed
all the
test and after each we're going to
delete everything after each test we're
going to delete everything from the
songs table that's why I'm using the
songs Repository do clear method and
after all we're going to stop the
application we're going to use this
method to test it's a helper function to
perform our testing nothing more it's
just creating a new
song and this is how you can test a root
end point it means our testing is
working fine let's implement
it there is no script for end to end
testing for the we have an end to end
test but I'm looking for a watch mode
testing that's why I'm going to add a
new script it will run end to endend
testing in the watch
mode let me run the end to end
test in the watch
mode it should be e to
e e to
e right now we have only a single file
which is AB
do E2 e-pack
dojon if you run this file let's say
app it is going to run this
file I'm going to copy this source
code and let's create a new file inside
the test
folder we will use this test folder for
in to end
testing let's define a new file
song SL do E2
e-. I have copied the source
code
this is the default
code we need to add a type orm setting
before all the
test we need to create a new
database let's run it here
we need to import couple of
modules we need a song module and
song entity let's get
it type Ork
module we also need to import type or
module actually I'm going to copy
everything and paste it
here now we have before
all we also
need let's
define it should be song
resolver end to end
test we need after all and after
each after each test you need to clear
the songs table and after all the test
you have to close the
application
I'm also going to use this helper
function I already taught you these
Basics when we were building when we
were testing the rest
apis that's it our setup is complete
now let's run the
test this time I would like to run songs
file
let's try to run the song file song. E2
e-pack our test has passed now and you
can see this test is running fine now
now so we have successfully done the
setup now it's time to test the
query we need to create the song first
because there is no record in our
database table which is songs there is
an empty here there is no
record so I'm just trying to write the
query to fetch all the
songs I created the query data object
I'm providing the
query and I'm sending the query in the
HTTP
request when you test the API graphql
API you will get the data or the
response in data object and we have the
songs I'm just expecting the songs
array uh uh let me run the application
in development so you will understand it
more
deeply application is running
now let's try to write the query to
fetch all the
songs if you write the query or you can
do without without query I'm going to
write query
query and I would like to fetch all the
songs ID and the
title so you got the result in the data
object and we have the songs
array one more thing if you write the
name of the query you can also do that
if you have experience in graphql then
you will know what I am doing you I'm
just I just gave the name of the query
get songs you can also do that it will
work fine there is no
issue now we're going to test a single
song
query
this time first step I created this
song and I created the query
object now we need the variable this is
how you can Define the variable in
graphql so I'm providing the variable ID
here you can exactly
query in your graphql playground let's
say
it this is a new
tab I can give you the name of the query
get
song let me copy that get
song now I def I created the get song
query and I'm expecting the ID as a
variable here I'm providing the variable
ID this is how you will set the query
variable this is a another way to fetch
the get song query I already taught you
this method it will work fine you got to
provide the
ID and here you can expect the name it
will work fine but this is another
alternative way of doing this
thing if you have an ID you can provide
the ID
here ID
we don't have any record that's why I
got the
error now we going to test
it you can see our test has passed now
because first we are creating the song
then I'm providing the
ID variable from the new song object you
don't need to change anything here you
can also do expectation
for assertion check for the status code
here instead of calling this
one that's why I I'm expecting the 200
status code and it is going to give give
me the response data and the song and
I'm checking on the based on new song
both are
same now our next step is to test the
create song
mutation it is the same way you define
the mutation I give the name create song
mutation instead of ID I'm expecting the
create song input we have created the
variable and I'm getting the create song
input we have title and here you can
provide the values for your
variables if you want you can do the
exact same
thing from your graphql playground let's
say I can say I'm going to create a new
song I just past it pasted the
mutation if you run there is no query
variable for create song
input let's define it you have to
provide the title I can
say
lover
song you can see the lover
song now I can provide the ID here let's
test it
here I provided the ID so I got the song
object there is a data object and we
have a create song
object that's why I used create song
Here create sing do title should be
animals our test has passed now we need
to run update mutation similarly just
like for just like with create
mutation it is expecting to arguments ID
and the update song input and we are
providing the ID in the variables and
update song input here
here it is going to return the affected
with
integer now we're going to copy this
delete
mutation delete is expecting only the ID
and it is going to return the
affected I defined the delete song
mutation and here I'm expecting the
value which is
one
our test have has P tests have
passed
query and we also need to test delete
[Music]
mutation delete mutation test has passed
F this is how you will do end to end
testing in
graphql in this lesson I'm going to
teach you the concept of
caching Apollo server provides caching
on the server site you can implement
it caching is a process of or method of
storing copies of file or data in a
temporary storage location
or cash to be accessed quickly like you
want to store the data temporarily in
some type of in memory built-in memory
you can store the data Maybe for 30
seconds or 60 seconds or a 1
minute it's called caching what is
server side caching you want to store
let's say you want to fetching the query
results you have a
query and user is fetching the
query constantly after every 10 seconds
after every 20 seconds or after every 10
seconds in that case you need caching
you don't want to send the request
backend server to DB server again and
again so it will increase the massive
traffic
load you are thinking why do why need
why do we need
caching if user is fetching the query
after 3 seconds again and again you did
not implement the caching your
application will send the request to the
backend server DB server and it will and
it will fetch the data from that server
again and
again it will decrease the performance
so the help of caching you can improve
the performance of your
application you can avoid unnecessary
request to server because the data will
be fetched from the cache
immediately you can reduce the bandwidth
which will be benefit to user you can
reduce the massive DB
loads with the help of caching you can
handle massive Network traffic
request yeah you can decrease the
service
calls so that was the basic fundamental
concept of caching now we're going to
implement the caching in in nests
project nests already using Apollo
service AP poo server Apollo
package so we're going to install the
package uh install this caching module
Apollo server plug-in response
cache this plug-in helps optimize the
performance of graphql queries by
caching the responses
this this plugin will help us to Cache
the response and serving the data from
the cache instead of executing the same
query
repeatedly our next step will be
register the caching
plugins when you install this plugin you
can register it as a plugins
array I have set the default maximum age
which is 5 Seconds I'm
saying hey
Apollo you can keep the data in
cash for 5
seconds after 5 Seconds you have to
refresh the
cache you have to refresh the
data and then you need to create a
directive cash controls SC private or
public you want to fetch the data
publicly or you want to fetch save the
data privately private represents a cash
control scope where the response should
be cached privately if you want to fetch
the authenticated user something like
that then then you need to set the
private represent a cache control scope
where the response can be cached
publicly this directive will have max
age scope and inherit max age and you
can apply cache control directive on
field
definition you can apply on a fing field
like title field in a song
type you can apply on object interface
and Union the max age is an optional
argument of type in that represents the
maximum age of the cach control in
seconds how long the
response can be considered a fresh and
cachable you can read this documentation
of maxh I've written down for
you private and public scope this will
be used for parent let's suppose your
query is dependent on parent
query then you need to use this
one you can also set the cach control
set cach
hint in the resolver by using this
line our next step will be apply the
cache control directive I applying it
for titled field inside the song
type cache control maximum age for 30
seconds I'm saying to Apollo hey
Apollo you can keep the title field
record
for 30 seconds in a
cache if user is fetching this title
field constantly after 20 seconds or
after 10
seconds then it will fetch from the
cash if user needs to fetch record after
a minute or after a 2 minute it will
fetch the data from the DB server but it
depends on you on your case on your use
case but 30 60 and 40 are the
recommended values on the based on
Apollo
documentation Apollo server uses
inmemory cache by default we are we are
going to use inmemory cache but you can
also configure different backend like
redis or M
cach you can also apply cash control
directive on a complete type let's say
if you have a scenario where you need to
fetch all of the fields from a specific
type then you can
add here cache control directive maximum
age to 40
seconds I just give you the basics
Basics when you implement in real world
scenario in real world large application
you will know your use case better now
it's time to implement it or you can
implement it by your own
let's install the plug-in
first plug-in have installed let's
import it in the app
module now we're going to register the
plug-in into plug array when you are
creating graphql module you can register
it
here so our third step is to creating a
cache control
directive I can do it
here it will have max age scope inherit
inherit max age private if you want to
dig into more deeper you can look at
from the Apollo server
documentation when you Google Apollo
server
caching this is the document you got to
read if you want to dig into deeper what
is Max age what is cach control scope
you can read this
document this is the implementation of
caching in AP poo server
if you want to do ready setup you can
also do
that we have created the cache control
directive
now I want to apply the cache control
directive on our field right now I have
only one single Field title I'm saying
I'm assuming that my
title field is going to be
feted
after 10 seconds I have a query in that
use case like client is asking title
field again and
again let's try to test it
first
my application server has
started now I can say I want to access
the
query of the songs I want to fetch the
title you can see it's working fine
now let's fetch the title again
now it is accessing the title field from
the inmemory
cache one last thing you can also apply
cache control directive on a type here I
want to say I have only single type
that's why I want to use it for only
demo purpose in real world application
you will have a different use case
restart the
[Music]
application
[Music]
my application is running now I'm going
to access this song FEI
songs it's still working
fine if I try to access the
song we need to provide the ID
let's fetch the
ID I'm going to copy the ID and let me
paste it
here now I would like to access the ID
and the title let's access the title
only or the
ID now the data is is going to be
cached I can access it
easily it's working
fine in this lesson I'm going to teach
you the concept of data loader why do we
need data
loer we have this schema I've already
found example project regarding data
loader we have a user and we have a post
there is a
relationship between user and the
post when you send the graphql request
to fetch all the post and you also want
to the owner of this post who has
created this
post under the
hood graphql your application will send
a a different different a new data
request to the database a new request to
the database to fetch a user for each
post this will decrease the performance
of your application because you're going
to do lot of database
request here your output will look like
that if I will show you
here let me show you with the help of
example I'm going to send the
request it is going to take a 3 seconds
because I have set this delay for the 3
second we have how many post we have we
have three post you can look at the
schema or our database I don't I'm not
using any database
here
so here is the
data we have a three
post inside the post we have a user
ID when you look at the user service we
have all of these
users every time let's say I log the
message fetching data from DB
let's example you can say that getting
user ID 1 fetching the user ID one this
is the you can imagine this is the
database
request every time it is going to fetch
the post for each user against post it
has to fetch the record from the
database you can imagine if you want to
load 50 post and you have to send the
API or backend DB request for each user
separately so what data loader will do
data loader will batch all of the users
it's going to wait and say I can send
you
request here what data loader will
do it will say
I
will get all of the IDS of the
users like one 2
3 and then I will
fetch all of the
users for all post and then if you need
any post if you need any
user against each
post you will fetch from the cash or
from the data loader cash data loader
maintains cash
also did you get the
point let's say I'm going to add I have
four users inside the post
service I'm going to add post
for title post
for
something and user ID which is for this
one application is running now I'm going
to send the request to fetch all the
post
now I got the for post and it has sent
the DB request to fetch a single user
what we can do we can say I want to
fetch if we are using data loader please
fetch all the users it's batching all
the users from the DB and maintains a
cache and next time our application will
fetch the user from this cache
I have already implemented the data
loader in this project actually I found
the source code on the internet to
explain the data loader it's a simple
source code so I thought I should teach
it with the help of this source
code inside the post
resolver here they are resolving the
created by field created by and it is
going to return the
user here instead of loading the user
from the database let's user service
will send the DB request so I'm going to
comment and now you will see the magic
instead of loading the user from the
DB I would like to fetch the user from
data
loader now we're going to send the
request
you can see that getting the users with
ID 1 2 and
4 it has bashed all the users and
created the user map to send the ID's
record to data loader and here is the
result so let me
explain what this source code is doing
if you check the app
module here we are providing the loader
I created the create user loader and
they are injecting the user
service inside the user service inside
the create user loader I'm passing the
user
service to work with data loader you
only need a single package which is data
loader this one you have to install only
the data
loader here you will have a user
loader what this loader will do it is
it's nothing more it's just a function
takes a user
service so I created the instance of a
data loader the ID will ID would be
number and another type which is the
object should be the
user this when you create the data
loader you have to provide it is going
to give me the IDS all of the
IDS and here I can fetch all of the
users against IDs here I did the users
map you you saw the users map here 1 2 3
because data loader Works in this way
you have to provide the results in this
way like I got 1 2 4 then I did the map
to fetch all the records ID 1 2 and
4 we created the user loader I have
attached inside the context
object remember graph resolver can have
four arguments in for context and
parent we have user loader here to fetch
all the users against a
post here this one inside the post
resolver I'm resolving the created by
field I got the user loader from the
context here you need to load the
user from the user
loader I got the parent I parent record
from the post which is the
post so I got the user
ID which we saved
here we have one more thing we have used
a schema based approach to build graphql
apis but I also wanted to show you
another way to build graphql API which
is code first approach this code first
approach will generate the schema.
graphql file automatically it depends on
you but I like the most schema based
approach but you can use both of them it
depends on your use case this is how you
will Define the graph qu object
type but we have worked with this schema
based
approach let's say you want to create
this graphel type which is posted with
the help of code based
approach you will say this is the graph
object type you can get it from nestjs
graphql package and this is the field
you can say this one this is the field
and you can
say title field and we have the body
field and we have the user ID I'm not
I'm not saving into the graphql datab
graphql graphql type that's why I keep
the user ID for entity based to build a
relationship with them so created by
this is the relationship between a user
here you can see that created by the
return type should not be null that's
why I they have used the user this is
this represents the return type what
your field will return so it's the type
of this created by it should return a
user user
type similarly you can look at the user
entity
object type this is how you will Define
here this is graphql type and my user id
the type should be number that should be
int that's why it's a nonn knowable
field and it should return or the type
of this ID should be int and we have a
field which is graphical type so this
code will be converted into this schema
type and how can you resolve the
resolver when you look at the post
resolver this is the resolver and I say
this is the post resolver that's why I
provided the post
entity now we have the post resolver the
query
tag so here you want to say what
resolver this will do in we are in the
post we are here
so this query will return all the post
and the name of the query should be post
I'm resolving this query so I'm fetching
the post similarly if you want to
resolve the created by here this one you
have to provide the resolve
field is all
field there is a field inside the post
Ty which is created by and it should
return a
user so this is the return type this is
how you will mention the return type it
should give the user and I got the
parent and the
context this is a uh nextjs has
documentation on
graphql you can learn more about a code
based approach if you like the code
based approach you can learn more about
from the
[Music]
documentation this is the code first
approach the object types you can read
the documentation if you are not getting
what I'm talking about you can just read
this text it will help you to understand
the code very easily so this is how a
field and type should be post array I
want you to check this documentation one
more package I want to share you have
graph nestjs graphql
tools if you want to use the code based
approach
and let's say you are using post or type
orm this is the package if you want to
work with
database and and you want to use loader
they have already built a data loader
here if you like this package you can
implement it it's simple you need to
provide resolver user object type user
resolver here it will have graphql
loader you only need to just provide The
Decorator graphql loader and it is going
to implement the loading stuff
here if you like it you can implement it
there is a this is how you will
Implement one to many many to one and
this is the usage
I just want to show
you you can do if you want to use
database and data loader you can
Implement by using this package this
package also have more features on
pagination sorting and field extraction
Etc if you want to fetch data from
external rest API you can do that we're
using Apollo server AP poo server
provides a package to fetch data from
external rest API a
poloo data source rest I have attached a
started
project I have already in I have already
have this package in package.json file
you have to install it Apollo data
source
rest you have to do npm install to
install all the dependencies
this is a class you have to extend
it we're going to do we're going to
fetch
todos from this Json placeholder API
it's a fake API with real data let's say
I want to send to-dos
request it is going to give me all of
the to-dos I want to fetch this rest
API
now this is how you will implement
it you will have this schema you will
create the schema to do ID user ID title
completed with
Boolean I'm using the same property I
defined a graphql type and then we have
a query query to fetch all the
to-dos I have a to-do module inside
to-do service to-do resolver now to-do
service is is going to f fetch the data
from external rest API instead of data
database inside the to- do service here
you have to extend the rest data source
it will it will ask the call the super
Constructor this is the base URL I'm
going to call this.get to fetch all the
to-dos you can use this method I I can
get the data source object from the
context here you got call data sources.
too api. getet too I'm talking about
this too API like this one so another
important thing this is how you will add
a data sources inside the context it's
an asynchronous so I provided the data
sources if you want to implement you can
go ahead and do it and let me do that
for
you I have I have to do docraft in my
started kit
project now let's extend data
source rest rest data
source let's have the
Constructor I'm going to call the super
Constructor now let's set the base
URL I can get the base URL from
here I don't need to provide todos this
should be the base URL now let's define
a function to get
to-dos and it is going to return the
array of
to-dos I can get the type from the
source. graphql file the typescript file
I've generated the typing by executing
this
command npm run generat typing
so let's call this
dot here disor get and provide the path
to
do is everything right I can check the
path which is to
do so we created the data
source and now we have to add this data
source
into to do resolver we got to call this
actually we need to add in the
context I'm going to create the data
sources
function it's going to return a to-do
API let's create import to-do
service it's going to return the object
and the function is going to return the
object now I can add in the
context
here it looks good so you can use the
context object here inside the to-do
resolver to do resolver let me get the
context data sources and I'm going to
call all this
method data source is a function there
is a to-do API object and we have get
too
function let's start the
project project is already Runing on
3,000 let me stop the project let's run
it again
my project is running I'm going to send
the
request I got all the 200 toos
Unfortunately they don't have pagination
otherwise I can implement the pagination
but you got the concept how to implement
the rest data source if you want to do
more Advanced Thing by using the rest
data source package there is also a
caching functionality you can override
the method I want you to check the
documentation if you want to implement
the rest data source there is also a
data loader you can also use the data
loader with rest data
source I want you to check this
documentation it also provide to fetch
duplicate
records you can read the documentation
to understand how to use the
cache stuff like
that in this module we're going to use
Prisma orm and we're going to build rest
apis Prisma is an orm in nodejs or
JavaScript when you look at the
documentation it's they are saying it's
a Next Generation orm for nodejs and
typescript
project it's similar to type orm but it
is faster it's an efficient they are
maintaining this project
regularly so you can look at the use
cases and customer stories when when do
you need
Prisma you can read the customer stories
and use
cases so in this video I'm going to
teach you how to set a Prisma in next
nestjs project you can also get the
Prisma documentation from nestjs package
from nestjs package inside the njs
documentation you will find a Prisma
folder you will see the Prisma section
here is a Prisma orm
documentation the first step we need to
install the
Prisma I have provided the started kit
code for you you can go to the starter
branch and run nbm install to install
all the dependencies this is just a
basic Nest CH
project I don't have anything here just
Basics basic setting for nest CH
project it is taking some time to
install the dependencies meanwhile I'm
going to create a new database for
Prisma because we're going to use postp
with
Prisma I'm going to create a new
database
Prisma API something like that you can
choose any
name all the packages have
installed now we need to install a
Prisma as a dep
dependency
Prisma left dependency has
installed now we need to initialize the
Prisma project I can use npx init Prisma
in
it it will set up the Prisma in our
project you will see schema. Prisma file
inside the Prisma folder here I'm
telling I'm going to use Prisma client
Library this is my post database
provider this is my database
URL they have also added a created EnV
file here we have postp database URL
make sure you have ADD theb in the git
ignore I think I've already added it yes
no I cannot see that let's add EnV I
don't want to put push my EnV to
GitHub they have already installed post
so I'm going to work with
post this is how you will set a Prisma
in your project in your nestjs
project in the previous video we have
set up our Prisma
application now we're going to create
our first
model I'm going to create the song
model the type should be int
and by
default this should be
int by default I'm going to set it to
Auto
increment and this is the
ID let's add another property this time
the type should be
[Music]
string but we did not set
database URL for the
post I'm going to create a new
database let's create a new
DB
Nest Prisma app or Nest
prisma-p my username or owner is
postgress now we need to replace the
owner here
postgress and your
password and the name of your database
and schema should be
public I'm going to run the
application my application is running
fine let's try to check the tables
inside the schema I'm going to
refresh and inside the tables I cannot
see any table because we did not migrate
the
database let's create our first
migration migrate
F Prisma migr F and the name of your
migration I can say in it this is my
first
migration
I think I did not provide the right
command Prisma
migr
DB or Dev yeah npx PR migrate
Dev Das Das name of your
migration this is my first migration
that's why I chose the init name but you
can choose anything
here
Local Host provided DB credentials are
not
valid post
SC there was an issue with double
s now a new migrations folder has
created inside the
folder we have in it migration
file we have song table this is the
migration log
let's try to check in our database I'm
going to refresh my
tables and you can see the song table in
our
database but we also have two columns ID
and
title in the previous video we have
created our first model and we ran
migrations but Prisma also provides a
Prisma client to perform cred operation
this Prisma client will generate the
correct
apis correct functions for song model
you will have prism client. creat song
prism client. find song all of these
methods in the prisman client Library
here we are using the prisman client but
we have to install this package Prisma
client and P install at Prisma
client this package will provide scrud
operations for all of your
models this Prisma client will interact
directly to the
database so we created the Prisma Cent
installed the Prisma client now we need
a service inside the source directory
and I call it Prisma dos service.
s it's injectable
service
exort class Prisma
service and I'm going to extend the
Prisma
client Prisma client
here we also need to
implement on module in it because we
have to set up the Prisma client when
our application is
running I can call it on module in
it on module in it this
do
connect this connect method will connect
our uh connect this Prisma client to our
database
I have I have not imported injectable
decorator let me get it that's all you
need to connect Prisma client to
our
database so we will not use Prisma
client we will use Prisma service to
interact with
database we're going to talk about how
to create cred
operations we have created a song model
here I want to create the correct end
points one more thing I did not talk
about or I did not teach there is a
resource
generator this CLI command will generate
the correct API endpoints controller
module service dto object something like
that if you need to scaold your
application you can use this command
resource
it can also works with work with graphql
code first approach schema first
approach or you can create a micro
service or you can create the web socket
but I chose the rest API because I would
like to build the rest API yes I also
want to generate correct entry end
points we have the songs model we have d
object entities so on
controller
service we have all of these method
inside the
service we have created a Prisma service
now I'm going to use a Prisma service
here to interact with database can call
it
Prisma Prisma
service it is going to give me the
error that's why I use this
path first of all let's create the
create
method return this do
Prisma
Dot Song you can see we have a song
object there is a create method and you
have to provide the data here you have
to provide create song
dto one more thing I want to talk about
you can use the types from Prisma client
Prisma client already generated couple
of typescript typing let's
say first I need to import
Prisma from Prisma
client
you will find book create input the
type in this type you will have title
field we also need to update inside the
song
controller we got to get Prisma client
and you will have book
DOT
book create
input my vs code is not giving me the
hint or
suggestion now we're going to run the
application it is going to give me a
couple of Errors
maybe oh it's not a book it should be a
song because I'm accessing the song
model I'm using the
book
song song.
input not a book song create
input
I did not import Prisma service inside
the song
module because we have to import it
that's why you have to register it as a
provider
Prisma service so I can get the Prisma
service my application is running fine
now now we're going to test it with the
help of fresh client let's create a new
file I can say HTTP
client.
HTTP create
song post
HTTP HTTP Local Host colum
3000 SL
songs what is the name of the API I can
check it from the
controller we have the
songs content
type application
Json let's provide the
title follow
me you can see a new song has created
successfully now we're going to write
the function to fetch all the song This
start
Prisma
I'm going to reload my window it is not
giving me
suggestions Prisma
Dot
Song dot find many there is a method
find
many
let's try to get all the
songs you can see I have a single
song now we have to implement the find
by ID this do
Prisma do song now it is giving me
suggestion find
unique and we have to provide the
ID where clause and you have to provide
the
ID
let's try to fetch the song on the based
on
ID fetch song by
ID so I got the song by ID if I provide
the invalid
ID I should get the empty
record I'm getting issues here I think I
need to generate the typing you can call
this method npx Prisma
generate it is going to generate the
typing inside the node node modules and
Prisma inside the Prisma you will get
the typing I got this from
documentation this typing will be stored
inside the node modules inside the
Prisma and the client
directory generated Prisma client
reload the
window now the error should be gone
now I have to update it it's a song
create
input we also need to update in the
controller we have the song
controller
here it should be
Prisma Prisma
SL song create
input I have to get this ke Prisma
client now the error should be gone now
it looks
good
so I can create a new
song and I can fetch all the songs that
looks
good in this lesson I'm going to teach
you how to create update endpoint
actually we have already created the
update
endpoint you will see the patch endpoint
Point inside the song
controller there is also a method inside
the song service there's an update
method all I need to do is to use a
Prisma service inside the song
service we have have to use the update
method from the
Prisma and there is an update method
inside the
song
update here you got to
provide we clause and the
data where and
data we have to fix a little bit
changing
here I'm getting I'm going to get we
clause and I can get the type for for Vi
song We unique input similarly I would
like to change the type here Prisma do
song update
input you can remove the V because both
the key and the value are same so I can
use a single
V we also need to update the type in
controller file let me update the type
here
here I would like to send the object
instead of single parameter which is
ID here I can change the type Prisma do
song update
input we also need to update the find
one a little
bit
I would like to get the songw
unique input and let me get the
songw
unique
input and I'm going to
provide song wear unique
input
we also need to
update controller for the find
one let me send the ID in the
object because I'm receiving the object
here
here if you want to look at all of these
types where these types have
stored when you go to the node modules
you will find there is a package
Prisma do Prisma
client you will have all of your types
in index. D.S
file so I can get song whereare input
you can see we have a song We
input can say
type here here we have a song We input
you can have ID and the
title here we have the song where unique
input you have you can have ID and or
note in the
title now we have to test it run run the
application cannot find
primsa let me fix
that there is an issue
Prisma
now my code looks
good I'm going to send the update
request from my rest client from my HTTP
client the song by ID we have to send
the patch request instead of
put and going to update this song with
id2 copy the content
type dancing
feet let's see a song has updated
successfully if I fetch the song on the
based on ID it looks good we have
dancing feed
let's create another
song I have created another song I would
like to update the
title my title has updated so you can
fetch all of the
songs it looks
good we have implemented the update
operation now now we have to implement
delete
operation I'm going to use the same
strategy to delete let me get the ver
clause in the
input there is a method in the
Prisma Prisma do song. delete it is
going to accept the V
Clause now I have to get it in the
controller we need to pass
that inside the song
controller here I have to provide the ID
inside the
object
ID
let's try to test it with the help of
HTTP
client I can say delete song by
ID I'm going to provide the ID instead
of patch we need to use the delete
operation you can see this song has
deleted I can verify by fetching all of
the
songs you can see we have only only two
songs right
now now we're going to build
relationship between
models Prisma also provides one to one
relation one to many relation and many
to one
relation and also have many to many
relation I'm going to add a new model
artist let's add Fields inside the
artist I will have the ID and the name
of the
artist now each
song an
artist
I'm going to add one to M relationship
between artist and
songs each artist can publish many
songs I saved the application you can
see it has automatically added a
relation let's rename a small a to a
capital A to small a
here you can see there is a reference
here
artist and fields which is artist ID and
the reference with the
ID now we have to run the migrations npm
run
migrations oh I have to run
npx Prisma migrate
Dev the name of the
migration which is ADD
artist it has also generated the Prisma
client queries or Prisma client
types when you see the migrations you
will
have the create table cury it is going
to create the artist table it has also
added a relationship between song
relationship between songs
model let me try to check the types you
can check it from Prisma client index. D
dots do I have the artist type yes let
me find artist create input yep it has
generated the types for
me now I'm going to generate a new
resource for
artist an artist resource has created I
don't need entities I'm going to delete
them
here I also don't need entities in this
song because we are defining our models
in the schema. Prisma
file let's create the
artist we have to open the r service and
here we need to
inject the artist the Prisma
service I can get it from the song
service which we have to import these
two dependency Prisma service and the
Prisma
client I'm going to copy the
Constructor here we have to
find the Prisma create
input command F to to
find artist
create
input yes I would like to use that type
I can get it from the Prisma
client
Artist Artist create input that's it now
I can
use Prisma do
artist do
create here we have to provide the data
object and inside the data I can
provide create
artist
dto one more thing you need to add
Prisma service in the artist
module we have to register it Prisma
service let me import Prisma
service and here I need to add Prisma
service we also need to adjust a type in
the controller for artist controller we
have to update our
type I have to use the same
type Prisma dot artist create we have to
import a
Prisma otherwise it will give you the
error I'm not going to use the create
artist
dto so the artist create input can take
the name of the artist if you want to
inject the multiple songs you can also
do that you can look up the
documentation of Prisma how can you
insert multiple
records if you want to do in this way
you can also do that artist unchecked
create input but I'm going to use this
one simple one npm R start
Dev my application is running fine now
let me open the HTT HTTP client let's
send the
request to create new
artist create
Artist
Artist here I can provide the name of
the
artist can say Martin
Garrick a new record has created
successfully the artist record has saved
let's add a new
artist V
another artist has
created we have made one too many
relationship between artist and songs
when you add a new song you can add a
relationship for the artist here when
you check the schema. Prisma file you
will have the artist ID in the song
model that's why we need this is how you
can build a relationship between song
and the artist so what I can do inside
the song
service we have to
expect the song actually author ID I can
find
that song
create
input so I have this song create input
type I also have song unchecked create
input did you notice the difference
between these two types here we have the
artist ID I can add the artist ID if you
want to insert a complete artist while
creating a new song you can also do that
you can look up the
documentation and here you
can you can do in this way
you can provide the array if you want to
do that if you want to insert a single
record you can also do that but I just
want to show you the way to
add
record so I'm going to use this
type instead of
simple song create
input now you also need to provide the
author ID in the in the request
parameter here I'm creating a new song
here let's provide the author
ID which is one I'm going to create a
new song let's say
Animals by Martin
gck I got an issue not an author ID it's
an artist
ID why I'm saying the author ID I got
the record with this author ID if you
want to
query the artist in
the response let's say I'm going to I'm
going to fetch all these songs but here
we have artist ID null here we have the
artist ID one if you want to populate
the record of the artist you you can do
that in the find menu and here you can
say
include artist to true that's
it let's fetch all the
songs here the artist ID is null artist
is null here you can see
the artist ID one and we have a complete
artist
record that's how you do
population we have used this include
syntax you can also use the connect
object if you want to make the
connection or update the reference ID
you can use the
connect now we're going to implement one
to one relationship between two models
we're going to have a user model here we
have a one to one relationship between
user and profile each user will have one
unique profile in the profile we have
photo we have the phone number of the
client of the user this is how you will
make a one toone relationship user and a
relation and this makes each profile
will have a unique ID of a user table
then we will generate Prisma
migrations then we will generate a new
user with the help of nest generat
resource a user we're going to use cred
AP endpoints and finally we're going to
save a user on the based on profile like
when we are when we are saving a user I
also want to save the profile this is
how you can do that profile and a create
object and the attributes of profile
table it will automatically made a
relationship between user and a profile
and finally I want to fetch all the user
with the
profile if you want to implement it you
can do it but let me show you how can I
implement it I'm going to copy the
model here here here inside the
schema let's add two new
models I've added two new models let's
run the
migration
npx Prisma migrate Dev the name of the
migration one
to1
[Music]
relation it has run the
migrations and now it has also generated
the types inside the Prisma client I can
double check that from the Prisma here
you have all of your user types user and
profile when you search the
profile here we have profile
stuff our next step is to generate a
resource Nest generate
resource
users
select rest API end
points getri
of the
entities and I need to inject Prisma
service inside the
module inside the users module I have to
inject the Prisma service
here Prisma
service inside the user service we need
to inject Prisma service
dependency I can get that from the song
service we need the Prisma
service
and I'm going to copy this one as a
Constructor so we have to call the
create method I'm going to copy the
exact create
method and provide it
here that's it this time I'm going to
use the create user
dto I have not defined the properties in
the create user user dto if you want to
add the validation you can use the class
validator I taught you earlier in the
previous
modules we will have photo the URL of
the photo should be
string and phone number the type should
be
string now we're going to I'm going to
copy find all method
and I'm going to use this profile I want
to fetch the profile with each user now
let's try to test it run the
application this create object is used
to create an nested object a relation
relation
object
let's create a new
user
users provide the name of the user
jendo and we have to provide the photo
URL some
api. com/
phos 1. J
APG and you need to provide the phone
number let me create a new
user a user has created successfully
let's try to find all the
users VCH
users
here you can see that I can see the
user and we have the profile object
inside the user you will also see a
relationship with user ID one which is
one that's how you implement one to one
relation in this lesson you're going to
learn how to implement many to many
relationship between
models I have this use case one blog
post can belong to many categories and
many categories can belong to a single
block post so there is a many to many
relationship when you implement many to
many relationship you need a third model
in the third model you store the foreign
key of your first model and the foreign
key or prime for foreign key as the
primary key the foreign constraint here
it's a it's a foreign key of category
table and in Prisma you define the
primary key by combination of post ID
and the category
ID this is how you will make uh many to
many relationship now the categories
instead of categories array you will use
the categories on post array the same
stuff here instead of using post array
here you will use the categories on post
array and then
you we will generate
migrations we will generate migrations
and it will also generate the Prisma
client
types and then we will generate the
resource post we will create the post by
using this input type post create
input and I also have to update the type
in the
controller and this is how you will send
the request to create a new
post here the title of the post one to
many
relation this this is the Prisma post
and it it can have two
categories here you can say I I'm going
to create a new category this post can
also belong to Prisma category this post
can also belong to nestjs category that
is why I created two categories you can
see that category number one and this is
category number two here I here we have
the array of the
categories similarly you can do the same
thing if you don't want to create a new
post you can connect with existing
post I'm going to teach you transaction
let's say I'm going to write blog post
on transactions in
Prisma and here this post also belong to
nestjs category and Prisma category
that's
why I'm I'm connecting to category
number one and the category number two
and finally you can also do a relation
queries with the help of this type post
where uni input also have to update in
the
controller this is how you can send the
request categories this is a we Clause
category and the name you can check all
of different type of queries in the
documentation let's try to implement it
first if you want you can Implement by
yourself many to
many
relation I'm going to create a post
model and my next model model is
category it will have name and the ID
and my third model is categories on post
I'm going to save now you can see
that these two properties are inside the
categories on post I would like to store
the
date and I want to store who has created
this
let's run the
migration it has also generated a Prisma
client
types you can check it in the node
modules at Prisma /
client our next step step is to generate
the post resource we're going to perform
some cred
operations please select the rest
API yes I want create entry end
points I have the post get rid of the
entities
one more thing I would like to register
a Prisma
service inside the post module otherwise
you will get the
error now we're going to write the code
in to create a new
post we also need to inject Prisma
Service as a
dependency I'm going to copy these two
lines and I'm going to paste here Post
Service let me copy The Constructor we
need to inject the
dependency I'm going to copy my
create
function
something is
missing I have done something
wrong so let's you use the
Constructor pris
private Prisma and Prisma
service let's use this type
actually I don't need
that let me copy the fold
create what is
this now it looks
good so we also need to use that post
create post create input in the post
controller let me import
Prisma now it's time to test this
application
the application is running fine let's
send the API
request I'm going to copy my API
request here I'm going to create a new
post and I'm going to also create a two
categories so you can use the create
array
inside the create array I have the
category this is the post on category
object so that's why I use that
properties let's send the
request it should be 3,000
or 3,000 it should
3,000 now you can see that one to many
relation post has created
successfully now it's time to do a
register another
post this time I don't want to create a
new
category create a post
with existing
categories I would like to create a new
post and I want to use
the category number one and category
number two let's create a new post has
created it has also made a
connection with this category you can
double check from the PG
admin meanwhile I'm going to write the
code to do relational
queries let's
update the find find
all that looks good we also have to
update the
get inside the post
controller
now we have to fetch all the post with
nestjs
category so you can do that you can
learn more about how to do queries in
Prisma
documentation I'm going to send the
request the post the should be
3,000 now you can
see I got these two post with the help
with the I justed query with
category what is my name of the database
let me get it from
EnV PR
Nest Prisma
DB here I have Nest Prisma DB let me
find the
tables and we have post category and
categories on post let's look at the
post we should have two
post you can
see I have one too many and
transaction I must have two
categories you can see that let me find
categories on
post here you can see I have four
records there is another way to use
transac ction feature if you have to
perform the batch or bulk operations
like delete manyu create manyu and
update manyu you can use all of these in
a one query you want to create three
records you want to delete two records
or maybe you want to update a single
record or maybe you want to update five
records so in that case let's say if any
query fail
then all of the operation will be
discarded I'm going to run multiple
queries at same time if any query failed
you will not get result
back you can use this query or
transaction API when you want to create
batch
operation here is an example
I want to find all of the post I want to
find all of the artist I want to find
all songs I want to find all
applications in a single query if this
query fails it is going to give me the
this operation this complete operation
will be discarded I will not get any
result that is why you use this
transaction
API to implement the demo or to
implement the transaction
API let's do it in app
controller we have to inject Prisma
service I just want to show you the demo
how can you use the transaction
API this my
service we have to inject it
here I can say
transaction let me register Prisma
service now I have injected it
here we have to import
it sounds good I'm going to create a new
method with name
sequential and get
sequential result results this could be
the name of the
query and here I'm going to copy my
code so let's try to test it I'm going
to run the
application let me send the request for
sequential query in my HTTP
client
sequential
query
HTTP Local Host colum
3000 and
sequential you can see I got the result
of all of my post
applications this these should be post
the
songs
and here you will have application these
are all the applications with customer
ID this is how it will
work if you want to add include or to
fetch nested record you can also do
that now I'm going to talk about the
concept of nested
queries this topic already is in the
transaction
API I'm talking about transaction when
you have this type of use case let's
say first I have to create the customer
email customer or the user and then
there is an address let me look at the
model structure we have a customer model
and we have an address model there is a
one toone relationship between customer
and the address and I have created the
enum application type and I have the
application model and the type should be
application type and default to now and
I choose a loan loan
here and I have made one to many
relationship between application and the
customer we have the applications array
here so let's say I want to create a new
customer address and here I'm creating a
new address and here is the Fe here are
the fields of
customers and I'm going to create
applications basically we going to we
are talking about a banking type
application let's say a customer comes
to apply for the loan customer can apply
for multiple loan applications loan car
financing or business financing a
customer can apply apply all of these or
can can apply to one or second type
application so tenure of your
application would be 5 years or 2 years
how many amount you want how much how
much loan you
want so this type of application when
banking banking in banking application
when an application comes they create a
new customer record they create the
address and they create the application
based on current user or current
customer
demand let's say a new customer comes
with business financing application John
wants to get the business financing from
a bank so he's decided he's going to
apply for business financing application
what under the hood is saying what under
the hood banking application will create
a new customer they will create a new
address and they will also create a new
application but they have a
feature a customer can apply for two
loans two applications or three
applications he can also apply on
business financing he can also apply on
car
financing so that's why there is a
create array
here what what are the benefits of using
transaction under the
hood Prisma is using transaction when
you run the nested queries these are all
the this is the nested
query we are creating address and we are
creating applications this is the nested
query let's say if an error comes here
if I will add the invalid value
here it will not create the complete app
application it will not create the
customer it will not create the
address so that is the benefit of
transaction I'll show you with the help
of demo this is how you can
implement the nested queries in Prisma
I've already done that for you I'm not
going to implement it here first of I
can walk walk through the code I created
the customer model we have the ID we
have the name field we have the email we
have the address and we have the
applications
array so address should be here it
should be at the top here so I have made
a on to one relationship between address
and the customer here is a unique
denotes to denotes to one to one
relationship we have Zip City Country
inside the address and there is a on
toone relationship between customer and
the address but I also have one too many
relationship between application and
customer so I told you a John can apply
for car car financing he can apply for
business
financing that's why I use the
application
array so the tenure amount application
type I have set the default to
loan so that was our model structure
next step I have executed nested query
Migration by executing this command
nested
queries
here it is going to create the customer
table it is going to create the address
table and create the constraint with
customer and the address it is also
going to create uh application table and
create constraint between application
and the customer
and then I have set the default value to
laan and then I have created the
application resource by running Nest
generate resource and you will see the
application inside the application
module I have injected the Prisma
service and then here I'm injecting the
Prisma Service as a dependency and I
just
called create application dto by using
the customer customer create input you
can double check it from the customer
create input you can get name email
address and
application all of this stuff
here name
email address I provided the address and
I'm creating it here I also can provide
the applications array you can check the
type by copying it and type and paste
so it should give me
the this one
type so I got this application create
nested with custom customer input so I
use the create did you see I use the
create can have the array so create can
have the array
here so you can provide the application
object
here if any fails the transaction will
roll back or discarded the
operation let's try to test
it you have to send the AP request
inside the HTTP
client here I'm going to send the API
request John J
2 jendo City New York ZIP code this one
amount he wants say
10,000 inue over 5 years and he wants
business financing I'm going to create a
new
application you you can see a new
application has created if I provide the
invalid value I have set the integer
here I'm providing the float or float
value I got the issue now it will not
create an application you can double
check it from PG
admin that's the benefit of
transaction in this lesson you're going
to learn the interactive
transactions what do I mean by
interactive
transaction when one query is dependent
on another query one query result is
dependent on another query result let's
take a use case you're going to build
account transfer feature in banking
application we're going to build this
use case a John has an account in a bank
and he want to he want to transfer the
$100 to Sam account so what would be the
process you have you have to implement
as a developer you have to update the J
account or deduct the $10000 from a Jone
account and then you have to check the
balance of JN account if balance is less
than zero you have to roll back the
transaction the operation should not be
continue
so this query result is dependent on
this query result you can see if any of
the step fails operation will be
discarded if there is an error occurs
here it will roll back the
transaction so first of all we need
account model we will have these
properties
ID balance and the title then we're
going to generate migration and resource
for
accounts we will inject Prisma service
here I will use Prisma account create
input
and I'm also going to update in the
controller we we're going to create
first account John then we will create
second account which is
Sam and we will implement the logic to
transfer amount to One account to
another
account I'm going to create a route
Handler for
transfer we will need transfer account
dto because I cannot use from from
Prisma
types there is no specific type for
transfer account I have to use the
custom data transfer object here when I
will transfer I will send the transfer
account request you need to provide
sender ID receiver ID and the amount you
want a
transfer so we will create a simple
basic transfer from transer method
inside the account service here is the
logic from the controller I will get the
sender and I have renamed to
from here I will have receiver I have
renamed to two and I will get the amount
and first we will
deduct the balance from the John account
by getting by getting the account on the
Bas ID here decrement the amount from
the John account then we try to verify
the balance of the John if balance is
less than zero we have to send the error
back and we have to roll back the
transaction here we here we got to roll
back the transaction but this
transaction object will do for us and
this transaction function it will take
all it will take it's a it's a call it's
a asynchronous operation it it's going
to take TX
so first this is the asynchronous
operation if error comes please scroll
back the transaction do not deduct any
amount from the John account and here is
our second
operation if everything is fine we got
to add balance to the same account and
finally we have to return the balance or
return the
recipient that's our trans transer
process this is how you can test you
have to provide the sender ID receiver
ID and amount you want to transfer here
I'm saying I want to transfer $50 from
join account to Sam account and here I
want to transfer $40 from J account to
Sam account we created both account with
$100 now if I try to send $20 now John
will have $10 in account in his account
if I try to send or deduct the $20 from
Jo
account you will receive this error
balance is less than zero and our
transaction will automatically roll back
this operation that's how the
transaction is helpful when your one
query result is dependent on another if
you want to implement it you can do it
on your own but let me do that for
you first of all we got to create a new
model inside the schema file
I have already done that
model oh I have to implement
here interactive transaction op schema.
Prisma and we have to
add a new
model finally we got to run the
migration
migrate not a
migrate also have to update here M
crate our next step is to generate the
accounts
select the rest
API let me
delete
entities and we have to register a
Prisma service inside the account module
I can register as a provider Prisma
service and we have to import Prisma
service Prisma service
from Prisma
service let's inject Prisma service
inside the account
service I'm going to do dependent see
injection I have to copy this
line and I'm going to paste it here I
also need to get Prisma client so I
imported the Prisma
client let's rename or add a logic to
create a new
account we got to do the same stuff
inside the account
controller import
[Music]
Prisma let's run the application and
create two accounts in our database for
testing
e
application is running now I'm going to
create a new account let me send the
request for account
creation board should be 3,000 not
3001
so I have created the account John now
we have to create another account with
Sam name account has
created let's implement the
transfer account logic transfer amount
not an account transfer amount
logic open the account controller we
have to register a new route for
transfer
amount I'm going to create a post method
we don't have transfer dto let's create
that transfer dto in our dto
accounts
dto
transfer
account -
D.S so here we have transfer account dto
we also don't have a method
yet inside the service account service
so I can
open account
controller let me import transfer dto we
don't have method I can use the vs code
please declare the
method inside the account
service now you will have a method
inside the account
service this is the transfer
method so here we're going to implement
our logic to transfer the account from
John to Sam I'm going to copy the
complete op complete function I'm going
to paste it
here so everything is good to go now we
have to test the
process let's send the transfer amount
request it should be
3,000
let's deduct the $50 from John account
to Sam account I'm going to deduct $50
from John now you can see the balance of
the
Sam if I deduct the $40
again let's use it
here so now the Sam has 190 and the John
has
$10 if I try to
uh deduct $20 from John right now the
balance of John is 10 it should give me
the
error you can see I got the error one
does not have one the ID sender sender
ID with one does not have enough to send
$20 so I got the
eror so I got the error here my
transaction function automatically roll
back back this
operation that's why transaction is very
helpful if you are doing 1020 operations
or 1020
queries your one query result is
dependent on another another query
result is dependent on another let's
imagine after 10th query there is an
error then the transaction will do the
roll back for
you
in this lesson I'm going to teach you
how to upload the file in
njs nestjs has already created a molter
module if you have used molter in
Express we're going to use the same
logic they have created the molter
module they also have nests platform
Express to
implement file upload feature so this
package provides the typescript typing
to work with multer package which is a
middleware for handling multiart form
data and then we will create our route
Handler for
update they have we're going to use the
Interceptor that's why I use the use use
Interceptor
decator here we have file
Interceptor they have already created
this file Interceptor and you got to
provide the name of your file and here
we will have the upload file decorator
the type should be express. multer do
file that's it then it will log the file
when you send the API request from Front
End application or Postman to upload a
file it will receive the
file so this decorator indicates that
the method should use the f file
Interceptor
Interceptor to handle the file uploads
the string file inside the file
Interceptor decorator refers to the
field name in the request
body now we're going to implement this
file upload
method first of all we have to install
the molter
type I've already attached the started
kit project or if you don't have an sjs
project you can create a brand new
project and start from them start from
there we have
installed uh package now I'm going to
copy the same
code and I'm going to do it here inside
the app
controller
we also need to import file Interceptor
from nestjs platform
Express whenever you need to upload the
file you have to use the use Interceptor
and they have created the file
Interceptor the name of the file here
you will provide the molter options when
you worked with molon if you already
work with molter opt molter package
these are the options are same these
options are same when you work with
molter
package so I'm not going to do it
here and we will have upload file now we
need to test it I'm going to start the
project we need a postman to send the
API
request in terms of
file
so here I'm going to send
request to the upload and we have to
provide the
file select the body and you got to
provide file you can select the file
from here a body and a file and then you
have to select the file
I'm going to use this PNG file you can
choose any
file B request I have to remove this one
now I'm going to send request you can
see a file has created successfully
actually uploaded this is the original
name this is the field file but I want
to save this file some somewhere in my
folder you can create a disc folder and
you can save save that save there to
implement this logic you going to
provide these two
options actually I'm going to copy the
complete
file intercept use
intercept I'm going to copy the complete
use Interceptor now it looks
good so we have to import this package
from disk
storage I think I can get that from
molter
package
molter disktop
storage now it looks
good so it will create the upload folder
for me and here I will have the files
folder now we're going to send the
request to save upload the
file and you can see there is a file
inside the upload folder and inside the
files we have create song mutation. PNG
file you can also add a
validation let's say you can
say I only want
to accept PNG
file how can you add a
validation I can say upload
PNG you can do the validation upload PNG
[Music]
file you can implement the validation
here let me copy the validation
logic they provided the pars file pip
Builder what this pipe Builder will do
this is a custom utility that creates a
pipe for validating uploaded files if
you want to add a maximum size you can
can accept you can also do that but I'm
not going to implement
that we need this
logic inside the upload
file
here I also added an error status code
if error comes it is going to log this
error
message unprocessable
entity now it can accept only the PNG
file type I've applied the pipe to add
PNG validation let's test it
out if I add upload
PNG if I add invalid file what will
happen I'm going to add jpack
I got the
error oh upload Das
PNG I got the error for double to
unprocessable
entity if I provide the valid file which
is
PNG what will happen
can get that from
here this is the PNG
file now the file has uploaded
successfully
here
one more thing we got to return the
message I forgot to return the
message
from here
to also need to upload the
message file uploaded
successfully let's test it out
out this is the PNG
file you should see the
message file uploaded
successfully and you you will see your
file
here in this lesson I'm going to teach
you the concept of custom
decorator if you want to add additional
functionality to a class to a method you
can use custom decorator just like we
did with app module app controller we
use decorator a lot when you look at the
app module here we have used a decorator
this module decorator in the controller
app. controller we have controller
decorator it mean this decorator is
adding an additional functionality to
the app
controller like they are adding
metadata this controller can have
functions attributes all of the
stuff
so you can improve your modularity and
reusability with the help of custom
decorator you can organize code very
easily you can extend Nest functionality
by adding custom
decorator here we're going to use custom
decorator I have a basic simple example
we're going to create our own custom
decorator the user decorator.
this you use pram decorator so I can
apply it on a
parameter and I'm using a function this
function is accepting to argument data
it should be unknown type and we are
getting the execution
context and I can get the request from
this execution context here I'm am
adding a user into the request. user
when you have implemented auth tication
you can create a custom decorator for a
user imagine you can get
this request. user from a Json web token
and Json web token Parts the token and
found the user you can imagine that but
I hardcoded it and return request.
user yeah this is The Decorator Factory
function it takes to parameter data and
the Conta execution
context
and now we're going to create a new user
entity here we have applied a user
decorator let's say this is this is
authenticated route only authenticated
user can access this route so I would
like to get the user so you can use a
user
decorator and the user entity this user
decorator is going to execute this
function and this function will be
executed and it is going to add a user
in the request EST object that's how you
can implement the custom decorator let's
create a new file here I can say a user
decorator
decorator. I'm going to copy my
code user
decorator you can use any name
here I also need to create another
entity this time I'm going to call user.
entity
TS now we're going to apply The
Decorator on a
user do I have a route I can create the
complete route to implement this user
decorator copy this and and paste it
here and we need these two
Imports now we have to test our
application so whenever you need to get
a user inside any function all you need
to do is to apply the decorator
here you can apply The Decorator upload
file you can apply decorator here it
depends on your use
case so my application is
running I'm going to create a new HTTP
client. HTTP file to send API
request can say that find
user only based on
ID we have to send the get
request 3,000 slash user and you got to
provide a user
ID now you can see I got a user so this
decorator a user decorator is calling
the user decorator function and this
function is getting a user or setting a
user to the request object and returning
the
request get decorator is nothing it's
just like a function here in our
case I'm running a function
here uh in this lesson I'm going to
teach you if you want to schedule any
method or any function you can do with
grown
task uh let's uh if you want to schedule
any task let's say you want to run you
want to
calculate the expiry date of a license
let's say your trial version is going to
be expired after 7 days You're Building
this type of SAS application you your
company provides 14 days free trial
and the trial version will be expired
after 14
days what your application will do under
the hood application will run a crown
task it will execute every day in try to
find out the expiry date for the current
user if user has used software for 14
days your Chown to will determine that
and it will send the notification to the
user into your application hey this user
has used 14 days free trial and you may
must have a logic or a code to handle
this
situation maybe you can send the credit
card information to
upgrade so nestjs provide a package to
implement this type of
functionality we're going to we're going
to we're going to install a couple of
packages first you
need next
JS
schedule
and you also need or I can install it
here
types of
grown actually I need a type as a Chone
SE as a Dev dependency let's first
install this package
now we
install the
types or I can use the minus
t and types
Chone NJ has provide a schedule
module from nestjs casual package I have
to import it if you want to use this
package let's import the module schedule
module I have to register it or create
this
module this root module will initialize
this casual
module and it will register any
declarative chrone jobs timeouts
interval that exist assist within your
application right now we did not Define
any Crone task if you have defined Crone
task this for root will initialize all
of your crown
task and registration occurs when the
application when the own application
bootstrap life cycle hook
occurs now we're going to declare some
cras this cronas will run the function
autom automatically we will specify some
specific dat time when this Crown task
will run it depends on your use case do
you want to run this Crown task every
week or every day or every 5 minutes or
every 10 minutes or every hour it
depends on your use use case now we're
going to create a new task
service let's create a new to
service
so let's define our first gr task in
task
service private read only logger it will
log some
message task
service do
name if you want to Define a crown task
you need a decorator in the previous
video I taught you what are the benefits
of decorator like I can extend the
functionality of a function by adding
the Chone
decorator here you will provide your
time path time date something like
that so start start
start you can learn learn more
about this strategy by looking at Crown
task schedu Nest or
npm
you can play around with these timing
settings from this package this package
you can learn more
about how can you set the current dat
stuff like
that here the first star
represent second the second star
represent minute the third star
represent R and the fourth star
represent the day of the month and the
fifth star represent the
month and the last star represent the
week
day did you get that let's say I want to
run the crown task after every 10
seconds so what I want to do I want to
log a simple message after every 10
seconds and say Myron
task I'm going to log a message this do
logger not a
throw this. logger do
debug called when the
current second is
10 let's try to test the
application I have registered the
schedule module here this for will will
initialize this method and we set up the
configuration to run after 10
second let's do
that
you can
see it has run this debug after every 10
seconds
what if I change the setting to
five
now after 5 Seconds it has
executed
e
actually it is running called when the
current second is actually it is wait it
will wait for 1 minute and 5 Seconds
then it will
run wait for 1 minute and 5 Seconds
is
now you can see at
519 and then it has ran after a minute
and on the fifth
second what if I run this cronas after
every
[Music]
second you can see it's running after
every
seconds so I can use
that called when the
crun C call that's
it so it will wait for a minute and a 15
seconds
if you want to do a little bit setting
let's say I want to run every hour at
the start of five uh at the start of the
fifth
minutes but it depends on you how you
want to run
this will
run
after
every
minute
yep after every minute it's
running
this is how you can play around with
crown
task in this lesson you're going to
learn cookies cookies are small pieces
of data dat a server sends to a user
browser while the user is browsing a
website these cookies are stored in user
device and are used to store information
about the user interaction with website
if you look up the Google Chrome you
will see the developer tools and you can
find the application
tab here you will find all of your
cookies if you have
stored we have only single cookie you
can Implement also cookie based
authentication just like we did in
authentication module we saved at
Json web token into a local
storage but if you were if you work with
a local storage or front-end application
you can store your Json web token in
this storage but you can also use a
cookie and you can save your token in
encrypted
format so these are all the use cases of
cookies like most of the time when
you when you access or fetch or look at
the same look at the website or when you
visit the same website again and again
the next time it tries to fetch the data
from your cookies it has saved all of
your
authentication Lo all of your password
in cookies when you go to the Google
password
manager where all of this data is stored
all of this data is stored in your cook
is remember when you look at the history
or let
me you look at the
history if you want to delete all of
your data it will also ask you hey do
you want to do you want to delete all of
your cookie stuff you have data inside
the
cookie so you can save any token inside
the
cookie let me talk about the use cases
of
cookies you can manage user sessions
let's say if you want to expire a user
session after 30 days or after 24
hours you can have that type of logic in
cookie and this cookie will be stored
here inside the application and the
cookies
tab if you have any type of shopping
cart application you can also do a
little bit saving in
the in the cookies let's say a user has
uh add added three to four items to the
checkout and he left the website and
then you can send user hey you left
something a user can see all of his
checkout
items you can do some type of tracking
and analytics you can do authentication
like cookies can help with
authentication and security by storing
tokens or other information that
verifies a user
identity you can use load balancing
State Management and cashing stuff with
cookies now I'm going to implement the
cookies in NS project you got to install
these two packages I have already
installed them
I've already installed in my
package.json file this is the cookie
parser you need and then you also need a
typing for cookie parser go ahead and
install
them all right our next step is to
register a cookie parts sir in main.ts
file this is our main entry file here I
have registered a cookie parser you can
import it as a
star and here if you want to add add
your secret you can do it here or if you
want to
add uh some logic or decode something
like that this is the option from a
cookie package you can go to cookie
parser so this package is similar to
this one this one cookie parser but you
can look at the documentation what type
of options you
have
now our next step is to set the
cookie I'm going to create a new route
to set the cookie and we need a response
from the nestjs comment and response
type from the Express package here I'm
allowing the framework you can set the
cookie I am I'm going to set the cookie
cooking token name encrypted cookie
string something here it's a key value
PA here and I'm sending a message cookie
saved
successfully here here I'm trying to log
all of your cookies and return cookies
in the get route now we need to test the
application when you look the app
controller here let's say I'm want to
set a new
cookie I've already saved that cookie in
my application when you look at the
Local Host colon application tab here we
have the cookie let's say I want to set
a new cookie it should be let's say a
user
token or authenticated token something
like that JWT
or
JWT encrypt something like
that yes jw.
iio so what I want to do I want to
so
let's can I do
that let's add this payload
here or you can say I want to add a user
ID let's
say
token I'm going to add a user
ID
let's say a mongod DB
ID or you can say user
ID so let's send the request from our
browser to first set the
cookie so I can set the request please
set the cookie cookie saved successfully
and you can see your user ID here this
one but it did not
encrypt but it did not save as
encrypted you have to save your
encrypted value here let's say I'm going
to copy this
token and you got to paste it
[Music]
here now I have an encrypted
value so cookie saved successfully what
if I try to get the
cookie get all of my
cookie it is going to give me the user
ID and cookie token
name that's how if you want to implement
cookie based authentication you can do
that if you want to implement High
intent intensive task then you need
cues High intensive task
mean sending emails generating reports
processing images or any task that can
be offloaded from the main application
flow with the help of cues you can
manage in process task in the background
without blocking the main application
execution
so you can use cues in task
generation when you you identify task
that can be processed
asynchronously let's consider sending an
email after a user register instead of
sending email directly with the
registration endpoint you can push the
task of a sending email to a
queue
so this task is executed in the
background separate from the main
application thread this this ensure that
the main application remains responsive
and does not get blogged by the time
consuming
tasks so if you have highly CPU
intensive task then you can use
qes let's dive into the implementation
of cues in nestjs nestjs provided the
bull package they have written their own
implementation by using the original
bull package you have to install the
package
first I'm going to install the nestjs
bll I also need to install npm B npm
install B the simple bull
package nextjs pull is using the redish
under the
hood so you need radish caching
Library make sure you have Docker in
your
system we're going to use Docker to pull
redish image I'm not going to install
redish separately so that's why I'm
going to use docker
now let's create a new module our
application what we want to do we're
going to create a fake implementation to
convert do wave audio file to MP3 we're
going to write fake implementation let's
say you have a use case where you want
to convert do wave file to MP3 or you
have an application where you need this
functionality you want to convert video
MP4 to MP3 in that case you need a
q
let's create a new audio module we're
going to write implementation here to
convert do wave file to
MP3 then we need a docket
compose we're going to use redish
image
now we're going to set up Ries in the
docket compose file let's create a new
file inside the root
directory I'm going to do it here docket
compos
yl let's rename it to
yl so we have to in start the docker
compose my Docker is running
now let's install Docker
compose
up it will pull the redish image from
the docker Hub but I have already pulled
Docker radish
image so my
radish server has
started I think I've already installed
another extension to work with redes if
you want you can install
that here you can see the redis I have
installed this one database manager for
my SQL Maria B post sqlite and redis
here you will see the database if I try
to create a connection for the
redes Local Host
6379 that's my port so I can connect now
now you will
see all of my
databases so this is my current or the
latest I'm going to delete the rest of
the
other now I have the empty let's remove
everything let's
connect so I have the audio
que so get rid of this
one now we have the empty data
SP now we need to
register a bull
module so in the app
module I'm going to register it
here your module
and I'm going to do it
here make sure you imported a bull
module bull
module
import from Nest
CHS SGS Bull and bull
module so I'm going to open a new tab to
run my
application next we need to register a
queue inside the audio module you will
find the audio module here so we got a
register it
here make sure you imported the bull
module and I'm going to copy
that and let me paste it
here so this register Q This method is
used to register a queue with your
within your application it takes an
optional object as an argument to
configure the que we have provided the
name of our Q audio
q and this is the name you will see the
name here
here it should be the audio Q this one
where is my redish
yep you will see the audio queue
here let's move forward now we're going
to create a convert end point I'm going
to copy
that into audio
controller and
I'm so we have audio Q let's imagine we
would like to convert v file into MP3
this is my I'm just writing the fake
implementation we are not writing the
exact logic to convert the file but you
can do that this is just a file name
this is an optional object so this will
add a new entry inside the
Q so we have injected the audio q i got
this Q from from The Bu package the type
now we need a processor to process the
queue let's define a new audio
processor audio.
processor. it would be a service or
provider so we got to register it here
inside the
providers
AIO
processor
so
here when you want to process this when
the application wants to process it is
going to call this handle convert this
job will take this argument as a job
here inside the audio
processor so I'm just trying to do the
log here let's run the
application to convert W file to m B3 we
have to send the convert request
so in the HTTP
client I'm going to send the post
request convert let's say dot v file to
MP3
post HTTP Local Host Callum 3000 SL
audio SL convert I don't need to provide
any argument but if you want to provide
argument or or request body you can do
that now you can see it has run
successfully I got this message starting
wave file inside the audio
processor here starting start converting
v file to MP3 and I got the object which
is sample. W file which which I have
passed here whatever you pass here it
will be received here inside the job.
data and finally it has completed this
one if you have any type of logic to
convert P file to MP3 you will Implement
here
here but what if I look up the
database do you have this
one convert yep you can see the bull and
we we have the audio Q this is our
message I can show
you here you can see the name is
convert which we named here the convert
this one q key key is here
convert
convert and the data is sample. W file
and all of these metad data
what if I provide additional data let's
say ID which is one so it is going to
save also
ID let's run the request you can see I
got the file and
ID and Let me refresh
it
I'm going to
connect uh you can
see file sample
do wave and you can see the ID the name
is convert and the audio CU which is we
have named here here inside the audio
module this is the audio
Q in this lesson I'm going to teach you
the event
emitter in nextjs event emitor is a
mechanism that allows different parts of
your application to communicate with
each other and even driven
approach so you can learn more about you
can do communication between module
Services components or classes under the
hood nestjs uses event emiter to
collaborate with these services and
modules and
components so an event emitter works
with Publisher and subscriber pattern if
you heard about this design pattern or
you have used this design
pattern now we're going to talk about
some practical use cases of event
emitter you can do module communication
you can send the notification
system we're going to use this use
case in the previous video we have
converted wave file to
MP3 now I want to convert I want to send
the notification if the file has
successfully converted we need to send
the notification to the user we can also
use from for Real Time updates if you
have any plugin syst system you can do
with the help of event emitter you can
achieve logging and monitoring you can
do error handling and Reporting this one
is also useful you can Implement in user
authentication and
authorization for example authorization
service could emit an event when user
logs in and other parts of application
can respond Accord accordingly let's say
user has logged after 10 days your you
can your system or your application can
have
notification you can also Implement in
the caching and management in our case
we're going to take example from our
previous
example let's say you want to send the
notification when w file converts
successfully into MP3 format you can use
event emitter to send the
notification
you got to install the package first
nestjs event
emitter and Next Step you got to
register the event emitter in the app
module let me change my
Branch
here
event emitter Pro
we got to create install event emitter
again because I was in a different
branch let's install
it we have event
emitter let's register it in the app
module I'm going to do it here
we have to import the event emiter
module I have to import it manually
event emitter
module from
nestjs event
emiter that looks good we have
registered the event emitter module this
will register all of your event listener
or or create all of your event listener
we will have audio converted
listener it's a service it's a
provider this we have just a method it
will accept the event and the audio
event we will create the type this is
the name of the listener or the name of
the event that's why I used on event
here when you emit the event this audio
converted event this function will be
called we're going to emit this event in
the handle convert in the previous video
we used this method to convert fave into
MP3 so when you emit this event this
method will be
called so you can have any type of logic
here maybe you will have an email
service and your email service will have
a method to send email let's create a
new file I'm going to copy all of the
code this is a provider we're going to
in we're going to create inside
the
audio
converted what's the name of the file
audio converted
listener I can say audio do
converted or you can say audio
converted
listener. so we have this
file we did not create this type let's
create this
type in audio
folder I can say
audio actually we can do it in an events
folder we're going to store all of the
types
audio converted
event. it's nothing it's just a type for
types typescript
class it looks good make sure you
register your provider in the audio
module so audio
converted
listener
now we need to import we need to emit
this
event in your handle convert we have
done it in the
processor while converted successfully
and you can send a
message make sure you
have import or inject event
emitter event emitter
event emitter
2 from njs event emitter
package
njs event
emiter
oops event emiter I don't know why they
use two so I'm going to use the same
stuff two event emitter
to and we have emit this
event this
one now we have to test the application
let's run the
application I think do I need a
Docker let's run the
application yes I need a
Docker let's install the uh let's start
the docker first because we were using
redes when we were building this Q so
this Q is dependent on bull module is
dependent on
rades let me start my
Docker now my Docker is running now
let's run the application to test this
event
emitor we have to send the API request
to convert fa file to
MP3 it should log the message actually
it should run this
event this
meth
let's send the
request I'm not able to send the request
why saying
waiting I think I did something wrong
here look at the audio
processor or audio
controller
wa I think it is not calling this method
or emitting this
method emitting this IM
event oh I think we did not stop part
that is
server let's do it I'm going to send the
request connect with
r
so it has X executed
successfully and I got the message
notification has sent to the user that
file is converted
successfully so I also loged the
event that looks good we have
successfully
achieved our desired use
case here it has emited the event I also
passed a data object from the Q job.
data which we were sending from here so
I received the same
object inside the event
listener here I received the same event
here and here I locked the event the
first one is the event and the message
notification has sent to user
successfully this is how you will
Implement event emitter in
nestjs in this lesson I'm going to teach
you the streaming in
sjs streaming is the process of sending
or receiving data in small chunks called
streams rather than sending or receiving
the entire data at once the concept is
based on stream API in
nodejs and is utilized for more
efficient data handling especially when
dealing with large amounts of data such
as files Network request or realtime
data
Transmissions you can use streaming for
file upload and file download you can do
realtime communication if you have to
build a media streaming type application
like Netflix then you need streaming
API API responses reading and writing
from
stream when processing data from sources
that generate data
incrementally such as reading log file
or parsing large XML or Json
documents you can do some data
aggregation server sent events database
operations proxy servers all of these
practical use cases of streaming in this
video I'm just showing you how to
download a file with the help of
streaming we need a nest controller a
file controller here I will
specify a a a method it will download
the file from this crun project as a
package.json file it is going to save in
my computer this is another customized
way to download the
file when you download the file with
this method it will download the exact
package.json file here it will not
download with extension only text file
let me show you the difference between
them let's create a new
controller open the file controller let
me import some
dependencies and we need to use this
method to download the file I'm going to
create a new method here let's run the
application let's try to send the
request to the
file file we have the endpoint file and
the stream
file file and stream
file now it is going to
download the package.json
file you can
see it is giving just only a stream file
it did not download with package.json
file if I open the file you will see it
is nothing more it's just a simple text
file in a Json
format but we going to we want to
download the exact Json file you can do
the same stuff when you down when you
want to download
images or video you have to specify here
the content type should be video or
audio it depends on your use case and
you also can provide the name of your
file just like we did the package.json
file you have to do it content dispo dis
disposition now we're going to copy the
same part method and place it
here it will return a streamable file I
have created the stream by you joining
the path which is this one I'm referring
to package.json file
file and finally I'm setting the
response by setting application Json my
file name would be this one act as the
attachment and finally it is going to
return the streamable file now if I go
to this
endpoint file and/ stream file
customize what will
happen now it is going to do stream file
customize. Json on not not it should be
Json now it is going to see you will see
the package.json file I already
downloaded the package.json file when we
were when I was practicing this I can
replace that you will see the
package.json
file I have opened the file in my
Mozilla
Firefox you can see your the package
Json file we have scripts we have all
the dependencies and we have the dev
dependencies this is how you can
download any file if you have images you
can specify your image format or you can
name the file name or your image file
name you can also set your image content
type in this lesson you're going to
learn this session in
sjs session refers to the concept of
maintaining stateful data between
consecutive request from the same client
a session allows you to send allows you
to store and retrieve user specific
information on the server server on the
server across multiple request typically
using cookies to identify the session if
you have used session based
authentication in your project the
concept is
same you can use session to maintain the
authentication state of a user when a
user log in logs in session can be
created with their authen authentication
data and subsequent request can be
authenticated based on the session you
can use session in authorization user
preferences shopping cards user tracking
caching
personalization and form data
persistence we going to use the express
session let's install these two
packages I have already installed in my
package.json
file
session Express session and the next
package you need type of Express session
then our next step is to register a
middleware when you go to main.ts you
got to register it
here AB do session make make sure you
import your session from the express
session you can use any secret key you
can also set resave you can read the
documentation of resave what this resave
is doing you can also read the
documentation of save
uninitialized you can find documentation
here from the express
session when you check a save or
resave here you will find the
documentation
uninitialized initialized you can also
find the documentation of
uninitialized next we have app
controller here I'm going to create a
simple route to login let's say uh a
user wants to log in when logged in
successfully we have verified the user
from the database then you can set the
user into the session I have set the
object ID and the username and when
later user wants to access his profile
he can do that because we have saved the
user in the session so here if there is
a user in the session it is going to
return user else not logged in you can
test it simple by sending the login
request it is saying a user has logged
in just like we did just like it did if
I said if I try to retrieve the profile
it is going to give me the profile
because we have set that user when we
were logged in this one now I got this
hello with the user and the name this is
how uh if you use Json web token we
basically stored a Json web token in the
storage but if you want to use session
based authentication on front end you
can do that
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.