geilt

Fix Extra Records on Post SailsJS Policy

Dec 11th, 2014
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. /**
  4.  * Policy to fix data records coming in from Angular via "Record"
  5.  * We pass any relational data into a relational key and delete the previous key to prevent Waterline from Updating It.
  6.  * We set any key that has a property of id, to that id
  7.  * We delete the id, since we should be passing it in via REST
  8.  * We delete createdBy, updatedBy, createdAt, and updatedAt
  9.  * Note, to use the addDataCreate and addDataUpdate, it must come AFTER this function.
  10.  *
  11.  * @param   {Request}   request     Request object
  12.  * @param   {Response}  response    Response object
  13.  * @param   {Function}  next        Callback function
  14.  */
  15. module.exports = function(request, response, next) {
  16.     sails.log.verbose(' POLICY - ' + __filename + ':' + __line);
  17.         if(_.has(request.body, 'record')){
  18.             request.body.record = fix(request.body.record);
  19.             // Remove Extras.
  20.             var itemsToRemove = [
  21.                 'id',
  22.                 'createdBy',
  23.                 'updatedBy',
  24.                 'createdAt',
  25.                 'updatedAt'
  26.             ];
  27.              if(_.has(request.body, 'record')){
  28.                 _.each(itemsToRemove, function(item) {
  29.                     if( _.has(request.body.record, item)) delete request.body.record[item];
  30.                 });
  31.             }
  32.             console.log(request.body.record);
  33.         }
  34.  
  35.         sails.log.verbose('     OK');
  36.  
  37.         next();    
  38. };
  39.  
  40. function fix(record){
  41.     if(!record) return;
  42.     var relational = {};
  43.     _.each(record, function(item, key) {
  44.         // Fix One to One and push back the ID.
  45.         if( _.has(item, 'id') && item.id) {
  46.             record[key] = item.id;
  47.         }
  48.         // Fix Many to Many and Push it into a Relational Key
  49.         if( _.isArray(item) || _.isObject(item) ) {
  50.             relational[key] = _.cloneDeep(item);
  51.             delete record[key];
  52.         }
  53.     });
  54.     record.relational = relational;
  55.     if(!_.isEmpty(record.relational)) return record;
  56.     fix(record.relational);
  57. }
Advertisement
Add Comment
Please, Sign In to add comment