Example #1
0
var writeValue = function(value, fieldSchema) {
  // onBeforeValueSet allows you to cancel the operation.
  // It doesn't work like transform and others that allow you to modify the value because all typecast has already happened.
  // For use-cases where you need to modify the value, you can set a new value in the handler and return false.
  if(_.isFunction(this._options.onBeforeValueSet)) {
    if(this._options.onBeforeValueSet.call(this, value, fieldSchema.name) === false) {
      return;
    }
  }

  // Alias simply copies the value without actually writing it to alias index.
  // Because the value isn't actually set on the alias index, onValueSet isn't fired.
  if(fieldSchema.type === 'alias') {
    this[fieldSchema.index] = value;
    return;
  }

  // Write the value to the inner object.
  this._obj[fieldSchema.name] = value;

  // onValueSet notifies you after a value has been written.
  if(_.isFunction(this._options.onValueSet)) {
    this._options.onValueSet.call(this, value, fieldSchema.name);
  }
};
Example #2
0
File: cache.js Project: ADn06/cdnjs
 var $fn = function() {
   var args = Array.prototype.slice.apply(arguments);
   var callback = args.pop();
   if (!_.isFunction(callback)) {
     args.push(callback);
   }
   var key = _.isString(options.key) ? options.key :
             _.isFunction(options.key) ? options.key.apply(scope, args) :
             createCacheKey(options.namespace, args);
   var entry = cache.get(key);
   if (!_.isFunction(callback)) { // if callback is not given in last arg, return cached result (immediate).
     var value = entry.get();
     if (!value) { throw new Error('Function call result is not cached yet.'); }
     if (value.error) { throw value.error; }
     return value.result;
   }
   entry.get(function(value) {
     callback(value.error, value.result);
   });
   if (!entry.fetching) { // only when no other client is calling function
     entry.fetching = true;
     args.push(function(err, result) {
       entry.set({ error: err, result: result });
     });
     fn.apply(scope || this, args);
   }
 };
Example #3
0
Executable.prototype.invoke = function(params, opts, next) {
  if (_.isFunction(params)) {       // invoked as db.function(callback)
    next = params;
    params = [];
    opts = {};
  } else if (_.isFunction(opts)) {  // invoked as db.function(something, callback)
    next = opts;

    // figure out if we were given params or opts as the first argument
    // lucky for us it's mutually exclusive: opts can only be an object, params can be a primitive or an array
    if (_.isObject(params) && !_.isArray(params)) { // it's an options object, we have no params
      opts = params;
      params = [];
    } else {                                        // it's a parameter primitive or array, we have no opts
      opts = {};
    }
  }

  if (!_.isArray(params)) {
    params = [params];
  }

  if (opts.stream) {
    this.db.stream(this.sql, params, null, next);
  } else {
    this.db.query(this.sql, params, null, next);
  }
};
Example #4
0
 function getOne(options, cb) {
   if (!_.isFunction(cb)) cb = function(){};
   if (!options) return cb(new Error('No Options Specified'));
   
   console.log(' - users.getOne');
   
   var defaultOptions = {
     internal: true,
     fields: {avatarpic: 0}
   };
   options = _.extend(defaultOptions, options);
   
   var query = {};
   var fields = options.fields;
   
   if (options.userID) {
     if (_.isString(options.userID)) options.userID = new ObjectID(options.userID);
     if (!isObjectID(options.userID)) return cb(new Error('Invalid User ID'));
     query._id = options.userID;
   }
   
   db.users.findOne(query, fields, function(err, user){
     if (err) return cb(err);
     if (!user) return cb(null, false);
     console.log(' - users.getOne - DONE');
     if (options.internal){
       return cb(null, user);
     } else {
       return cb({success: true, user: user});
     }
   });
 }
Example #5
0
  //create a new user
  function create(user, cb) {
    if (!_.isFunction(cb)) cb = function(){};
    if (!user) return cb(new Error('No User Specified'));
    if (!_.isObject(user)) return cb(new Error('User must be an Object'));
    
    var reqdUserFields = ['id', 'password', 'nickname', 'male'],
        hasReqdFields = true;

    reqdUserFields.forEach(function(field){if (!user[field]) hasReqdFields = false;});
    if (!hasReqdFields) return cb(new Error('Missing Required User Fields'));
    
    hashedPw = hashPassword(pw);
    emailExists(user.id, function(err, exists){
      if (err) return cb(err);
      if (exists) return cb(new Error('Email Address Exists'));
      nicknameExists(user.nickname, function(err, exists){
        if (err) return cb(err);
        if (exists) return cb(new Error('Nickname Exists'));
        db.users.insert(user, {safe: true}, function(err, object) {
          if (err) return cb(err);
          cb(null, object);
        });
      });
    });
  }
Example #6
0
Field.prototype.authorize = function (newDoc, oldDoc, newVal, oldVal, userCtx) {
    var perms = this.permissions;
    var errors = [];
    if (_.isFunction(perms)) {
        errors = errors.concat(
            utils.getErrors(perms, arguments)
        );
    }
    // on update
    var fn;
    // on add
    if (newDoc && !oldDoc) {
        fn = perms.add;
    }
    // on remove
    else if (!newDoc || newDoc._deleted) {
        fn = perms.remove;
    }
    // on update
    else if (newVal !== oldVal) {
        fn = perms.update;
    }
    if (fn) {
        errors = errors.concat(
            utils.getErrors(fn, arguments)
        );
    }
    return errors;
};
Example #7
0
exports.find = function(){
  var args = ArgTypes.findArgs(arguments);
  if(_.isFunction(args.conditions)){
    // all we're given is the callback:
    args.next = args.conditions;
  }

  //set default options
  args.options.order || (args.options.order = util.format('"%s"', this.pk));
  args.options.limit || (args.options.limit = "1000");
  args.options.offset || (args.options.offset = "0");
  args.options.columns || (args.options.columns = "*");

  order = " order by " + args.options.order;
  limit = " limit " + args.options.limit;
  offset = " offset " + args.options.offset;

  var sql = util.format("select id, body from %s", this.fullname);
  if (_.isEmpty(args.conditions)) {
    // Find all
    sql += order + limit + offset;
    this.executeDocQuery(sql, [], args.options, args.next);
  } else {
    // Set up the WHERE statement:
    var where = this.getWhereForDoc(args.conditions);
    sql += where.where + order + limit + offset;
    if(where.pkQuery) {
      this.executeDocQuery(sql, where.params, {single:true}, args.next);
    } else {
      this.executeDocQuery(sql, where.params,args.options, args.next);
    }
  }
};
Example #8
0
 _.functions = _.methods = function(obj) {
   var names = [];
   for (var key in obj) {
     if (_.isFunction(obj[key])) names.push(key);
   }
   return names.sort();
 };
Example #9
0
/**
 * Map all node-salesforce object to REPL context
 * @private
 */
function defineBuiltinVars(context) {
  // define salesforce package root objects
  for (var key in sf) {
    if (sf.hasOwnProperty(key) && !global[key]) {
      context[key] = sf[key];
    }
  }
  // expose salesforce package root as "$sf" in context.
  context.$sf = sf;

  // create default connection object
  var conn = new sf.Connection();

  for (var prop in conn) {
    if (prop.indexOf('_') === 0) { // ignore private
      continue;
    }
    if (_.isFunction(conn[prop])) {
      context[prop] = _.bind(conn[prop], conn);
    } else if (_.isObject(conn[prop])) {
      defineProp(context, conn, prop);
    }
  }

  // expose default connection as "$conn"
  context.$conn = conn;
}
Example #10
0
 _.each(value, function(arrayItem,arrayIndex)
 {
     if (_.isObject(arrayItem) && _.isFunction(arrayItem.validate))
         error = arrayItem.validate(options, (parentPath && '.') + index + '[' + arrayIndex + ']');
     else if (properties.validators)
         error = validateItem(index + '[' + arrayIndex + ']', arrayItem, properties);
 })
Example #11
0
Type.prototype.authorizeTypeLevel = function (nDoc, oDoc, user) {
    var perms = this.permissions;
    var errs = [];
    if (_.isFunction(perms)) {
        errs = errs.concat(
            utils.getErrors(perms, [nDoc, oDoc, null, null, user])
        );
    }
    // on update
    var fn = perms.update;
    // on add
    if (nDoc && !oDoc) {
        fn = perms.add;
    }
    // on remove
    else if (!nDoc || nDoc._deleted) {
        fn = perms.remove;
    }
    if (fn) {
        errs = errs.concat(
            utils.getErrors(fn, [nDoc, oDoc, null, null, user])
        );
    }
    return errs;
};
Example #12
0
Executable.prototype.invoke = function() {

  var args = Array.prototype.slice.call(arguments);
  var next = args.pop();
  var opts = {};
  var params = [];

  if (!_.isFunction(next)) {
    throw "Function or Script Execution expects a next function as the last argument";
  }

  if (!_.isArray(_.last(args)) && _.isObject(_.last(args))) {
    opts = args.pop();
  }

  if (_.isArray(args[0])) {          // backwards compatible -- db.function([...], ?opts, callback)
    params = args[0];
  } else {
    params = args;
  }

  // console.log("invoke next: ", next);
  // console.log("invoke opts: ", opts);
  // console.log("invoke params: ", params);

  if (opts.stream) {
    this.db.stream(this.sql, params, null, next);
  } else {
    this.db.query(this.sql, params, null, next);
  }
};
Example #13
0
  //PROTOTYPE - update split.person data
  function updateSplitPerson(options, cb) {
    console.log(' >> START splits.updateSplitPerson');
    if (!_.isFunction(cb)) cb = function(){};
    if (!options) return cb(new Error('No Options Specified'));      

    var splitID = options.splitID;
    var userID = options.userID;
    var successVal;
    var query = {};

    if (options.update && options.update.name) query['people.$.name'] = options.update.name;
    if (options.update && options.update.amount) query['people.$.amount'] = options.update.amount;
    if (options.update && options.update.original_amount) query['people.$.original_amount'] = options.update.original_amount;
    if (options.update && options.update.status) query['people.$.status'] = options.update.status;
    if (options.update.status == 'declined') query['people.$.amount'] = 0;

    if (_.isString(splitID)) splitID = new ObjectID(splitID);
    if (_.isString(userID)) userID = new ObjectID(userID);
    if (!splitID) return cb(new Error('Invalid Split ID'));
    if (!userID) return cb(new Error('Invalid User ID'));

    db.splits.update({_id: splitID, 'people._id': userID}, {$set: query}, function(err){
      if (err) return cb(err);
      console.log(' >> RETURN splits.updateSplitPerson');

      if (options.socket && options.update.status) {
        //broacast to channel splitID
        if (options.update.status == 'approved') {
          options.socket.broadcast.to(splitID.toHexString()).emit('split-person-approved', {splitID: splitID, userID: userID, person: options.update});
        } else if (options.update.status == 'declined') {
          options.socket.broadcast.to(splitID.toHexString()).emit('split-person-declined', {splitID: splitID, userID: userID, person: options.update});
        }

        //fake broadcasts for the rest of the people in this split
        getLast({splitID: splitID}, function(data){
          if (data && data.success && data.split) {
            if (data.split.people.length > 0) {
              var delay = 1000;
              _(data.split.people).forEach(function(person){

                //emit if the person is not the host, and is not the current user who issued this request
                if (person._id.toHexString() !== userID.toHexString() && person.host !== true) {
                  console.log(person);
                  delay += 3000;
                  setTimeout(function(){
                    //broadcast back to the calling socket
                    options.socket.emit('split-person-approved-fake', {splitID: splitID, userID: userID, person: person});
                    //broadcast back to the all other sockets
                    options.socket.broadcast.to(splitID.toHexString()).emit('split-person-approved-fake', {splitID: splitID, person: person});
                  }, delay);
                }
              });
            }
          }
        });        
      }

      return cb({success: true});
    });
  }
Example #14
0
  //PROTOTYPE - resets a Split to default values
  function resetSplit(options, cb) {
    console.log(' >> START splits.resetSplit');
    if (!_.isFunction(cb)) cb = function(){};
    if (!options) return cb(new Error('No Options Specified'));      

    var splitID = options.splitID;
    var successVal;

    if (_.isString(splitID)) splitID = new ObjectID(splitID);
    if (!splitID) return cb(new Error('Invalid Split ID'));

    var defaults = {
      amount: "",
      created: new Date(),
      date: new Date(),
      host_id: "",
      name: "",
      status: "setup",
      people: [{
        "_id": new ObjectID("507dc02da7f5fb75de24328f"),
        host: true,
        name: "Dean Gebert",
        pic: "/images/Dean_Gebert.jpg",
        status: "approved"
      }]
    };

    db.splits.update({_id: splitID}, {$set: defaults}, function(err){
      if (err) return cb(err);
      console.log(' >> RETURN splits.resetSplit');
      return cb({success: true});
    });
  }
Example #15
0
/**
 * @class Action
 * 
 * 动作规则
 * 
 * 执行流程: pattern -> handler -> register reply action
 * 
 * @constructor 动作规则
 * @param {Mixed}  cfg    Action的配置
 * @param {String} [prex] 动作名的前缀
 */
function Action(cfg, prex){
  if(_.isString(cfg)){
    //为字符串时,pattern为通过匹配,handler为直接返回该值
    this.name = prex + '_' + cfg;
    this.description = '发送任意字符,直接返回:' + cfg;
    this.handler = cfg;
  }else if(_.isFunction(cfg)){
    //为函数时,pattern为通过匹配,handler为该函数
    this.name =  prex + '_' + cfg.name;
    this.description = cfg.description || '发送任意字符,直接执行函数并返回';
    this.handler = cfg;
  }else if(_.isArray(cfg)){
    throw new Error('no support cfg type: Array')
  }else if(_.isObject(cfg)){
    /**
     * 匹配这种格式:
     * {
     *   name: 'say_hi', 
     *   description: 'pattern可以用正则表达式匹配,试着发送「hi」',
     *   pattern: /^Hi/i,
     *   handler: function(info) {
     *     //回复的另一种方式
     *     return '你也好哈';
     * }
     * @ignore
     */
    _.extend(this,cfg)
    this.name = cfg.name || prex || cfg.pattern
  }
  if(!this.name) this.name = 'it_is_anonymous_action';
  return this;
};
Example #16
0
Info.pack = function(info, mapping){
  var data = _.clone(info);
  var reply = data.reply;

  //log('packing reply: ', reply);

  // 具备图文消息的特征
  if (_.isObject(reply) && !_.isArray(reply) && !reply.type) {
    reply = data.reply = [reply];
  }
  if (_.isArray(reply)) {
    if (_.isFunction(mapping)) {
      reply = reply.map(function(item, i) {
        return mapping.call(reply, item, i, info);
      });
    } else if (mapping) {
      reply.forEach(function(item, index){
        item['title'] = item[ mapping['title'] || 'title'];
        item['description'] = item[ mapping['description'] || 'description'];
        item['pic'] = item[ mapping['picUrl'] || 'picUrl'] || item[ mapping['pic'] || 'pic'];
        item['url'] = item[ mapping['url'] || 'url'];
      });
    }
  }
  data.reply = reply;

  var xml = _.template(Info.TEMPLATE_REPLY)(data);

  return xml;
};
Example #17
0
 _.each(obj, function (v, k) {
   var completer = cmd + '.' + k;
   if (_.isFunction(obj[k])) {
     completer += '(';
   }
   completion.push(completer);
 });
Example #18
0
Promise.prototype.thenCall = function(callback) {
  return _.isFunction(callback) ? this.then(function(res) {
    return callback(null, res);
  }, function(err) {
    return callback(err);
  }) : this;
};
Example #19
0
  this.submit = function (opts, cb) {
    cb = _.isFunction(cb) ? cb : function () {};

    //Resolve RESTful stuff
    opts = opts || {};
    var content;
    if (opts.content) {
      content = JSON.stringify(opts.content);
    }
    opts = _.extend(opts, {
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': content ? Buffer.byteLength(content, 'utf8') : 0
      }
    });
    http.request(opts, function (res) {
      var data = '';
      res
        .on('data', function (c) { data += c; })
        .on('end', function () {
          try {
            data = JSON.parse(data);
          } catch (e) {
            return cb(e);
          }
          return cb(data.error, data.result);
        });
    })
    .on('error', cb)
    .end(content);
  };
    w.clientInit = function (field, path, value, raw, errors, options) {

        this.cacheInit();

        this.path = path;
        this.field = field;
        this.render_options = (options || {});
        value = this.normalizeValue(value || []);

        var item_elts = (
            this.discoverListItemsElement().children('.item')
        );

        for (var i = 0, len = item_elts.length; i < len; ++i) {
            this.bindEventsForListItem(item_elts[i]);

            if (_.isFunction(this.widget.clientInit)) {
                this.widget.clientInit(
                    this.field, this.path, value[i], value[i], [], {
                        offset: (this.singleton ? null : i)
                    }
                );
            }
        }

        this.renumberList();
        this.bindEventsForList();
    };
 w.renumberListItem = function (elt, offset) {
     var widget_options = {
         offset: (this.singleton ? null : offset)
     };
     if (_.isFunction(this.widget.updateName)) {
         this.widget.updateName(elt, this.path, widget_options);
     }
 };
Example #22
0
    return _.reduce(_.keys(fields), function (result, k) {
        var f = fields[k];
        if (f instanceof fields_module.AttachmentField) {
            if (f.hasOwnProperty('default_value')) {
                var val,
                    dir = path.concat([k]).join('/');
                if (_.isFunction(f.default_value)) {
                    val = f.default_value(req);
                }
                else {
                    val = f.default_value;
                }
                var d = doc || result;
                if (!d._attachments) {
                    d._attachments = {};
                }
                for (var ak in val) {
                    d._attachments[dir + '/' + ak] = val[ak];
                }
            }
        }
        else if (f instanceof fields_module.Field ||
                 f instanceof fields_module.Embedded ||
                 f instanceof fields_module.EmbeddedList) {

            if (f.hasOwnProperty('default_value')) {
                if (_.isFunction(f.default_value)) {
                    result[k] = f.default_value(req);
                }
                else {
                    result[k] = f.default_value;
                }
            }
        }
        else if (f instanceof Object) {
            result[k] = exports.createDefaults(
                f, req, doc || result, path.concat([k])
            );
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
        return result;
    }, {});
Example #23
0
 _.groupBy = function(obj, val) {
   var result = {};
   var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
   each(obj, function(value, index) {
     var key = iterator(value, index);
     (result[key] || (result[key] = [])).push(value);
   });
   return result;
 };
Example #24
0
 //checks whether a user with the specified email address exists
 function emailExists(email, cb) {
   if (!_.isFunction(cb)) cb = function(){};
   if (!_.isString(email)) cb(new Error('Invalid Email Address'));
   db.users.count({id: new RegExp('^' + escapeRegExp(email) + '$', 'i')}, function(err, count){
     if (err) return cb(err);
     if (count > 1) return cb(new Error('Multiple users found with the specified email address: ' + email));
     return cb(null, !!count);
   });
 }
Example #25
0
 //checks whether a user with the specified nickname exists
 function nicknameExists(nickname, cb) {
   if (!_.isFunction(cb)) cb = function(){};
   if (!_.isString(nickname)) cb(new Error('Invalid Nickname'));
   db.users.count({nickname: new RegExp('^' + escapeRegExp(nickname) + '$', 'i')}, function(err, count){
     if (err) return cb(err);
     if (count > 1) return cb(new Error('Multiple users found with the specified nickname: ' + nickname));
     return cb(null, !!count);
   });
 }
Example #26
0
            _.each(schema, function (properties, index)
            {
                var realProperties = properties.index ? schema[properties.index] : properties;
                var realIndex = properties.index ? properties.index : index;

                if (options.all !== true && properties.type != 'object' && properties.type != 'array' &&
                    ((properties.invisible || (properties.toObject == 'never' && options.nevers !== false)
                    || (properties.toObject == 'changed' && (options.changed === false || !self.tracking.hasChanged(realIndex)))
                    || (properties.type == 'alias' && !options.alias === false)
                    || (properties.toObject == 'hasValue' &&
                        ((_.isUndefined(self[index]) && options.undefineds === false) ||
                        (_.isNull(self[index]) && options.nulls == false) ||
                        options.hasValues === false))
                    || (properties.toObject == 'always' && options.always === false)
                    || (properties.toObject == 'hasValue' && ((_.isNull(self[index]) && !options.nulls === false) || options.hasValues === false))) ))
                {
                    return;
                }

                // Fetch value from self[index] to route through getter.
                var value = self[index];
                if ((_.isNull(value) && !options.includeNull) || (_.isUndefined(value) && !options.includeUndefined))
                    return;

                // If value does not need to be cloned, place in index.
                if ((value === undefined || value === null)
                || properties.type !== 'object' && properties.type !== 'array' && properties.type !== 'date')
                {
                    getObj[index] = value;
                    // Clone Object
                } else if (properties.type === 'object')
                {
                    // Call toObject() method if defined (this allows us to return primitive objects instead of SchemaObjects).
                    if (_.isFunction(value.toObject))
                    {
                        getObj[index] = value.toObject(options);
                        // If is non-SchemaType object, shallow clone so that properties modification don't have an affect on the original object.
                    } else if (_.isObject(value))
                    {
                        getObj[index] = _.clone(value);
                    }

                    // Clone Array
                } else if (properties.type === 'array')
                {
                    // Built in method to clone array to native type
                    getObj[index] = value.toArray();

                    // Clone Date object.
                } else if (properties.type === 'date')
                {
                    // https://github.com/documentcloud/underscore/pull/863
                    // _.clone doesn't work on Date object.
                    getObj[index] = new Date(value.getTime());
                }
            });
Example #27
0
 socket.on('ship.destruct', function(message, fn) {
   socket.broadcast.emit('openspace.destruct.ship', {msg: 'Ship destruction detected', type: 'self', ship: ship.getState()});
   ships = _.filter(ships, function(s) { return s.id != ship.id});
   ship = null;
   session.shipId = null;
   session.save();
   if (_.isFunction(fn)) {
     fn({status: 'success', msg: 'Your ship has self-destructed'});
   }
 });
Example #28
0
 _.each(reply, function(item, index){
   if(_.isFunction(mapping)){
     item = mapping(item, index, info)
   }else{
     item['title'] = item[ mapping['title'] || 'title']
     item['description'] = item[ mapping['description'] || 'description']
     item['pic'] = item[ mapping['pic'] || 'pic']
     item['url'] = item[ mapping['url'] || 'url']
   }
 })
Example #29
0
File: cache.js Project: ADn06/cdnjs
 return function() {
   var args = Array.prototype.slice.apply(arguments);
   var callback = args.pop();
   if (!_.isFunction(callback)) {
     args.push(callback);
     callback = null;
   }
   var key = _.isString(options.key) ? options.key :
             _.isFunction(options.key) ? options.key.apply(scope, args) :
             createCacheKey(options.namespace, args);
   var entry = cache.get(key);
   entry.fetching = true;
   if (callback) {
     args.push(function(err, result) {
       entry.set({ error: err, result: result });
       callback(err, result);
     });
   }
   var ret, error;
   try {
     ret = fn.apply(scope || this, args);
   } catch(e) {
     error = e;
   }
   if (ret && _.isFunction(ret.then)) { // if the returned value is promise
     if (!callback) {
       return ret.then(function(result) {
         entry.set({ error: undefined, result: result });
         return result;
       }, function(err) {
         entry.set({ error: err, result: undefined });
         throw err;
       });
     } else {
       return ret;
     }
   } else {
     entry.set({ error: error, result: ret });
     if (error) { throw error; }
     return ret;
   }
 };
Example #30
0
    socket.on('publish', function() {
      var args = Array.prototype.slice.call(arguments);
      
      var packet = args.shift()
        , fn = args.pop() || function() {};

      if (!isPacket(packet) || !_.isFunction(fn)) {
	fn({
	  message: 'invalid packet or callback passed',
	  code: 400
	});
	return;
      }
      
      keys = packet.things;
      payload = packet.payload;
  
      if (!_.every(keys, isKey)) {
	fn({
	  message: 'some keys seem to be invalid',
	  code: 400
	});
	return;
      }
      
      var master = false;
      if (keys.indexOf('master') > -1) {
	keys = _.without(keys, 'master');
	master = true;
      }
      
      User.owns(
	user, keys, function(err, owned) {
	  if (err) {
	    fn(err);
	    return;
	  }

	  if (!owned) {
	    fn({
	      message: 'sorry, not authorized',
	      code: 401
	    });
	    return;
	  }

	  if (master) {
	    keys.push(['~user', user].join('+')); 
	  }
	  publish(keys, payload, fn);
	}
      );
      
    });