Example #1
0
				safe.trap(done, function () {
					_id = docs[0]._id;
					assert.equal(docs[0].num, 10);
					assert.equal(docs.length, 1);
					assert.equal(_.isDate(docs[0]._dt),true);
					done();
				})()
Example #2
0
Driver.prototype.propertyToValue = function (value, property) {
  var customType;

  switch (property.type) {
    case "object":
      if (value !== null && !Buffer.isBuffer(value)) {
        value = new Buffer(JSON.stringify(value));
      }
      break;
    case "date":
      if (_.isDate(value) && this.config.timezone && this.config.timezone != 'local') {
        var tz = convertTimezone(this.config.timezone);

        // shift local to UTC
        value.setTime(value.getTime() + (value.getTimezoneOffset() * 60000));
        if (tz !== false) {
          // shift UTC to timezone
          value.setTime(value.getTime() + (tz * 60000));
        }
      }
      break;
    case "point":
      return function () {
        return "POINT(" + value.x + ', ' + value.y + ")";
      };
      break;
    default:
      customType = this.customTypes[property.type];

      if (customType && 'propertyToValue' in customType) {
        value = customType.propertyToValue(value);
      }
  }
  return value;
};
Example #3
0
 // ############
 // ## OBJECT ##
 // ############
 /**
  * The declaration of a terminal property.  This declaration includes the path and value of the
  * property.
  * Example Input:
  * {
  *   foo: {
  *     bar: 'baz'
  *   }
  * }
  * Example Result:
  * [
  *   {
  *     path: ['foo', 'bar']
  *     value: 'baz
  *   }
  * ]
  * @typedef {Object} TerminalProperty
  * @property {String[]} path The path to the terminal property
  * @property {Date|RegEx|String} The value of the terminal property
  */
 /**
  * Generate an array of objects noting the terminal properties of the given root object and their
  * paths
  * @param root The object to generate a terminal property path/value set for
  * @param current The current part of the given root that terminal properties are being sought
  * within
  * @param [context] An array containing the path to the current object root (intended for internal
  * use)
  * @param [results] An array of current results (intended for internal use)
  * @returns {TerminalProperty[]} The terminal properties of the given root object, with the path
  * and value of each
  */
 getProperties(root, atRoot, current, cntxt, rslts) {
   let context = cntxt;
   if (!context) {
     context = [];
   }
   let results = rslts;
   if (!results) {
     results = [];
   }
   const addContext = (value, key) =>
     this.getProperties(root, false, value, context.concat(key), results);
   if (
     _.isArray(current)
   ) {
     _.map(current, addContext);
   } else if (
     _.isObject(current) &&
     !_.isDate(current) &&
     !_.isRegExp(current) &&
     !_.isFunction(current)
   ) {
     if (atRoot || current !== root) {
       _.mapValues(current, addContext);
     }
   } else {
     results.push({ path: context, value: current });
   }
   return results;
 }
Example #4
0
		_.each(query, function (v,k) {
			var op = ops[k];
			var n = null;		
			if (op!=null) {
				n = new op();
				n._args = stree(v,ctx);
				if (ctx!=null)
					n._args.splice(0,0,ctx);
				args.push(n);					
			}
			else {
				if (_.isObject(v) && !(v instanceof tdb.ObjectID || _.isDate(v) || _.isFunction(query) || query instanceof tdb.Code)) {
					var sub = stree(v,new field(k));
					if (sub.length==1)
						args.push(sub[0]);
					else if (sub.length>1) {
						n = new ops["$and"];
						n._args = sub;
						args.push(n);
					}
				} else {
					n = new ops["$eq"]();
					n._args = [new field(k)];
					var sub = stree(v);
					_.each(sub,function (v) {
						n._args.push(v);
					})						
					args.push(n);						
				}
			}
		})
                _.each(_.keys(o), function (key) {
                    var field = _.find(that.getFieldDefinitions(), { column: key });
                    if (!field || (field.internal) || (typeof field.externalizeOnEmpty !== 'undefined' && field.externalizeOnEmpty === false && o[key] === null)) {
                        delete obj[key];
                    } else if (field.type === "obj_array") {
                        var children = obj[key];
                        var childDef = require('./' + field.model);
                        obj[field.field] = [];
                        _.each(children, function (child) {
                            var c = childDef.externalize(child);
                            obj[field.field].push(c);
                        });
                        delete obj[key];
                    } else {
                        var val = obj[key];
                        delete obj[key];
                        switch (field.type) {
                            case 'boolean':
                                val = (!_.isBoolean(val)) ? (val === 1) : val;
                                break;
                            case 'date':
                                if( _.isDate(val) || _.isString(val)) {
                                    val = moment(val).format('YYYY-MM-DDTHH:mm:ss.SSSZ');
                                } else {
                                    logger.warn("object with id " + o.ID + " has invalid date: " + val);
                                }
                                break;
                        }
                        obj[field.field] = val;

                    }
                });
 formatValue: function(definition, value) {
     if (definition.type === 'id_array' || definition.type === 'obj_array') {
         return undefined;
     }
     var val = null;
     switch (definition.type) {
         case 'long':
         case 'float':
         case 'int':
             if (definition.joinWith) {
                 val = (value === null || +value === -1) ? null : +value;
             } else {
                 val = +value;
             }
             break;
         case 'date':
             if (_.isDate(value) || _.isString(value)) {
                 val = "\'" + moment(value).format(Constants.MYSQL_DATEFORMAT) + "\'";
             }
             break;
         case 'boolean':
             val = (value === true);
             break;
         default:
             val = (value === null) ? null : "\'" + value + "\'";
     }
     return val;
 },
Example #7
0
 var customTypeOf = function (inp) {
     if (_.isString(inp) && moment.utc(inp, 'YYYY-MM-DDTHH:mm:ss.SSSZ', true).isValid())
         return 'ISOStringDate';
     else if (_.isDate(inp))
         return 'JSDate';
     else if (inp instanceof moment().__proto__.constructor)
         return 'momentJSDate';
     else if (_.isArray(inp))
         return 'array';
     else if (_.isFinite(inp))
         return 'number';
     else if (_.isNaN(inp))
         return 'NaN';
     else if (_.isFunction(inp))
         return 'function';
     else if (_.isUndefined(inp))
         return 'undefined';
     else if (_.isNull(inp))
         return 'null';
     else if (_.isBoolean(inp))
         return 'boolean';
     else if (_.isRegExp(inp))
         return 'regExp';
     else if (inp instanceof Error)
         return 'error';
     else if (inp && _.isFunction(inp.getTimestamp) && _.isFunction(inp.toString) && inp.toString().length == 24)
         return 'ObjectId';
     else if (_.isPlainObject(inp))
         return 'plainObject';
     else {
         return typeof inp;
     }
 };
Example #8
0
var serializeFieldValue = function(value) {
    var result = "";
    if (_.isString(value)) {
        if (REGEXP_RID.test(value)) {
            result = result.concat(value);
        } else {
            result = result.concat("\"", value.replace(/\\/, "\\\\").replace(/"/g, "\\\""), "\"");
        }
    } else if (_.isNumber(value)) {
        result = result.concat(value);
        if (value.toString().indexOf(".") !== -1) {
            result = result.concat("f");
        }
    } else if (_.isBoolean(value)) {
        result = result.concat(value);
    } else if (_.isDate(value)) {
        result = result.concat(value.getTime(), "t");
    } else if (_.isArray(value)) {
        result = result.concat("[");
        for (var idx = 0, length = value.length; idx < length; idx++) {
            if (_.isObject(value[idx])) {
                result = result.concat(serializedObject(value[idx]));
            } else {
                result = result.concat(serializeFieldValue(value[idx]));
            }
            if (idx < value.length - 1) {
                result = result.concat(",");
            }
        }
        result = result.concat("]");
    } else if (_.isObject(value)) {
        result = serializedObject(value);
    }
    return result;
};
Example #9
0
module.exports.iso8601Date = function(d) {
  if (_.isUndefined(d) || _.isString(d) || !(_.isDate(d))) {
    return d;
  } else {
    return moment.utc(d).format('YYYY-MM-DD');
  }
};
Example #10
0
DATE.prototype.validate = function(value) {
  if (!_.isDate(value)) {
    throw new sequelizeErrors.ValidationError(util.format('%j is not a valid date', value));
  }

  return true;
};
Example #11
0
 /**
  * Turns `value` into a `Date` if it's either a `Date`, an ISO formatted string or a timestamp.
  *
  * **Throws:**
  * - `Restypie.TemplateErrors.BadType`: If `value` cannot be converted to an ISO date.
  *
  * @method hydrate
  * @param value
  * @return {Date}
  */
 hydrate(value) {
   value = super.hydrate(value);
   if (_.isDate(value) || _.isNull(value)) return value;
   if (this.ISOFormat.test(value)) return new Date(value);
   if (TIMESTAMP_REGEX.test(value)) return new Date(parseInt(value, 10));
   throw new Restypie.TemplateErrors.BadType({ key: this.key, value, expected: this.displayType });
 }
Example #12
0
 return formatField(val, function (val) {
   if (_.isNumber(val) || _.isDate(val)) {
     return moment(val).format(config.get('dateFormat'));
   } else {
     return val;
   }
 });
Example #13
0
 date : function (value) {
   if(_.isDate(value)) {
     return value.toISOString();
   } else {
     return new Date(value).toISOString();
   }
 },
    return this.sequelize.query(sql, options).then(data => {
      if (!options.plain) {
        return data;
      }

      const result = data ? data[attributeSelector] : null;

      if (!options || !options.dataType) {
        return result;
      }

      const dataType = options.dataType;

      if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
        if (!_.isNull(result)) {
          return parseFloat(result);
        }
      }
      if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
        return parseInt(result, 10);
      }
      if (dataType instanceof DataTypes.DATE) {
        if (!_.isNull(result) && !_.isDate(result)) {
          return new Date(result);
        }
      }
      return result;
    });
Example #15
0
	/**
	 * Formats a Gregorian/Unix timestamp or Date instances into a String
	 * representation of the corresponding date.
	 * @param  {Date|String} pDate   Representation of the date to format.
	 * @param  {String} pFormat      Tokens to format the date with.
	 * @param  {Object} pUser        Specific user to use for formatting.
	 * @param  {Boolean} pIsGregorian Indicate whether or not the date is in
	 *                                gregorian format.
	 * @param  {String} tz           Timezone to format the date with.
	 * @return {String}              Representation of the formatted date.
	 *
	 * If pDate is undefined then return an empty string. Useful for form which
	 * use toFriendlyDate for some fields with an undefined value. Otherwise it
	 * would display NaN/NaN/NaN in Firefox for example.
	 *
	 * By default, the timezone of the specified or logged in user will be used
	 * to format the date. If that timezone is not set, then the account
	 * timezone will be used. If not set, the browser’s timezone will be used as
	 * a last resort.
	 */
	function toFriendlyDate(pDate, pFormat, pUser, pIsGregorian, tz) {
		if (_.isUndefined(pDate)) {
			return '';
		}
		var isGregorian = _.isBoolean(pIsGregorian)
			? pIsGregorian
			: true;
		var date = _.isDate(pDate)
			? pDate
			: isGregorian
				? gregorianToDate(pDate)
				: unixToDate(pDate);
		var format = getMomentFormat(pFormat, pUser);
		if (!_.isNull(moment.tz.zone(tz))) {
			return moment(date).tz(tz).format(format);
		}
		if (_.has(monster, 'apps.auth.currentUser.timezone')) {
			return moment(date)
				.tz(monster.apps.auth.currentUser.timezone)
				.format(format);
		}
		if (_.has(monster, 'apps.auth.currentAccount.timezone')) {
			return moment(date)
				.tz(monster.apps.auth.currentAccount.timezone)
				.format(format);
		}
		return moment(date).tz(moment.tz.guess()).format(format);
	}
Example #16
0
		return keys.reduce( function( row, key ) {
			var value = obj[ key ];
			if ( value !== null && value !== undefined ) {
				row.setAttribute( key, _.isDate( value ) ? value.toISOString() : value );
			}
			return row;
		}, doc.createElement( "row" ) );
Example #17
0
function convertToString(input, options) {
    var type = typeof input;
    var result = input;

    if (_.isDate(input)) {
        result = input.toJSON();
    } else if (_.isPlainObject(input) || Array.isArray(input)) {
        result = JSON.stringify(input);
    } else if (type === 'boolean' || type === 'number') {
        result = '' + input;
    }

    if (options.split) {
        result = result.split(options.split.separator ? options.split.separator : /\s+/);
    }

    if (Array.isArray(result)) {
        result = result.reduce(function (r, val) {
            r.push(applyStringFormat(val, options));
            return r;
        }, []);
    } else {
        result = applyStringFormat(result, options);
    }
    return result;
}
Example #18
0
  /* This is a simplified version of elasticsearch's date parser */
  function parse(text, roundUp) {
    if (!text) return undefined;
    if (moment.isMoment(text)) return text;
    if (_.isDate(text)) return moment(text);

    var time;
    var mathString = '';
    var index;
    var parseString;

    if (text.substring(0, 3) === 'now') {
      time = moment();
      mathString = text.substring('now'.length);
    } else {
      index = text.indexOf('||');
      if (index === -1) {
        parseString = text;
        mathString = ''; // nothing else
      } else {
        parseString = text.substring(0, index);
        mathString = text.substring(index + 2);
      }
      // We're going to just require ISO8601 timestamps, k?
      time = moment(parseString);
    }

    if (!mathString.length) {
      return time;
    }

    return parseDateMath(mathString, time, roundUp);
  }
Example #19
0
export function castDate(format, value) {
  if (!lodash.isDate(value)) {
    if (!lodash.isString(value)) {
      return ERROR;
    }
    try {
      if (format === "default") {
        value = moment(timeParse(_DEFAULT_PATTERN)(value));
      } else if (format === "any") {
        value = moment(value);
      } else {
        if (format.startsWith("fmt:")) {
          console.warn(
            `Format "fmt:<PATTERN>" is deprecated.
             Please use "<PATTERN>" without "fmt:" prefix.`
          );
          format = format.replace("fmt:", "");
        }
        value = moment(timeParse(format)(value));
      }
      if (!value.isValid()) {
        return ERROR;
      }
      value = value.toDate();
    } catch (error) {
      return ERROR;
    }
  }
  return value;
}
var copydata = exports.copydata = function(obj) {
  var copy

  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;

  // Handle Date
  if( _.isDate(obj) ) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }

  // Handle Array
  if( _.isArray(obj) ) {
    copy = [];
    for (var i = 0, len = obj.length; i < len; ++i) {
      copy[i] = copydata(obj[i]);
    }
    return copy;
  }

  // Handle Object
  if( _.isObject(obj) ) {
    copy = {};
    for (var attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = copydata(obj[attr]);
    }
    return copy;
  }

  throw new Error("Unable to copy obj! Its type isn't supported.");
}
Example #21
0
    schema.methods.historicalTrim = function (date, callback) {
        var me              = this,
            HistoricalModel = getHistoricalModel(me);

        callback = _.isFunction(callback) ? callback : function () {
        };

        if (!_.isDate(date) || date.getTime() > new Date().getTime()) {
            return callback(new Error('Historical error: Invalid date.'));
        }

        me.historicalRestore(date, function (e, obj) {
            if (e) {
                return callback(e);
            }
            if (!obj) {
                return callback(null, me);
            }
            HistoricalModel.remove({document: me[primaryKeyName], timestamp: {$lte: date}}, function (e) {
                if (e) {
                    return callback(e);
                }
                var trimmed = new HistoricalModel({
                    document: me[primaryKeyName],
                    diff: obj.toObject(),
                    timestamp: date
                });
                trimmed.save(function (e) {
                    return e ? callback(e) : callback(null, me);
                });
            });
        });
    };
Example #22
0
    return this.sequelize.query(sql, options).then(data => {
      if (!options.plain) {
        return data;
      }

      let result = data ? data[attributeSelector] : null;

      if (options && options.dataType) {
        const dataType = options.dataType;

        if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
          result = parseFloat(result);
        } else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
          result = parseInt(result, 10);
        } else if (dataType instanceof DataTypes.DATE) {
          if (!_.isNull(result) && !_.isDate(result)) {
            result = new Date(result);
          }
        } else if (dataType instanceof DataTypes.STRING) {
          // Nothing to do, result is already a string.
        }
      }

      return result;
    });
Example #23
0
//helpers
function generateEntity(obj) {
    var entity = _.clone(obj);
    for (var property in entity) {
        if (property !== '_metadata') {
            if (_.isArray(entity[property])) {
                entity[property] = JSON.stringify(entity[property]);
                continue;
            }
            if (_.isBoolean(entity[property])) {
                entity[property] = eg.Boolean(entity[property]);
                continue;
            }
            if (_.isDate(entity[property])) {
                entity[property] = eg.DateTime(entity[property]);
                continue;
            }
            if (_.isString(entity[property])) {
                entity[property] = eg.String(entity[property]);
                continue;
            }
            if (_.isObject(entity[property])) {
                entity[property] = eg.String(JSON.stringify(entity[property]));
                continue;
            }

            entity[property] = eg.Entity(entity[property]);
        }
    }
    return entity;
}
Example #24
0
Surely.prototype._firstArgIsObjectWithParams = function(args) {
  return args.length === 1 &&
         _.isObject(args[0]) &&
         !_.isDate(args[0]) &&
         !_.isArray(args[0]) &&
         this.args[0].type !== 'object';
};
Example #25
0
internals.formatAttributeValue = function (val) {
  if(_.isDate(val)) {
    return val.toISOString();
  }

  return val;
};
Example #26
0
Entity.prototype.toString = function() {
  var self = this

  var sb = ['$', _.isFunction( self.canon$ ) ? 
            self.canon$({string:true}) : '', ':{id=',self.id,';']
  var hasp = 0
  var fields = _.isFunction( self.fields$ ) ? self.fields$() : []
  fields.sort()
  for( var fI = 0; fI < fields.length; fI++ ) {
    if( 'id' == fields[fI] ) continue;
    hasp = 1
    sb.push(fields[fI])
    sb.push('=')

    var val = self[fields[fI]]
    if( _.isDate(val) ) {
      sb.push( val.toISOString() )
    }
    else if( _.isObject( val ) ) {
      val = util.inspect(val,{depth:3}).replace(/\s+/g,'')
      sb.push( val )
    }
    else sb.push( ''+val );

    sb.push(';')
  }
  sb[sb.length-hasp]='}'

  return sb.join('')
}
Example #27
0
function _resolveIsReturnable(obj) {
  return (
    _.isNull(obj) || _.isFunction(obj) ||
    _.isArray(obj) || _.isString(obj) || _.isNumber(obj) ||
    _.isDate(obj) || _.isRegExp(obj) || _.isArguments(obj)
  );
}
Example #28
0
function _resolveIsDescendable(obj) {
  return !(
    _.isUndefined(obj) || _.isNull(obj) || _.isFunction(obj) ||
    _.isArray(obj) || _.isString(obj) || _.isNumber(obj) ||
    _.isDate(obj) || _.isRegExp(obj) || _.isArguments(obj)
  );
}
Example #29
0
export function sanitize (value, mask) {
  if (!mask) {
    return value
  }
  if (_.isObject(mask) && !_.isObject(value)) {
    return value
  }
  if (_.isString(value)) {
    return '<string[' + value.length + ']>'
  }
  if (_.isNumber(value)) {
    return '<number>'
  }
  if (_.isDate(value)) {
    return '<date>'
  }
  if (_.isBoolean(value)) {
    return '<bool>'
  }
  if (_.isArray(value)) {
    return value.map((item) => sanitize(item, mask))
  }
  if (_.isObject(value)) {
    return _.mapValues(value, (val, key) => sanitize(val, mask === true ? true : mask[key]))
  }
  return '<value>'
}
Example #30
0
                                    _.forOwn(row, function (value, key) {
                                        // if this is first row, record fields in fields array
                                        if (r === 0) fields.push(key);
                                        if (!meta[key]) meta[key] = {
                                            datatype: null,
                                            max: null,
                                            min: null,
                                            maxValueLength: 0
                                        };

                                        // if we don't have a data type and we have a value yet lets try and figure it out
                                        if (!meta[key].datatype && value) {
                                            if (_.isDate(value)) meta[key].datatype = 'date';
                                            else if (isNumberLike(value)) meta[key].datatype = 'number';
                                            else if (_.isString(value)) {
                                                meta[key].datatype = 'string';
                                                if (meta[key].maxValueLength < value.length) meta[key].maxValueLength = value.length;
                                            }
                                        }
                                        // if we have a value and are dealing with a number or date, we should get min and max
                                        if (
                                            value
                                            && (meta[key].datatype === 'number' || meta[key].datatype === 'date')
                                            && (isNumberLike(value) || _.isDate(value))
                                        ) {
                                            // if we haven't yet defined a max and this row contains a number
                                            if (!meta[key].max) meta[key].max = value;
                                            // otherwise this field in this row contains a number, and we should see if its bigger
                                            else if (value > meta[key].max) meta[key].max = value;
                                            // then do the same thing for min
                                            if (!meta[key].min) meta[key].min = value;
                                            else if (value < meta[key].min) meta[key].min = value;
                                        }
                                        // if the datatype is number-like, 
                                        // we should check to see if it ever changes to a string
                                        // this is hacky, but sometimes data will be 
                                        // a mix of number-like and strings that aren't number like
                                        // in the event that we get some data that's NOT NUMBER LIKE, 
                                        // then we should *really* be recording this as string
                                        if (meta[key].datatype === 'number' && value) {
                                            if (!isNumberLike(value)) {
                                                meta[key].datatype = 'string';
                                                meta[key].max = null;
                                                meta[key].min = null;
                                            }
                                        }
                                    });