Skip to content

Instantly share code, notes, and snippets.

@grncdr
Created November 7, 2014 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grncdr/cd3ebfe4d709481357ff to your computer and use it in GitHub Desktop.
Save grncdr/cd3ebfe4d709481357ff to your computer and use it in GitHub Desktop.
Prototype of formatter for tcomb errors
'use strict';
var xtend = require('xtend');
var op = require('object-path');
var isMeta = /^meta\./;
module.exports = function formatErrors (errors, options) {
options = options || {};
var byPath = options.paths || {};
var byType = options.types || {};
return errors.map(function (error) {
var formatString = getFormatString(error.path, error.expected);
return xtend(error, {
message: formatString.replace(/{([\w. _-]+)}/g, function (_, key) {
switch (key) {
case 'path': return error.path.join('.');
case 'jsonPath': return JSON.stringify(path);
}
debugger
var root = isMeta.test(key) ? error.expected : error;
return op.get(root, key);
})
});
});
// Precedence for format string is:
//
// 1. path-specific override
// 2. type-specific override
// 3. type-meta default
// 4. global default
function getFormatString (path, type) {
var pathOpts = byPath[path.join('.')];
if (pathOpts && 'message' in pathOpts) {
return pathOpts.message;
}
var typeOpts = byType[type.meta.name];
if (typeOpts && 'message' in typeOpts) {
return typeOpts.message;
}
if ('message' in type.meta) {
return type.meta.message;
}
return 'value "{actual}" at {path} was expected to be a {meta.name}';
}
};
var T = require('tcomb');
var formatErrors = require('./formatter');
var errors = [{
actual: 'toast',
expected: T.Num,
path: ['count']
}, {
actual: 'beer',
expected: T.Num,
path: ['people', 'count']
}];
var messages = formatErrors(errors, {
types: {
Num: {
message: '{path} should be a {meta.name}, was "{actual}"'
}
},
paths: {
'people.count': {
message: 'The count of people must be a {meta.name}, was "{actual}"'
}
}
}).map(function (formatted) {
return formatted.message;
});
require('assert').deepEqual(messages, [
'count should be a Num, was "toast"',
'The count of people must be a Num, was "beer"'
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment