Skip to content

Instantly share code, notes, and snippets.

@zhangchiqing
Last active November 24, 2016 18:05
Show Gist options
  • Save zhangchiqing/30881b5f2791a90391a32467aee9ca57 to your computer and use it in GitHub Desktop.
Save zhangchiqing/30881b5f2791a90391a32467aee9ca57 to your computer and use it in GitHub Desktop.
Validation with liftp and toPromise
// I've been writing validation utilities for many times,
// never satisfied until I realize that the combination of `liftp` and `toPromise`
// is just perfect.
// It could work with any number of arguments. Leaving
// the choices to you of what error to return and how to check if an argument is valid.
var P = require('bluebird-promisell');
var R = require('ramda');
// Number -> Number -> Promise Number
var addAsync = function(a, b) {
return P.purep(a + b);
};
// String -> () -> Error
var toError = function(fieldname) {
return function() {
return new Error('invalid field: ' + fieldname);
};
};
// Number -> Number -> Promise Number
exports.addAsync = function(a, b) {
return P.liftp(addAsync)(
P.toPromise(R.is(Number), toError('a'))(a),
P.toPromise(R.is(Number), toError('b'))(b));
};
exports.addAsync(1, 2); // Resolved Promise: 3
exports.addAsync("1", 2); // Rejected Promise: Error "invalid field: a"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment