Example #1
0
export function merge(a, b) {
  if (isPlainObject(a) && isPlainObject(b)) {
    // recursively merge() each matching property
    const merged = {};
    var k;
    for (k in a) {
      if (k in b) {
        merged[k] = merge(a[k], b[k]);
      } else {
        merged[k] = a[k];
      }
    }
    for (k in b) {
      if (!(k in merged)) {
        merged[k] = b[k];
      }
    }
    return merged;
  } else {
    // (true, true) => true
    // (true, false) => true
    // (false, true) => true
    // (false, false) => false
    return a || b;
  }
}
Example #2
0
export default function DragSource(type, spec, collect, options = {}) {
	checkDecoratorArguments(
		'DragSource',
		'type, spec, collect[, options]',
		...arguments, // eslint-disable-line prefer-rest-params
	)
	let getType = type
	if (typeof type !== 'function') {
		invariant(
			isValidType(type),
			'Expected "type" provided as the first argument to DragSource to be ' +
				'a string, or a function that returns a string given the current props. ' +
				'Instead, received %s. ' +
				'Read more: http://react-dnd.github.io/react-dnd/docs-drag-source.html',
			type,
		)
		getType = () => type
	}
	invariant(
		isPlainObject(spec),
		'Expected "spec" provided as the second argument to DragSource to be ' +
			'a plain object. Instead, received %s. ' +
			'Read more: http://react-dnd.github.io/react-dnd/docs-drag-source.html',
		spec,
	)
	const createSource = createSourceFactory(spec)
	invariant(
		typeof collect === 'function',
		'Expected "collect" provided as the third argument to DragSource to be ' +
			'a function that returns a plain object of props to inject. ' +
			'Instead, received %s. ' +
			'Read more: http://react-dnd.github.io/react-dnd/docs-drag-source.html',
		collect,
	)
	invariant(
		isPlainObject(options),
		'Expected "options" provided as the fourth argument to DragSource to be ' +
			'a plain object when specified. ' +
			'Instead, received %s. ' +
			'Read more: http://react-dnd.github.io/react-dnd/docs-drag-source.html',
		collect,
	)

	return function decorateSource(DecoratedComponent) {
		return decorateHandler({
			connectBackend: (backend, sourceId) =>
				backend.connectDragSource(sourceId),
			containerDisplayName: 'DragSource',
			createHandler: createSource,
			registerHandler: registerSource,
			createMonitor: createSourceMonitor,
			createConnector: createSourceConnector,
			DecoratedComponent,
			getType,
			collect,
			options,
		})
	}
}
Example #3
0
export const withDefaults = defaults => handler => args => {
  const { data } = args.message;
  const isMergeable = isPlainObject(defaults) && isPlainObject(data);
  const finalData = isMergeable ? { ...defaults, ...data } : data || defaults;

  Object.assign(args.message, {
    data: finalData,
  });

  return handler(args);
};
  this.serialize = function (dest, current, attribute, opts) {
    var that = this;
    var data = null;

    if (opts && opts.ref) {
      if (!dest.relationships) { dest.relationships = {}; }

      if (Array.isArray(current[attribute])) {
        data = current[attribute].map(function (item) {
          return that.serializeRef(item, current, attribute, opts);
        });
      } else {
        data = that.serializeRef(current[attribute], current, attribute,
          opts);
      }

      dest.relationships[keyForAttribute(attribute)] = {};
      if (!opts.ignoreRelationshipData) {
        dest.relationships[keyForAttribute(attribute)].data = data;
      }

      if (opts.relationshipLinks) {
        var links = getLinks(current[attribute], opts.relationshipLinks, dest);
        if (links.related) {
          dest.relationships[keyForAttribute(attribute)].links = links;
        }
      }

      if (opts.relationshipMeta) {
        dest.relationships[keyForAttribute(attribute)].meta =
          getMeta(current[attribute], opts.relationshipMeta);
      }
    } else {
      if (Array.isArray(current[attribute])) {
        if (current[attribute].length && isPlainObject(current[attribute][0])) {
          data = current[attribute].map(function (item) {
            return that.serializeNested(item, current, attribute, opts);
          });
        } else {
          data = current[attribute];
        }

        dest.attributes[keyForAttribute(attribute)] = data;
      } else if (isPlainObject(current[attribute])) {
        data = that.serializeNested(current[attribute], current, attribute, opts);
        dest.attributes[keyForAttribute(attribute)] = data;
      } else {
        dest.attributes[keyForAttribute(attribute)] = current[attribute];
      }
    }
  };
 // Get the theme from the props, supporting both (outerTheme) => {} as well as object notation
 getTheme(passedTheme: (outherTheme: Theme) => void | Theme) {
   const theme = passedTheme || this.props.theme
   if (isFunction(theme)) {
     const mergedTheme = theme(this.outerTheme)
     if (!isPlainObject(mergedTheme)) {
       throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!')
     }
     return mergedTheme
   }
   if (!isPlainObject(theme)) {
     throw new Error('[ThemeProvider] Please make your theme prop a plain object')
   }
   return Object.assign({}, this.outerTheme, (theme: Object))
 }
Example #6
0
const buildRoutes = routes => function(options = {}) {
  if (!isPlainObject(options)) {
    throw new TypeError(
      "Options for controller should be passed as plain JavaScript object, " +
      `but given value has type of ${getType(options)}.`
    )
  }

  options = merge({}, defaults, options)

  for (const [name, route] of objectIterator.entries(routes)) {
    if (!isFunction(route.default)) {
      warn(`Controller "${name}" is not a function.`)
      continue
    }

    const prefix = name !== options.indexRoute ? `/${name}` : ""

    const Ctor = route.default

    r.use(prefix, new Ctor())
  }

  return mountNonMatchedHandlers(r, options.nonMatched)
}
Example #7
0
function invertValidity(validity) {
  if (isPlainObject(validity)) {
    return mapValues(validity, invertValidity);
  }

  return !validity;
}
Example #8
0
/**
 * Recursively update an object or array.
 *
 * Can update with values:
 * update({ foo: 3 }, { foo: 1, bar: 2 });
 * // => { foo: 3, bar: 2 }
 *
 * Or with a function:
 * update({ foo: x => (x + 1) }, { foo: 2 });
 * // => { foo: 3 }
 *
 * @function
 * @name update
 * @param {Object|Function} updates
 * @param {Object|Array}    object to update
 * @return {Object|Array}   new object with modifications
 */
function update(updates, object, ...args) {
  if (typeof updates === 'function') {
    return updates(object, ...args);
  }

  if (!isPlainObject(updates)) {
    return updates;
  }

  const defaultedObject = (typeof object === 'undefined' || object === null) ?
    {} :
    object;

  const resolvedUpdates = resolveUpdates(updates, defaultedObject);

  if (isEmpty(resolvedUpdates)) {
    return defaultedObject;
  }

  if (Array.isArray(defaultedObject)) {
    return updateArray(resolvedUpdates, defaultedObject);
  }

  return { ...defaultedObject, ...resolvedUpdates };
}
Example #9
0
    args.forEach((arg) => {
        if (isPlainObject(arg)) {
            arg.inspect = () => JSON.stringify(arg, null, 2);
        }

        return arg;
    });
Example #10
0
  /**
   * Dispatches an action. It is the only way to trigger a state change.
   *
   * The `reducer` function, used to create the store, will be called with the
   * current state tree and the given `action`. Its return value will
   * be considered the **next** state of the tree, and the change listeners
   * will be notified.
   *
   * The base implementation only supports plain object actions. If you want to
   * dispatch a Promise, an Observable, a thunk, or something else, you need to
   * wrap your store creating function into the corresponding middleware. For
   * example, see the documentation for the `redux-thunk` package. Even the
   * middleware will eventually dispatch plain object actions using this method.
   *
   * @param {Object} action A plain object representing “what changed”. It is
   * a good idea to keep actions serializable so you can record and replay user
   * sessions, or use the time travelling `redux-devtools`. An action must have
   * a `type` property which may not be `undefined`. It is a good idea to use
   * string constants for action types.
   *
   * @returns {Object} For convenience, the same action object you dispatched.
   *
   * Note that, if you use a custom middleware, it may wrap `dispatch()` to
   * return something else (for example, a Promise you can await).
   */
  function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error("Actions must be plain objects. Use custom middleware for async actions.");
    }

    if (typeof action.type === "undefined") {
      throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constan' +
        't?');
    }

    // 规定: reducer代码中不能触发dispatch,这样会使整个state的处理逻辑变得复杂。reducer应该仅仅处理state对象
    if (isDispatching) {
      throw new Error("Reducers may not dispatch actions.");
    }

    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }

    const listeners = (currentListeners = nextListeners);

    // 执行订阅的listener队列
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i];
      listener();
    }

    return action;
  }
Example #11
0
const getSanitizedRecords = () => {
    const records = _castArray(config.get(CONFIG_KEY, []));

    let shouldUpdate = false;
    for (let i = 0; i < records.length; ++i) {
        if (!_isPlainObject(records[i])) {
            records[i] = {};
        }

        const record = records[i];

        if (!record.id) {
            record.id = uuid.v4();
            shouldUpdate = true;
        }
    }

    if (shouldUpdate) {
        log.debug(`update sanitized records: ${JSON.stringify(records)}`);

        // Pass `{ silent changes }` will suppress the change event
        config.set(CONFIG_KEY, records, { silent: true });
    }

    return records;
};
Example #12
0
function deepValues(obj) {
  // creates flat list of all `obj` values (including nested)
  if(isPlainObject(obj) || Array.isArray(obj)) {
    return flatMapDeep(obj, deepValues)
  }
  return obj
}
Example #13
0
  static createObservableItem(itemBranch: Object, definition: Object) {
    if (!isPlainObject(definition.properties)) return;
    const deeperObjectKeys = new Map();

    const propertiesToExtend = Object.keys(definition.properties)
      .filter(key => !Schema.isPrimaryKey(definition.properties[key]))
      .reduce((observableValues, key) => {
        const property = definition.properties[key];
        if (property.type !== Object) {
          if (property.observable === false) {
            return observableValues;
          }

          if (property.type === Array) {
            observableValues[key] = observable.array();
            return observableValues;
          }

          observableValues[key] = undefined;
          return observableValues;
        }

        observableValues[key] = observable({});
        deeperObjectKeys.set(key, property);
        return observableValues;
      }, {});


    extendObservable(itemBranch, propertiesToExtend);
    deeperObjectKeys.forEach(
      (property, key) => Schema.createObservableItem(itemBranch[key], property),
    );
  }
function castGeojson(format, value) {
  if (!isObject(value)) {
    if (!isString(value)) {
      return ERROR
    }
    try {
      value = JSON.parse(value)
    } catch (error) {
      return ERROR
    }
    if (!isPlainObject(value)) {
      return ERROR
    }
  }
  if (format === 'default') {
    try {
      const valid = tv4.validate(value, geojsonProfile)
      if (!valid) {
        return ERROR
      }
    } catch (error) {
      return ERROR
    }
  } else if (format === 'topojson') {
    try {
      const valid = tv4.validate(value, topojsonProfile)
      if (!valid) {
        return ERROR
      }
    } catch (error) {
      return ERROR
    }
  }
  return value
}
 (res, val) =>
   res &&
     isPlainObject(val) &&
     isString(val.name) &&
     (isUndefined(val.label) || isString(val.label)) &&
     (isUndefined(val.template) || isString(val.template) || isFunction(val.template)) &&
     (isUndefined(val.transformData) || isFunction(val.transformData)),
Example #16
0
function setMiddlewares(name, schema) {
  const path = join(DATABASE_ROOT, "middleware", camelCase(name))

  let middlewares = null
  try {
    middlewares = require(path)
  } catch (err) {
    invariant(err.code !== "MODULE_NOT_FOUND", err)
  }

  if (isEmpty(middlewares)) {
    return schema
  }

  invariant(
    !isPlainObject(middlewares), TypeError,
    "Middlewares module should export a plain object."
  )

  for (const {kind, type, parallel, handler} of objectIterator(middlewares)) {
    const args = [type]

    if (kind !== "post") {
      args.push(parallel)
    }

    schema[kind](...args, handler)
  }

  return schema
}
    return mapValues(object, value => {
      if (isPlainObject(value)) {
        return this.replaceValues(value)
      }

      return this._variables[value] || value
    })
Example #18
0
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
  var reducerKeys = Object.keys(reducers)
  var argumentName = action && action.type === ActionTypes.INIT ?
    'initialState argument passed to createStore' :
    'previous state received by the reducer'

  if (reducerKeys.length === 0) {
    return (
      'Store does not have a valid reducer. Make sure the argument passed ' +
      'to combineReducers is an object whose values are reducers.'
    )
  }

  if (!isPlainObject(inputState)) {
    return (
      `The ${argumentName} has unexpected type of "` +
      ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
      `". Expected argument to be an object with the following ` +
      `keys: "${reducerKeys.join('", "')}"`
    )
  }

  var unexpectedKeys = Object.keys(inputState).filter(key => !reducers.hasOwnProperty(key))

  if (unexpectedKeys.length > 0) {
    return (
      `Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` +
      `"${unexpectedKeys.join('", "')}" found in ${argumentName}. ` +
      `Expected to find one of the known reducer keys instead: ` +
      `"${reducerKeys.join('", "')}". Unexpected keys will be ignored.`
    )
  }
}
Example #19
0
export const bulkUpdate = (req, res) => {
    const { records } = { ...req.body };

    if (!records) {
        res.status(ERR_BAD_REQUEST).send({
            msg: 'The "records" parameter must not be empty'
        });
        return;
    }

    const filteredRecords = ensureArray(records)
        .filter(record => isPlainObject(record));

    for (let i = 0; i < filteredRecords.length; ++i) {
        const record = filteredRecords[i];
        const { id, name, command, grid = {} } = { ...record };

        if (!id) {
            record.id = uuid.v4();
        }
        record.name = String(name || '');
        record.command = String(command || '');
        record.grid = isPlainObject(grid) ? grid : {};
    }

    try {
        config.set(CONFIG_KEY, filteredRecords);
        res.send({ err: null });
    } catch (err) {
        res.status(ERR_INTERNAL_SERVER_ERROR).send({
            msg: 'Failed to save ' + JSON.stringify(settings.cncrc)
        });
    }
};
Example #20
0
function isValid(validity) {
  if (isPlainObject(validity)) {
    return every(validity, isValid);
  }

  return !!validity;
}
Example #21
0
	function iterateTree(tree, level=0, index=0) {
		let tag = tree.shift();
		const key = onGenerateKey(tag, index);

		const props = (tree.length && isPlainObject(tree[0])) ?
		Object.assign(tree.shift(), { key: key }) :
		{ key: key };

		if (level === 0 && className) {
			props.className = className;
		}

		const children = tree.map(
			(branch, idx) => Array.isArray(branch) ?
			iterateTree(branch, level + 1, idx) :
			branch
		);

		tag = tags[tag] || tag;

		if (isString(props.style)) {
			props.style = zipObject(
				props.style.split(';')
				.map(prop => prop.split(':'))
				.map(keyVal => [camelCase(keyVal[0].trim()), keyVal[1].trim()])
			);
		}

		return (typeof onIterate === 'function') ?
		onIterate(tag, props, children, level) :
		React.createElement(tag, props, children);
	}
Example #22
0
function isInvalid(errors) {
  if (isPlainObject(errors)) {
    return some(errors, isInvalid);
  }

  return !!errors;
}
Example #23
0
  _createObservableKeyList(definition: Object, parentPath : string = '') {
    if (!isPlainObject(definition.properties)) return;

    Object.keys(definition.properties)
      .filter(key => !Schema.isPrimaryKey(definition.properties[key]))
      .forEach((key) => {
        const property = definition.properties[key];
        if (property.type !== Object) {
          if (property.observable === false) {
            this.nonObservables.push(`${parentPath}${key}`);
          } else if (
            Schema.isKey(property) ||
            (property.type === Array && Schema.isKey(property.items))
          ) {
            this.references.set(`${parentPath}${key}`, property);
          } else {
            this.observables.push(`${parentPath}${key}`);
          }
          return;
        }

        const newParentPath = `${parentPath}${key}.`;
        this._createObservableKeyList(property, newParentPath);
      });
  }
 calculator.forEach(p => {
   if (isPlainObject(p)) {
     params.push(domGeometryStore.getAttr(p.identifier, p.attr));
   } else {
     params.push(p);
   }
 });
 function keyForAttribute(attribute) {
   if (isPlainObject(attribute)) {
     return _transform(attribute, function (result, value, key) {
       if (isComplexType(value)) {
         result[keyForAttribute(key)] = keyForAttribute(value);
       } else {
         result[keyForAttribute(key)] = value;
       }
     });
   } else if (Array.isArray(attribute)) {
     return attribute.map(function (attr) {
       if (isComplexType(attr)) {
         return keyForAttribute(attr);
       } else {
         return attr;
       }
     });
   } else {
     if (isFunction(opts.keyForAttribute)) {
       return opts.keyForAttribute(attribute);
     } else {
       return Inflector.caserize(attribute, opts);
     }
   }
 }
Example #26
0
    var methodBody = function() {
        var argsLength = arguments.length;
        var args = new Array(argsLength);
        for (var i = 0; i < argsLength; i++) {
            args[i] = arguments[i];
        }

        var requiredParamsStart = apiPathParamsCount;
        var requiredParamsEnd = requiredParamsStart + paramNames.length;
        var requiredParamArgs = args.slice(requiredParamsStart, requiredParamsEnd);

        // Callback is at the end
        var callback = isFunction(args[args.length - 1]) ? args.pop() : null;

        // Required Parmas
        var params = zipObject(paramNames, requiredParamArgs);
        extend(params, isPlainObject(args[args.length - 1]) ? args.pop() : {});

        // Path arguments are determined after required parameters
        var apiPathArgs = args.slice(0, apiPathParamsCount);

        var request = requestType;
        if (isString(requestType)) {
            request = requestType.toUpperCase() === 'POST' ? client.postRequest : client.getRequest;
        } else if (!isFunction(requestType)) {
            request = client.getRequest;
        }

        return request.call(client, buildApiPath(apiPathArgs), params, callback);
    };
Example #27
0
  /**
   * Dispatches an action. It is the only way to trigger a state change.
   *
   * The `reducer` function, used to create the store, will be called with the
   * current state tree and the given `action`. Its return value will
   * be considered the **next** state of the tree, and the change listeners
   * will be notified.
   *
   * The base implementation only supports plain object actions. If you want to
   * dispatch a Promise, an Observable, a thunk, or something else, you need to
   * wrap your store creating function into the corresponding middleware. For
   * example, see the documentation for the `redux-thunk` package. Even the
   * middleware will eventually dispatch plain object actions using this method.
   *
   * @param {Object} action A plain object representing “what changed”. It is
   * a good idea to keep actions serializable so you can record and replay user
   * sessions, or use the time travelling `redux-devtools`. An action must have
   * a `type` property which may not be `undefined`. It is a good idea to use
   * string constants for action types.
   *
   * @returns {Object} For convenience, the same action object you dispatched.
   *
   * Note that, if you use a custom middleware, it may wrap `dispatch()` to
   * return something else (for example, a Promise you can await).
   */
  function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. ' +
        'Use custom middleware for async actions.'
      )
    }

    if (typeof action.type === 'undefined') {
      throw new Error(
        'Actions may not have an undefined "type" property. ' +
        'Have you misspelled a constant?'
      )
    }

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }

    try {
      isDispatching = true
      currentState = currentReducer(currentState, action)
    } finally {
      isDispatching = false
    }

    var listeners = currentListeners = nextListeners
    for (var i = 0; i < listeners.length; i++) {
      listeners[i]()
    }

    return action
  }
Example #28
0
export function execute({
  http: userHttp,
  fetch, // This is legacy
  spec,
  operationId,
  pathName,
  method,
  parameters,
  securities,
  ...extras
}) {
  // Provide default fetch implementation
  const http = userHttp || fetch || stockHttp // Default to _our_ http

  if (pathName && method && !operationId) {
    operationId = legacyIdFromPathMethod(pathName, method)
  }

  const request = self.buildRequest({spec, operationId, parameters, securities, http, ...extras})

  if (request.body && (isPlainObject(request.body) || isArray(request.body))) {
    request.body = JSON.stringify(request.body)
  }

  // Build request and execute it
  return http(request)
}
Example #29
0
request.Request.prototype.init = function RP$initInterceptor(options) {

    var self = this;

    // Init may be called again - currently in case of redirects
    if (isPlainObject(options) && self._callback === undefined && self._rp_promise === undefined) {

        self._rp_promise = new Bluebird(function (resolve, reject) {
            self._rp_resolve = resolve;
            self._rp_reject = reject;
        });

        self._rp_callbackOrig = self.callback;
        self.callback = RP$callback;

        if (isString(options.method)) {
            options.method = options.method.toUpperCase();
        }

        options.transform = options.transform || defaultTransformations[options.method];

        self._rp_options = options;
        self._rp_options.simple = options.simple === false ? false : true;
        self._rp_options.resolveWithFullResponse = options.resolveWithFullResponse === true ? true : false;

    }

    return originalInit.apply(self, arguments);

};
Example #30
0
const __createTypes = (context, prefix, typesAdd) => {
  const classType = context.constructor.__dangerDontUseThisType;
  const classTypesList = context.constructor.__dangerDontUseThisTypesList;
  if (isString(prefix)) {
    context.PREFIX = prefix;
  } else {
    context.PREFIX = '@@Redbone/' + classType +
      '/' + context.constructor.name + '/';
  }
  if (context.pid) {
    context.PREFIX += context.pid + '/';
  }
  let types = {};
  Object.keys(classTypesList).forEach((key) => {
    const type = key.toUpperCase() + '_';
    types[type + 'REQUESTING'] = context.PREFIX + type + 'REQUESTING';
    types[type + 'REQUESTED'] = context.PREFIX + type + 'REQUESTED';
    types[type + 'ERROR'] = context.PREFIX + type + 'ERROR';
  });
  context.TYPES = types;
  if (isObject(typesAdd)) {
    context.addTypes(typesAdd, true);
  }
  if (context.constructor.TYPES) {
    context.addTypes(context.constructor.TYPES, true);
  }
}