search
HomeWeb Front-endJS TutorialPath to scalability (How to Manage Services in Frontend.

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:

Camino hacia la escalabilidad ( Cómo Gestionar Servicios en Frontend.

// 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:

Camino hacia la escalabilidad ( Cómo Gestionar Servicios en Frontend.



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.

Camino hacia la escalabilidad ( Cómo Gestionar Servicios en Frontend.



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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

MantisBT

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor