Example #1
0
    // create the datafeedConfig section of the job config
    function getDatafeedSelection() {
      if ($scope.ui.isDatafeed) {
        const df = $scope.ui.datafeed;

        if (df.queryText === '') {
          df.queryText = '{"match_all":{}}';
        }
        let query = df.queryText;
        try {
          query = JSON.parse(query);
        } catch (e) {
          console.log('getDatafeedSelection(): could not parse query JSON');
        }

        let indices = [];
        if (df.indicesText) {
          indices = df.indicesText.split(',').map(i => i.trim());
        }

        let types = [];
        if (df.typesText) {
          types = df.typesText.split(',');
          for (let i = 0; i < types.length; i++) {
            types[i] = types[i].trim();
          }
        }
        // if the selected types is different to all types
        // the user must have edited the json, so use the types object
        // otherwise, the types object is the same as all types, so set
        // types to an empty array
        const typeKeys = Object.keys($scope.ui.types);
        if (_.difference(typeKeys, types).length === 0) {
          types = [];
        }

        // create datafeedConfig if it doesn't already exist
        if (!$scope.job.datafeed_config) {
          $scope.job.datafeed_config = {};
        }

        const config = $scope.job.datafeed_config;

        config.query = query;

        if (df.queryDelayText === '' || df.queryDelayText === null || df.queryDelayText === undefined) {
          delete config.query_delay;
        }
        else {
          config.query_delay = df.queryDelayText;
        }

        if (df.frequencyText === '' || df.frequencyText === null || df.frequencyText === undefined) {
          delete config.frequency;
        }
        else {
          config.frequency = df.frequencyText;
        }

        if (df.scrollSizeText === '' || df.scrollSizeText === null || df.scrollSizeText === undefined) {
          delete config.scroll_size;
        }
        else {
          config.scroll_size = df.scrollSizeText;
        }

        config.indices = indices;
        config.types = types;
      }
    }
Example #2
0
 .spread(function(all, completed) {
   return this.runBatch(_.difference(all, completed), 'up');
 })
 _.forEach(missingLanguages, function(language){
     options.taskTree.build = _.difference(options.taskTree.build, langMap[language]);
     options.taskTree.lint = _.difference(options.taskTree.lint, langMap[language]);
     options.taskTree.minify = _.difference(options.taskTree.minify, langMap[language]);
     options.taskTree.preTest = _.difference(options.taskTree.preTest, langMap[language]);
 });
        it("drops the keys", function() {
          var expectedKeys = _.difference(_.keys(immutable), keys);
          var result = immutable.without(keys);

          TestUtils.assertJsonEqual(_.keys(result), expectedKeys);
        });
module.exports = function(grunt) {
    
 var _ = require('lodash'),
    path = require("path"),
    fs = require("fs"),
    step = require("step");
    
  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks
  
 grunt.config.merge({
    copy: {
        macDistributionCopy: {
            options: {
                process: function(content, srcpath) {
                    return content.replace(/&lt;/g, "<").replace(/^\s*[\r\n]/gm,"");
                }
            }
        }
    },
    clean: {
        pkgfiles: []
    },
    exec: {
        mkdir: {
            cmd: function(dir) {
                return "mkdir -p " + dir;
            }
        },
        mv: {
            cmd: function(file1, file2) {
                return 'mv "' + file1 + '" "' + file2 + '"';
            }
        },
        synthesizeMacProduct: {
			cmd: function(cwd, packages, distr) {
                var packagesStr = _.map(packages.split(","), function(p) {return ' --package "' + path.join(cwd, p) + '"'; }).join(' ');
                return "productbuild --synthesize " + packagesStr + ' "' + distr + '"';
			},
			stdout: true
		},
		createMacProduct: {
			cmd: function(distr, packpath, respath, scriptpath, dest, pkgname) {
                return 'productbuild --distribution "' + distr + '"' +
                            ((!!respath && respath.length > 0) ? (' --resources "'+ respath + '"'):"") +
                            ((!!scriptpath && scriptpath.length > 0) ? (' --scripts "' + scriptpath + '"'):"") +
                            ' --package-path "' + packpath + '" "' + path.join(dest, pkgname) + '.pkg"';
			},
		    stdout: true
		}
	},
    xmlpoke: {
        setLine: {
            options: {
                xpath: '/installer-gui-script',
                valueType: "append"
            }
        },
        setScript: {
            options: {
                replacements: [
                    {
                        xpath: "/installer-gui-script/options",
                        valueType: "remove"
                    },
                    {
                        xpath: '/installer-gui-script',
                        valueType: "append"
                    },
                    {
                        xpath: '//script'
                    }
                ]
            }
        }
    }
 });
    
    var libs = ['grunt-contrib-clean', 'grunt-contrib-copy', 'grunt-exec', 'grunt-pkgbuild', 'grunt-xmlpoke'];
    
    var apppath = process.cwd(),
    dirfiles = [],
    libfiles = [];
    
    process.chdir(__dirname);
    var currpath = process.cwd();
    
    while(currpath !== "/" && libs.length > 0) {
        if(fs.existsSync("node_modules")) {
            dirfiles = grunt.file.expand({cwd: path.join(currpath,"node_modules"), filter:"isDirectory"}, "*" );
            libfiles = _.intersection(dirfiles, libs);
            for(var i = 0; i<libfiles.length; i++) {
                grunt.loadNpmTasks(libfiles[i]);
            }
            libs = _.difference(libs, libfiles);
        }
        currpath = path.join(process.cwd(), "../");
        process.chdir(currpath);
    }
    
    process.chdir(apppath);
    
  //create pkgbuild tasks
  var pkgbuild = {};
  _.each(grunt.config("productbuild"), function(val, key) {
      pkgbuild[key] = val.packages;
         var cwd = val.options.cwd || val.cwd;
         var dest = val.options.dest || val.dest;
         if(!pkgbuild[key].cwd && !!cwd) {
            pkgbuild[key].cwd = cwd;
         }
        if(!pkgbuild[key].dest && !!dest) {
           pkgbuild[key].dest = dest;
        }
  });
  
  grunt.config.merge({pkgbuild: pkgbuild});


  function setTitle(title) {
      return ((!!title && title.length >  0) ? ("<title>"+title+"</title>"+grunt.util.linefeed) : "");
  }
    
  function setResource(type, file) {
      return ((!!file && file.length > 0) ? ("<"+type+" file='"+file+"' />"+grunt.util.linefeed) : "");
  }
    
  function setScriptFunctionName(name) {
      return "<options allow-external-scripts='yes' />" + grunt.util.linefeed + "<installation-check script='" + name + ";' />" + grunt.util.linefeed + "<script />" + grunt.util.linefeed;
 
  }
    
  function getFunction(name, dir, title, message) {
      var str = "";
      var runscr = grunt.file.expand({cwd: dir}, "*").join(" && ");
      if(!!runscr && runscr.length > 0) {
          str = "function " + name + "() {" + grunt.util.linefeed;
          str += 'var exit_code = system.run("'+runscr+'");' + grunt.util.linefeed;
          str += 'if(exit_code !== 0) {' + grunt.util.linefeed;
          str += 'my.result.title = "' + title + '";' + grunt.util.linefeed;
          str += 'my.result.message = "' + message + '";' + grunt.util.linefeed;
          str += 'my.result.type = "Fatal";' + grunt.util.linefeed;
          str += 'return false;' + grunt.util.linefeed;
          str += '}' + grunt.util.linefeed;
          str += 'return true;' + grunt.util.linefeed;
          str += '}';
      }
      return str;
  }
    
  function setScript(script_str) {
      return ((!!script_str && script_str.length > 0) ? ("<![CDATA[" + grunt.util.linefeed + script_str + grunt.util.linefeed + "]]>") : "");
  }
    
  grunt.registerMultiTask('productbuild', 'Create Mac product', function() {
	//Check platform
	if(process.platform !== 'darwin') {
		grunt.log.error("This should be run on a Mac computer");
		return false;
	} 
	  
    var data = this.data,
        options = this.options({cwd: process.cwd(), dest: process.cwd()}),
        packages = _.defaults(data.packages, {cwd: options.cwd, dest: options.dest}),
        taskname = this.target,
        files = packages.files;
                          
    _.each(data, function(val, key) {
        if(key !== "options" && key !== "files") {
            options[key] = val;
        }
    });
                          
    _.each(["cwd", "dest"], function(d) {
        _.each([options, packages], function(a) {
               if(!grunt.file.isPathAbsolute(a[d])) {
                    a[d] = path.resolve(a[d]);
               }
        });
    });
                          

    if(!options.pkgname) {
        console.log("No package name provided, skipping");
        return;
    }
                          
    if(!!options.dest) {
        grunt.task.run("exec:mkdir:"+options.dest);
    }
                          
    var cwd = options.cwd || ".",
        pkgcwd = packages.dest || options.dest || ".",
        dest = options.dest || ".",
        distrfile = path.join(dest, "distribution.dist"),
        distrfile1 = path.join(dest, "distribution1.dist"),
        script_path = "",
        res_path = "",
        distrfiles = {},
        pkgfiles = [];
        distrfiles[distrfile1] = distrfile;
                          
                          
    step(
         function create_pkg() {
            grunt.config("pkgbuild."+taskname+".callback", this);
            grunt.task.run("pkgbuild:"+taskname);
         },
         function synthesize() {
            pkgfiles = grunt.file.expand({cwd: pkgcwd}, "*.pkg");
         
            grunt.config("exec.synthesizeMacProduct.callback", this);
            grunt.task.run("exec:synthesizeMacProduct:"+pkgcwd+":"+pkgfiles+":"+distrfile);
         },
         function set_resources(err, stdout, stderr) {
            if(!!options.resources && (!!options.title || !!options.license || !!options.welcome || !!options.readme)) {
                res_path = grunt.file.isPathAbsolute(options.resources) ? options.resources : path.join(cwd, options.resources);
         
                grunt.config("xmlpoke.setLine.files", distrfiles);
         
                //set title and resource tags in the distribution file
                var line = _.reduce(["welcome", "license", "readme"], function(result, d) {
                    return result + setResource(d, options[d]);
                }, setTitle(options.title));
                          
                grunt.config("xmlpoke.setLine.options.value", line);
                grunt.task.run("xmlpoke:setLine");
         
                grunt.config("exec.mv.callback", this);
                grunt.task.run("exec:mv:"+distrfile1+":"+distrfile);
            } else {
                this.call();
            }
         },
         function get_validation_script() {
            var script_content = "";
            if(_.isString(options.script)) {
                script_content = grunt.file.read(grunt.file.isPathAbsolute(options.script) ? options.script : path.join(cwd, options.script));
            } else if(_.isObject(options.script)) {
                if(!!options.script.src) {
                   var p = grunt.file.isPathAbsolute(options.script.src) ? options.script.src : path.join(cwd, options.script.src);
                   if(grunt.file.isFile(p)) {
                        script_content = grunt.file.read(p);
                   } else if(grunt.file.isDir(p)){
                        script_content = getFunction(options.script.func || "check_installation", p, options.script.title || "Error", options.script.message || "Validation has failed");
                        script_path = p;
                   } else {
                        grunt.log.warn("The script files don't exist, skipping");
                   }
                } else {
                    grunt.log.warn("Script for " + taskname + " is missing, skipping");
                }
            }
            return script_content;
         },
         function set_validation_function(err, scriptContent) {
            var checkfunc = /function\s+(.+\(\))/.exec(scriptContent || "");
            if(!!checkfunc && _.size(checkfunc) > 1) {
                var func_index = _.findIndex(grunt.config.get("xmlpoke.setScript.options.replacements"), function(r) {
                    return r.xpath === "/installer-gui-script";
                });
                grunt.config("xmlpoke.setScript.options.replacements."+func_index+".value", setScriptFunctionName(checkfunc[1]));
                return scriptContent;
            } else {
                grunt.log.warn("No function found in the script, skipping");
                return null;
            }
         },
         function set_validation_script(err, scriptStr) {
            if(!!scriptStr && scriptStr.length > 0) {
                var script_index = _.findIndex(grunt.config.get("xmlpoke.setScript.options.replacements"), function(r) {
                    return r.xpath === "//script";
                });
                grunt.config("xmlpoke.setScript.files", distrfiles);
                grunt.config("xmlpoke.setScript.options.replacements."+script_index+".value", setScript(scriptStr));
                grunt.task.run("xmlpoke:setScript");
                          
                grunt.config("copy.macDistributionCopy.src", distrfile1);
                grunt.config("copy.macDistributionCopy.dest", distrfile);
                          
                // hack, correct messed up symbols in the distribution file
                grunt.task.run("copy:macDistributionCopy");
            }
            return true;
         },
         function create_package() {
                          
            grunt.config("exec.createMacProduct.callback", this);
            grunt.task.run("exec:createMacProduct:"+distrfile+":"+pkgcwd+":"+res_path+":"+script_path+":"+dest+":"+options.pkgname);
            
         },
         function cleanup() {
            //callback
            var func = options.callback;
            if(!func || typeof func !== "function") {
                func = function() {
                    grunt.log.ok("PACKAGE " + options.pkgname +" FOR TASK " + taskname+ " HAS BEEN CREATED");
                };
            }
                          
            grunt.config("clean.pkgfiles", [dest + "/*.dist", dest + "/*.plist"]
                                       .concat(_.map(pkgfiles, function(p) {
                                                    return path.join(dest,p);
                                                } )));
            grunt.task.run("clean:pkgfiles");
            func.call();
         }
    );
                          
  });

};
Example #6
0
    const values = params.parseRelationships === false ? params.values : Object.keys(JSON.parse(JSON.stringify(params.values))).reduce((acc, current) => {
      const association = this.associations.find(x => x.alias === current);
      const details = this._attributes[current];

      if (_.get(this._attributes, `${current}.isVirtual`) !== true && _.isUndefined(association)) {
        acc[current] = params.values[current];
      } else {
        switch (association.nature) {
          case 'oneWay':
            acc[current] = _.get(params.values[current], this.primaryKey, params.values[current]) || null;

            break;
          case 'oneToOne':
            if (response[current] !== params.values[current]) {
              const value = _.isNull(params.values[current]) ? response[current] : params.values;
              const recordId = _.isNull(params.values[current]) ? getValuePrimaryKey(value, this.primaryKey) : value[current];

              const model = module.exports.getModel(details.model || details.collection, details.plugin);

              // Remove relation in the user side.
              virtualFields.push(
                model
                  .findOne({ [model.primaryKey]: value[current] })
                  .populate(details.via)
                  .then(record => {
                    if (record && _.isObject(record[details.via])) {
                      return module.exports.update.call(this, {
                        id: getValuePrimaryKey(record[details.via], model.primaryKey),
                        values: {
                          [current]: null
                        },
                        parseRelationships: false
                      });
                    }

                    return Promise.resolve();
                  })
                  .then(() => {
                    return module.exports.update.call(model, {
                      id: getValuePrimaryKey(response[current] || {}, this.primaryKey) || value[current],
                      values: {
                        [details.via]: null
                      },
                      parseRelationships: false
                    });
                  })
                  .then(() => {
                    if (!_.isNull(params.values[current])) {
                      return module.exports.update.call(model, {
                        id: recordId,
                        values: {
                          [details.via]: getValuePrimaryKey(params, this.primaryKey) || null
                        },
                        parseRelationships: false
                      });
                    }

                    return Promise.resolve();
                  })
              );

              acc[current] = _.isNull(params.values[current]) ? null : value[current];
            }

            break;
          case 'oneToMany':
          case 'manyToOne':
          case 'manyToMany':
            if (association.nature === 'manyToMany' && details.dominant === true) {
              acc[current] = params.values[current];
            } else if (response[current] && _.isArray(response[current]) && current !== 'id') {
              // Records to add in the relation.
              const toAdd = _.differenceWith(params.values[current], response[current], (a, b) =>
                a[this.primaryKey].toString() === b[this.primaryKey].toString()
              );

              // Records to remove in the relation.
              const toRemove = _.differenceWith(response[current], params.values[current], (a, b) =>
                a[this.primaryKey].toString() === b[this.primaryKey].toString()
              )
                .filter(x => toAdd.find(y => x.id === y.id) === undefined);

              const model = module.exports.getModel(details.model || details.collection, details.plugin);

              // Push the work into the flow process.
              toAdd.forEach(value => {
                value = _.isString(value) ? { [this.primaryKey]: value } : value;

                if (association.nature === 'manyToMany' && !_.isArray(params.values[this.primaryKey] || params[this.primaryKey])) {
                  value[details.via] = (value[details.via] || [])
                    .concat([(params.values[this.primaryKey] || params[this.primaryKey])])
                    .filter(x => {
                      return x !== null && x !== undefined;
                    });
                } else {
                  value[details.via] = getValuePrimaryKey(params, this.primaryKey);
                }

                virtualFields.push(
                  module.exports.addRelation.call(model, {
                    id: getValuePrimaryKey(value, this.primaryKey),
                    values: _.pick(value, [this.primaryKey, details.via]),
                    foreignKey: current
                  })
                );
              });

              toRemove.forEach(value => {
                value = _.isString(value) ? { [this.primaryKey]: value } : value;

                if (association.nature === 'manyToMany' && !_.isArray(params.values[this.primaryKey] || params[this.primaryKey])) {
                  value[details.via] = value[details.via].filter(x => _.toString(x) !== _.toString(params.values[this.primaryKey] || params[this.primaryKey]));
                } else {
                  value[details.via] = null;
                }

                virtualFields.push(
                  module.exports.removeRelation.call(model, {
                    id: getValuePrimaryKey(value, this.primaryKey),
                    values: _.pick(value, [this.primaryKey, details.via]),
                    foreignKey: current
                  })
                );
              });
            } else if (_.get(this._attributes, `${current}.isVirtual`) !== true) {
              acc[current] = params.values[current];
            }

            break;
          case 'manyMorphToMany':
          case 'manyMorphToOne':
            // Update the relational array.
            acc[current] = params.values[current].map(obj => {
              const globalId = obj.source && obj.source !== 'content-manager' ?
                strapi.plugins[obj.source].models[_.toLower(obj.ref)].globalId:
                strapi.models[_.toLower(obj.ref)].globalId;

              // Define the object stored in database.
              // The shape is this object is defined by the strapi-mongoose connector.
              return {
                ref: obj.refId,
                kind: globalId,
                [association.filter]: obj.field
              };
            });
            break;
          case 'oneToManyMorph':
          case 'manyToManyMorph': {
            const transformToArrayID = (array) => {
              if (_.isArray(array)) {
                return array.map(value => {
                  if (_.isPlainObject(value)) {
                    return getValuePrimaryKey(value, this.primaryKey);
                  }

                  return value;
                });
              }

              if (association.type === 'model' || (association.type === 'collection' && _.isObject(array))) {
                return _.isEmpty(array) ? [] : transformToArrayID([array]);
              }

              return [];
            };

            // Compare array of ID to find deleted files.
            const currentValue = transformToArrayID(response[current]).map(id => id.toString());
            const storedValue = transformToArrayID(params.values[current]).map(id => id.toString());

            const toAdd = _.difference(storedValue, currentValue);
            const toRemove = _.difference(currentValue, storedValue);

            const model = module.exports.getModel(details.model || details.collection, details.plugin);

            // Remove relations in the other side.
            toAdd.forEach(id => {
              virtualFields.push(
                module.exports.addRelationMorph.call(model, {
                  id,
                  alias: association.via,
                  ref: this.globalId,
                  refId: response._id,
                  field: association.alias
                })
              );
            });

            // Remove relations in the other side.
            toRemove.forEach(id => {
              virtualFields.push(
                module.exports.removeRelationMorph.call(model, {
                  id,
                  alias: association.via,
                  ref: this.globalId,
                  refId: response._id,
                  field: association.alias
                })
              );
            });
            break;
          }
          case 'oneMorphToOne':
          case 'oneMorphToMany':
            break;
          default:
        }
      }

      return acc;
    }, {});
Example #7
0
      _.forEach(functionObject.events, (event) => {
        if (_.has(event, 'http')) {
          const http = this.getHttp(event, functionName);

          http.path = this.getHttpPath(http, functionName);
          http.method = this.getHttpMethod(http, functionName);

          if (http.authorizer) {
            http.authorizer = this.getAuthorizer(http, functionName);
          }

          if (http.cors) {
            http.cors = this.getCors(http);

            const cors = corsPreflight[http.path] || {};

            cors.headers = _.union(http.cors.headers, cors.headers);
            cors.methods = _.union(http.cors.methods, cors.methods);
            cors.origins = _.union(http.cors.origins, cors.origins);
            cors.origin = http.cors.origin || '*';
            cors.allowCredentials = cors.allowCredentials || http.cors.allowCredentials;

            corsPreflight[http.path] = cors;
          }

          http.integration = this.getIntegration(http, functionName);

          if ((http.integration === 'HTTP' || http.integration === 'HTTP_PROXY') &&
            (!http.request || !http.request.uri)) {
            const errorMessage = [
              `You need to set the request uri when using the ${http.integration} integration.`,
            ];
            throw new this.serverless.classes.Error(errorMessage);
          }

          if (http.integration === 'AWS' || http.integration === 'HTTP') {
            http.request = this.getRequest(http);
            http.request.passThrough = this.getRequestPassThrough(http);
            http.response = this.getResponse(http);
            if (http.integration === 'AWS' && _.isEmpty(http.response)) {
              http.response = {
                statusCodes: DEFAULT_STATUS_CODES,
              };
            }
          } else if (http.integration === 'AWS_PROXY' || http.integration === 'HTTP_PROXY') {
            // show a warning when request / response config is used with AWS_PROXY (LAMBDA-PROXY)
            if (http.request) {
              const keys = Object.keys(http.request);
              const allowedKeys =
                http.integration === 'AWS_PROXY' ? ['parameters'] : ['parameters', 'uri'];

              if (!_.isEmpty(_.difference(keys, allowedKeys))) {
                const requestWarningMessage = [
                  `Warning! You're using the ${http.integration} in combination with a request`,
                  ` configuration in your function "${functionName}". Only the `,
                  _.map(allowedKeys, value => `request.${value}`).join(', '),
                  ` configs are available in conjunction with ${http.integration}.`,
                  ' Serverless will remove this configuration automatically',
                  ' before deployment.',
                ].join('');
                this.serverless.cli.log(requestWarningMessage);
                for (const key of keys) {
                  if (!_.includes(allowedKeys, key)) {
                    delete http.request[key];
                  }
                }
              }
              if (Object.keys(http.request).length === 0) {
                // No keys left, delete the request object
                delete http.request;
              } else {
                http.request = this.getRequest(http);
              }
            }
            if (http.response) {
              const warningMessage = [
                `Warning! You're using the ${http.integration} in combination with response`,
                ` configuration in your function "${functionName}".`,
                ' Serverless will remove this configuration automatically before deployment.',
              ].join('');
              this.serverless.cli.log(warningMessage);

              delete http.response;
            }
          }

          events.push({
            functionName,
            http,
          });
        }
      });
Example #8
0
var checkAllRequiredSchemes = function(required_schemes, errors) {
  var missing = _.difference(required_schemes, ids.filter(id => !id.void).map((id) => id.scheme));
  if (missing.length > 0) {
    errors.push("missing schemes: " + missing.join(', '));
  }
};
	return inlineWhitelistTagGroups.some( ( tagGroup ) =>
		difference( [ tag, contextTag ], tagGroup ).length === 0
Example #10
0
 it('should not leave unmentioned rules against the eslint all rules', () => {
   var unspecified = _.difference(_.keys(eslintAllRules), _.keys(mentionedAllRules));
   expect(unspecified).to.be.empty;
 });
Example #11
0
 it('should not contain invalid rules', () => {
   var invalid = _.difference(_.keys(mentionedAllRules), _.keys(eslintAllRules));
   expect(invalid).to.be.empty;
 });
Example #12
0
 return new Disposable(() => this.tools = _.difference(this.tools, builders));
Example #13
0
      errorMatch: ''
    };
  },

  settingsMakeUnique(settings) {
    let diff;
    const appender = (setting) => {
      setting._uniqueIndex = setting._uniqueIndex || 1;
      setting._originalName = setting._originalName || setting.name;
      setting.name = `${setting._originalName} - ${setting._uniqueIndex++}`;
      settings.push(setting);
    };
    let i = 0;
    do {
      const uniqueSettings = _.uniq(settings, 'name');
      diff = _.difference(settings, uniqueSettings);
      settings = uniqueSettings;
      diff.forEach(appender);
    } while (diff.length > 0 && i++ < 10);

    return settings;
  },

  refreshTargets(refreshPaths) {
    refreshPaths = refreshPaths || atom.project.getPaths();

    const pathPromise = refreshPaths.map((p) => {
      this.targetsLoading[p] = true;
      this.targets[p] = this.targets[p] || [];

      this.instancedTools[p] = (this.instancedTools[p] || [])
Example #14
0
 // look at the difference between loaded ES influencers and the ones in the current job.
 // unrecognised influencers must have been added by the user.
 function extractCustomInfluencers() {
   const allInfluencersList = $scope.ui.influencers;
   $scope.ui.customInfluencers = _.difference($scope.job.analysis_config.influencers, allInfluencersList);
   console.log('extractCustomInfluencers: ', $scope.ui.customInfluencers);
 }
Example #15
0
 return this._migrationData().tap(validateMigrationList).spread(function (all, completed) {
   return _this._runBatch(_.difference(all, completed), 'up');
 });
Example #16
0
File: apidoc.js Project: spark/docs
    _.each(route.parameter.fields, function(params, title) {
      if (title === 'Parameter') {
        baseParams = params;
        baseSuccess = (route.success.fields || {})['Success 200'] || [];
        baseError = (route.error.fields || {})['Error 4xx'] || [];
        return;
      }

      // create new clone route
      var groupKey = params[0].group;
      var newRoute = _.cloneDeep(route);
      newRoute.title = title;
      newRoute.description = null;
      newRoute.parameter.fields = {
        Parameter: baseParams.concat(params)
      };

      // grab op specific response fields too
      var responseFields = (route.success.fields || {})[title];
      if (responseFields) {
        newRoute.success.fields = {
          'Success 200': baseSuccess.concat(responseFields)
        };
        delete route.success.fields[title];
      }
      var errorFields = (route.error.fields || {})[title];
      if (errorFields) {
        newRoute.error.fields = {
          'Error 4xx': baseError.concat(errorFields)
        };
        delete route.error.fields[title];
      }

      // copy over specific examples
      if (examplesIndex[groupKey] && examplesIndex[groupKey].length) {
        newRoute.examples = examplesIndex[groupKey];
        newRoute.examples.forEach(function (ex) {
          ex.title = ex.content;
        });
      } else {
        newRoute.examples = null;
      }
      // remove copied examples from base
      route.examples = _.difference(route.examples, newRoute.examples);

      if (successExamplesIndex[groupKey] && successExamplesIndex[groupKey].length) {
        newRoute.success.examples = successExamplesIndex[groupKey];
        newRoute.success.examples.forEach(function (ex) {
          ex.title = ex.content;
        });
      } else {
        newRoute.success.examples = null;
      }
      route.success.examples = _.difference(route.success.examples, newRoute.success.examples);

      if (errorExamplesIndex[groupKey] && errorExamplesIndex[groupKey].length) {
        newRoute.error.examples = errorExamplesIndex[groupKey];
        newRoute.error.examples.forEach(function (ex) {
          ex.title = ex.content;
        });
      } else {
        newRoute.error.examples = null;
      }
      route.error.examples = _.difference(route.error.examples, newRoute.error.examples);

      // add to list of all routes
      i++;
      data.splice(i, 0, newRoute);
    });
Example #17
0
 onClick={() =>
     this.setState({
         nextSelectedTags: !tagSelected
             ? union(nextSelectedTags, [tag])
             : difference(nextSelectedTags, [tag]),
     })
Example #18
0
    self.indexPage = function(req, callback) {

      // Finesse so we can use queryToFilters but we still support q, which is
      // a common expectation/preference
      req.query.search = req.query.search || req.query.q;

      // Cope with filters
      var allowedTypes;

      var defaultingToAll = false;

      var cursor = self.apos.docs.find(req, {})
        .queryToFilters(req.query, 'public')
        .perPage(self.perPage);
      if (self.filters) {
        var filterTypes = _.filter(
          _.pluck(self.filters, 'name'),
          function(name) {
            return name !== '__else';
          }
        );
        var found = false;
        allowedTypes = _.filter(self.types, function(name) {
          return _.has(req.query, name);
        });
        if (req.query.__else) {
          allowedTypes = allowedTypes.concat(_.difference(self.types, filterTypes));
        }
        if (!allowedTypes.length) {
          // Default is everything
          defaultingToAll = true;
          allowedTypes = self.types;
        }
      } else {
        allowedTypes = self.types;
      }
      cursor.and({ type: { $in: allowedTypes } });

      var docs = [];

      if (self.filters) {
        req.data.filters = _.cloneDeep(self.filters);

        _.each(req.data.filters, function(filter) {
          if (defaultingToAll || req.query[filter.name]) {
            filter.value = true;
          }
        });
      }

      return async.series([ totalDocs, findDocs ], function(err) {

        if (err) {
          return callback(err);
        }

        if (self.apos.utils.isAjaxRequest(req)) {
          req.template = self.renderer('indexAjax');
        } else {
          req.template = self.renderer('index');
        }
        req.data.currentPage = cursor.get('page');
        req.data.docs = docs;

        return self.beforeIndex(req, callback);
      });

      function totalDocs(callback) {
        return cursor.toCount(function(err, count) {
          if (err) {
            return callback(err);
          }
          if (cursor.get('page') > cursor.get('totalPages')) {
            req.notFound = true;
            return callback(null);
          }
          req.data.totalDocs = count;
          req.data.totalPages = cursor.get('totalPages');
          return callback();
        });
      }

      function findDocs(callback) {

        // Polymorphic find: fetch just the ids at first, then go back
        // and fetch them via their own type managers so that we get the
        // expected joins and urls and suchlike.

        var idsAndTypes;
        var byType;

        return async.series([
          getIdsAndTypes,
          getDocs
        ], callback);

        function getIdsAndTypes(callback) {
          return cursor.projection({ _id: 1, type: 1 }).toArray(function(err, _idsAndTypes) {
            if (err) {
              return callback(err);
            }
            idsAndTypes = _idsAndTypes;
            return callback(null);
          });
        }

        function getDocs(callback) {
          byType = _.groupBy(idsAndTypes, 'type');
          return async.eachSeries(_.keys(byType), getDocsOfType, function(err) {
            if (err) {
              return callback(err);
            }
            // Restore the intended order ($in doesn't respect it and neither does
            // fetching them all by type). ACHTUNG: without this search quality goes
            // right out the window. -Tom
            docs = self.apos.utils.orderById(_.pluck(idsAndTypes, '_id'), docs);
            return callback(null);
          });
        }

        function getDocsOfType(type, callback) {
          var manager = self.apos.docs.getManager(type);
          if (!manager) {
            return setImmediate(callback);
          }
          return manager.find(req,
            {
              type: type,
              _id: {
                $in: _.pluck(byType[type], '_id')
              }
            }
          ).toArray(function(err, docsOfType) {
            if (err) {
              return callback(err);
            }
            docs = docs.concat(docsOfType);
            return callback(null);
          });
        }

      };

    };
Example #19
0
var compact = _.compact([0, 1, false, 2, '', 3]);
console.log('compact', compact);

/**
 * difference(array, [values])
 * 取出array中values中没有的。
 * create an array excluding all values of the provided arrays using strict equality for comparisons. i.e ===
 * arguments:
 *  |-- array(Array):
 *      the array to process
 *  |-- values(Array)
 *      the array of values to exclude
 * returns:
 *  (array): returns a new array of values to exclude
 */
var diff = _.difference([1,2,3,4,5], [5,2,3]);
console.log('diff', diff); // [1,4]

/**
 * _.findIndex(array, [callback=_.identity], [thisArg])
 * this method is like _.find except that it returns the index of the first element that passes the callback check.
 *返回找到的第一个数组索引值
 * Arguments:
 *  |-- array(Array)
 *      the array to search
 *  |-- thisArg(*)
 *      the this binding of callback
 *
 * returns
 * (number): Returns the index of the found ele, else -1
 *
Example #20
0
    paths: React.PropTypes.object,
  },

  getInitialState() {
    return {
      paths: null
    }
  },

  render() {
    const {
      idsOfAeObjects,
      idsNotImportable,
    } = this.props
    const { paths } = this.state
    const idsImported = difference(idsOfAeObjects, idsNotImportable)
    const first5Ids = idsImported.slice(0, 5)
    const alertStyle = { marginTop: 11 }

    // only get paths on first render
    if (!paths) {
      getPathsFromLocalDb()
        .then((paths) =>
          this.setState({ paths })
        )
        .catch((error) =>
          addError({
            title: 'Fehler beim Aufbauen der Beispiele:',
            msg: error
          })
        )
Example #21
0
function optsInvalid(opts, valid_opts) {
  return _.difference(_.keys(opts), valid_opts).length;
}
/////////////////////////////////////////////////////////////////////
// Reference file logic
////////////////////////////////////////////////////////////////////
// Updates the reference file
function updateReferenceFile(files, generatedFiles, referenceFile, referencePath, eol) {
    var referenceIntro = '/// <reference path="';
    var referenceEnd = '" />';
    var referenceMatch = /\/\/\/ <reference path=\"(.*?)\"/;
    var ourSignatureStart = '//grunt-start';
    var ourSignatureEnd = '//grunt-end';
    // remove the generated files from files:
    files = _.difference(files, generatedFiles);
    var lines = []; // All lines of the file
    var origFileLines = []; // The lines we do not modify and send out as is. Lines will we reach grunt-ts generated
    var origFileReferences = []; // The list of files already there that we do not need to manage
    // Location of our generated references
    // By default at start of file
    var signatureSectionPosition = 0;
    var i;
    // Read the original file if it exists
    var referenceContents = '';
    if (fs.existsSync(referenceFile)) {
        referenceContents = fs.readFileSync(referenceFile).toString();
        lines = referenceContents.split(/\r\n|\r|\n/);
        var inSignatureSection = false;
        // By default our signature goes at end of file
        signatureSectionPosition = lines.length;
        for (i = 0; i < lines.length; i++) {
            var line = _str.trim(lines[i]);
            // Skip logic for our generated section
            if (_str.include(line, ourSignatureStart)) {
                // Wait for the end signature:
                signatureSectionPosition = i;
                inSignatureSection = true;
                continue;
            }
            if (_str.include(line, ourSignatureEnd)) {
                inSignatureSection = false;
                continue;
            }
            if (inSignatureSection) {
                continue;
            }
            // store the line
            origFileLines.push(line);
            // Fetch the existing reference's filename if any:
            if (_str.include(line, referenceIntro)) {
                var match = line.match(referenceMatch);
                var filename = match[1];
                origFileReferences.push(filename);
            }
        }
    }
    // Put in the generated files
    generatedFiles = _.map(generatedFiles, function (file) { return referenceIntro + utils.makeRelativePath(referencePath, file) + referenceEnd; });
    var contents = utils.insertArrayAt([ourSignatureStart], 1, generatedFiles);
    // Put in the new / observed missing files:
    files.forEach(function (filename) {
        // The file we are about to add
        var filepath = utils.makeRelativePath(referencePath, filename);
        // If there are orig references
        if (origFileReferences.length) {
            if (_.contains(origFileReferences, filepath)) {
                return;
            }
        }
        // Finally add the filepath
        contents.push(referenceIntro + filepath + referenceEnd);
    });
    contents.push(ourSignatureEnd);
    var updatedFileLines = utils.insertArrayAt(origFileLines, signatureSectionPosition, contents);
    var updatedFileContents = updatedFileLines.join(eol);
    // Modify the orig contents to put in our contents only if changed
    // Also Return whether the file was changed
    if (updatedFileContents !== referenceContents) {
        grunt.file.write(referenceFile, updatedFileContents);
        return true;
    }
    else {
        return false;
    }
}
Example #23
0
 return function (newFitlers, oldFilters) {
   var diff = _.difference(oldFilters, newFitlers);
   return (diff.length && _.every(diff, pluckDisabled));
 };
Example #24
0
var preparingData = function() {
  var fsOptions = {encoding: 'utf8'};
  var uiBase = fs.readFileSync('./less/amui.less', fsOptions);
  var widgetsStyleDeps = [];
  var widgetsStyle = '';
  var widgetsStyleWithDeps = '';
  var WIDGET_DIR = './widget';
  var rejectWidgets = ['.DS_Store', 'blank', 'layout2', 'layout3', 'layout4',
    'container', 'powered_by', 'tech_support', 'toolbar', 'switch_mode'];
  var allWidgets = _.reject(fs.readdirSync(WIDGET_DIR), function(widget) {
    return rejectWidgets.indexOf(widget) > -1;
  });

  var modules = [];
  var modulesBasic = [];
  var modulesWidgets = [];

  allPlugins = fs.readdirSync('./js');
  plugins = fs.readdirSync('./js');

  var partials = '(function(undefined){\n';
  partials += '  \'use strict\';\n\n';
  partials += '  var registerAMUIPartials = function(hbs) {\n';

  allWidgets.forEach(function(widget, i) {
    // read widget package.json
    var pkg = fs.readJsonFileSync(path.
      join(WIDGET_DIR, widget, 'package.json'));
    var srcPath = '../widget/' + widget + '/src/';

    if (i === 0) {
      widgetsStyleDeps = _.union(widgetsStyleDeps, pkg.styleBase);
    }

    widgetsStyleDeps = _.union(widgetsStyleDeps, pkg.styleDependencies);
    jsWidgets.push(pkg.script);

    jsWidgets = _.union(jsWidgets, pkg.jsDependencies);

    widgetsStyle += '\r\n// ' + widget + '\r\n';

    widgetsStyle += '@import "' + srcPath + pkg.style + '";' + '\r\n';
    _.forEach(pkg.themes, function(item, index) {
      if (!item.hidden && item.name) {
        widgetsStyle += '@import "' + srcPath + widget + '.' +
        item.name + '.less";' + '\r\n';
      }
    });

    // read tpl
    var tpl = fs.readFileSync(path.
      join(WIDGET_DIR, widget, 'src', widget + '.hbs'), fsOptions);
    partials += format('    hbs.registerPartial(\'%s\', %s);\n\n',
      widget, JSON.stringify(tpl));
  });

  widgetsStyleDeps.forEach(function(dep) {
    widgetsStyleWithDeps += format('@import "%s";\n', dep);
  });

  fs.writeFileSync('./less/amazeui.less', uiBase + widgetsStyle);

  fs.writeFileSync('./less/amazeui.widgets.less',
    widgetsStyleWithDeps + widgetsStyle);

  /**
   *  Prepare JavaScript Data
   */

    // for amazeui.basic.js
  jsBasic = _.union(config.js.base, allPlugins);

  // for amazeui.js
  jsAll = _.union(jsBasic, jsWidgets);

  jsWidgets = _.union(config.js.base, jsWidgets);

  pluginsNotUsed = _.difference(plugins, jsWidgets);

  pluginsUsed = _.remove(plugins, function(plugin) {
    return pluginsNotUsed.indexOf(plugin) == -1;
  });

  jsWidgets = _.union(config.js.base, pluginsUsed, jsWidgets);

  // seajs.use[''...]
  jsAll.forEach(function(js) {
    var basename = path.basename(js, '.js');
    modules.push(basename);

    if (basename !== 'amazeui' || basename !== 'amazeui.legacy') {
      initAll += 'require(\'./' + basename + '\');\n';
    }

    if (jsWidgets.indexOf(js) > -1) {
      modulesWidgets.push(basename);
    }

    if (jsBasic.indexOf(js) > -1) {
      modulesBasic.push(basename);
    }
  });

  initAll += '\nmodule.exports = $.AMUI;\n';

  // initAll = 'require(' + JSON.stringify(modules) + ');';
  initBasic = 'require(' + JSON.stringify(modulesBasic) + ');';
  initWidgets = 'require(' + JSON.stringify(modulesWidgets) + ');';

  // sort for concat
  jsWidgetsSorted = _.union(jsWidgets, [initWidgets]);

  jsAllSorted = _.union(jsAll);

  jsBasicSorted = _.union(jsBasic, [initBasic]);

  partials += '  };\n\n';
  partials += '  if (typeof module !== \'undefined\' && module.exports) {\n';
  partials += '    module.exports = registerAMUIPartials;\n' +
  '  }\n\n';
  partials += '  this.Handlebars && registerAMUIPartials(this.Handlebars);\n';
  partials += '}).call(this);\n';

  // write partials
  fs.writeFileSync(path.join('./vendor/amazeui.hbs.partials.js'), partials);
  fs.writeFileSync(path.join('./js/amazeui.js'), initAll);
};
Example #25
0
    .then(function () {
      if (type === 'search') {
        // This is down here to prevent the circular dependency
        flatState.body = flatState.body || {};

        const computedFields = flatState.index.getComputedFields();
        flatState.body.stored_fields = computedFields.storedFields;
        flatState.body.script_fields = flatState.body.script_fields || {};
        flatState.body.docvalue_fields = flatState.body.docvalue_fields || [];

        _.extend(flatState.body.script_fields, computedFields.scriptFields);
        flatState.body.docvalue_fields = _.union(flatState.body.docvalue_fields, computedFields.docvalueFields);

        if (flatState.body._source) {
          // exclude source fields for this index pattern specified by the user
          const filter = fieldWildcardFilter(flatState.body._source.excludes);
          flatState.body.docvalue_fields = flatState.body.docvalue_fields.filter(filter);
        }

        // if we only want to search for certain fields
        const fields = flatState.fields;
        if (fields) {
          // filter out the docvalue_fields, and script_fields to only include those that we are concerned with
          flatState.body.docvalue_fields = _.intersection(flatState.body.docvalue_fields, fields);
          flatState.body.script_fields = _.pick(flatState.body.script_fields, fields);

          // request the remaining fields from both stored_fields and _source
          const remainingFields = _.difference(fields, _.keys(flatState.body.script_fields));
          flatState.body.stored_fields = remainingFields;
          _.set(flatState.body, '_source.includes', remainingFields);
        }

        flatState.body.query = buildESQuery(flatState.index, flatState.query, flatState.filters);

        if (flatState.highlightAll != null) {
          if (flatState.highlightAll && flatState.body.query) {
            flatState.body.highlight = getHighlightRequest(flatState.body.query, getConfig);
          }
          delete flatState.highlightAll;
        }

        /**
         * Translate a filter into a query to support es 3+
         * @param  {Object} filter - The filter to translate
         * @return {Object} the query version of that filter
         */
        const translateToQuery = function (filter) {
          if (!filter) return;

          if (filter.query) {
            return filter.query;
          }

          return filter;
        };

        // re-write filters within filter aggregations
        (function recurse(aggBranch) {
          if (!aggBranch) return;
          Object.keys(aggBranch).forEach(function (id) {
            const agg = aggBranch[id];

            if (agg.filters) {
              // translate filters aggregations
              const filters = agg.filters.filters;

              Object.keys(filters).forEach(function (filterId) {
                filters[filterId] = translateToQuery(filters[filterId]);
              });
            }

            recurse(agg.aggs || agg.aggregations);
          });
        }(flatState.body.aggs || flatState.body.aggregations));
      }

      return flatState;
    });
Example #26
0
              insertionIndex++
            }
            for (let k = 0; k < str.length; k++) {
              genTs = ts + (seqi ? Spec.int2base(seqi++, 2) : '') + '+' + vt.ext
              this.data.insertChar(insertionIndex + k, str.charAt(k), genTs, attrs)
              if (!seqi) {
                seqi = 1 // FIXME repeat ids, double insert
              }
            }
            i = str.length + insertionIndex - 1
          }
        }
      }
      if(matchedInsKeys.length < insertKeys.length) {
        console.warn('Insert op does not match any tree content, ignoring. Failed ops=',
          _.difference(insertKeys, matchedInsKeys))
      }
      if (genTs) {
        this._host.clock.checkTimestamp(genTs)
      }
    },

    remove(spec, rm, src) {  // eslint-disable-line no-unused-vars
      //let v = spec.version()
      if(!rm) return
      let rmKeys = Object.keys(rm)
      for (let i = 1; i < this.data.len(); i++) {
        if (this.data.matches(i, rmKeys)) {
          this.data.deleteChar(i)
          i -= 1
        }
Example #27
0
List.prototype.fetch = function(req, res, context) {
  var model = this.model,
      endpoint = this.endpoint,
      criteria = context.criteria || {},
      include = this.include,
      includeAttributes = this.includeAttributes,
      Sequelize = this.resource.sequelize,
      defaultCount = 100,
      count = +context.count || +req.query.count || defaultCount,
      offset = +context.offset || +req.query.offset || 0;

  offset += context.page * count || req.query.page * count || 0;
  if (count > 1000) count = 1000;
  if (count < 0) count = defaultCount;

  var options = { offset: offset, limit: count };
  if (!this.resource.pagination)
    delete options.limit;

  if (include.length) {
    options.include = include;
    options.attributes =
      Object.keys(model.rawAttributes).filter(function(attr) {
        return includeAttributes.indexOf(attr) === -1;
      });
  }



  if(this.resource.hasOwnProperty('search')){
    var searchParam = this.resource.search;
    if(_.isArray(searchParam)){
    var search = []
    searchParam.forEach(function(item){
        if(_.has(req.query,item.param)){
            console.log("inside if")
            var searchAttributes =
            item.attributes || Object.keys(model.rawAttributes);

            searchAttributes.forEach(function(attr) {
              var items = {};
              items[attr] = { like: '%' + req.query[item.param] + '%' };
              search.push(items);
            });
        }
    })

    // if (Object.keys(criteria).length)
    //   criteria = Sequelize.and(criteria, Sequelize.or.apply(null, search));
    // else
    //   criteria = Sequelize.or.apply(null, search);

    criteria = search
    }
}

  // if (_.has(req.query, searchParam)) {
  //   var search = [];
  //   var searchAttributes =
  //     this.resource.search.attributes || Object.keys(model.rawAttributes);
  //
  //   searchAttributes.forEach(function(attr) {
  //     var item = {};
  //     item[attr] = { like: '%' + req.query[searchParam] + '%' };
  //     search.push(item);
  //   });
  //
  //   if (Object.keys(criteria).length)
  //     criteria = Sequelize.and(criteria, Sequelize.or.apply(null, search));
  //   else
  //     criteria = Sequelize.or.apply(null, search);
  // }


  var sortParam = this.resource.sort.param;
  if (_.has(req.query, sortParam)) {
    var order = [];
    var columnNames = [];
    var sortColumns = req.query[sortParam].split(',');
    sortColumns.forEach(function(sortColumn) {
      if (sortColumn.indexOf('-') === 0) {
        var actualName = sortColumn.substring(1);
        order.push([actualName, 'DESC']);
        columnNames.push(actualName);
      } else {
        columnNames.push(sortColumn);
        order.push([sortColumn, 'ASC']);
      }
    });
    var allowedColumns = this.resource.sort.attributes || Object.keys(model.rawAttributes);
    var disallowedColumns = _.difference(columnNames, allowedColumns);
    if (disallowedColumns.length) {
      throw new errors.BadRequestError('Sorting not allowed on given attributes', disallowedColumns);
    }

    if (order.length)
      options.order = order;
  }

  // all other query parameters are passed to search
  var extraSearchCriteria = _.reduce(req.query, function(result, value, key) {
    if (_.has(model.rawAttributes, key)) result[key] = value;
    return result;
  }, {});

  // if (Object.keys(extraSearchCriteria).length)
  //   criteria = _.assign(extraSearchCriteria, criteria);

  // do the actual lookup
  if (Object.keys(criteria).length)
    options.where = criteria;

  var self = this;
  return model
    .findAndCountAll(options)
    .then(function(result) {
      context.instance = result.rows;
      var start = offset;
      var end = start + result.rows.length - 1;
      end = end === -1 ? 0 : end;

      if (!!self.resource.pagination)
        res.header('Content-Range', 'items ' + [[start, end].join('-'), result.count].join('/'));

      return context.continue;
    });
};
Example #28
0
Model.prototype._updateOne = function(id, obj){
  var data = this._getRaw(id);
  id = isNaN(+id) ? id : +id;

  for (var i in obj){
    var target = obj[i],
      origin = data[i];
    if (data.hasOwnProperty(i) && _.isObject(target) && !Array.isArray(target)){
      if (Array.isArray(origin)){
        for (var j in target){
          var prop = target[j];
          switch (j){
            case '$push':
              if (Array.isArray(prop)){
                data[i] = origin.concat(prop);
              } else {
                data[i].push(prop);
              }
              break;
            case '$pull':
              if (Array.isArray(prop)){
                data[i] = _.difference(origin, prop);
              } else {
                data[i] = _.without(origin, prop);
              }
              break;
            case '$shift':
              prop = parseInt(prop, 10);
              if (prop > 0){
                data[i] = origin.slice(prop);
              } else {
                data[i] = origin.slice(0, origin.length + prop);
              }
              break;
            case '$pop':
              prop = parseInt(prop, 10);
              if (prop > 0){
                data[i] = origin.slice(0, origin.length - prop);
              } else {
                data[i] = origin.slice(-prop);
              }
              break;
            case '$addToSet':
              if (Array.isArray(prop)){
                for (var k=0, len=prop.length; k<len; k++){
                  var item = prop[k];
                  if (origin.indexOf(item) === -1){
                    data[i].push(item);
                  }
                }
              } else {
                if (origin.indexOf(prop) === -1){
                  data[i].push(prop);
                }
              }
              break;
          }
        }
      } else if (_.isNumber(origin)){
        for (var j in target){
          var prop = target[j];
          switch (j){
            case '$inc':
              data[i] += prop;
              break;
            case '$dec':
              data[i] -= prop;
              break;
          }
        }
      } else {
        data[i] = target;
      }
    } else {
      data[i] = target;
    }
  }

  this._store.set(id, this._schema.save(data));
  this.emit('update', data, id);
};
Example #29
0
File: index.js Project: 4MAW/sails
          _.each(changes, function(val, key) {

            // If value wasn't changed, do nothing
            if (val == previous[key]) return;

            // Find an association matching this attribute
            var association = _.find(this.associations, {alias: key});

            // If the attribute isn't an assoctiation, return
            if (!association) return;

            // Get the associated model class
            var ReferencedModel = sails.models[association.type == 'model' ? association.model : association.collection];

            // Bail if this attribute isn't in the model's schema
            if (association.type == 'model') {

              var previousPK = _.isObject(previous[key]) ? previous[key][ReferencedModel.primaryKey] : previous[key];
              var newPK = _.isObject(val) ? val[this.primaryKey] : val;
              if (previousPK == newPK) return;

              // Get the inverse association definition, if any
              reverseAssociation = _.find(ReferencedModel.associations, {collection: this.identity, via: key}) || _.find(ReferencedModel.associations, {model: this.identity, via: key});

                if (!reverseAssociation) {return;}

                // If this is a to-many association, do publishAdd or publishRemove as necessary
                // on the other side
                if (reverseAssociation.type == 'collection') {
                  // If there was a previous value, alert the previously associated model
                  if (previous[key]) {
                    ReferencedModel.publishRemove(previousPK, reverseAssociation.alias, id, {noReverse:true});
                  }
                  // If there's a new value (i.e. it's not null), alert the newly associated model
                  if (val) {
                    ReferencedModel.publishAdd(newPK, reverseAssociation.alias, id, {noReverse:true});
                  }
                }
                // Otherwise do a publishUpdate
                else {

                  var pubData = {};

                  // If there was a previous association, notify it that it has been nullified
                  if (previous[key]) {
                    pubData[reverseAssociation.alias] = null;
                    ReferencedModel.publishUpdate(previousPK, pubData, req, {noReverse:true});
                  }
                  // If there's a new association, notify it that it has been linked
                  if (val) {
                    pubData[reverseAssociation.alias] = id;
                    ReferencedModel.publishUpdate(newPK, pubData, req, {noReverse:true});
                  }

                }

            }

            else {

              // Get the reverse association definition, if any
              reverseAssociation = _.find(ReferencedModel.associations, {collection: this.identity, via: key}) || _.find(ReferencedModel.associations, {model: this.identity, alias: association.via});

              if (!reverseAssociation) {return;}

                // If we can't get the previous PKs (b/c previous isn't populated), bail
                if (typeof(previous[key]) == 'undefined') return;

                // Get the previous set of IDs
                var previousPKs = _.pluck(previous[key], ReferencedModel.primaryKey);
                // Get the current set of IDs
                var updatedPKs = _.map(val, function(_val) {
                  if (_.isObject(_val)) {
                    return _val[ReferencedModel.primaryKey];
                  } else {
                    return _val;
                  }
                });
                // Find any values that were added to the collection
                var addedPKs = _.difference(updatedPKs, previousPKs);
                // Find any values that were removed from the collection
                var removedPKs = _.difference(previousPKs, updatedPKs);

                // If this is a to-many association, do publishAdd or publishRemove as necessary
                // on the other side
                if (reverseAssociation.type == 'collection') {

                  // Alert any removed models
                  _.each(removedPKs, function(pk) {
                    ReferencedModel.publishRemove(pk, reverseAssociation.alias, id, {noReverse:true});
                  });
                  // Alert any added models
                  _.each(addedPKs, function(pk) {
                    ReferencedModel.publishAdd(pk, reverseAssociation.alias, id, {noReverse:true});
                  });

                }

                // Otherwise do a publishUpdate
                else {

                  // Alert any removed models
                  _.each(removedPKs, function(pk) {
                    var pubData = {};
                    pubData[reverseAssociation.alias] = null;
                    ReferencedModel.publishUpdate(pk, pubData, req, {noReverse:true});
                  });
                  // Alert any added models
                  _.each(addedPKs, function(pk) {
                    var pubData = {};
                    pubData[reverseAssociation.alias] = id;
                    ReferencedModel.publishUpdate(pk, pubData, req, {noReverse:true});
                  });

                }

            }
          }, this);
Example #30
0
    const { group } = options;
    let { user } = options;
    if (!user) {
      user = Meteor.user();
    }
    const userPermissions = user.roles[group.shopId];
    const groupPermissions = group.permissions;

    // granting invitation right for user with `owner` role in a shop
    if (this.hasPermission(["owner"], getUserId(), group.shopId)) {
      return true;
    }

    // checks that userPermissions includes all elements from groupPermissions
    // we are not using Reaction.hasPermission here because it returns true if the user has at least one
    return _.difference(groupPermissions, userPermissions).length === 0;
  },

  /**
   * @name registerTemplate
   * @method
   * @memberof Core
   * @summary Registers Templates into the Templates Collection
   * @return {function} Registers template
   */
  registerTemplate,

  /**
   * @name hasPermission
   * @method
   * @memberof Core