Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- /**
- * Policy to fix data records coming in from Angular via "Record"
- * We pass any relational data into a relational key and delete the previous key to prevent Waterline from Updating It.
- * We set any key that has a property of id, to that id
- * We delete the id, since we should be passing it in via REST
- * We delete createdBy, updatedBy, createdAt, and updatedAt
- * Note, to use the addDataCreate and addDataUpdate, it must come AFTER this function.
- *
- * @param {Request} request Request object
- * @param {Response} response Response object
- * @param {Function} next Callback function
- */
- module.exports = function(request, response, next) {
- sails.log.verbose(' POLICY - ' + __filename + ':' + __line);
- if(_.has(request.body, 'record')){
- request.body.record = fix(request.body.record);
- // Remove Extras.
- var itemsToRemove = [
- 'id',
- 'createdBy',
- 'updatedBy',
- 'createdAt',
- 'updatedAt'
- ];
- if(_.has(request.body, 'record')){
- _.each(itemsToRemove, function(item) {
- if( _.has(request.body.record, item)) delete request.body.record[item];
- });
- }
- console.log(request.body.record);
- }
- sails.log.verbose(' OK');
- next();
- };
- function fix(record){
- if(!record) return;
- var relational = {};
- _.each(record, function(item, key) {
- // Fix One to One and push back the ID.
- if( _.has(item, 'id') && item.id) {
- record[key] = item.id;
- }
- // Fix Many to Many and Push it into a Relational Key
- if( _.isArray(item) || _.isObject(item) ) {
- relational[key] = _.cloneDeep(item);
- delete record[key];
- }
- });
- record.relational = relational;
- if(!_.isEmpty(record.relational)) return record;
- fix(record.relational);
- }
Advertisement
Add Comment
Please, Sign In to add comment