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 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 22 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,17 +180,35 @@ The `errors` attribute contains a list of all original values that failed the un

### 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 `ValidatorError` message will be the formatted value of a String `options.message` (which is set automatically by this package if not already defined).

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).
The default value of `options.message` 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).
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are going to introduce more API surface, I think we should be extra-clear on when one mechanism for overriding the message should be used instead of the other one. Currently, I have the feeling that options.message and the custom message in the unique field might feel redundant to the users.

In my opinion, the main use for options.message is for when the plugin is used globally. If you want to, I can try to improve the docs after merging this PR. I think renaming options.message to options.defaultMessage will make things clearer.


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:
If you want to override it, you have two choices:

1. Add your custom message in the `unique` field (instead of `true`), during the schema's creation:

```diff
const userSchema = mongoose.Schema({
name: {
type: String,
+ unique: 'Two users cannot share the same username ({VALUE})'
- unique: true
}
});
```

2. Override the global default through `options.message` while initializing the schema plugin:

```js
// change this however you'd like
mongoose.Error.messages.general.unique = 'Path `{PATH}` ({VALUE}) is not unique.';
userSchema.plugin(beautifyUnique, {
message: "Path `{PATH}` ({VALUE}) is not unique."
});
```

> **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
20 changes: 10 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} message Default message formatter string
* @return {Promise.<ValidationError>} Beautified error message
*/
function beautify(error, collection, values, messages) {
function beautify(error, collection, values, messages, message) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should rename message to defaultMessage to avoid confusion between the singular message and the plural messages variable.

// 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 = message;
}

suberrors[path] = new mongoose.Error.ValidatorError(props);
Expand All @@ -105,9 +100,14 @@ 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.message) {
options.message = 'Path `{PATH}` ({VALUE}) is not unique.';
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid confusion between the different ways to provide a custom error message, I suggest using options.defaultMessage instead of options.message.

}

// 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 +161,7 @@ module.exports = function (schema) {
values = doc;
}

beautify(error, collection, values, messages)
beautify(error, collection, values, messages, options.message)
.then(next)
.catch(function (beautifyError) {
setTimeout(function () {
Expand Down