Extending Services
In SolidX, services are responsible for implementing business logic and handling data manipulation.
By extending services, you can introduce custom logic that goes beyond the default CRUD behavior provided by SolidX.
This is especially useful when:
- You want to add domain-specific operations (e.g., activating a portal, sending notifications).
- You need to encapsulate logic that should be reused across multiple controllers.
- You want to keep your controllers thin (focused on request/response) while moving logic into services (focused on business rules).
Why Create Service Methods?
Creating methods inside services provides several benefits:
- Separation of Concerns → Business logic resides in services, keeping controllers simple.
- Reusability → The same service method can be reused by multiple controllers or scheduled jobs.
- Testability → Service methods are easier to unit test compared to full controller logic.
- Consistency → Centralized service methods reduce duplication across your codebase.
Adding a New Method
To add a new method to an existing service:
- Identify the service you want to extend.
- Add a method in the service class that implements your business logic.
- Update the corresponding controller if you want to expose this functionality via an API endpoint.
Example: Add activateInstitutePortal to InstituteService
activateInstitutePortal to InstituteService@Injectable()
export class InstituteService {
constructor(private readonly instituteRepo: Repository<Institute>) {}
async activateInstitutePortal(ids: (number | string)[]): Promise<any> {
// Example: update the status of multiple institutes to "Active"
await this.instituteRepo.update(
{ id: In(ids) },
{ portalActive: true, activatedAt: new Date() }
);
// Example: trigger a domain event or send notifications
// await this.notificationService.notifyAdmins(ids, 'Institute portal activated');
return { success: true, activatedIds: ids };
}
}
This method encapsulates the logic required to activate an institute’s portal.
It could include database updates, event publishing, or notification sending.
Using Service Methods in Controllers
Once you’ve created a service method, you can call it from a controller endpoint.
This keeps the controller lightweight while delegating heavy logic to the service.
See the Extending Controllers guide for details on adding endpoints.
Example: Connecting activateInstitutePortal to InstituteController
@ApiBearerAuth("jwt")
@Post("activate-institute-portal")
async activateInstitute(@Body() ids: (number | string)[]) {
return this.service.activateInstitutePortal(ids);
}
Here, the controller method simply delegates to the service method, ensuring a clean separation of responsibilities.