UNPKG

@playkit-js/dynamic-watermark

Version:
73 lines (57 loc) 1.65 kB
type RequestOptions = RequestInit & { params?: ConstructorParameters<typeof URLSearchParams>[0]; responseType?: 'raw' | 'json'; }; type GetOptions = Omit<RequestOptions, 'method' | 'body'>; type PostOptions = Omit<RequestOptions, 'method' | 'body'> & { body?: Record<PropertyKey, unknown>; }; const DEFAULT_HEADERS = { Accept: 'application/json', }; const DEFAULT_BODY_HEADERS = { 'Content-Type': 'application/json', }; const request = async (resource: string, options?: RequestOptions) => { const url = options?.params ? `${resource}${resource.includes('?') ? '&' : '?'}${new URLSearchParams(options.params)}` : resource; const response = await fetch(url, { ...options, headers: { ...(options?.responseType === 'raw' ? null : DEFAULT_HEADERS), ...options?.headers, }, }); if (!response.ok) { throw new Error(response.statusText); } if (options?.responseType === 'raw') { return response; } const body = await response.json(); return body as unknown; }; export const http = { get: async (resource: string, options?: GetOptions) => { return request(resource, { ...options, method: 'GET' }); }, head: async (resource: string, options?: GetOptions) => { return request(resource, { ...options, method: 'HEAD', responseType: 'raw', }); }, post: async (resource: string, options?: PostOptions) => { return request(resource, { ...options, method: 'POST', headers: { ...DEFAULT_BODY_HEADERS, ...options?.headers, }, body: options?.body && JSON.stringify(options.body), }); }, };