Skip to content

Instantly share code, notes, and snippets.

@LinZap
Last active June 18, 2019 16:27
Show Gist options
  • Save LinZap/cb5f4310cf2c9b6c7cf74043b02ef41b to your computer and use it in GitHub Desktop.
Save LinZap/cb5f4310cf2c9b6c7cf74043b02ef41b to your computer and use it in GitHub Desktop.
Pseudocode - Custom Saga Flow
const flow1 = new SagaFlow('name')
flow1.run()
/*
output:
call api: name
dispatch: SUCC_GET_MAME im response
*/
//--------------------------------------------------------------------//
const flow2 = new SagaFlow()
flow2
.callapi(()=>api('custom get book api',false))
.ok(res=>action.succ_get_book(res))
.fail(res=>action.fail_get_book(res))
.callapi(()=>api('custom get name api',true))
.ok(res=>action.succ_get_name(res))
.fail(res=>action.fail_get_name(res))
flow2.run()
/*
output:
call api: custom get book api
dispatch: FAIL_GET_BOOK im response
call api: custom get name api
dispatch: SUCC_GET_MAME im response
*/
const action = {
succ_get_name : res=>console.log('dispatch: SUCC_GET_MAME',res),
fail_get_name : res=>console.log('dispatch: FAIL_GET_MAME',res),
succ_get_book : res=>console.log('dispatch: SUCC_GET_BOOK',res),
fail_get_book : res=>console.log('dispatch: FAIL_GET_BOOK',res),
}
function api(param,result=true) {
console.log('call api: ', param)
return {body:'im response', result}
}
class SagaFlow {
constructor(key){
if(key) this.key = key
this.flow = []
this.res = null
this.incall = false
}
addflow(type,func){
this.flow.push({type,func})
}
ok(func){
this.addflow('ok',func)
return this
}
fail(func){
this.addflow('fail',func)
return this
}
callapi(func){
this.addflow('call',func)
return this
}
run(){
if(this.key && this.flow.length==0){
this
.callapi(()=>api(this.key))
.ok(res=>action['succ_get_'+this.key](res))
.fail(res=>action['fail_get_'+this.key](res))
}
while(!!this.flow){
this.item = this.flow.shift()
if(!this.item) break;
switch(this.item.type){
case 'ok':
if(this.res.result && this.incall) {
this.item.func(this.res.body)
this.incall = false
}
break;
case 'fail':
if(this.res.result===false && this.incall) {
this.item.func(this.res.body)
this.incall = false
}
break;
case 'call':
this.res = this.item.func(this.key)
this.incall = true
break;
default:
continue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment