实现类useTranslations的API端点路径获取功能遇阻求助
实现类似i18n的API端点路径获取功能
需求说明
我打算把所有API端点集中存放在api文件夹的单个JSON文件里,JSON结构如下:
{ "EndPoint": { "Action": { "path1": "/thisispath1/{id}", "path2": "/thisispath2/" } } }
希望能实现像useTranslations那样的调用方式来获取路径,示例用法:
const t = useTranslations('Endpoint'); const path = t('Action.path1', 1); // 期望结果:path = '/thisispath1/1';
问题现状
目前调用顶层节点是正常的,比如:
GetEndpoint('EndPoint');
返回结果:
{ "Action": { "path1": "/thisispath1/{id}", "path2": "/thisispath2/" } }
但调用GetEndpoint('EndPoint.Action.path1', 1);时返回undefined,初始实现代码如下:
type EndPointKeys = keyof typeof endPoints; export const GetEndPoint = (action: string, parameter: string) => { // 我是不是需要递归处理keyof typeof? return endPoints[action as keyof typeof endPoints]; };
最终实现代码
import endPoints from '../service-end-points/service-constants.json'; const jsonPathToValue = (Points: any, path: string) => { let jsonData = Points; let newpath = path.replace(/\[(\w+)\]/g, '.$1'); // 将索引格式转换为属性访问格式 newpath = newpath.replace(/^\./, ''); // 移除路径开头的多余点 const pathArray = newpath.split('.'); for (const key of pathArray) { if (key in jsonData && jsonData[key] !== null) { jsonData = jsonData[key as keyof typeof jsonData]; } else { return null; } } return jsonData; }; export const GetEndPoint = (path: string, parameter?: string | number) => { const url = jsonPathToValue(endPoints, path); const HOST = process.env.CONSTELLATION_SERVICE_URL || null; if (!HOST) { throw new Error('SERVICE HOST NOT DEFINED'); } let finalUrl = `${HOST}${url}`; // 替换路径中的占位符 if (parameter !== undefined) { finalUrl = finalUrl.replace('{id}', String(parameter)); } return finalUrl; };
内容的提问来源于stack exchange,提问作者itsjustcarlos
相关产品推荐
相关产品推荐

