簡介:正確管理前端服務的重要性
了解如何以可擴展和可讀的方式管理服務非常重要,不僅對於應用程式的效能,而且對於維護開發人員的健康和福祉。服務是應用程式中與外部通訊的部分,例如呼叫 API、與資料庫交互,甚至管理電話權限(例如存取聯絡人)。對這些服務的良好管理可確保您的應用程式具有可擴展性,並且不會在將來造成麻煩。
在本文中,我們將探索如何使用儲存庫模式以可擴展的方式管理前端服務。這種方法允許以受控且清晰的方式存取服務,封裝對 API 的呼叫並促進程式碼重用及其可維護性。
在本文中,我們將了解如何實施此解決方案、要遵循的良好實踐以及它如何幫助您確保程式碼可擴展且易於維護。
管理服務的基本概念:DTO 與適配器
在組織良好的架構中,了解應用程式不同層的結構非常重要。基礎層之一是基礎設施層,它是管理與外部互動的服務的地方。
在這個基礎設施層中,經常出現的兩個關鍵概念是DTO(資料傳輸物件)和適配器。
DTO(資料傳輸物件):DTO 是表示 API 或資料庫回應中的資料的介面。它們的作用是確保我們從外部服務接收的資訊符合我們的應用程式可以輕鬆處理的特定格式。例如,DTO 可以定義我們從 API 接收的使用者物件的結構。
適配器:適配器是負責將資料從 DTO 轉換為應用程式域介面的函數,反之亦然。也就是說,它們可以翻譯我們接收的資料或翻譯我們發送的資料。這樣,如果我們收到的資訊將來發生變化,我們只需專注於適配器,而不是整個應用程式。
DTO和適配器的使用使得基礎設施層能夠靈活、輕鬆地適應外部服務的變化,而不影響應用程式邏輯。此外,它在各層之間保持明確的分離,並且每個層都履行其特定的職責。
我們收到的資料範例:
// getUserProfile.adapter.ts const userProfileAdapter = (data: UserProfileDto): UserProfile => ({ username: data.user_username, profilePicture: data.profile_picture, about: data.user_about_me, }) export deafult userProfileAdapter;
我們傳送的資料範例:
儲存庫模式
儲存庫模式是基於將資料存取邏輯與應用程式或業務邏輯分開的想法。這提供了一種以集中和封裝的方式擁有實體在應用程式中擁有的方法的方法。
最初,我們必須使用該實體將具有的方法的定義來建立儲存庫的介面。
// UserProfileRepository.model.ts export interface IUserProfileRepository { getUserProfile: (id: string) => Promise<userprofile>; createUserProfile: (payload: UserProfile) => Promise<void>; } </void></userprofile>
我們繼續創建我們的儲存庫。
// 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>
這種方法允許我們封裝 API 調用,並透過適配器將我們收到的 DTO 格式的資料轉換為我們的內部格式。
下面您將看到我們遵循的架構或結構圖,其中基礎設施層包括服務、DTO 和適配器。這種結構使我們能夠清晰地分離業務邏輯和外部資料。
錯誤處理
我們可以透過建立錯誤處理程序來進一步改進我們的程式碼。
// 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!
以上是可擴展性之路(如何管理前端服務。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

本文討論了使用瀏覽器開發人員工具的有效JavaScript調試,專注於設置斷點,使用控制台和分析性能。

將矩陣電影特效帶入你的網頁!這是一個基於著名電影《黑客帝國》的酷炫jQuery插件。該插件模擬了電影中經典的綠色字符特效,只需選擇一張圖片,插件就會將其轉換為充滿數字字符的矩陣風格畫面。快來試試吧,非常有趣! 工作原理 插件將圖片加載到畫布上,讀取像素和顏色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地讀取圖片的矩形區域,並利用jQuery計算每個區域的平均顏色。然後,使用

本文將引導您使用jQuery庫創建一個簡單的圖片輪播。我們將使用bxSlider庫,它基於jQuery構建,並提供許多配置選項來設置輪播。 如今,圖片輪播已成為網站必備功能——一圖胜千言! 決定使用圖片輪播後,下一個問題是如何創建它。首先,您需要收集高質量、高分辨率的圖片。 接下來,您需要使用HTML和一些JavaScript代碼來創建圖片輪播。網絡上有很多庫可以幫助您以不同的方式創建輪播。我們將使用開源的bxSlider庫。 bxSlider庫支持響應式設計,因此使用此庫構建的輪播可以適應任何

數據集對於構建API模型和各種業務流程至關重要。這就是為什麼導入和導出CSV是經常需要的功能。在本教程中,您將學習如何在Angular中下載和導入CSV文件


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。