78 lines
2.0 KiB
TypeScript
78 lines
2.0 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import type { FormerAPICallType } from './Former.types';
|
|
|
|
interface ResolveSpecRequest {
|
|
data?: Record<string, any>;
|
|
operation: 'create' | 'delete' | 'read' | 'update';
|
|
options?: {
|
|
columns?: string[];
|
|
computedColumns?: any[];
|
|
customOperators?: any[];
|
|
filters?: Array<{ column: string; operator: string; value: any }>;
|
|
limit?: number;
|
|
offset?: number;
|
|
preload?: string[];
|
|
sort?: string[];
|
|
};
|
|
}
|
|
|
|
function FormerResolveSpecAPI(options: {
|
|
authToken: string;
|
|
fetchOptions?: Partial<RequestInit>;
|
|
signal?: AbortSignal;
|
|
url: string;
|
|
}): FormerAPICallType {
|
|
return async (mode, request, value, key) => {
|
|
const baseUrl = options.url.replace(/\/$/, '');
|
|
|
|
// Build URL: /[schema]/[table_or_entity]/[id]
|
|
let url = `${baseUrl}`;
|
|
if (request !== 'insert' && key) {
|
|
url = `${url}/${key}`;
|
|
}
|
|
|
|
// Build ResolveSpec request body
|
|
const resolveSpecRequest: ResolveSpecRequest = {
|
|
operation:
|
|
mode === 'read'
|
|
? 'read'
|
|
: request === 'delete'
|
|
? 'delete'
|
|
: request === 'update'
|
|
? 'update'
|
|
: 'create',
|
|
};
|
|
|
|
if (mode === 'mutate') {
|
|
resolveSpecRequest.data = value;
|
|
}
|
|
|
|
const fetchOptions: RequestInit = {
|
|
cache: 'no-cache',
|
|
signal: options.signal,
|
|
...options.fetchOptions,
|
|
body: JSON.stringify(resolveSpecRequest),
|
|
headers: {
|
|
Authorization: `Bearer ${options.authToken}`,
|
|
'Content-Type': 'application/json',
|
|
...options.fetchOptions?.headers,
|
|
},
|
|
method: 'POST',
|
|
};
|
|
|
|
const response = await fetch(url, fetchOptions);
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
if (text && text.length > 4) {
|
|
throw new Error(`${text}`);
|
|
}
|
|
throw new Error(`API request failed with status ${response.status}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
return data as unknown;
|
|
};
|
|
}
|
|
|
|
export { FormerResolveSpecAPI, type ResolveSpecRequest };
|