Skip to content

Instantly share code, notes, and snippets.

@i-am-tom i-am-tom/db-alt.js

Last active Feb 20, 2020
What would you like to do?
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 = [
[ '', 'user', 'password' ],
[ '', 'user', 'password' ],
[ '', 'user', 'password' ]
const connect = config => new Task((rej, res) =>
// 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!')))

This comment has been minimized.

Copy link

DrBoolean commented Mar 31, 2017

Interestingly, you can wrap any Alternative in Alt to make it a monoid:

const Alt = x =>
  concat: o => Alt(x.alt(o.x))

Then you can foldMap instead of manually reducing

const I = require('immutable-ext')
.foldMap(Alt, Alt(Task.rejected('No DBs available!')))

This comment has been minimized.

Copy link
Owner Author

i-am-tom commented Apr 4, 2017

Aha, a sneaky semigroup!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.