柯里化可分层固化 baseURL、认证信息和请求方法,形成语义化 API 调用链:单层固定域名,两层追加 Token,三层封装 get/post 方法,并支持统一错误处理与响应解析。
直接用柯里化把 baseURL 提前“锁住”,后续所有接口只关心路径和参数,不用反复写域名或环境地址。
定义一个接收 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 });柯里化本身不处理错误,但它是组织逻辑的好起点。可在最内层封装通用响应解析和错误拦截:
data 字段(适配后端返回格式)这些增强逻辑都挂在最后一层函数里,不影响上层预设逻辑的复用性。