Skip to content

Instantly share code, notes, and snippets.

@kaze
Last active August 30, 2020 20:03
Show Gist options
  • Save kaze/3b2dafdc75c875c41dc0b81cf6424046 to your computer and use it in GitHub Desktop.
Save kaze/3b2dafdc75c875c41dc0b81cf6424046 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const request = (context) => {};
const build_request_params = () => {};
const make_signal = (context) => {
const controller = new AbortController();
context.signal = controller.signal;
}
const abort_request = (context) => {
return context.signal.abort;
}
const build_params = (context) => build_request_params(context);
const update_context = assign({retries: (context) => context.retries + 1});
const can_retry = (context) => context.retries < context.max_retries;
const default_context = {
endpoint: null,
headers: {},
method: 'GET',
data: null,
data_type: 'json',
timeout: 1000,
max_retries: 5,
retries: 0,
retry_throttle: [
0,
1000,
3000,
10000,
30000,
],
signal: null,
api_request: true,
versioned: true,
authenticated: true,
handle_errors: true,
result: null,
error: null,
};
const request_machine = Machine({
id: 'request',
initial: 'idle',
context: default_context,
states: {
idle: {
on: {
'fetch': 'build'
}
},
build: {
on: {
'': {
target: 'loading',
actions: [
'make_signal',
'build_params',
]
},
'cancel': 'cancelled'
}
},
loading: {
on: {
'cancel': 'cancelled',
'resolve': 'success',
'reject': 'failure'
},
invoke: {
src: (context) => request(context),
onDone: {
target: 'success',
actions: assign({ result: (context, event) => event.data })
},
onError: {
target: 'failure',
actions: assign({ error: (context, event) => event.data })
}
}
},
failure: {
on: {
'': [{
target: 'loading',
actions: 'update_context',
cond: 'can_retry'
}, {
target: 'error'
}],
'cancel': 'cancelled'
}
},
success: {
type: 'final'
},
cancelled: {
type: 'final'
},
error: {
type: 'final'
}
}
},
{
actions: {
make_signal,
build_params,
update_context,
abort_request
},
activities: {},
guards: {
can_retry,
},
services: {}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment