Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed default message formatter (closes #41) #42

Merged
merged 4 commits into from
Aug 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,21 +176,34 @@ Schemata in which this module is plugged in will produce beautified duplication

**You need to plug in this module after declaring all indexes on the schema, otherwise they will not be beautified.**

The `errors` attribute contains a list of all original values that failed the unique contraint.
The reported error has the same shape as normal validation errors. For each field that has a duplicate value, an item is added to the `errors` attribute. See examples above.

### Error messages

By default, the `ValidatorError` message will be the formatted value of `mongoose.Error.messages.general.unique` (which is set automatically by this package if not already defined).
By default, the validation error message will be ``Path `{PATH}` ({VALUE}) is not unique.``, with `{PATH}` replaced by the name of the duplicated field and `{VALUE}` by the value that already existed.

The default value of `mongoose.Error.messages.general.unique` is ``"Path `{PATH}` ({VALUE}) is not unique."`` which adheres to [the Mongoose error message defaults](https://github.com/Automattic/mongoose/blob/master/lib/error/messages.js).
To set a custom validation message on a particular path, add your message in the `unique` field (instead of `true`), during the schema's creation.

If you want to override it, add your custom message in the `unique` field (instead of `true`), during the schema's creation (or) override the default global Mongoose error:
```diff
const userSchema = mongoose.Schema({
name: {
type: String,
+ unique: 'Two users cannot share the same username ({VALUE})'
- unique: true
}
});
```

When using the plugin globally or with a schema that has several paths with unique values, you might want to override the default message value. You can do that through the `defaultMessage` option while adding the plugin.

```js
// change this however you'd like
mongoose.Error.messages.general.unique = 'Path `{PATH}` ({VALUE}) is not unique.';
userSchema.plugin(beautifyUnique, {
defaultMessage: "This custom message will be used as the default"
});
```

> **Note**: Custom messages defined in the schema will always take precedence over the global default message.

## Contributions

This is free and open source software. All contributions (even small ones) are welcome. [Check out the contribution guide to get started!](CONTRIBUTING.md)
Expand Down
24 changes: 14 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@

var mongoose = require('mongoose');

// Bind custom message for mongoose if it doesn't already exist
if (mongoose.Error.messages.general.unique === undefined) {
mongoose.Error.messages.general.unique =
'Path `{PATH}` ({VALUE}) is not unique.';
}

var errorRegex = /index:\s*(?:.+?\.\$)?(.*?)\s*dup/;
var indexesCache = {};

Expand Down Expand Up @@ -56,9 +50,10 @@ function getIndexes(collection) {
* @param {Collection} collection Mongoose collection.
* @param {Object} values Hashmap containing data about duplicated values
* @param {Object} messages Map fields to unique error messages
* @param {String} defaultMessage Default message formatter string
* @return {Promise.<ValidationError>} Beautified error message
*/
function beautify(error, collection, values, messages) {
function beautify(error, collection, values, messages, defaultMessage) {
// Try to recover the list of duplicated fields
var onSuberrors = global.Promise.resolve({});

Expand Down Expand Up @@ -86,7 +81,7 @@ function beautify(error, collection, values, messages) {
if (typeof messages[path] === 'string') {
props.message = messages[path];
} else {
props.message = mongoose.Error.messages.general.unique;
props.message = defaultMessage;
}

suberrors[path] = new mongoose.Error.ValidatorError(props);
Expand All @@ -105,9 +100,15 @@ function beautify(error, collection, values, messages) {
});
}

module.exports = function (schema) {
module.exports = function (schema, options) {
var tree = schema.tree, key, messages = {};

options = options || {};

if (!options.defaultMessage) {
options.defaultMessage = 'Path `{PATH}` ({VALUE}) is not unique.';
}

// Fetch error messages defined in the "unique" field,
// store them for later use and replace them with true
for (key in tree) {
Expand Down Expand Up @@ -161,7 +162,10 @@ module.exports = function (schema) {
values = doc;
}

beautify(error, collection, values, messages)
beautify(
error, collection, values,
messages, options.defaultMessage
)
.then(next)
.catch(function (beautifyError) {
setTimeout(function () {
Expand Down
41 changes: 41 additions & 0 deletions tests/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,47 @@ test('should use custom validation messages', function (t) {
});
});

test('should allow overriding the default validation message', function (t) {
var DefaultMessageSchema = new Schema({
address: {
type: String,
unique: true
}
});

DefaultMessageSchema.plugin(beautifulValidation, {
defaultMessage: 'Default message override test, {PATH}'
});

var DefaultMessage = mongoose.model('DefaultMessage', DefaultMessageSchema);

DefaultMessage.on('index', function (indexErr) {
t.error(indexErr, 'indexes should be built correctly');

new DefaultMessage({
address: '123 Fake St.'
}).save().then(function () {
return new DefaultMessage({
address: '123 Fake St.'
}).save();
}, function (err) {
t.error(err, 'should save the first document successfully');
t.end();
}).then(function () {
t.fail('should not save the duplicate document successfully');
t.end();
}, function (err) {
assertUniqueError(
t, err,
{address: '123 Fake St.'},
{address: 'Default message override test, address'}
);

t.end();
});
});
});

test('should use custom validation messages w/ compound', function (t) {
var CompoundMessageSchema = new Schema({
name: String,
Expand Down