josal/client.ts

43 lines
935 B
TypeScript
Raw Normal View History

type Headers = {
"Content-Type": string
"X-Version": string
Authorization?: string
}
async function createClient<T>(config: {
baseUrl: string
token: string
version: string
method: string
publicKey: string
}): Promise<T> {
const version = config.version ?? "1.0.1"
const method = config.method ?? "GET"
const headers: Headers = {
"Content-Type": "application/json",
"X-Version": version,
}
if (config.token !== undefined) {
headers.Authorization = `Bearer ${config.token}`
const response = await fetch(config.baseUrl, { method: method, headers })
if (!response.ok) {
throw new Error(response.statusText)
}
return (await response.json()) as T
}
const response = await fetch(`${config.baseUrl}/token`, {
method: "POST",
headers,
body: JSON.stringify({
publicKey: config.publicKey,
}),
})
if (!response.ok) {
throw new Error(response.statusText)
}
return (await response.json()) as T
}