Last active
May 17, 2022 00:34
-
-
Save marshallswain/9fa3b1e855633af00998 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('./hook.find-or-create.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'); | |
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. | |
response = response.data || response; | |
if (data.length) { | |
// Set `hook.result` to skip the db call to `create` if a record was found. | |
hook.result = response[0]; | |
} | |
// Return the `hook` object for the next hook to use. | |
return hook; | |
}); | |
}; |
Improvement: line 7 - use 'hook.path' to generalize for all services.
Fix: line 9 - should be 'hook.data'.
Very helpful!
Helpful for inspiration.
I would replace this with something that is atomic, such as sequelize.findOrCreate for SQL db.
Depending on your logical constraints for the schema/table, you don't want someone slipping in a create between your find that returns 0 records, and the subsequent create, if you aren't using DB level constraints.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 18 data should be response i guess.