✨ Basics
Services

Services in AdonisJS

Services in AdonisJS

Services in AdonisJS encapsulate business logic and enable interaction between controllers and models. They help keep your codebase organized by separating concerns and promoting reusability.

Creating a Service

Services are typically created manually by defining a new file in a designated folder, such as app/features/services.

Example AccountService

Here's an example of an AccountService that interacts with a User model and uses a validator to update user information.

app/services/AccountService.ts
import User from "#common/models/user";
import { UpdateUser } from "../validators/account_validator.js";
 
export default class AccountService {
  async updateUser(user: User, payload: UpdateUser) {
    user.name = payload.name;
    user.surname = payload.surname;
    await user.save();
  }
}

Service Methods

  • updateUser: Updates the name and surname fields of a User based on the provided payload (UpdateUser). This method uses the save() method from the User model to persist changes to the database.

Usage in Controllers

Services are commonly used within controllers to delegate complex operations and maintain separation of concerns.
Important! Services are injected into controllers using the @inject() decorator. This ensures that the service is available to the controller.

Example Usage in a Controller

app/account/controllers/AccountController.ts
import { HttpContext } from "@adonisjs/core/http";
import User from "#common/models/user";
import AccountService from "../services/AccountService";
import { updateUserValidator } from "../validators/account_validator";
import { inject } from "@adonisjs/core";
 
@inject()
export default class AccountController {
  private accountService: AccountService;
 
  constructor(accountService: AccountService) {
    this.accountService = accountService;
  }
 
  async update({ request, auth, response, session, logger }: HttpContext) {
    try {
      const payload = await updateUserValidator.validate(request.all());
      const user = auth.user as User;
      await this.accountService.updateUser(user, payload);
      session.flash("toast", {
        type: "success",
        message: "Your account has been successfully updated"
      });
      return response.redirect().toRoute("dashboard.account");
    } catch (error) {
      logger.fatal(error);
      session.flash("errors", "An unexpected error occurred, please try again later or contact support.");
      return response.redirect().back();
    }
  }
}

Benefits of Using Services

  • Encapsulation: Business logic is encapsulated within services, promoting code organization and maintainability.
  • Reusability: Services can be reused across different parts of your application, reducing code duplication.
  • Separation of Concerns: Services help separate business logic from presentation and data access layers, improving overall architecture.

See more

Using services in AdonisJS allows you to manage complex business logic in a structured manner, enhancing the maintainability and scalability of your application.