import type { HTTPClientPlugin, PluginHookResult, RequestMethod, RequestConfig } from '../types' /** * 方法重写插件配置 */ export interface HTTPMethodOverridePluginOptions { /** * 需要被重写的请求方法 * - 默认为 ['DELETE', 'PUT', 'PATCH'] */ methods?: RequestMethod[] /** * 重写后的请求方法 * - 默认为 'POST' */ overrideMethod?: RequestMethod /** * 方法覆盖请求头名称 * - 默认为 'X-HTTP-Method-Override' */ headerName?: string } export type MethodOverridePluginOptions = HTTPMethodOverridePluginOptions /** * 方法重写插件 * * 用于绕过某些环境对特定 HTTP 方法的限制 * * @example * ```ts * import { MethodOverridePlugin, HTTPClient } from '@cat-kit/http' * const http = new HTTPClient('', { * plugins: [ * MethodOverridePlugin() * ] * }) * ``` */ export function HTTPMethodOverridePlugin( options: HTTPMethodOverridePluginOptions = {} ): HTTPClientPlugin { const { methods = ['DELETE', 'PUT', 'PATCH'], overrideMethod = 'POST', headerName = 'X-HTTP-Method-Override' } = options return { name: 'method-override', beforeRequest({ config }): PluginHookResult { const { method } = config // 如果没有指定方法或者方法不需要被重写,不做任何处理 if (!method || !methods.includes(method as RequestMethod)) { return {} } // 创建新的请求头对象 const headers = { ...config.headers } // 添加原始方法到请求头 headers[headerName] = method // 返回修改后的请求选项 return { config: { ...config, method: overrideMethod, headers } } } } } export const MethodOverridePlugin = HTTPMethodOverridePlugin