const { log } = actions; const apolloRequest = (data) => Promise.resolve(data); const MOCK_RETURN_ACTION = { type: 'ADD_VIDEO_TO_YOUR_LIST', variables: { id: "1755", secondsPlayed: 0, } }; const responseHasError = (errorName) => (data) => data && data.data && data.data.errors && data.data.errors.includes('errorName'); const handleResponse = { onDone: [ { cond: 'needsAuthentication', actions: [log('onDoneFailure')], target: 'failure', }, { actions: [log('onDoneSuccess')], target: 'success', }, ], onError: [ { actions: log('onError'), }, { target: 'failure', actions: ['onFailure'], }, ], }; const authMachine = Machine( { id: "authManager", initial: "idle", context: { retries: 0, errors: [], variables: {}, }, states: { idle: { invoke: { id: "queue-latent-actions", src: "checkQueue", }, on: { UPDATE_VARIABLES: { actions: ["updateVariables"], }, SAVE_VIDEO_TO_YOUR_LIST: { target: "savingVideoToYourList", }, }, }, loading: { on: {}, }, success: { type: "final", }, failure: { on: { RETRY: { target: "loading", actions: assign({ retries: (context, event) => context.retries + 1, }), }, }, }, savingVideoToYourList: { invoke: { id: 'save-video-to-your-list', src: 'saveVideoToYourList', ...handleResponse, }, }, }, }, { actions: { storeAction: (context, event) => { console.log("actions", "store action and redirect"); }, updateVariables: assign({ variables: (context, event) => ({ ...context.variables, ...((event && event.payload) || {}), }), }), }, services: { saveVideoToYourList: apolloRequest({ data: { data: { errors: ['NotAuthenticated'] } } }), checkQueue: () => (callback) => { const { type, ...variables } = MOCK_RETURN_ACTION; if (type && variables) { callback({ type: "UPDATE_VARIABLES", payload: variables, meta: "FROM_QUEUE", }); callback({ type }); return () => { return "NEW_URL_WITHOUT_ACTION"; }; } return null; }, }, guards: { needsAuthentication: responseHasError('NotAuthenticated'), needsAuthorization: responseHasError('NotAuthorized'), }, } );