_.forEach(data, function (item) {
     if (!(_.intersection(item.usersRoles, user.roles).length))
         phase.push(item);
 });
Ejemplo n.º 2
0
  Instance.prototype.save = function(options, deprecated) {
    if (options instanceof Array) {
      options = { fields: options };
    }

    options = Utils._.extend({
      hooks: true,
      validate: true
    }, options, deprecated);

    if (!options.fields) {
      if (this.isNewRecord) {
        options.fields = Object.keys(this.Model.attributes);
      } else {
        options.fields = _.intersection(this.changed(), Object.keys(this.Model.attributes));
      }

      options.defaultFields = options.fields;
    }

    if (options.returning === undefined) {
      if (options.association) {
        options.returning = false;
      } else if (this.isNewRecord) {
        options.returning = true;
      }
    }

    var self = this
      , updatedAtAttr = this.Model._timestampAttributes.updatedAt
      , createdAtAttr = this.Model._timestampAttributes.createdAt
      , hook = self.isNewRecord ? 'Create' : 'Update';

    if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) === -1) {
      options.fields.push(updatedAtAttr);
    }

    if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, {raw: true}))) {
      // UpdateAtAttr might have been added as a result of Object.keys(Model.attributes). In that case we have to remove it again
      Utils._.remove(options.fields, function(val) {
        return val === updatedAtAttr;
      });
      updatedAtAttr = false;
    }

    if (this.isNewRecord === true && createdAtAttr && options.fields.indexOf(createdAtAttr) === -1) {
      options.fields.push(createdAtAttr);
    }

    return Promise.bind(this).then(function() {
      // Validate
      if (options.validate) {
        return Promise.bind(this).then(function () {
          // hookValidate rejects with errors, validate returns with errors
          if (options.hooks) return this.hookValidate(options);

          return this.validate(options).then(function (err) {
            if (err) throw err;
          });
        });
      }
    }).then(function() {
      return Promise.bind(this).then(function() {
        // Run before hook
        if (options.hooks) {
          var beforeHookValues = _.pick(this.dataValues, options.fields)
            , afterHookValues
            , hookChanged
            , ignoreChanged = _.difference(this.changed(), options.fields); // In case of update where it's only supposed to update the passed values and the hook values

          if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) !== -1) {
            ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
          }

          return this.Model.runHooks('before' + hook, this, options).bind(this).then(function() {
            if (options.defaultFields && !this.isNewRecord) {
              afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));

              hookChanged = [];
              Object.keys(afterHookValues).forEach(function (key) {
                if (afterHookValues[key] !== beforeHookValues[key]) {
                  hookChanged.push(key);
                }
              });

              options.fields = _.unique(options.fields.concat(hookChanged));
            }

            if (hookChanged) {
              if (options.validate) {
                // Validate again

                options.skip = _.difference(Object.keys(this.Model.rawAttributes), hookChanged);
                return Promise.bind(this).then(function () {
                  // hookValidate rejects with errors, validate returns with errors
                  if (options.hooks) return this.hookValidate(options);

                  return this.validate(options).then(function (err) {
                    if (err) throw err;
                  });
                }).then(function() {
                  delete options.skip;
                });
              }
            }
          });
        }
      }).then(function() {
        if (!options.fields.length) return this;

        var values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.Model)
          , query = null
          , args = [];

        if (updatedAtAttr && !options.silent) {
          self.dataValues[updatedAtAttr] = values[self.Model.rawAttributes[updatedAtAttr].field || updatedAtAttr] = self.Model.__getTimestamp(updatedAtAttr);
        }

        if (self.isNewRecord && createdAtAttr && !values[createdAtAttr]) {
          self.dataValues[createdAtAttr] = values[self.Model.rawAttributes[createdAtAttr].field || createdAtAttr] = self.Model.__getTimestamp(createdAtAttr);
        }

        if (self.isNewRecord) {
          query = 'insert';
          args = [self, self.Model.getTableName(options), values, options];
        } else {
          var identifier = self.primaryKeyValues;

          if (identifier) {
            identifier = Utils.mapValueFieldNames(identifier, Object.keys(identifier), this.Model);

          } else if (identifier === null && self.__options.whereCollection !== null) {
            identifier = self.__options.whereCollection;
          }

          query = 'update';
          args = [self, self.Model.getTableName(options), values, identifier, options];
        }

        return self.QueryInterface[query].apply(self.QueryInterface, args)
          .then(function(result) {
            // Transfer database generated values (defaults, autoincrement, etc)
            Object.keys(self.Model.rawAttributes).forEach(function (attr) {
              if (self.Model.rawAttributes[attr].field &&
                  values[self.Model.rawAttributes[attr].field] !== undefined &&
                  self.Model.rawAttributes[attr].field !== attr
              ) {
                values[attr] = values[self.Model.rawAttributes[attr].field];
                delete values[self.Model.rawAttributes[attr].field];
              }
            });
            values = _.extend(values, result.dataValues);

            result.dataValues = _.extend(result.dataValues, values);
            return result;
          })
          .tap(function(result) {
            // Run after hook
            if (options.hooks) {
              return self.Model.runHooks('after' + hook, result, options);
            }
          })
          .then(function(result) {
            options.fields.forEach(function (field) {
              result._previousDataValues[field] = result.dataValues[field];
            });
            self.isNewRecord = false;
            return result;
          });
      });
    });
  };
Ejemplo n.º 3
0
 selectedRegions.forEach(function(selectedRegion) {
   if (availableRegions[selectedRegion]) {
     availableTypes = _.intersection(availableTypes, _.map(availableRegions[selectedRegion], 'name'));
   }
 });
 it('should have .gitignore coverage to be a subset of .npmignore coverage', function () {
     expect(_.intersection(gitignore, npmignore)).to.eql(gitignore);
 });
Ejemplo n.º 5
0
 prepareInclude: function prepareInclude(include, allowedIncludes) {
     return _.intersection(this.trimAndLowerCase(include), allowedIncludes);
 },
Ejemplo n.º 6
0
 var results = _.reject(recordList, function (x) {
     return (_.intersection(x.geocells, geocells).length < 1);
 });
Ejemplo n.º 7
0
router.get("/productattr", function (req, resp) {
    var fields=["id","attribute","product","attrValue"];
    var maxItems = (isNaN(parseInt(req.query.pageSize)) ? 10 : parseInt(req.query.pageSize));
    var page = (isNaN(parseInt(req.query.page)) ? 1 : parseInt(req.query.page)) || 1;
    var replaceRemoved = (isNaN(parseInt(req.query.replaceRemoved)) ? 0 : parseInt(req.query.replaceRemoved)) || 0;

    var sortOrder = null;
    var sortField = null;
    var isTrueRegEx = /true/i;

    if (req.query[params.sortField]) {
        var orderString = req.query[params.sortField];
        var split = orderString.split(" ");
        sortOrder = _.first(split);
        sortField = split.length > 1 ? split[1] : "asc";
    }

    var skip = (page - 1) * maxItems;
    var getFirst = maxItems;

    if (replaceRemoved > 0) {
        skip += (maxItems - replaceRemoved);
        getFirst = replaceRemoved;
    }

    var productsattr = _(db).values();

    if (sortField) {
        productsattr.sortBy(function (item) {
            return [item[sortField]];
        });

        if (/desc/i.test(sortOrder)) {
            productsattr.reverse();
        }
    }

    if (isTrueRegEx.test(req.query[params.search])) {
        var filter_on_fields = _.intersection(_.keys(req.query), fields);
        if (filter_on_fields) {
            _.forEach(filter_on_fields, function (field) {
                if (_.has(req.query, field)) {
                    productsattr = productsattr.filter(function (productattr) {
                        var regex = new RegExp(req.query[field], "i");
                        return regex.test(productattr[field]);
                    });
                }
            });
        }
    }

    if (!isTrueRegEx.test(req.query["showInactive"])) {
        productsattr = productsattr.filter({"active": true});
    }

    var inlineCount = productsattr.size();

    productsattr = productsattr.rest(skip).first(getFirst);

    var pagedResult = {
        maxItems: maxItems,
        page: page,
        inlineCount: inlineCount,
        results: productsattr.value()
    };

    resp.json(pagedResult);
});
Ejemplo n.º 8
0
    'convert-filters':  'convert type1 filters to type2',
    'force-update':     'force update of all feeds',
    'list-plugins':     'list all available plugins',
    /* print "Plugin options:\n";

    foreach (PluginHost::getInstance()->get_commands() as $command => $data) {
      $args = $data['arghelp'];
      printf(" --%-19s - %s\n", "$command $args", $data["description"]);
    }*/
  })
  .help('help', 'show this help')
  .version(version.get_version())
  .usage("Friggin Fast RSS data update script.\n\nUsage: ffrss-update [OPTIONS]")
  .strict();

var options = l.intersection(longopts, l.keys(yargs.argv));

if (options.length === 0 || l.contains(options, 'help')) {
  console.err(yargs.help());
  process.exit(1);
}

if ('daemon' in options) {
  require('./include/errorhandler'); // TODO: this is kind of a php-specific thing
}

if ('update-schema' in options) {
  var schema_version = funcs.get_schema_version();
  if (schema_version !== config.SCHEMA_VERSION) {
    console.error("Schema version is wrong, please upgrade the database");
    process.exit(1);
Ejemplo n.º 9
0
  'toArray',
  'uniqueId',
  'value',
  'values'
];

/** List of all functions. */
exports.funcs = _.filter(_.difference(_.keys(mapping.funcDep), exports.objDeps, exports.varDeps).sort(), function(key) {
  var type = typeof _.prototype[key];
  return type == 'function' || type == 'undefined';
});

/** List of lodash functions included by default. */
exports.includes = _.intersection(exports.funcs, _.concat(
  _.functions(_),
  _.functions(_.prototype),
  mapping.category.Seq,
  ['main']
));

/** List of dependencies that should not cause a minor bump when changed. */
exports.laxSemVerDeps = [
  'eq',
  'gt',
  'gte',
  'isArguments',
  'isArray',
  'isArrayBuffer',
  'isArrayLike',
  'isArrayLikeObject',
  'isBoolean',
  'isBuffer',
Ejemplo n.º 10
0
// accepts an array of status effects
// returns a string of the ones that should be displayed
function displayStatus (status) {
  var display = ['CF', 'DE', 'DR', 'FR', 'NU', 'PO', 'SL', 'ST', 'SU'];
  var message = _.intersection(status, display);
  message = message.length ? (' ' + message.join(' ')) : '';
  return message;
}
Ejemplo n.º 11
0
var program = new Command('bin/kibana');

program.version(pkg.version).description('Kibana is an open source (Apache Licensed), browser ' + 'based analytics and search dashboard for Elasticsearch.');

// attach commands
require('./serve/serve')(program);
//require('./plugin/plugin')(program);

program.command('help <command>').description('Get the help for a specific command').action(function (cmdName) {
  var cmd = _.find(program.commands, { _name: cmdName });
  if (!cmd) return this.error('unknown command ' + cmdName);
  cmd.help();
});

program.command('*', null, { noHelp: true }).action(function (cmd, options) {
  program.error('unknown command ' + cmd);
});

// check for no command name
var subCommand = argv[2] && !String(argv[2][0]).match(/^-|^\.|\//);

if (!subCommand) {
  if (_.intersection(argv.slice(2), ['-h', '--help']).length) {
    program.defaultHelp();
  } else {
    argv.splice(2, 0, ['serve']);
  }
}

program.parse(argv);
Ejemplo n.º 12
0
		result.push  (_.filter(obj.children,function(child){
			return  ((filter.key.length)?(child.key == filter.key):1)
					&& _.intersection(child.tags,filter.tags).length == filter.tags.length;
		}));
Ejemplo n.º 13
0
 .mapValues(function (districts) {
     return _.intersection(districts, common.districtCodes);
 })
Ejemplo n.º 14
0
internals.determineBedWetter = function(route, thisRouteOpts) {
    
    var method  = route.method;
    var path    = route.path;
    
    path = internals.normalizePath(path, thisRouteOpts);
    
    var pathInfo = internals.Router.analyze(path);
    var pathSegments = pathInfo.segments.length;
    var err;
    
    // Account for `update` allowing POST or PATCH
    if (_.isArray(method) &&
        method.length == 2 &&
        _.intersection(method, ['post', 'patch']).length == 2) {
        
        method = 'patch';
    }
    
    var countIsOkay = false;
    var bedwetter;
    switch (method) {
        
        case 'post':
            
            if (pathSegments == 1 &&
                pathInfo.segments[0].literal) {         // model
                
                // Create
                bedwetter = BedWetters.create;
            
            } else if (pathSegments == 2 &&
                pathInfo.segments[0].literal &&         // model
                pathInfo.segments[1].name) {            // record
                
                // Patched update
                bedwetter = BedWetters.update;
            
            } else if (pathSegments == 3 &&
                      pathInfo.segments[0].literal &&   // model
                      pathInfo.segments[1].name &&      // record
                      pathInfo.segments[2].literal) {   // association
                
                // Create and add to relation
                bedwetter = BedWetters.add;
            
            } else {
                err = new Error('This ' + method + ' route does not match a BedWetting pattern.');
            }
            
            break;
        
        case 'patch':
            
            if (pathSegments == 2 &&
                pathInfo.segments[0].literal &&   // model
                pathInfo.segments[1].name) {      // record
                
                // Patched update
                bedwetter = BedWetters.update;
            
            } else {
                err = new Error('This ' + method + ' route does not match a BedWetting pattern.');
            }
            
            break;
        
        case 'put':
            
            if (pathSegments == 4 &&
                      pathInfo.segments[0].literal &&   // model
                      pathInfo.segments[1].name &&      // record
                      pathInfo.segments[2].literal &&   // association
                      pathInfo.segments[3].name) {      // record_to_add
                
                // Add to a relation
                bedwetter = BedWetters.add;
            
            } else {
                err = new Error('This ' + method + ' route does not match a BedWetting pattern.');
            }
            
            break;
            
        case 'get':
            
            if (pathSegments == 1 &&
                pathInfo.segments[0].literal) {         // model
                
                countIsOkay = true;
                
                // Find with criteria
                bedwetter = BedWetters.find;
            
            } else if (pathSegments == 2 &&
                      pathInfo.segments[0].literal &&   // model
                      pathInfo.segments[1].name) {      // record
                
                // Find one by id
                bedwetter = BedWetters.findone;
            
            } else if (pathSegments == 3 &&
                      pathInfo.segments[0].literal &&   // model
                      pathInfo.segments[1].name &&      // record
                      pathInfo.segments[2].literal) {   // association
                
                countIsOkay = true;
                
                // Get associated records
                bedwetter = BedWetters.populate;
            
            } else if (pathSegments == 4 &&
                      pathInfo.segments[0].literal &&   // model
                      pathInfo.segments[1].name &&      // record
                      pathInfo.segments[2].literal &&   // association
                      pathInfo.segments[3].name) {      // record_to_check
                
                // Check for an association between records
                bedwetter = BedWetters.populate;
            
            } else {
                err = new Error('This ' + method + ' route does not match a BedWetting pattern.');
            }
            
            break;
        
        case 'delete':
            
            if (pathSegments == 2 &&
                pathInfo.segments[0].literal &&   // model
                pathInfo.segments[1].name) {      // record
                
                bedwetter = BedWetters.destroy;
            
            } else if (pathSegments == 4 &&
                      pathInfo.segments[0].literal &&   // model
                      pathInfo.segments[1].name &&      // record
                      pathInfo.segments[2].literal &&   // association
                      pathInfo.segments[3].name) {      // record_to_remove
                
                bedwetter = BedWetters.remove;
            
            } else {
                err = new Error('This ' + method + ' route does not match a BedWetting pattern.');
            }
            
            break;
        
        default:
            err = new Error('Method isn\'t a BedWetter.  Must be POST, GET, DELETE, PUT, or PATCH.');
            break;
    }
    
    // Only allow counting on find and array populate
    if (thisRouteOpts._private.count && !countIsOkay) {
        err = new Error('This bedwetter can\'t count!');
    }
    
    if (err) {
        throw err;
    } else {
        return bedwetter;
    }
    
}
Ejemplo n.º 15
0
      showFiltered: false
    }
  },

  componentDidMount() {
    fetch(testResultUrl + this.props.testId)
      .then(response => response.json())
      .then(json => this.setState({
        testResults: json.all,
        testResultsFiltered: json.filtered
      }))
      .catch(error => console.log(error));
  },

  getMatches(arr1, arr2) {
    const intersection = _.intersection(arr1, arr2);
    return intersection.length;
  },

  getTestResultRow(testResult) {

    const numOfDeclined = testResult.declinedTypes.length;
    const numOfApproved = testResult.approvedTypes.length;

    const numOfApprovedMatches = this.getMatches(testResult.approvedTypes, testResult.result);
    const numOfDeclinedMatches = this.getMatches(testResult.declinedTypes, testResult.result);;

    const approvedStyle = numOfApprovedMatches < numOfApproved ? 'danger' : 'default';
    const declinedStyle = numOfDeclinedMatches > 0 ? 'danger' : 'default';

    return (
Ejemplo n.º 16
0
Array.prototype.intersection = function (array) {
    return _.intersection(this, array);
};
Ejemplo n.º 17
0
    crawler.discoverResources = function(buf, queueItem) {
      var urlis = classifyUrl(queueItem);
      if (urlis.external || urlis.image) {
        return [];
      }

      var $ = cheerio.load(buf.toString(), {
        normalizeWhitespace: false,
        xmlMode: false,
        decodeEntities: true
      });

      var parsedUrl = url.parse(queueItem.url);
      // is this the redirector page? follow device tree from here
      // this might make the crawl take ALOT longer
      if ($('#device-redirector').length === 1) {
        // determine if fromUrl was device specific
        var selectDevice;
        var parsedFromUrl = url.parse(queueItem.referrer);
        var devicePath = _.intersection(parsedFromUrl.pathname.split('/'), devices);
        if (devicePath.length > 0) {
          selectDevice = devicePath[0];
        }

        $('ul.devices').find('a').each(function(index, a) {
          // if we come from a device-specific page, only choose that device link forward
          if (selectDevice && $(a).attr('id') !== (selectDevice + '-link')) {
            return;
          }

          var toQueueUrl = $(a).attr('href');

          // include hash used to access redirector
          var absolutePath = url.resolve(queueItem.url, toQueueUrl) + (parsedUrl.hash || '');
          // preserve original fromUrl and content
          // c.queue([{
          //   uri: absolutePath,
          //   callback: crawlCallback.bind(null, fromUrl, absolutePath, content)
          // }]);
          if (!queueItem.meta) {
            console.log(queueItem);
          }
          crawler.queueURL(absolutePath, queueItem, { content: queueItem.meta.content });
        });
        return [];
      }

      // make sure the hash used is valid on this page
      if (parsedUrl.hash) {
        if (isPullRequest && urlis.autogeneratedApiLink) {
          return [];
        }

        if ($(parsedUrl.hash).length === 0) {
          console.error(chalk.red(util.format('ERROR: 404 (missing hash) ON %s CONTENT %s LINKS TO %s', queueItem.referrer, queueItem.meta.content, queueItem.url)));
          errors++;
        }
        // only check the hash here
        // let the non-hash version crawl the rest of the tree
        return [];
      }

      $('a').each(function(index, a) {
        var toQueueUrl = $(a).attr('href');
        var linkContent = $(a).text();
        if (!toQueueUrl) return;

        if (toQueueUrl.indexOf('#') === 0 && toQueueUrl.length > 1) {
          if (isPullRequest && urlis.autogeneratedApiLink) {
            return;
          }

          if ($(toQueueUrl).length === 0) {
            console.error(chalk.red(util.format('ERROR: 404 relative link ON %s CONTENT %s LINKS TO %s', queueItem.url, linkContent, toQueueUrl)));
            errors++;
          }
        }

        if (!shouldCrawl(toQueueUrl)) {
          return;
        }
        var absolutePath = url.resolve(queueItem.url, toQueueUrl);
        // Remove hash
        absolutePath = absolutePath.replace(/#.*/, '');
        crawler.queueURL(absolutePath, queueItem, { content: linkContent });
      });

      $('img').each(function (index, img) {
        var toQueueUrl = $(img).attr('src');
        if (!toQueueUrl) return;

        toQueueUrl = url.resolve(queueItem.url, toQueueUrl);
        crawler.queueURL(toQueueUrl, queueItem, { content: 'image' });
      });

      return [];
    };
Ejemplo n.º 18
0
sanitize = function sanitize(data) {
    var allProblems = {},
        tablesInData = _.keys(data.data),
        tableNames = _.sortBy(_.keys(tables), function (tableName) {
            // We want to guarantee posts and tags go first
            if (tableName === 'posts') {
                return 1;
            } else if (tableName === 'tags') {
                return 2;
            }

            return 3;
        });

    tableNames = _.intersection(tableNames, tablesInData);

    _.each(tableNames, function (tableName) {
        // Sanitize the table data for duplicates and valid uuid and created_at values
        var sanitizedTableData = _.transform(data.data[tableName], function (memo, importValues) {
            var uuidMissing = (!importValues.uuid && tables[tableName].uuid) ? true : false,
                uuidMalformed = (importValues.uuid && !validation.validator.isUUID(importValues.uuid)) ? true : false,
                isDuplicate,
                problemTag;

            // Check for correct UUID and fix if necessary
            if (uuidMissing || uuidMalformed) {
                importValues.uuid = uuid.v4();
            }

            // Custom sanitize for posts, tags and users
            if (tableName === 'posts') {
                // Check if any previously added posts have the same
                // title and slug
                isDuplicate = checkDuplicateAttributes(memo.data, importValues, ['title', 'slug']);

                // If it's a duplicate add to the problems and continue on
                if (isDuplicate) {
                    // TODO: Put the reason why it was a problem?
                    memo.problems.push(importValues);
                    return;
                }
            } else if (tableName === 'tags') {
                // Check if any previously added posts have the same
                // name and slug
                isDuplicate = checkDuplicateAttributes(memo.data, importValues, ['name', 'slug']);

                // If it's a duplicate add to the problems and continue on
                if (isDuplicate) {
                    // TODO: Put the reason why it was a problem?
                    // Remember this tag so it can be updated later
                    importValues.duplicate = isDuplicate;
                    memo.problems.push(importValues);

                    return;
                }
            } else if (tableName === 'posts_tags') {
                // Fix up removed tags associations
                problemTag = _.find(allProblems.tags, function (tag) {
                    return tag.id === importValues.tag_id;
                });

                // Update the tag id to the original "duplicate" id
                if (problemTag) {
                    importValues.tag_id = problemTag.duplicate.id;
                }
            }

            memo.data.push(importValues);
        }, {
            data: [],
            problems: []
        });

        // Store the table data to return
        data.data[tableName] = sanitizedTableData.data;

        // Keep track of all problems for all tables
        if (!_.isEmpty(sanitizedTableData.problems)) {
            allProblems[tableName] = sanitizedTableData.problems;
        }
    });

    return {
        data: data,
        problems: allProblems
    };
};
Ejemplo n.º 19
0
  Instance.prototype.save = function(options) {
    options = _.defaults(options || {}, {
      hooks: true,
      validate: true
    });

    if (!options.fields) {
      if (this.isNewRecord) {
        options.fields = Object.keys(this.Model.attributes);
      } else {
        options.fields = _.intersection(this.changed(), Object.keys(this.Model.attributes));
      }

      options.defaultFields = options.fields;
    }

    if (options.returning === undefined) {
      if (options.association) {
        options.returning = false;
      } else if (this.isNewRecord) {
        options.returning = true;
      }
    }

    var self = this
      , primaryKeyName = this.Model.primaryKeyAttribute
      , primaryKeyAttribute = primaryKeyName && this.Model.rawAttributes[primaryKeyName]
      , updatedAtAttr = this.Model._timestampAttributes.updatedAt
      , createdAtAttr = this.Model._timestampAttributes.createdAt
      , hook = self.isNewRecord ? 'Create' : 'Update'
      , wasNewRecord = this.isNewRecord;

    if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) === -1) {
      options.fields.push(updatedAtAttr);
    }

    if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, {raw: true}))) {
      // UpdateAtAttr might have been added as a result of Object.keys(Model.attributes). In that case we have to remove it again
      Utils._.remove(options.fields, function(val) {
        return val === updatedAtAttr;
      });
      updatedAtAttr = false;
    }

    if (this.isNewRecord === true) {
      if (createdAtAttr && options.fields.indexOf(createdAtAttr) === -1) {
        options.fields.push(createdAtAttr);
      }

      if (primaryKeyAttribute && primaryKeyAttribute.defaultValue && options.fields.indexOf(primaryKeyName) < 0) {
        options.fields.unshift(primaryKeyName);
      }
    }

    if (this.isNewRecord === false) {
      if (primaryKeyName && !this.get(primaryKeyName, {raw: true})) {
        throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global update');
      }
    }

    return Promise.bind(this).then(function() {
      // Validate
      if (options.validate) {
        return Promise.bind(this).then(function () {
          // hookValidate rejects with errors, validate returns with errors
          if (options.hooks) return this.hookValidate(options);

          return this.validate(options).then(function (err) {
            if (err) throw err;
          });
        });
      }
    }).then(function() {
      return Promise.bind(this).then(function() {
        // Run before hook
        if (options.hooks) {
          var beforeHookValues = _.pick(this.dataValues, options.fields)
            , afterHookValues
            , hookChanged
            , ignoreChanged = _.difference(this.changed(), options.fields); // In case of update where it's only supposed to update the passed values and the hook values

          if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) !== -1) {
            ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
          }

          return this.Model.runHooks('before' + hook, this, options).bind(this).then(function() {
            if (options.defaultFields && !this.isNewRecord) {
              afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));

              hookChanged = [];
              Object.keys(afterHookValues).forEach(function (key) {
                if (afterHookValues[key] !== beforeHookValues[key]) {
                  hookChanged.push(key);
                }
              });

              options.fields = _.unique(options.fields.concat(hookChanged));
            }

            if (hookChanged) {
              if (options.validate) {
                // Validate again

                options.skip = _.difference(Object.keys(this.Model.rawAttributes), hookChanged);
                return Promise.bind(this).then(function () {
                  // hookValidate rejects with errors, validate returns with errors
                  if (options.hooks) return this.hookValidate(options);

                  return this.validate(options).then(function (err) {
                    if (err) throw err;
                  });
                }).then(function() {
                  delete options.skip;
                });
              }
            }
          });
        }
      }).then(function() {
        if (!options.fields.length) return this;
        if (!this.isNewRecord) return this;
        if (!this.options.include || !this.options.include.length) return this;

        // Nested creation for BelongsTo relations
        return Promise.map(this.options.include.filter(function (include) {
          return include.association instanceof BelongsTo;
        }), function (include) {
          var instance = self.get(include.as);
          if (!instance) return Promise.resolve();

          return instance.save({
            transaction: options.transaction,
            logging: options.logging
          }).then(function () {
            return self[include.association.accessors.set](instance, {save: false});
          });
        });
      })
      .then(function() {
        if (!options.fields.length) return this;

        var values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.Model)
          , query = null
          , args = [];

        if (updatedAtAttr && !options.silent) {
          self.dataValues[updatedAtAttr] = values[self.Model.rawAttributes[updatedAtAttr].field || updatedAtAttr] = self.Model.__getTimestamp(updatedAtAttr);
        }

        if (self.isNewRecord && createdAtAttr && !values[createdAtAttr]) {
          self.dataValues[createdAtAttr] = values[self.Model.rawAttributes[createdAtAttr].field || createdAtAttr] = self.Model.__getTimestamp(createdAtAttr);
        }

        if (self.isNewRecord) {
          query = 'insert';
          args = [self, self.Model.getTableName(options), values, options];
        } else {
          var where = this.where();

          where = Utils.mapValueFieldNames(where, Object.keys(where), this.Model);

          query = 'update';
          args = [self, self.Model.getTableName(options), values, where, options];
        }

        return self.sequelize.getQueryInterface()[query].apply(self.sequelize.getQueryInterface(), args)
          .then(function(result) {
            // Transfer database generated values (defaults, autoincrement, etc)
            Object.keys(self.Model.rawAttributes).forEach(function (attr) {
              if (self.Model.rawAttributes[attr].field &&
                  values[self.Model.rawAttributes[attr].field] !== undefined &&
                  self.Model.rawAttributes[attr].field !== attr
              ) {
                values[attr] = values[self.Model.rawAttributes[attr].field];
                delete values[self.Model.rawAttributes[attr].field];
              }
            });
            values = _.extend(values, result.dataValues);

            result.dataValues = _.extend(result.dataValues, values);
            return result;
          })
          .tap(function(result) {
            // Run after hook
            if (options.hooks) {
              return self.Model.runHooks('after' + hook, result, options);
            }
          })
          .then(function(result) {
            options.fields.forEach(function (field) {
              result._previousDataValues[field] = result.dataValues[field];
              self.changed(field, false);
            });
            self.isNewRecord = false;
            return result;
          })
          .tap(function() {
            if (!wasNewRecord) return;
            if (!self.options.include || !self.options.include.length) return;

            // Nested creation for HasOne/HasMany/BelongsToMany relations
            return Promise.map(self.options.include.filter(function (include) {
              return !(include.association instanceof BelongsTo);
            }), function (include) {
              var instances = self.get(include.as);

              if (!instances) return Promise.resolve();
              if (!Array.isArray(instances)) instances = [instances];
              if (!instances.length) return Promise.resolve();

              // Instances will be updated in place so we can safely treat HasOne like a HasMany
              return Promise.map(instances, function (instance) {
                if (include.association instanceof BelongsToMany) {
                  return instance.save({transaction: options.transaction, logging: options.logging}).then(function () {
                    var values = {};
                    values[include.association.foreignKey] = self.get(self.Model.primaryKeyAttribute, {raw: true});
                    values[include.association.otherKey] = instance.get(instance.Model.primaryKeyAttribute, {raw: true});
                    return include.association.throughModel.create(values, {transaction: options.transaction, logging: options.logging});
                  });
                } else {
                  instance.set(include.association.identifier, self.get(self.Model.primaryKeyAttribute, {raw: true}));
                  return instance.save({transaction: options.transaction, logging: options.logging});
                }
              });
            });
          });
      });
    });
  };
Ejemplo n.º 20
0
// ## Helpers
function prepareInclude(include) {
    include = _.intersection(include.split(','), allowedIncludes);
    return include;
}
Ejemplo n.º 21
0
function hasOne(changeset, triggers) {
  return _.intersection(
    changeset, triggers
  ).length > 0;
}
Ejemplo n.º 22
0
 return _.pickBy(topic, function (value, key) {
     var theseCities = value.map(function (location) { return location.toLowerCase(); });
     // console.log(theseCities);
     return _.intersection(allPhrases, theseCities).length > 0;
 });
  constructor(...args) {
    super(...args)

    const { autoControlledProps } = this.constructor
    const state = _.invoke(this, 'getInitialAutoControlledState', this.props) || {}

    if (process.env.NODE_ENV !== 'production') {
      const { defaultProps, name, propTypes } = this.constructor
      // require static autoControlledProps
      if (!autoControlledProps) {
        console.error(`Auto controlled ${name} must specify a static autoControlledProps array.`)
      }

      // require propTypes
      _.each(autoControlledProps, (prop) => {
        const defaultProp = getDefaultPropName(prop)
        // regular prop
        if (!_.has(propTypes, defaultProp)) {
          console.error(`${name} is missing "${defaultProp}" propTypes validation for auto controlled prop "${prop}".`)
        }
        // its default prop
        if (!_.has(propTypes, prop)) {
          console.error(`${name} is missing propTypes validation for auto controlled prop "${prop}".`)
        }
      })

      // prevent autoControlledProps in defaultProps
      //
      // When setting state, auto controlled props values always win (so the parent can manage them).
      // It is not reasonable to decipher the difference between props from the parent and defaultProps.
      // Allowing defaultProps results in trySetState always deferring to the defaultProp value.
      // Auto controlled props also listed in defaultProps can never be updated.
      //
      // To set defaults for an AutoControlled prop, you can set the initial state in the
      // constructor or by using an ES7 property initializer:
      // https://babeljs.io/blog/2015/06/07/react-on-es6-plus#property-initializers
      const illegalDefaults = _.intersection(autoControlledProps, _.keys(defaultProps))
      if (!_.isEmpty(illegalDefaults)) {
        console.error([
          'Do not set defaultProps for autoControlledProps. You can set defaults by',
          'setting state in the constructor or using an ES7 property initializer',
          '(https://babeljs.io/blog/2015/06/07/react-on-es6-plus#property-initializers)',
          `See ${name} props: "${illegalDefaults}".`,
        ].join(' '))
      }

      // prevent listing defaultProps in autoControlledProps
      //
      // Default props are automatically handled.
      // Listing defaults in autoControlledProps would result in allowing defaultDefaultValue props.
      const illegalAutoControlled = _.filter(autoControlledProps, prop => _.startsWith(prop, 'default'))
      if (!_.isEmpty(illegalAutoControlled)) {
        console.error([
          'Do not add default props to autoControlledProps.',
          'Default props are automatically handled.',
          `See ${name} autoControlledProps: "${illegalAutoControlled}".`,
        ].join(' '))
      }
    }

    // Auto controlled props are copied to state.
    // Set initial state by copying auto controlled props to state.
    // Also look for the default prop for any auto controlled props (foo => defaultFoo)
    // so we can set initial values from defaults.
    const initialAutoControlledState = autoControlledProps.reduce((acc, prop) => {
      acc[prop] = getAutoControlledStateValue(prop, this.props, state, true)

      if (process.env.NODE_ENV !== 'production') {
        const defaultPropName = getDefaultPropName(prop)
        const { name } = this.constructor
        // prevent defaultFoo={} along side foo={}
        if (!_.isUndefined(this.props[defaultPropName]) && !_.isUndefined(this.props[prop])) {
          console.error(
            `${name} prop "${prop}" is auto controlled. Specify either ${defaultPropName} or ${prop}, but not both.`,
          )
        }
      }

      return acc
    }, {})

    this.state = { ...state, ...initialAutoControlledState }
  }
Ejemplo n.º 24
0
  instance.autorun(() => {
    let sortByParameter = FlowRouter.getQueryParam('sortBy');

    // Check URL parameter for sort direction and convert to integer
    let sortDirectionParameter = -1;

    // Check URL parameter for sorting
    switch (sortByParameter) {
      case 'name-asc':
        sortByParameter = 'name';
        sortDirectionParameter = 1;
        break;
      case 'name-desc':
        sortByParameter = 'name';
        sortDirectionParameter = -1;
        break;
      default:
        break;
    }
    // Create a object for storage sorting parameters
    let sort = {};
    // Check of existing parameters
    if (sortByParameter && sortDirectionParameter) {
      // Get field and direction of sorting
      sort[sortByParameter] = sortDirectionParameter;
    } else {
      // Otherwise get it like default value
      sort = defaultSort;
    }

    // Change sorting
    instance.pagination.sort(sort);

    let currentFilters = filters;

    // Check URL parameter for filtering
    const filterByParameter = FlowRouter.getQueryParam('filterBy');

    // Filtering available for registered users
    if (userId) {
      switch (filterByParameter) {
        case 'all': {
          // Delete filter for managed apis & bookmarks
          delete currentFilters.managerIds;
          delete currentFilters._id;
          break;
        }
        case 'my-apis': {
          // Delete filter for bookmarks
          delete currentFilters._id;
          // Set filter for managed apis
          currentFilters.managerIds = userId;
          break;
        }
        case 'my-bookmarks': {
          // Delete filter for managed apis
          delete currentFilters.managerIds;
          // Get user bookmarks
          const userBookmarks = ApiBookmarks.findOne() || '';
          // Set filter for bookmarks
          currentFilters._id = { $in: userBookmarks.apiIds };
          break;
        }
        default: {
          // Otherwise get it like default value
          currentFilters = { isPublic: true };
          break;
        }
      }
    } else {
      // Otherwise get it like default value
      currentFilters = { isPublic: true };
    }

    // Check URL parameter for filtering by lifecycle status
    const lifecycleStatusParameter = FlowRouter.getQueryParam('lifecycle');

    // Checking of filter bu lifecycle status was set
    if (lifecycleStatusParameter) {
      // Set filter
      currentFilters.lifecycleStatus = lifecycleStatusParameter;
    } else {
      // Can be case when filter was set and user clicks on Clear button.
      // Query parameter doesn't exists but database query has field.

      // Delete field from object.
      delete currentFilters.lifecycleStatus;
    }

    // Check URL parameter for apisWithDocumentation filter
    const apisWithDocumentation = FlowRouter.getQueryParam('apisWithDocumentation');

    // Checking if 'APIs with Documentation' filter is checked or not
    if (apisWithDocumentation === 'true') {
      // Fetching published ApiDocs
      const apiDocs = ApiDocs.find().fetch();
      // Creating array of ApiIds
      let apiIds = _.map(apiDocs, 'apiId');

      // checking if 'My Bookmarks' filter is checked or not
      if (filterByParameter === 'my-bookmarks') {
        // fetch bookmarked ApiIds
        const bookmarkedApiIds = currentFilters._id.$in;
        // find ApiIds that are bookmarked and that contains Api Documentation
        apiIds = _.intersection(bookmarkedApiIds, apiIds);
      }

      // Set filter for filtering out apiIds that dont contain Api Documentation
      currentFilters._id = { $in: apiIds };
    }

    const searchValue = instance.searchValue.get();
    // Construct query using regex using search value
    instance.query.set({
      $or: [
        {
          name: {
            $regex: searchValue,
            $options: 'i', // case-insensitive option
          },
        },
        {
          backend_host: {
            $regex: searchValue,
            $options: 'i', // case-insensitive option
          },
        },
      ],
    });
    if (searchValue !== '') {
      currentFilters = instance.query.get();
    }
    if (FlowRouter.current().route.name === 'myApiCatalog') {
      currentFilters.managerIds = userId;
    }
    instance.pagination.currentPage([Session.get('currentIndex')]);
    instance.pagination.filters(currentFilters);
  });
Ejemplo n.º 25
0
  /**
   * Upsert
   *
   * @param {string} tableName    table to upsert on
   * @param {Object} insertValues values to be inserted, mapped to field name
   * @param {Object} updateValues values to be updated, mapped to field name
   * @param {Object} where        various conditions
   * @param {Model}  model        Model to upsert on
   * @param {Object} options      query options
   *
   * @returns {Promise<boolean,?number>} Resolves an array with <created, primaryKey>
   */
  upsert(tableName, insertValues, updateValues, where, model, options) {
    const wheres = [];
    const attributes = Object.keys(insertValues);
    let indexes = [];
    let indexFields;

    options = _.clone(options);

    if (!Utils.isWhereEmpty(where)) {
      wheres.push(where);
    }

    // Lets combine unique keys and indexes into one
    indexes = _.map(model.uniqueKeys, value => {
      return value.fields;
    });

    _.each(model._indexes, value => {
      if (value.unique) {
        // fields in the index may both the strings or objects with an attribute property - lets sanitize that
        indexFields = _.map(value.fields, field => {
          if (_.isPlainObject(field)) {
            return field.attribute;
          }
          return field;
        });
        indexes.push(indexFields);
      }
    });

    for (const index of indexes) {
      if (_.intersection(attributes, index).length === index.length) {
        where = {};
        for (const field of index) {
          where[field] = insertValues[field];
        }
        wheres.push(where);
      }
    }

    where = { [Op.or]: wheres };

    options.type = QueryTypes.UPSERT;
    options.raw = true;

    const sql = this.QueryGenerator.upsertQuery(tableName, insertValues, updateValues, where, model, options);
    return this.sequelize.query(sql, options).then(result => {
      switch (this.sequelize.options.dialect) {
        case 'postgres':
          return [result.created, result.primary_key];

        case 'mssql':
          return [
            result.$action === 'INSERT',
            result[model.primaryKeyField]
          ];

        // MySQL returns 1 for inserted, 2 for updated
        // http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html.
        case 'mysql':
          return [result === 1, undefined];

        default:
          return [result, undefined];
      }
    });
  }
Ejemplo n.º 26
0
 hasPrivateExtensions: function (options) {
   return _.intersection(
     util.extension_prefixes.private, util.editions[options.xt.edition]
   ).length > 0;
 },
Ejemplo n.º 27
0
function userCan( userRoles, actionRoles ) {
	return actionRoles.length === 0 || _.intersection( actionRoles, userRoles ).length > 0;
}
 function filterUserType (value, references) {
   return _.intersection(references, value).length > 0;
 }
Ejemplo n.º 29
0
Validator.prototype.validate = function(values, presentOnly, cb) {
  var self = this,
      errors = {},
      validations = Object.keys(this.validations);

  // Handle optional second arg
  if(typeof presentOnly === 'function') {
    cb = presentOnly;
  }
  // Use present values only or all validations
  else if(presentOnly) {
    validations = _.intersection(validations, Object.keys(values));
  }

  function validate(validation, cb) {
    var curValidation = self.validations[validation];

    // Build Requirements
    var requirements = anchor(curValidation);

    // Grab value and set to null if undefined
    var value = values[validation];
    if(typeof value == 'undefined') value = null;

    // If value is not required and empty then don't
    // try and validate it
    if(!curValidation.required) {
      if(value === null || value === '') return cb();
    }

    // If Boolean and required manually check
    if(curValidation.required && curValidation.type === 'boolean' && (typeof value !== 'undefined' && value !== null)) {
      if(value.toString() == 'true' || value.toString() == 'false') return cb();
    }

    // If type is integer and the value matches a mongoID let it validate
    if(hasOwnProperty(self.validations[validation], 'type') && self.validations[validation].type === 'integer') {
      if(utils.matchMongoId(value)) return cb();
    }

    // Rule values may be specified as sync or async functions.
    // Call them and replace the rule value with the function's result
    // before running validations.
    async.each( Object.keys(requirements.data), function (key, cb) {
      if (typeof requirements.data[key] !== 'function') return cb();

      // Run synchronous function
      if (requirements.data[key].length < 1) {
        requirements.data[key] = requirements.data[key].apply(values, []);
        return cb();
      }

      // Run async function
      requirements.data[key].call(values, function (result) {
        requirements.data[key] = result;
        cb();
      });
    }, function() {

      // Validate with Anchor
      var err = anchor(value).to(requirements.data, values);

      // If No Error return
      if(!err) return cb();

      // Build an Error Object
      errors[validation] = [];

      err.forEach(function(obj) {
        if(obj.property) delete obj.property;
        errors[validation].push({ rule: obj.rule, message: obj.message });
      });

      return cb();
    });

  }

  // Validate all validations in parallel
  async.each(validations, validate, function allValidationsChecked () {
    if(Object.keys(errors).length === 0) return cb();

    cb(errors);
  });

};
Ejemplo n.º 30
0
 _configure: function (options) {
   _.each(_.intersection(_.keys(options), routeObjectOptions), function (key) {
     this[key] = options[key];
   }, this);
 },