I expected service.create(obj) to fail when existing entry with same id in database already existed. Not sure if this is in the scope of feathers, the specific database service interface (here feathers-nedb) or feathers-hooks-common.
const feathers = require('feathers');
const NeDB = require('nedb');
const service = require('feathers-nedb');
const app = feathers()
app.use('/users', service({ Model: userModel(), id: 'email' }));
const users = app.service('/users');
let user = { email: '[email protected]', password: '11111', role: 'admin' }
Promise.all([
users.create(user),
users.create(user)
]).then(results => console.log(results))
.catch(err => console.log('Error occurred:', err));
function userModel() {
return new NeDB({
filename: 'users.db',
autoload: true
});
}
I expected second users.create to fail.
Same user is added to database twice.
const { validate } = require('feathers-hooks-common')
/**
* Checks if item with same id already exists.
*/
module.exports = function unique () {
return validate((values, hook) => {
return hook.service.get(values[hook.service.id])
.catch(() => null) // not found, pass null to next .then
.then(res => res === null
? null
: Promise.reject(new Error(`${res[hook.service.id]} already exists in db`)))
})
}
As an aside on hooks, there's a commonly missed issue with your hook, the param value. For example, no authentication info is passed with the get. See how the hook stashBefore handles it.
This is a problem that should generally be handled by the database for efficiency reasons. It's definitely possible to implement as a hook, but it won't be nearly as efficient as using NeDB unique constraint indexes: https://github.com/louischatriot/nedb/wiki/Indexing
Thanks for the help. Here's the solution, for others stumbling over the same:
function userModel() {
let Model = new NeDB({
filename: 'users.db',
autoload: true
});
Model.ensureIndex({ fieldName: 'email', unique: true }, err => {
if (err) throw err
});
return Model;
}
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue with a link to this issue for related bugs.
Most helpful comment
Thanks for the help. Here's the solution, for others stumbling over the same: