A developer builds a custom, injectable HTTP service in NestJS using Axios. The process involves creating an HttpService to manage a singleton Axios instance, defining request configurations, implementing convenience methods for HTTP verbs, and setting up a dynamic HttpModule for global registration and dependency injection.
Length 11:29
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #nestjs #axios #http-service #dependency-injection #typescript #web-development #software-engineering #coding #programming #module-configuration
0:00 All right, so before moving on, I wanna rename Resilient HTTP, 0:04 make this more generic, like a real world production 0:07 application. We'll just call this HTTP, 0:11 and also rename this http.types. 0:16 And same thing for the module, I wanna rename this to 0:19 HttpModuleOptions, 0:21 and then go back to the factory and just make sure we have swapped this 0:25 out for 0:25 just regular HTTP. I like this naming better. 0:29 And now what we're gonna do is set up our own custom HTTP 0:33 injectable service that we can then reuse elsewhere inside of 0:37 our 0:37 NestJS application, and we'll have this Axios instance 0:41 created inside of it. And as we know, our NestJS 0:45 services are always singletons, so this is a very good use case for it. 0:49 We only need to set up Axios once, and then reuse the instance whenever 0:53 we need it in the app. So for this, let's go ahead inside of 0:57 HTTP and create a new 0:59 http.service.ts file. Inside, 1:04 I'm gonna mark this with @injectable, which is NestJS 1:08 way to mark a provider which will allow us to inject it 1:11 into other classes. So we'll call this the 1:15 HttpService. And inside, I want to now 1:18 declare a member variable, which is going to be our 1:22 instance of Axios that we're going to keep hold of inside of 1:26 this 1:26 singleton. And then inside of the constructor, we 1:30 are going 1:30 to now get access to the private readonly options. 1:34 This will be our HttpModule options. 1:38 And I'm gonna show you how to wire this in into our root app 1:42 module so that we can actually provide these options in a dynamic 1:46 way, which will be very useful. Now, if you get some error here 1:50 with TypeScript, make sure that you go back to your 1:53 tsconfig.json and set your isolated 1:57 modules to false and remove base URL.
The rest of the transcript is for members.
Sign in