Skip to content

Instantly share code, notes, and snippets.

@dmitriz
Forked from i-am-tom/db-alt.js
Created May 13, 2017 06:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitriz/c235dfeb38f19b0753ec704f63d3e18c to your computer and use it in GitHub Desktop.
Save dmitriz/c235dfeb38f19b0753ec704f63d3e18c to your computer and use it in GitHub Desktop.
Database failover modelled with the `alt` typeclass.
const Task = require('data.task')
Task.prototype.alt = function (that) {
return new Task((rej, res) =>
this.fork(_ => that.fork(rej, res), res))
}
const hosts = [
[ 'db1.mysite.com', 'user', 'password' ],
[ 'db2.mysite.com', 'user', 'password' ],
[ 'db3.mysite.com', 'user', 'password' ]
]
const connect = config => new Task((rej, res) =>
doSomeConnection(config).then(res).else(rej))
// The first available DB or an error!
// db :: Task String DB
const db = hosts.reduceRight(
(acc, host) => connect(host).alt(acc),
new Task((rej, res) => rej('No DBs available!')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment