60 lines
2 KiB
TypeScript
60 lines
2 KiB
TypeScript
import {
|
|
storedSourceCoverageSchema,
|
|
storedSourceInspectionSchema,
|
|
storedSourceQuerySchema,
|
|
storedSourceSelectionSchema,
|
|
type StoredSourceQuery,
|
|
type StoredSourceSelection,
|
|
} from '@stock-bot/stock-config/stored-source';
|
|
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
|
|
|
async function read(path: string, init: RequestInit): Promise<unknown> {
|
|
const response = await apiFetch(`${API_BASE_URL}/api/v2/datasets/stored-eod/${path}`, init);
|
|
const body: unknown = await response.json().catch(error => {
|
|
if (init.signal?.aborted) {
|
|
throw error;
|
|
}
|
|
return null;
|
|
});
|
|
init.signal?.throwIfAborted();
|
|
if (!response.ok) {
|
|
throw new Error(
|
|
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
|
|
? body.error
|
|
: `Source inspection failed (${response.status})`
|
|
);
|
|
}
|
|
return body;
|
|
}
|
|
export const storedSourceApi = {
|
|
async coverage(input: StoredSourceSelection, signal: AbortSignal) {
|
|
const query = storedSourceSelectionSchema.parse(input);
|
|
const result = storedSourceCoverageSchema.parse(
|
|
await read(`coverage?${new URLSearchParams(query)}`, { signal })
|
|
);
|
|
if (
|
|
JSON.stringify(result.query) !== JSON.stringify(query) ||
|
|
result.series.some(
|
|
item => item.instrumentId !== query.instrumentId || item.interval !== query.interval
|
|
)
|
|
) {
|
|
throw new Error('Source coverage differs from the selected instrument and timeframe');
|
|
}
|
|
return result;
|
|
},
|
|
async inspect(input: StoredSourceQuery, signal: AbortSignal) {
|
|
const query = storedSourceQuerySchema.parse(input);
|
|
const result = storedSourceInspectionSchema.parse(
|
|
await read('inspect', {
|
|
method: 'POST',
|
|
signal,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(query),
|
|
})
|
|
);
|
|
if (JSON.stringify(result.query) !== JSON.stringify(query)) {
|
|
throw new Error('Source inspection differs from the selected window');
|
|
}
|
|
return result;
|
|
},
|
|
};
|