Skip to content

Service Layer

Purpose of the Service Layer

The Service Layer acts as a crucial bridge between the frontend UI and backend data sources. Its primary responsibilities include:

  • Making HTTP requests to APIs and processing responses.
  • Managing data transformations and state updates.
  • Encapsulating backend logic and maintaining separation of concerns.

Structure of a Service Class

A Service Class in our applications should follow a structured approach:

Using Route Getters

  • Base API Path: Utilize routeGetters for defining base API paths. This approach simplifies the management of endpoint URLs and enhances maintainability.
const routeFactory = (path?: string) => {
return `software-tracking${path ? '/' + path : ''}`
}

Methods

  • Typed Methods: Ensure that all methods in the Service Class are properly typed. While the return type for some POST requests can be omitted if the client does not rely on the response, it’s generally good practice to maintain type consistency.
class ExampleService {
async getSoftwares(
query: SoftwareQueries,
): Promise<NonPaginatedAPIResponse<SoftwareListResponse[]>['data']> {
const params = {
search: query.search ? query.search : undefined,
filter_category: query.filters.filter_category || undefined,
filter_software_type: query.filters.filter_software_type || undefined,
}
const res = await apiAxios.get(routeFactory('list'), {params})
return res.data?.data
}
async postData(data): Promise<void> {
// Post data implementation
}
}