Introduction: The importance of correct management of services in Frontend
Knowing how to manage services in a scalable and readable way is very important, not only for the performance of the application, but also to maintain the health and well-being of the developers. Services are the part of the application that communicates with the outside, such as calls to APIs, interaction with databases, or even managing phone permissions, such as access to contacts. Good management of these services ensures that your application can be scalable and will not cause headaches in the future.
In this article, we are going to explore how to manage frontend services in a scalable way using the repository pattern. This approach allows access to services in a controlled and clear manner, encapsulating calls to APIs and facilitating code reuse, as well as its maintainability.
Throughout this article, we will see how to implement this solution, the good practices to follow and how it can help you ensure that your code is scalable and easy to maintain.
Fundamental Concepts for Managing Services: DTOs and Adapters
In a well-organized architecture, it is important to understand how the different layers of an application are structured. One of the fundamental layers is the infrastructure layer, which is where the services that interact with the outside are managed.
Within this infrastructure layer, two key concepts that often appear are DTOs (Data Transfer Objects) and adapters.
DTO (Data Transfer Object): DTOs are interfaces that represent data in the responses of APIs or databases. They serve to ensure that the information we receive from external services conforms to a specific format that our application can easily handle. For example, a DTO could define the structure of a user object that we receive from an API.
Adapters: Adapters are functions responsible for translating data from DTOs to application domain interfaces, or vice versa. That is, they can be to translate the data we receive or to translate the data we send. This way, if the information we receive changes in the future, we will only have to focus on the adapter, and not throughout the application.
The use of DTOs and adapters allows the infrastructure layer to be flexible and easily adaptable to changes in external services without affecting the application logic. In addition, it maintains a clear separation between the layers and that each one fulfills its specific responsibilities.
Example of data we receive:
// getUserProfile.adapter.ts const userProfileAdapter = (data: UserProfileDto): UserProfile => ({ username: data.user_username, profilePicture: data.profile_picture, about: data.user_about_me, }) export deafult userProfileAdapter;
Example of data we send:
The Repository Pattern
The repository pattern is based on the idea of having your data access logic separate from your application or business logic. This provides a way to have in a centralized and encapsulated way the methods that an entity has in your application.
Initially we will have to create the interface of our repository with the definition of the methods that this entity will have.
// UserProfileRepository.model.ts export interface IUserProfileRepository { getUserProfile: (id: string) => Promise<UserProfile>; createUserProfile: (payload: UserProfile) => Promise<void>; }
And we continue with the creation of our repository.
// userProfile.repository.ts export default function userProfileRepository(): IUserProfileRepository { const url = `${BASE_URL}/profile`; return { getUserProfile: getProfileById(id: string) { try { const res = await axios.get<UserProfileDto>(`${url}/${id}`); return userProfileAdapter (userDto); } catch(error){ throw error; } }, createUserProfile: create(payload: UserProfile) { try { const body = createUserProfilAdapter(payload); await axios.post(`${url}/create`, payload); } catch(error) { throw error; } } } }
This approach allows us to encapsulate the API calls and convert the data we receive in the DTO format to our internal format through the adapter.
Below you will see a diagram of the architecture or structure that we follow, where the infrastructure layer includes services, DTOs and adapters. This structure allows us to have a clear separation between business logic and external data.
Error Handling
We can further improve our code by creating an error handler.
// errorHandler.ts export function errorHandler(error: unknown): void { if (axios.isAxiosError(error)) { if (error.response) { throw Error(`Error: ${error.response.status} - ${error.response.data}`); } else if (error.request) { throw Error("Error: No response received from server"); } else { throw Error(`Error: ${error.message}`); } } else { throw Error("Error: An unexpected error occurred"); } }
// userProfile.repository.ts import { errorHandler } from './errorHandler'; export default function userProfileRepository(): IUserProfileRepository { const url = `${BASE_URL}/profile`; return { async getUserProfile(id: string) { try { const res = await axios.get<UserProfileDto>(`${url}/${id}`); return userProfileAdapter(res.data); } catch (error) { errorHandler(error); } }, async createUserProfile(payload: UserProfile) { try { const body = createUserProfileAdapter(payload); await axios.post(`${url}/create`, body); } catch (error) { errorHandler(error); } } } }
Esto nos permite desacoplar la lógica de presentación de la lógica de negocio, asegurando que la capa de UI solo se encargue de manejar las respuestas y actualizar el estado de la aplicación.
Implementación de los servicios
Una vez que hemos encapsulado la lógica de acceso a datos dentro de nuestro repositorio, el siguiente paso es integrarlo con la interfaz de usuario (UI).
Es importante mencionar que no hay una única forma de implementar el patrón Repository. La elección de la implementación dependerá mucho de la arquitectura de tu aplicación y de qué tan fiel quieras a las definiciones de la misma. En mi experiencia, una de las formas más útiles y prácticas de integrarlo ha sido mediante el uso de hooks, el cual desarrollaremos a continuación.
export function useGetUserProfile(id: string) { const [data, setData] = useState<UserProfile | null>(null); const [loading, setLoading] = useState<boolean>(true); const [error, setError] = useState<string | null>(null); const repository = userProfileRepository(); useEffect(() => { const fetchData = async () => { setLoading(true); try { const userProfile = await repository.getUserProfile(id); setData(userProfile); } catch (err) { setError((err as Error).message); } finally { setLoading(false); } }; fetchData(); }, [id]); return { data, loading, error }; }
interface UserProfileProps { id: string; } export function UserProfile({ id }: UserProfileProps) { const { data, loading, error } = useUserProfile(id); if (loading) return <Skeleton />; if (error) { toast({ variant: "destructive", title: "Uh oh! Something went wrong.", description: error, }); } return ( <div> <h1>{data?.username}</h1> <img src={data?.profilePicture} alt={`${data?.username}'s profile`} /> <p>{data?.about}</p> </div> ); }
Ahora, el componente UserProfile no necesita saber nada sobre cómo se obtienen los datos del perfil, solo se encarga de mostrar los resultados o mensajes de error.
Esto se puede mejorar aún más si las necesidades lo requieren, por ejemplo con la utilizacion de react query dentro del hook para tener un mayor control sobre el cacheo y actualización de datos.
export function useGetUserProfile(id: string) { const repository = userProfileRepository(); return useQuery({ queryKey: ['userProfile', id], queryFn: () => repository.getUserProfile(id), }); }
Conclusión
En este artículo, hemos explorado cómo implementar el patrón Repository en frontend, encapsulando las llamadas a las APIs y manteniendo una separación clara de responsabilidades mediante el uso de DTOs y adaptadores. Este enfoque no solo mejora la escalabilidad y el mantenimiento del código, sino que también facilita la actualización de la lógica de negocio sin tener que preocuparse por los detalles de la comunicación con los servicios externos. Además, al integrar React Query, obtenemos una capa extra de eficiencia en la gestión de datos, como el cacheo y la actualización automática.
Recuerda que no existe una manera única del manejo de servicios (por ejemplo también existe el patrón sagas para el manejo de side-effects). Lo importante es aplicar las buenas prácticas para asegurarnos de que nuestro código siga siendo flexible, limpio y fácil de mantener en el tiempo.
Espero que esta guía te haya sido útil para mejorar la manera en la que gestionas los servicios en tus proyectos frontend. Si te ha gustado, no dudes en dejar un comentario, darle me gusta o compartir el artículo para que más desarrolladores puedan beneficiarse. ¡Gracias por leer!
The above is the detailed content of Path to scalability (How to Manage Services in Frontend.. For more information, please follow other related articles on the PHP Chinese website!