最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
如何利用函数柯里化预设 API 的公共前缀构建可复用的网络请求工具
时间:2026-06-27 10:06:46 编辑:袖梨 来源:一聚教程网
柯里化可分层固化 baseURL、认证信息和请求方法,形成语义化 API 调用链:单层固定域名,两层追加 Token,三层封装 get/post 方法,并支持统一错误处理与响应解析。
直接用柯里化把 baseURL 提前“锁住”,后续所有接口只关心路径和参数,不用反复写域名或环境地址。
用单层柯里化固定基础 URL
定义一个接收 baseUrl 的函数,返回另一个接收请求配置的函数:
const createAPI = (baseUrl) => (options) => { const { method = 'GET', path = '', headers = {}, body } = options; const url = `${baseUrl}${path}`; return fetch(url, { method, headers: { 'Content-Type': 'application/json', ...headers }, body: method !== 'GET' && body ? JSON.stringify(body) : undefined });};
这样就能生成不同环境的专属请求函数:
const devAPI = createAPI('https://api.dev.example.com');const prodAPI = createAPI('https://api.prod.example.com');
调用时只需传具体路径和数据:devAPI({ path: '/users', method: 'POST', body: { name: 'Alice' } });
两层柯里化:再固化请求头(如认证)
如果每个请求都要带 Token,可以再加一层,让认证信息也预置:
const createAPI = (baseUrl) => (authToken) => (options) => { const { method = 'GET', path = '', headers = {}, body } = options; const url = `${baseUrl}${path}`; return fetch(url, { method, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, ...headers }, body: method !== 'GET' && body ? JSON.stringify(body) : undefined });};
使用方式更清晰:
const userAPI = createAPI('https://api.example.com')('abc123');userAPI({ path: '/profile' });userAPI({ path: '/settings', method: 'PUT', body: { theme: 'dark' } });
配合模块路径,自然形成语义化调用链
进一步把业务路径也柯里化,让调用像读句子一样直观:
const createAPI = (baseUrl) => (authToken) => { const withAuth = (headers = {}) => ({ get: (path) => fetch(`${baseUrl}${path}`, { method: 'GET', headers: { 'Authorization': `Bearer ${authToken}`, ...headers } }), post: (path, body) => fetch(`${baseUrl}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, ...headers }, body: JSON.stringify(body) }) }); return { withAuth };};
调用示例:
const api = createAPI('https://api.example.com')('token').withAuth();api.get('/users');api.post('/orders', { amount: 99 });
实际项目中建议搭配类型与错误统一处理
柯里化本身不处理错误,但它是组织逻辑的好起点。可在最内层封装通用响应解析和错误拦截:
- 自动识别 4xx/5xx 并抛出结构化错误对象
- 对 200 响应统一解包
data字段(适配后端返回格式) - 添加简易 loading 状态或 abort 控制(可选)
这些增强逻辑都挂在最后一层函数里,不影响上层预设逻辑的复用性。
相关文章
- 抖音赚钱攻略大全如何从零开始到月入过万 07-10
- mshen6666/HTML-PPT-Editor 教程 07-10
- 快剪辑如何设置导出位置 07-10
- 孩子通家长版app如何绑定接送卡 07-10
- 23Amansharma/agentic-ai-ppt-generator 使用教程:用 python-pptx 生成固定 PPTX 07-10
- 生存33天挂机资源怎么获得 07-10