Skip to content

Instantly share code, notes, and snippets.

@UberMouse
Created August 9, 2022 22:00
Show Gist options
  • Save UberMouse/10014ba6c7072b8138050a249b54f054 to your computer and use it in GitHub Desktop.
Save UberMouse/10014ba6c7072b8138050a249b54f054 to your computer and use it in GitHub Desktop.
type Arguments<TContext> = {
name: string;
successTarget: string;
id?: string;
successActions?: string[];
errorActions?: string[];
otherDoneTargets?: TransitionConfig<TContext, DoneInvokeEvent<$YesReallyAny>>[];
errorTarget?: string;
errorPredicate?: (_ctx: unknown, e: DoneInvokeEvent<$YesReallyAny>) => boolean;
};
/**
* This provides a simple invoked promise pattern. You specify a service name
* and where you want the machine to transition to on success
*
* It works out of the box for Promises that resolve to a boolean indicating success/failure
*
* onDone will transition to the errorTarget if the errorPredicate is true, otherwise the success target
* onError always transitions to the errorTarget
*
* @param args
* @param args.name name of the service definition to invoke
* @param args.successTarget target to transition to for a successful invocation
* @param args.successActions actions to run on successful invocation
* @param args.errorActions actions to run on failed invocation
* @param args.otherDoneTargets if you need to cater for more conditional transition targets add them here
* @param [args.errorTarget="error"] - target to transition to for onError or a promise that fails the errorPredicate, defaults to "error"
* @param args.errorPredicate returns true if promise resolved to error, defaults to checking if resolved to false
*/
export function invokePromise<TContext, TEvent extends EventObject>({
name,
successTarget,
id,
successActions = [],
errorActions = [],
otherDoneTargets = [],
errorTarget = "error",
errorPredicate = (_ctx: unknown, e: DoneInvokeEvent<$YesReallyAny>) => e.data === false,
}: Arguments<TContext>): InvokeConfig<TContext, TEvent> {
return {
id: id ?? name,
src: name,
onDone: [
{ target: errorTarget, cond: errorPredicate, actions: errorActions },
...otherDoneTargets,
{ target: successTarget, actions: successActions },
],
onError: { target: errorTarget, actions: errorActions },
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment