-
Notifications
You must be signed in to change notification settings - Fork 0
providers
With this chapter, if you want to follow along, check out the providers-start
branch, then continue to the following along section.
If you just want a final version of the project as of the end of the chapter, check out the providers-end
branch, and proceed to the Upon completion section.
In this chapter, you'll basically follow along with the official NestJS Docs Providers chapter, editing and adding to the code from the providers-start
branch. This is a pretty straightforward chapter. There are a number of code fragments for illustration purposes, but only a few parts that contribute code to our "nest cats project mainline".
Refer to the comments below, corresponding to chapter sections, to guide you through the code changes for nest cats as you proceed through the docs chapter.
In the Services section of the docs, create the cats.service.ts
file in our newly organized src/cats
folder (as described at the end of the Controllers chapter), pasting in the code from that docs section.
For the Cat
interface, create a folder in src/cats
called interfaces
, and put the code in src/cats/interfaces/cat.interface.ts
.
For the CatsController
, rather than completely replacing the contents of the existing file with the code in this section of the docs, update just the POST /cats
and GET /cats
endpoints, leaving the other endpoints from the previous chapter intact.
You'll also need to:
- import the
CatsService
and add a constructor to inject it (as shown in the docs). - import the Cat interface you just created
Continue reading until you reach the Provider registration section.
In the Provider registration section of the docs, make the update to the src/app.module.ts
file, as described. If you've been following along, your AppModule
will look a little different than what's shown in the docs. Unlike the docs sample, we still have an AppService
and AppController
hanging around; we'll deal with them later, so leave them be for now!
You now have a functioning app that calls an injected service provider. As usual, you can either proceed to test using your code or, if you've run into any issues, no worries: you can checkout the providers-end
branch to get caught up with the mainline nest-cats code as of the end of the Providers chapter.
You should now be able to test the app with some REST requests. Make sure the app is running with either npm run start
or npm run start:dev
. I recommend the latter, as it will watch for code changes and recompile automatically as you make changes.
If you've installed HTTPie, you can now test the routes by pasting the following commands at your OS command prompt.
Create a cat
http POST :3000/cats \ name=Fred \ age:=3 \ breed='Alley Cat'
This should return a 201 Created
HTTP status. You can repeat this several times to add a few cats if you want.
Get cats
http GET :3000/cats
Next up is the Modules chapter.