Create a gist now

Instantly share code, notes, and snippets.

A FeathersJS hook to implement `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
};
function processRequest(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];
}
resolve(hook);
}
service.find(params)
.then(response => processRequest(response))
.catch(e => {
console.log('Error message.', hook.data, e);
reject(e);
});
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment