import { assign, createMachine, send, sendParent } from 'xstate'; // import type { QueryManager } from '$lib/services/query-manager-test'; export type FetchContext = { id: string; verb: string; endpoint: string; query: any; body: any; requestTimestamp: any, responseTimestamp: any, response: any; errorMessage: string; broadcastEvent: string; // manager: QueryManager } export const fetchMachine = createMachine ( { tsTypes: {} as import("./fetch.machine.typegen").Typegen0, schema: { context: {} as FetchContext, events: {} as { type: 'FETCH', endpoint: string, query?: string, body?: any } | { type: 'FETCH_SUCCESS', data: any } | { type: 'FETCH_ERROR', error: any } | { type: 'FETCH_CANCEL' } }, initial: 'inFlight', context: { id: null, verb: null, endpoint: null, query: null, body: null, requestTimestamp: null, responseTimestamp: null, response: null, errorMessage: null, broadcastEvent: 'RECEIVE_DATA' // manager: null }, states: { inFlight: { invoke: { src: 'fetchCall', onDone: { target: 'success', actions: [ 'assignDataToContext' ] }, onError: { target: 'error', actions: 'assignErrorToContext', } }, on: { // CANCEL: { // target: 'complete', // } } }, success: { entry: [ 'notifyParent' ], type: 'final' // data: { // id: (context: FetchContext, event: FetchEvent) => context.id, // endpoint: (context: FetchContext, event: FetchEvent) => context.endpoint, // data: (context: FetchContext, event: FetchEvent) => context.response, // } }, error: { // work in retries and exponential backoff entry: [ // (c,e) => console.log("Error in fetch: ", c, e) ] } }, }, { services: { fetchCall: (context, event): Promise => { return fetch(`${context.endpoint}`).then((response) => response.json()); // return context.endpoint.includes('http') ? // fetch(`${context.endpoint}${context.query}`).then((response) => response.json()) : // context.manager[ context.endpoint ]( context.query ) } }, actions: { assignDataToContext: assign({ response: (context, event) => event.data }), assignErrorToContext: assign({ errorMessage: (context, event) => 'An unknown error occurred', }), notifyParent: sendParent((context, event) => { return { type: context.broadcastEvent, data: { id: context.id, responseTimestamp: context.responseTimestamp, endpoint: context.endpoint, data: context.response, } } }) } });