Skip to content

Instantly share code, notes, and snippets.

@VinSpee
Last active June 3, 2020 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinSpee/1bc6c824eae7831a26ad935be46463f8 to your computer and use it in GitHub Desktop.
Save VinSpee/1bc6c824eae7831a26ad935be46463f8 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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'),
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment