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>; } </void></userprofile>
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; } } } } </userprofiledto>
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); } } } } </userprofiledto>
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 }; } </string></boolean></userprofile>
interface UserProfileProps { id: string; } export function UserProfile({ id }: UserProfileProps) { const { data, loading, error } = useUserProfile(id); if (loading) return <skeleton></skeleton>; if (error) { toast({ variant: "destructive", title: "Uh oh! Something went wrong.", description: error, }); } return ( <div> <h1 id="data-username">{data?.username}</h1> <img src="%7Bdata?.profilePicture%7D" 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!

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft