Skip to content

Instantly share code, notes, and snippets.

@daffl
Forked from marshallswain/example-usage.js
Last active April 14, 2017 23:09
Show Gist options
  • Save daffl/9fa91a2d47f08ddcfbbac152a7f06e6b to your computer and use it in GitHub Desktop.
Save daffl/9fa91a2d47f08ddcfbbac152a7f06e6b to your computer and use it in GitHub Desktop.
A FeathersJS hook to implement `findOrCreate`
const findOrCreate = require('./find-or-create-hook.js')
app.service('messages').hooks({
before: {
create: [findOrCreate()]
}
})
'use strict';
/**
* If the record doesn't already exist, create it and return it to the user.
*/
module.exports = function(){
return function(hook){
const service = hook.app.service('/api/records');
return new Promise(function(resolve, reject){
let params = {
query: hook.params.data,
user: hook.params.user
};
return service.find(params)
.then(response => {
// If a service has pagination enabled or not, handle either way.
if (response.length || response.data && response.data.length) {
// Set the result to skip the call to `create` if a record was found.
hook.result = response.data ? response.data[0] : response[0];
}
return hook;
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment