UNPKG

@planbgmbh/flinkey-web-components

Version:

This project provides some Web Components built for usage in combination with the flinkey API.

80 lines (79 loc) 2.49 kB
import { http } from './http'; /** * Global parameters that all web components use to call flinkey API endpoints. */ class Globals { } /** * Sets the default headers for API calls. * @returns {HeadersInit} The default headers. */ function setDefaultHeaders() { return { 'Authorization': `Bearer ${Globals.token}`, 'flinkey-API-Key': Globals.apiKey, 'Content-Type': 'application/json', 'Accept': 'application/json', }; } /** * Sets the default headers for API calls. * @param {string} path - The path of the endpoint. * @param {URLSearchParams} [searchParams] - The search params to append to the endpoint. * @returns {string} The generated endpoint. */ function setEndpoint(path, searchParams) { let endpoint = `${Globals.apiBaseUrl}/${path}`; if (searchParams) { endpoint += `?${searchParams}`; } return endpoint; } /** * Sends an HTTP GET request via fetch API. * @param {string} path - The path of the endpoint to call in the request. * @param {URLSearchParams} [searchParams] - The search params to send in the request. * @returns {Promise<HttpResponse<T>>} The HTTP response. * @template T */ async function httpGet(path, searchParams) { const args = { method: 'GET', headers: setDefaultHeaders(), }; const endpoint = setEndpoint(path, searchParams); return await http(new Request(endpoint, args)); } /** * Sends an HTTP PUT request via fetch API. * @param {string} path - The path of the endpoint to call in the request. * @param {unknown} body - The body to send in the request. * @returns {Promise<HttpResponse<T>>} The HTTP response. * @template T */ async function httpPut(path, body) { const args = { method: 'PUT', headers: setDefaultHeaders(), body: body ? JSON.stringify(body) : undefined, }; const endpoint = setEndpoint(path); return await http(new Request(endpoint, args)); } /** * Sends an HTTP DELETE request via fetch API. * @param {string} path - The path of the endpoint to call in the request. * @param {unknown} [body] - The body to send in the request. * @returns {Promise<HttpResponse<T>>} The HTTP response. * @template T */ async function httpDelete(path, body) { const args = { method: 'DELETE', headers: setDefaultHeaders(), body: body ? JSON.stringify(body) : undefined, }; const endpoint = setEndpoint(path); return await http(new Request(endpoint, args)); } export { Globals, httpGet, httpPut, httpDelete, setDefaultHeaders, setEndpoint };