-
-
Save daffl/9fa91a2d47f08ddcfbbac152a7f06e6b to your computer and use it in GitHub Desktop.
A FeathersJS hook to implement `findOrCreate`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const findOrCreate = require('./find-or-create-hook.js') | |
app.service('messages').hooks({ | |
before: { | |
create: [findOrCreate()] | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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