kwhitley / itty-fetcher

An even simpler wrapper around native Fetch to strip boilerplate from your fetching code!
MIT License
99 stars 4 forks source link

feature request: passthrough fetch options in fetcher configuration #43

Open wellcaffeinated opened 11 months ago

wellcaffeinated commented 11 months ago

I was trying to pass { credentials: 'include' } for CORS stuff but it seems like these aren't passed when declaring a fetcher instance...

being able to do this would be great:

const corsKittensAPI = fetcher({
   base: 'https://api.kittens.com',
   headers: {
     'Authorization': 'Token FooBarBaz',
   },
   credentials: 'include' // currently ignored
})
sheecegardezi commented 7 months ago

Some hints from AI; To include the credentials: 'include' option in your fetcher instance, you need to modify the fetchy function to accept and pass through the credentials option from the FetcherOptions to the fetch call. This involves updating the fetchy function to include credentials in the init object passed to the fetch call.

export interface FetcherOptions {
 base?: string;
 autoParse?: boolean;
 transformRequest?: (request: RequestLike) => RequestLike | Promise<RequestLike>;
 handleResponse?: (response: Response) => any;
 fetch?: typeof fetch;
 headers?: Record<string, string>;
 credentials?: RequestCredentials; // Add this line
}

const fetchy =
 (options: FetchyOptions): FetchyFunction =>
 async (url_or_path: string, payload?: RequestPayload, fetchOptions?: FetchOptions) => {
    // Existing code...

    let req: RequestLike = {
      url: full_url,
      method,
      body: stringify ? JSON.stringify(payload) : (payload as PassThroughPayload),
      ...fetchOptions,
      headers: {
        ...jsonHeaders,
        ...options?.headers,
        ...fetchOptions?.headers,
      },
      credentials: options.credentials, // Add this line to include credentials
    };

    // Existing code...

    const { url, ...init } = req;

    const f = options?.fetch || fetch;
    let error;

    return f(url, init).then(async (response) => {
      // Existing code...
    });
 };

export function fetcher(fetcherOptions?: FetcherOptions) {
 return <FetcherType>new Proxy(
    {
      base: '',
      autoParse: true,
      ...fetcherOptions,
    },
    {
      get: (obj, prop: string) => obj[prop] ?? fetchy({ method: prop, ...obj }),
    }
 );
}