Performance: Service creation
Service creation affects initial application startup time and memory usage, impacting how fast the app becomes responsive.
import { Injectable, OnModuleInit } from '@nestjs/common'; @Injectable() export class HeavyService implements OnModuleInit { private initialized = false; async onModuleInit() { // defer heavy logic asynchronously await this.lazyInit(); } private async lazyInit() { if (!this.initialized) { // heavy initialization logic this.initialized = true; } } } // In AppModule providers: [HeavyService]
import { Injectable } from '@nestjs/common'; @Injectable() export class HeavyService { constructor() { // heavy initialization logic } } // In AppModule providers: [HeavyService]
| Pattern | Startup Delay | Memory Usage | Responsiveness | Verdict |
|---|---|---|---|---|
| Eager heavy service creation | High (100+ ms) | High | Slow initial response | [X] Bad |
| Lazy asynchronous service init | Low (10-20 ms) | Moderate | Fast initial response | [OK] Good |
What is the main purpose of creating a service in a NestJS application?
Which decorator is used to make a class injectable as a service in NestJS?
@Injectable() marks a class as a provider that can be injected.@Controller() is for controllers, @Module() for modules, and @Service() does not exist in NestJS.Given the following service code, what will be the output when getHello() is called?
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
getHello(): string {
return 'Hello, NestJS!';
}
}getHello() returns exactly the string defined, no errors or undefined.Identify the error in this service code snippet:
import { Injectable } from '@nestjs/common';
@Injectable()
export class MathService {
add(a: number, b: number) {
return a + b
}
}add correctly takes two numbers and returns their sum. Semicolons are optional in TypeScript.You want to create a service that provides a list of users and inject it into a controller. Which of the following is the correct way to create and inject the service?
1. Create service with @Injectable()
2. Define a methodgetUsers()returning an array
3. Inject service in controller constructor
4. Use service method inside controller method
Pass the test and this pattern moves unknown