Skip to content

Instantly share code, notes, and snippets.

@indolering
Last active December 2, 2015 00:29
Show Gist options
  • Save indolering/963091dcda47b6d008d0 to your computer and use it in GitHub Desktop.
Save indolering/963091dcda47b6d008d0 to your computer and use it in GitHub Desktop.
class Thing {
constructor(type) {
this.type = type;
this.conflicts = [];
}
conflict(that){
if(this.type === 'water' && that.type === "fire"){
this.conflicts.push({id: that.id, message: "fire and water don't mix"});
}
}
}
class ThingTracker {
constructor(things) {
this.things = things;
}
preflight(newThing){
this.things.forEach(function(existingThing){
newThing.conflict(existingThing);
});
if(magicalPromiseDetector){
if(newThing.conflicts.length === 0){
return Promise.resolve(newThing);
} else {
return Promise.reject(newThing.conflicts);
}
} else {
return newThing.conflicts.length === 0;
}
}
}
//usage on server
var newThing = new Thing(request.data.thing);
var thingTracker = new ThingTracker(db.lookup(request.data.id));
var valid = thingTracker.preflight(newThing);
if(valid){
db.save(newThing, request.data.id);
} else {
request.respond(400, newThing.conflicts)
}
//usage on client
localTracker.preflight(newThing).then(function(newThing){
return client.request.addThing(newThing);
}).then(function(newThing){
localTracker.save(newThing);
}).catch(function(conflicts){
ui.show(conflicts);
});
//mixing on client
Promise.resolve().then(localTracker.preflight(newThing)).then(function(valid){
if(valid){
return client.request.addThing(newThing);
} else {
throw newThing.conflicts;
}
}).then(function(newThing){
localTracker.save(newThing);
}).catch(function(conflicts){
ui.show(conflicts);
});
//sync on client
new Promise(function(resolve, reject){
var valid = localTracker.preflight(newThing);
if(valid){
return client.request.addThing(newThing);
} else {
reject(newThing.conflicts);
}
}).then(function(newThing){
localTracker.save(newThing);
}).catch(function(conflicts){
ui.show(conflicts);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment