import { createPlugin, beforeRequestPlugin, RequestParams, } from "../type/PluginType"; type LookUp = U extends Record ? U["type"] extends T ? U : never : never; type AuthInfo = | { type: "basic"; username: string; password: string; } | { type: "bearer"; token: string; }; const authSets = { basic: (data: RequestParams, info: LookUp) => { data.headers.set( "Authorization", `Basic ${btoa(info.username + ":" + info.password)}` ); return data; }, bearer: (data: RequestParams, info: LookUp) => { data.headers.set("Authorization", `Bearer ${info.token}`); return data; }, }; export const authPlugin: createPlugin = (input) => { if (input && input.type) { const func = (authSets as any)[input.type]; const plugin: beforeRequestPlugin = (data) => { return func.call(null, data, input); }; return plugin; } throw "authPlugin: Your must input a auth type! "; };