Best way to create GraphQL API ?? | NestJS GraphQL Tutorial
In this video I walk you through how to create a new GraphQL server and API from scratch utilizing the NestJS framework. This is in my opinion one of the best ways to do it!
We'll also cover multiple topics including database integration with TypeORM, queries and mutations, validation, as well as some techniques to help you develop these as FAST as possible!
00:00 - Intro
00:47 - What we'll build
02:23 - PART I: Generate project
04:23 - Generate Pets module
05:27 - Code first vs Schema first
07:29 - GraphQL Module import
07:47 - Creating Pet Object Type
11:24 - Writing our first query within the resolver
14:18 - Testing our new query
15:32 - PART II: Database Integration
18:00 - Pet database entity
20:02 - Update PetsService to use database
22:13 - createPet implementation
24:41 - Writing an Input Type
26:46 - PART III: Mutations
30:35 - Validation setup
34:21 - Implement findOne query
37:28 - How to auto generate all the boilerplate
40:13 - Owner database entity
40:59 - Implementing Pet/Owner relationship
44:28 - Ability to add owner info along pet query
47:46 - Implementing query to get pet owner
52:19 - Conclusion
52:58 - Outro
Пікірлер: 246
00:00 - Intro 00:47 - What we'll build 02:23 - PART I: Generate project 04:23 - Generate Pets module 05:27 - Code first vs Schema first 07:29 - GraphQL Module import 07:47 - Creating Pet Object Type 11:24 - Writing our first query within the resolver 14:18 - Testing our new query 15:32 - PART II: Database Integration 18:00 - Pet database entity 20:02 - Update PetsService to use database 22:13 - createPet implementation 24:41 - Writing an Input Type 26:46 - PART III: Mutations 30:35 - Validation setup 34:21 - Implement findOne query 37:28 - How to auto generate all the boilerplate 40:13 - Owner database entity 40:59 - Implementing Pet/Owner relationship 44:28 - Ability to add owner info along pet query 47:46 - Implementing query to get pet owner 52:19 - Conclusion 52:58 - Outro
Everything you need to know about Nest exists in your channel. Amazing tutorials. Thank you
Nice video like always, thank you ! For the guys who have this error with findOne(id), it doesn't work anymore, it's findOne({where: {id:id}}
@mariusespejo
2 жыл бұрын
Thanks! Yeah that syntax changed slightly in typeorm 0.3
I was a bit put off by the length of the video because I really just needed to brush up a bit. But I'm glad I watched it in its entirety. Thanks a lot, very nicely explained, helped me a lot!
I'm coming into NestJS new for a GraphQL solution, this is a great quickie to get things off the ground, appreciate it.
Good content. Simple and straightforward but extremely accurate and informative. It's hard to find a guide to anything in programming without a lot of dodging these days.
Thanks, Bro. Your tutorial has made my life easier trying to figure out how to implement GraphQL with NestJs.
I just want to say, thank you so mush for curating this amazing video.
@mariusespejo
3 жыл бұрын
no problem glad you found it useful!
Awesome as always! Loving the Nextjs / TypeOrm content
@flogginga_dead_horse4022
3 жыл бұрын
nest, next is a whole other story lol
Your walkthroughs are gold, thank you sir!
You are the master of nestjs on youtube
@mariusespejo
Жыл бұрын
Nah, lots of great content creators out there haha but I do hope that people are subscribing based on my teaching style
Hello Marius, Thank you very much for this great tutorial. The flow of the tutorial is so nice and easy to follow as well the way you introduce advanced scenario is really great. I admit this is the number one tutorial I have ever seen on KZread.
@mariusespejo
Жыл бұрын
Thank you for your feedback, glad you found it helpful 🙂
I'm glad it's comprehensive but on point with explanations.
Just started watching the video and you already cleared up some things for me in my mind. Can't wait to check out more of your content.
amazing, still relevant in 2024! thanks mate!
@mariusespejo
2 ай бұрын
Thanks! Good to know, I was thinking of maybe doing a refresh of this with current versions
@ViciuSRO
2 ай бұрын
@@mariusespejo will be amazing to include DataLoader topic as well
calm and collected, very good course ! looking forward for a more detailed and complete Nestjs course (paid why not) :) great job
@SpyingCraft
2 жыл бұрын
lols ap karwalein paid :)
i mean seriously brother you are a god level teacher everything you have explained is so straight forward... you explain every thing you are doing thank so much for this wonderful concept thank you so much , I hope you got many views and you grow faster thank you so much brother...
@mariusespejo
2 жыл бұрын
Thank you Raj 🙏 appreciate your support!!
That pretty much all I ever wanted and needed to get start modifying pre-made projects using this amazing tech Thank you so much
This is a great tutorial. Thank you so much for sharing it. It's really helpful for me, and I think it's also suitable for other people who are looking for more details on working with GraphQL + Nestjs. Thank you
Just finished. Loved your way of teaching, thanks brother
Great tutorial. Pretty simple and chilly explenation of basics.
Thankyou for the tutorial. Very helpful. I was wondering if you could share the repository of the code in the video, it would be much more impactful.
Your channel is a godsend
your subscribers should be wayyy up man.
@mariusespejo
2 жыл бұрын
Thanks 😄 still growing! Just takes time.. hope you’re one of them!!
Very useful, easy to follow along. Thanks. Looking forward to see more graphql content 😀
Marius, thank you for the video - it was very helpful! I'm just started learning NestJS, TypeScript and GraphQL concepts. And there you explained a lot. So your video worked as amazing starter boost for me :)
@mariusespejo
Жыл бұрын
Glad it was helpful!
This tutorial is AWESOME !!! Thank you Marius.
This is awesome content! Looking forward for more NestJS!!
@mariusespejo
2 жыл бұрын
More in the channel!
In Implement findOne query, use {where:{id:id}} as argument otherwise it will not compile.
Awesome man! There are lots of information. Thanks a lot ❤️
Good job ! It was very helpful ! Keep creating great content like this one
@mariusespejo
2 жыл бұрын
Thanks!!
Whats up Marius! There has been big changes in NestJS GraphQL. The GraphQL library is now a plugin which means you can use Mercurius instead of Apollo. What makes this really exciting is that just a few hours ago an update was merged that allows Mercurius subscriptions with federation! Something that is not possible with Apollo.
@mariusespejo
2 жыл бұрын
Interesting thanks for the heads up, I might make a newer follow up to this video, it’s getting a bit dated lol
If anybody getting error on 'npm start:dev', you should install 'graphql@^15' graphql version 16 does not work for this tutorial! Thank you for this video Espejo!
@mariusespejo
2 жыл бұрын
Yup, you can track the update required to allow v16 here: github.com/nestjs/graphql/pull/1834
@wealthifyme9738
2 жыл бұрын
thanks for saving the day!
Do we need circular dependencies? Isn't it something we should avoid? I mean if you also would like to query owners with their pets, we have to have a circular dependency. Owner service needs pet service and pet service needs owner service, right?
@mariusespejo
Жыл бұрын
If you can avoid it you probably should, but like you mention there are cases where you can’t avoid it when the relationships of your data are naturally circular. There is a documented way to resolve this in Nest, see: docs.nestjs.com/fundamentals/circular-dependency
Гигант мысли, In this video i find answers on all questions
Thanks sir! Would happily pay for some more advanced NestJS courses
@mariusespejo
Жыл бұрын
Thanks for the thought! I have been thinking about putting something together
at 15 min video you are running a video for pets query but you have not imported GraphQLModule in app module
Thank you, it inspired me, how to refactor one of my apps.
Can you share the repo Link of this demo project ? It can be helpful
Really helpful, thanks for doing this!
@mariusespejo
2 жыл бұрын
No problem!
Great video Bro! Thanks a lot, it was all explained very well and easy way you can't imagine how much its good for me thanks
@mariusespejo
2 жыл бұрын
Glad to help!
Pretty good! Keep it going sir!
Love your videos, keep it up m8.
@mariusespejo
3 жыл бұрын
thanks man, appreciate it
thanks for this journey. the content was useful and great for me
@mariusespejo
3 жыл бұрын
I’m glad you think so, thanks for stopping by to comment 🙏
Awesome tutorial subscribed and shared with friends, thanks!
@mariusespejo
3 жыл бұрын
Thank you! Appreciate the support
Thanks brad marius, Husay!
Perfect tutorial👍
It's Awesome 👍
Hello Marius, thanks for the great tutorials. What do you use to create that sparkling effect when typing on your terminal?
@mariusespejo
3 жыл бұрын
thanks! it’s the hyper terminal and it’s just one of the default plugins for it
great video and easy to understand! pretty nice for GraphQL beginners btw i wanna say nest cli is so strong
@mariusespejo
3 жыл бұрын
thanks James! I appreciate the feedback
Great video
Awesome! Really helpful!!
Better than any one in udemy 👍 plus, it's free
Nice video! Thx!
Very good, thanks!
Cool and useful! Thanks!
Excelent tutorial
you got a new sub
Does anyone has issue with starting app ? It shows error 'ReferenceError: globalThis is not defined'... something related to graphql-tools ??
What would a many-to-many relationship look like?
@mariusespejo
2 жыл бұрын
For typeorm? I have a relations vid on typeorm in the channel if you look
Hello, I'm struggling to customize response error/success when using nest-graphql do you have some resources/videos I can learn from?
@mariusespejo
11 ай бұрын
You need to throw http exceptions from nest, and those should be automatically caught & converted to apollo exceptions Look here github.com/nestjs/graphql/pull/1292
Great video man! Thanks a lot, it was all explained very well
great man
Thank you so much :)
Great one. but I have confusion about @ResolveField() decorater can please explain this decorater
@mariusespejo
2 жыл бұрын
It’s meant to resolve a nested field, e.g. if you had a resolver for books, within that you might have the ability to resolve the author of each book
Thank you Marius
@mariusespejo
2 жыл бұрын
You’re welcome!
really good tutorial. do you have a sample for pagination ?
@mariusespejo
Ай бұрын
Thanks! I don’t think so I do but I recommend first understanding the different approaches outlined here: graphql.org/learn/pagination/ Then depending on the approach you take, setting up the inputs to map to whatever your database requires, e.g. take/offset
Can anyone post Mutation updateOwner code for Owner Resolver and Owner Service.
Awesome tutorial 🔥 Make Nestjs course for beginner to advance in 2024 tutorial and also on the same topic 💚 Thanks a lot
@mariusespejo
4 ай бұрын
Thank you, yes hoping to produce more
@iUmerFarooq
4 ай бұрын
@@mariusespejo Make tutorial on Nestjs guard I know what is guard but I don't know how to implement that in practical projects. I am actually learning Nestjs for the first time.
@mariusespejo
4 ай бұрын
I did, if you look in the channel I have videos about nestjs authentication and authorization, which is what you would use guards for
@iUmerFarooq
4 ай бұрын
@@mariusespejo ok ok please answer my last question. How much Nestjs should I know to do job. I am already doing job in database mssql related so I am learning NodeJs/Nestjs I just want to know how to make restapi with validation. What more should I learn. I am actually confused is what kind of projects I will build, and how it is used in market like I will making authentication and authorization Al the time or making api most of the time. I hope you understand.
@mariusespejo
4 ай бұрын
Not a simple answer, because every job is different. However generally you need to have backend development fundamentals.. Nest is just a tool to help with that. Understand how to create basic REST APIs and how to do CRUD with a database… that is pretty much the main thing. Beyond that depending on your job there maybe other skills like validating requests, auth and maintaining user sessions, working with files (e.g. download/upload), caching, scaling & performance, security, etc.. However most of those things you can also learn on the job, as needed
hi mate thanks for your very informative videos do you have any idea if i can upload/download images using a dockerized nestjs application with graphql.i cant find any resource online to help me.will my images be uploaded in the container?Thanks in advance.
@mariusespejo
2 ай бұрын
You first need to understand the different approaches, then decide on where to store it, e.g. in a dedicated storage something like s3 and not in your container I recommend spend some time reading about it wundergraph.com/blog/graphql_file_uploads_evaluating_the_5_most_common_approaches
why you inject repository you can direct import Owner and do Owner.create(...) also after it you can do Owner.save(x) or direct do x.save()
@mariusespejo
2 жыл бұрын
I suggest reading about Data Mapper vs Active Record patterns, in Nest specifically it is recommended to use Data Mapper with the repositories
Amazing!
@mariusespejo
2 жыл бұрын
Thanks!
Thank you for example. I would like to know how did you Update and Delete data using Graphql ? I can't see any example here. Did I miss them ?
@mariusespejo
2 жыл бұрын
You would use mutations to provide that intent, then it’s up to your resolvers how the update/delete is performed
@Marius, Thanks for the great content. I have a query regarding Microservice Architecture with GraphQL API Gateway. The question is. How would i communication from GraphQL API Gateway to my service (HTTP or Message Queue) and how Service 1 would communicate with Service 2 (HTTP or Message Queue). Which one is the preferred way ? (HTTP or Message Queue).
@mariusespejo
2 жыл бұрын
I mean what your transport layer is between services or how you do it is up to you based on your own requirements I’m not sure I can answer that for you. Nest however has support for both request-response and event-based models, which should cover most typical use cases… e.g. I would imagine your queues by design won’t respond right away so communication via events probably makes sense
Is there a way to generate Swagger documentation off GraphQL Schema? If yes, can you create a tutorial for this? Awesome tutorial by the way!!
@mariusespejo
3 жыл бұрын
Thanks! You wouldn’t really typically use swagger for graphql, instead you’d use something specifically designed for graphql like the playground. You need something that allows you to explore the schema, as a form of documentation, and I don’t think swagger would be good for that purpose. It’s more for traditional rest APIs where you’d instead explore endpoints rather than one big schema
Anyone know what that extension in the terminal is?
Thanks amazing content 👌
Nice tutorial
How can you use or Have you used MongoDB in NestJS and GraphQL using TypeORM?
@mariusespejo
2 жыл бұрын
Typeorm does have some mongo support, check out the docs. You can also use mongoose with nest
@cruzergo
2 жыл бұрын
@@mariusespejo I am more interested in using Typeorm than mongoose. Will let you know how that goes.
@Marius what is your Vscode theme? I like it
@Marius can you share the github repo for this code ?
Hi Marius, great video! Does it still need 'graphql-tool' as dependency? I don't see it in the list of dependencies anymore in the official documentation of NestJs.
@mariusespejo
3 жыл бұрын
That dependency doesn’t ring a bell to me and perhaps I am misremembering but I don’t remember mentioning that in my video here. Anyways I would assume that the official docs is the source of truth, if it’s not mentioned there then I would assume no
Can you please create video how someone can protect graphql query based on my certain user role/permission? . Like a user with a role can only query but not create. It was very simple to do with REST api using Guards.
@mariusespejo
2 жыл бұрын
It should be mostly the same in graphql, couldn’t you simply add guards to your resolver methods?
@CJMFitnessJourney
2 жыл бұрын
@@mariusespejo I tried, but I wasn't able to get custom metadata from reflector. It was being undefined. But anyway I got it another way by creating global middleware and conditional checking req.body.operationName :)
@mariusespejo
2 жыл бұрын
Could maybe be an issue with how you’re registering your guard? The reflector usually should be injected automatically, but anyways I haven’t tried with graphql will give it a shot sometime
this is great
i want hearts while typing too. Where is your console theme guide?
struggling to get the pets of owners with graphql inverse relation. how can we do this? I am getting the circulation dependency error
@mariusespejo
2 жыл бұрын
I have a dedicated video on typeorm relations in the channel, might help you
@programmingdoze7025
2 жыл бұрын
@@mariusespejo Thankyou for your reply. we can load the relations in typeorm. but I want to do with @ResolveField() decorator. can't we use @ResolveField at both sides of resolvers?? here in video you have used @ResolverField() to get the owner of pets. Now i want to get the all the pets of the owner using @ResolverFiled at Owner Side. Can we do that in nestjs graphql??
@mariusespejo
2 жыл бұрын
Oh I’m sorry, I misunderstood your original question. Yes you can do that and yes you would need ResolveField on the other side. I would suggest removing the circular dependency by giving your owner service/resolver direct entity access to pets, e.g. via TypeormModule.forFeature([Owner, Pet]). But if you don’t like that you can try the documented solution for circular dependencies here: docs.nestjs.com/fundamentals/circular-dependency
@programmingdoze7025
2 жыл бұрын
@@mariusespejo Thanks
Hi there! I'd like to ask a question regarding the @Args in getPets query. The @Args states that it is taking in an 'id' of type Int but it seems there is a second declaration of id:number? Why is that so? Thank you in advance!
@mariusespejo
2 жыл бұрын
The Int is representation of the Scalar type for graphql. In javascript there isn’t really an “integer” type only number, so we’re basically saying that Int scalar in the graphql model maps to a number type in javascript. Hope that helps!
helo, this is a good video to get start on nestjs with graphql, when i keep move on, i try to do pagination in query. is there any tutorial can know more on it?
@mariusespejo
2 жыл бұрын
I don’t think I have one myself but it really mostly requires two things: one is you need to know how to do pagination with your ORM/database, for example with typeorm you can use limit/offset properties in queries. Two is you need to know how to add additional params to your graphql query request (basically inputs) which I believe I did cover in this video. You would basically need to have inputs for page/limit and feed that into the ORM query limit/offset
Epic video, thanks so much! Is there any way to use the entity model when creating the input type? Sort of like in Typescript you can do Pick, or Omit? There seems to be a doubling up of declaring the fields in the entity and input type that is not so DRY.
@mariusespejo
2 жыл бұрын
Yup there’s support for something like that, take a look at mapped types: docs.nestjs.com/graphql/mapped-types But also something to think about, while there is some duplication, the input type and the entity have somewhat different concerns, e.g. the input types can be utilized for validation
@oldo-nicho
2 жыл бұрын
@@mariusespejo thanks! Will take a look
Thanks
Dude, how did you setup that caret effect? I want it too!
@maksimzolotoi3379
2 жыл бұрын
@@mariusespejo cursor when you type something. Pink with effects )
@mariusespejo
2 жыл бұрын
On the terminal? That’s the hyper terminal and that effect is just one of the default plugins
@maksimzolotoi3379
2 жыл бұрын
@@mariusespejo Thanks )
offtop question: @Marius what MacOs Terminal plugins or app do you use? looks awesome!
@mariusespejo
2 жыл бұрын
In my older videos (probably like this one) I messed around with hyper, which is a hackable terminal. Nowadays I mostly keep it simple with iTerm2 and oh-my-zsh with auto complete and syntax highlighting
How do you get that animation on your cursor in terminal?
Nice
Can you make tutorial on NestJS with Prisma ORM and GraphQl
@mariusespejo
2 жыл бұрын
My teamseas video covers all of that if you’re interested
In your example you were able to show the owner data when querying for a pet. How do you implement this for the other way around? I tried exporting PetsModule and importing in OwnersModule to do a Pet search via OwnerId via PetsService but I got a "A circular dependency between modules." error.
@mariusespejo
3 жыл бұрын
Nest has docs on how to deal with circular dependencies: docs.nestjs.com/fundamentals/circular-dependency The other alternative is to simply add the other entity to the module, for example if you had: “TypeOrmModule.forFeature( [ Owner, Pet ])” in your module, then the service within that module can inject the repository for both entities without relying on a module dependency. Although in theory if you were utilizing relations properly (for example with the find API) I don’t think you even need to do any of that, e.g. you should be able to do something like: this.ownersRepo.find({ relations: [‘pets’] }); // returns owners with their pets That should work if all you need is to read/join the relation. I believe that’s covered in my video here
@mariusespejo
3 жыл бұрын
Actually I misspoke, not in this video but, I have another video in my channel specifically on TypeOrm relations which covers that topic in detail. Maybe check that out
@mariusespejo
3 жыл бұрын
kzread.info/dash/bejne/pH-bvK6Pl8fccbw.html
Great tutorial, but I'm running into a "Circular dependency" error when implementing the { owner: pets {...} } query.
@herberthenrique3898
2 жыл бұрын
I have the same problem
코딩 잘하네요👍
hey great tutorial, I followed and everything worked until the end. Instead of pets, I changed it to planets and instead of owners, I changed it to factions...but everything else is the same. Getting an error code that says, " Entity metadata for Planets#faction was not found. Check if you specified a correct entity object and if it's connected in the connection options." Uploading it to Github anyway lol
@mariusespejo
3 жыл бұрын
I would suggest double checking your ormconfig, specifically the entities property. Make sure you have the right string there which is able to find all your entities
anyone help me how to implement logic code at 52:19 ?