foxhound87
3/27/2016 - 1:10 AM

A FeathersJS hook to implement `findOrCreate`

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');
    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;
      });
};
const findOrCreate = require('./hook.find-or-create.js')

app.service('messages').hooks({
  before: {
    create: [findOrCreate()]
  }
})