Created
September 30, 2024 08:42
-
-
Save alonronin/a58696e582e9d816d46dbba0efc31ca7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RequestInit } from 'next/dist/server/web/spec-extension/request'; | |
type DefaultOptions = { | |
baseUrl: string; | |
headers: Headers; | |
}; | |
const defaultOptions: DefaultOptions = { | |
baseUrl: '', | |
headers: new Headers({ | |
'Content-Type': 'application/json; charset=UTF-8', | |
}), | |
}; | |
const methods = ['get', 'post', 'put', 'delete', 'patch', 'options'] as const; | |
export function create( | |
options: Partial<DefaultOptions>, | |
): Record< | |
(typeof methods)[number], | |
(url: URL | string, options?: RequestInit) => Promise<Response> | |
> { | |
const config = { ...defaultOptions, ...options }; | |
function getConfig(options: RequestInit = {}, method: string) { | |
const optionsHeaders = new Headers(options.headers); | |
const configHeaders = new Headers(config.headers); | |
const headers = new Headers([...optionsHeaders, ...configHeaders]); | |
return { | |
...config, | |
...options, | |
headers, | |
method: method.toUpperCase(), | |
}; | |
} | |
const api = methods.map((method) => { | |
return [ | |
method, | |
async (url: URL | string, options: RequestInit) => { | |
const { baseUrl, ...init } = getConfig(options, method); | |
const requestUrl = `${baseUrl}${url.toString()}`; | |
const request = await fetch(requestUrl, init); | |
if (!request.ok) { | |
throw new Error(request.statusText); | |
} | |
return request; | |
}, | |
]; | |
}); | |
return Object.fromEntries(api); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { create } from './http'; | |
const http = create({ baseUrl: 'https://jsonplaceholder.typicode.com/' }); | |
const result = await http.get('/posts/1').then((res) => res.json()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment