* Refactor Former components to streamline functionality * Update stories to reflect changes in form structure
51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import type { FormerAPICallType } from './Former.types';
|
|
|
|
function FormerRestHeadSpecAPI(options: {
|
|
authToken: string;
|
|
fetchOptions?: Partial<RequestInit>;
|
|
signal?: AbortSignal;
|
|
url: string;
|
|
}): FormerAPICallType {
|
|
return async (mode, request, value, key) => {
|
|
const baseUrl = options.url ?? ''; // Remove trailing slashes
|
|
let url = baseUrl;
|
|
const fetchOptions: RequestInit = {
|
|
cache: 'no-cache',
|
|
signal: options.signal,
|
|
...options.fetchOptions,
|
|
body: mode === 'mutate' && request !== 'delete' ? JSON.stringify(value) : undefined,
|
|
headers: {
|
|
Authorization: `Bearer ${options.authToken}`,
|
|
'Content-Type': 'application/json',
|
|
...options.fetchOptions?.headers,
|
|
},
|
|
method:
|
|
mode === 'read'
|
|
? 'GET'
|
|
: request === 'delete'
|
|
? 'DELETE'
|
|
: request === 'update'
|
|
? 'PUT'
|
|
: 'POST',
|
|
};
|
|
|
|
if (request !== 'insert') {
|
|
url = `${baseUrl}/${key}`;
|
|
}
|
|
|
|
const response = await fetch(url, fetchOptions);
|
|
if (!response.ok) {
|
|
throw new Error(`API request failed with status ${response.status}`);
|
|
}
|
|
|
|
if (mode === 'read') {
|
|
const data = await response.json();
|
|
return data as any;
|
|
} else {
|
|
return value as any;
|
|
}
|
|
};
|
|
}
|
|
|
|
export { FormerRestHeadSpecAPI };
|