<commit_before>var UpdateSet = require('../../../lib/commands/crdt/updateset');
var Rpb = require('../../../lib/protobuf/riakprotobuf');
var DtUpdateReq = Rpb.getProtoFor('DtUpdateReq');
var DtUpdateResp = Rpb.getProtoFor('DtUpdateResp');
var DtValue = Rpb.getProtoFor('DtValue');
var RpbErrorResp = Rpb.getProtoFor('RpbErrorResp');

var ByteBuffer = require('bytebuffer');
var assert = require('assert');

describe('UpdateSet', function() {
    describe('Build', function() {
        var builder = new UpdateSet.Builder().
                withBucketType('sets_type').
                withBucket('set_bucket').
                withKey('cool_set');

        // ikea rugs
        var hampenBuffer = ByteBuffer.fromUTF8("hampen");
        var snabbfotadBuffer = ByteBuffer.fromUTF8("snabbfotad");

        var someContext = ByteBuffer.fromUTF8("context");

        var includesBuffer = function(haystack, needle) {
            var len = haystack.length;
            for (var i = 0; i < len; i++) {
                if (haystack[i].toString('utf8') === needle) {
                    return true;
                }
            }

            return false;
        };

        it('builds a DtUpdateSet correctly', function(done){
            var update = builder.
                    withContext(someContext).
                    withAdditions(["gåser", hampenBuffer]).
                    withRemovals([snabbfotadBuffer, "valby ruta"]).
                    withCallback(function(){}).
                    withW(1).
                    withDw(2).
                    withPw(3).
                    withReturnBody(false).
                    withTimeout(12345).
                    build();

            var protobuf = update.constructPbRequest();

            assert.equal(protobuf.getType().toString('utf8'),
                         'sets_type');
            assert.equal(protobuf.getBucket().toString('utf8'),
                         'set_bucket');
            assert.equal(protobuf.getKey().toString('utf8'),
                         'cool_set');
            assert.equal(protobuf.getW(), 1);
            assert.equal(protobuf.getDw(), 2);
            assert.equal(protobuf.getPw(), 3);

            assert.equal(protobuf.getReturnBody(), false);
            assert.equal(protobuf.getTimeout(), 12345);

            assert(includesBuffer(protobuf.op.set_op.adds,
                                      "gåser"));
            assert(includesBuffer(protobuf.op.set_op.adds,
                                      "hampen"));

            assert(includesBuffer(protobuf.op.set_op.removes,
                                      "snabbfotad"));
            assert(includesBuffer(protobuf.op.set_op.removes,
                                      "valby ruta"));

            done();
        });
    });
});
<commit_msg>test updateset behavior with errors, returnbody, no returnbody<commit_after>var UpdateSet = require('../../../lib/commands/crdt/updateset');
var Rpb = require('../../../lib/protobuf/riakprotobuf');
var DtUpdateReq = Rpb.getProtoFor('DtUpdateReq');
var DtUpdateResp = Rpb.getProtoFor('DtUpdateResp');
var DtValue = Rpb.getProtoFor('DtValue');
var RpbErrorResp = Rpb.getProtoFor('RpbErrorResp');

var ByteBuffer = require('bytebuffer');
var assert = require('assert');

describe('UpdateSet', function() {
    // ikea rugs
    var hampenBuffer = ByteBuffer.fromUTF8("hampen");
    var snabbfotadBuffer = ByteBuffer.fromUTF8("snabbfotad");

    var someContext = ByteBuffer.fromUTF8("context");

    var builder = new UpdateSet.Builder().
            withBucketType('sets_type').
            withBucket('set_bucket').
            withKey('cool_set');

    describe('Build', function() {
        var includesBuffer = function(haystack, needle) {
            var len = haystack.length;
            for (var i = 0; i < len; i++) {
                if (haystack[i].toString('utf8') === needle) {
                    return true;
                }
            }

            return false;
        };

        it('builds a DtUpdateSet correctly', function(done){
            var update = builder.
                    withContext(someContext).
                    withAdditions(["gåser", hampenBuffer]).
                    withRemovals([snabbfotadBuffer, "valby ruta"]).
                    withCallback(function(){}).
                    withW(1).
                    withDw(2).
                    withPw(3).
                    withReturnBody(false).
                    withTimeout(12345).
                    build();

            var protobuf = update.constructPbRequest();

            assert.equal(protobuf.getType().toString('utf8'),
                         'sets_type');
            assert.equal(protobuf.getBucket().toString('utf8'),
                         'set_bucket');
            assert.equal(protobuf.getKey().toString('utf8'),
                         'cool_set');
            assert.equal(protobuf.getW(), 1);
            assert.equal(protobuf.getDw(), 2);
            assert.equal(protobuf.getPw(), 3);

            assert.equal(protobuf.getReturnBody(), false);
            assert.equal(protobuf.getTimeout(), 12345);

            assert(includesBuffer(protobuf.op.set_op.adds,
                                  "gåser"));
            assert(includesBuffer(protobuf.op.set_op.adds,
                                  "hampen"));

            assert(includesBuffer(protobuf.op.set_op.removes,
                                  "snabbfotad"));
            assert(includesBuffer(protobuf.op.set_op.removes,
                                  "valby ruta"));

            done();
        });
    });

    var includesBuffer = function(haystack, needle) {
        var needleBuf = new Buffer(needle);
        var len = haystack.length;
        for (var i = 0; i < len; i++) {
            if (haystack[i].equals(needleBuf)) return true;
        }

        return false;
    };

    var includes = function(haystack, needle) {
        var len = haystack.length;
        for (var i = 0; i < len; i++) {
            if (haystack[i] === needle) return true;
        }

        return false;
    };

    describe('with body, without key', function() {
        it('calls back with successful results', function(done) {
            var resp = new DtUpdateResp;
            resp.setContext(new Buffer("asdf"));
            resp.setSetValue([hampenBuffer, snabbfotadBuffer]);

            var callback = function(err, response) {
                assert(!err);
                assert(response);

                assert.equal(response.context.toString("utf8"), "asdf");
                assert.equal(response.dataType, 2);

                assert(includesBuffer(response.valueBuffers, "hampen"));
                assert(includes(response.value, "hampen"));

                assert(includesBuffer(response.valueBuffers, "snabbfotad"));
                assert(includes(response.value, "snabbfotad"));

                done();
            };

            var update = builder.
                    withCallback(callback).
                    withAdditions([hampenBuffer]).
                    build();

            update.onSuccess(resp);
        });
    });

    describe('without body, with key', function() {
        it('calls back with successful results', function(done) {
            var resp = new DtUpdateResp();
            resp.key = new Buffer("ikea_rugs");

            var callback = function(err, response) {
                assert.equal(response.key.toString("utf8"), "ikea_rugs");
                assert.equal(response.keyString, "ikea_rugs");
                done();
            };

            var update = builder.
                    withCallback(callback).
                    withAdditions([hampenBuffer]).
                    build();

            update.onSuccess(resp);
        });
    });

    describe('returning an error', function() {
        it('calls back with an error message', function(done) {
            var errorMessage = "couldn't crdt :(";
            var errorResp = new RpbErrorResp();
            errorResp.setErrmsg(new Buffer(errorMessage));

            var callback = function(err, response) {
                assert(err);
                assert(!response);

                assert.equal(err, errorMessage);

                done();
            };

            var update = builder.
                    withCallback(callback).
                    build();

            update.onRiakError(errorResp);
        });
    });
});
<|endoftext|>


<commit_before>var read = require("../../lib/parser").read;
var makeIdent = require("../../lib/syntax").makeIdent;
var unwrapSyntax = require("../../lib/syntax").unwrapSyntax;
var Env = require("../../lib/data/env.js");

var expect = require("expect.js");

describe("an env", function() {

    it("set a single identifier value", function() {
        var e = new Env();
        var stx = read("x")[0];
        e.set(stx, 0, 42);
        expect(e.get(stx, 0)).to.be(42);
    });

    it("getting a value not in the map returns null", function() {
        var e = new Env();
        var stx = read("x")[0];
        expect(e.get(stx, 0)).to.be(null);
    });

    it("set and get a multi token name", function() {
        var e = new Env();
        var stx = read("x?y");
        e.set(makeIdent(stx.map(unwrapSyntax).join(""), stx[0]), 0, 42);
        expect(e.get(read("x?y"), 0)).to.be(42);
        expect(e.get(read("x?y and other tokens"), 0)).to.be(42);
        expect(e.get(read("x?y?and other tokens"), 0)).to.be(42);
    });

});
<commit_msg>renamed<commit_after><|endoftext|>


<commit_before>var util = require('../util.test');

module.exports = function() {
	util.request('http://dispatch.test.whistlejs.com/index.html', function(res, data) {
		data.url.should.containEql('dispatch=test');
		data.url.should.containEql('timestamp=');
	});

	util.request({
		url: 'https://dispatch.test.whistlejs.com/index.html',
		method: 'post',
		body: 'sssssss'
	}, function(res, data) {
		data.url.should.containEql('dispatch=test');
		data.url.should.containEql('timestamp=');
	});
};<commit_msg>test: dispatch<commit_after>var util = require('../util.test');

module.exports = function() {
	util.request('http://dispatch.test.whistlejs.com/index.html', function(res, data) {
		data.url.should.containEql('dispatch=test');
		data.url.should.containEql('timestamp=');
		data.should.have.property('host', '127.0.0.1');
		data.should.have.property('port', '8080');
	});

	util.request({
		url: 'https://dispatch.test.whistlejs.com/index.html',
		method: 'post',
		body: 'sssssss'
	}, function(res, data) {
		data.url.should.containEql('dispatch=test');
		data.url.should.containEql('timestamp=');
		data.should.have.property('host', '127.0.0.1');
		data.should.have.property('port', '8080');
	});
};<|endoftext|>


<commit_before>function plugin()
{
    return document.getElementById('plugin0');
}

function get_valid_id() {
    var tracking_ids = plugin().trackedSkeletonIDs;
    return tracking_ids.shift();
}

function get_skeleton_data(tracking_id) {
    return plugin().getSkeletonData(tracking_id);
}

function get_joint_velocity(tracking_id) {
    return plugin().getVelocityData(tracking_id);
}

function is_tracking() {
    var tracking_ids = plugin().trackedSkeletonIDs;
    if( tracking_ids.length > 0 ) {
        return true;
    }
    return false;
}

function handle_new_data() {
    if ( is_tracking() ) {
        var tracking_ids = plugin().trackedSkeletonIDs;
        //console.log(tracking_ids);
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for ( var i = 0, l = tracking_ids.length; i < l; i++ ) {
            var id = tracking_ids[i];
            var data = get_skeleton_data(id);
            var velocity = get_joint_velocity(id);

            var width = canvas.width;
            var height = canvas.height;
            for( var joint = 0, l = data.length; joint < l; joint++ ) {
                var x = data[joint][0];
                var y = data[joint][1];
                var scaled_coord = scale_data(x,y,width,height);
                x = scaled_coord[0];
                y = scaled_coord[1];
                ctx.fillRect(x,height-y,5+100*velocity[joint][0],5+100*velocity[joint][0]);
            }
        }
    }
}

function scale_data(x, y, canvas_x, canvas_y) {
    x += 2.2;
    if ( x < 0 ) {
        x = 0;
    }
    x = (x/4.4) * canvas_x;

    y += 1.6;
    if ( y < 0 ) {
        y = 0;
    }
    y = (y/3.2) * canvas_y;

    return [x,y];
}

var canvas;
var ctx;

window.onload = function() {
    document.getElementById('plugin0').addEventListener("newskeletondata", handle_new_data, false);
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
}
<commit_msg>Minor bugfixes<commit_after>function plugin()
{
    return document.getElementById('plugin0');
}

function get_tracking_ids() {
    return plugin().trackedSkeletonIDs;
}

function get_skeleton_data(tracking_id) {
    return plugin().getSkeletonData(tracking_id);
}

function get_joint_velocity(tracking_id) {
    return plugin().getVelocityData(tracking_id);
}

function is_tracking() {
    var tracking_ids = get_tracking_ids();
    if( tracking_ids.length > 0 ) {
        return true;
    }
    return false;
}

function handle_new_data() {
    if ( is_tracking() ) {
        var tracking_ids = get_tracking_ids();

        ctx.clearRect(0,0,canvas.width,canvas.height);

        for ( var i = 0, l = tracking_ids.length; i < l; i++ ) {
            var id = tracking_ids[i];

            try {
                var data = get_skeleton_data(id);
            } catch (err) {
                continue;
            }
            var velocity = get_joint_velocity(id);

            var width = canvas.width;
            var height = canvas.height;
            for( var joint = 0, l_d = data.length; joint < l_d; joint++ ) {
                var x = data[joint][0];
                var y = data[joint][1];
                var scaled_coord = scale_data(x,y,width,height);
                x = scaled_coord[0];
                y = scaled_coord[1];
                ctx.fillRect(x,height-y,5+100*velocity[joint][0],5+100*velocity[joint][0]);
            }
        }
    }
}

function scale_data(x, y, canvas_x, canvas_y) {
    x += 2.2;
    if ( x < 0 ) {
        x = 0;
    }
    x = (x/4.4) * canvas_x;

    y += 1.6;
    if ( y < 0 ) {
        y = 0;
    }
    y = (y/3.2) * canvas_y;

    return [x,y];
}

var canvas;
var ctx;

window.onload = function() {
    document.getElementById('plugin0').addEventListener("newskeletondata", handle_new_data, false);
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
}
<|endoftext|>


<commit_before>Canvas.prototype.addControls = function(){
    primaryControls.update();
    renderer.render(scene, primaryCamera);
    this.controlsID = requestAnimationFrame(Canvas.prototype.addControls);
};

Canvas.prototype.resetControls = function() {
primaryControls.reset();

};

Canvas.prototype.addCameras = function() {
    for(var key in JSONObj.cameras){
        var _camera = JSONObj.cameras[key];

        switch(_camera.type){

        case "PerspectiveCamera":
            var _Camera = new THREE.PerspectiveCamera(
                                       _camera.fov, this.aspect_ratio,
                                         _camera.near, _camera.far );
            var _element = new Float32Array(_camera.simulation_matrix[0]);
            var initMatrix = new THREE.Matrix4();
            initMatrix.elements = _element;
            _Camera.applyMatrix(initMatrix);
        case "OrthoGraphicCamera":
            //TODO

        }
        console.log(_Camera);
        this.cameras.add(_Camera);

    }
    this.scene.add(this.cameras);
};

Canvas.prototype.addLights = function() {
    for(var key in JSONObj.lights){
        var _light = JSONObj.lights[key];

        switch(_light.type){

        case "PointLight":
            var color = new THREE.Color().setRGB(_light.color[0],
                                    _light.color[1], _light.color[2])
            var _Light = new THREE.PointLight(color);
            var _element = new Float32Array(_light.simulation_matrix[0]);
            var initMatrix = new THREE.Matrix4();
            initMatrix.elements = _element;
            _Light.applyMatrix(initMatrix);

        // case "MoreLights" ....

        }
        this.lights.add(_Light);

    }
    this.scene.add(this.lights);
};

Canvas.prototype.addFrames = function(){
    for(var key in JSONObj.frames){
        var _frame = JSONObj.frames[key];
        console.log(_frame);
        console.log(_frame.shape);
        switch(_frame.shape.type){

        case "Cylinder":
            var _color = new THREE.Color().setRGB(_frame.shape.color[0],
                           _frame.shape.color[1], _frame.shape.color[2])

            var _material = new THREE.MeshLambertMaterial({
                                    color:        _frame.shape.color,
                                    wireframe:          true,
                                    wireframeLinewidth: 0.1,
                                    opacity: 0.5
                                                     })

            var _geometry = new THREE.CylinderGeometry(
                                      _frame.shape.radius,
                                      _frame.shape.radius,
                                      _frame.shape.height,
                                      50,50);
            var _mesh = new THREE.Mesh(_geometry, _material);

            var _element = new Float32Array(_frame.simulation_matrix[0]);
            var initMatrix = new THREE.Matrix4();
            initMatrix.elements = _element;
            _mesh.matrix.identity();
            _mesh.applyMatrix(initMatrix);
            // case for more shapes ...

        }
        this.frames.add(_mesh);

    }
    this.scene.add(this.frames);
    for(var key in this.frames.children)
    {
    console.log("Auto Update activated");
    this.frames.children[key].matrixAutoUpdate = false;

    }

};
<commit_msg>Added a point SPhere to represent each point light<commit_after>Canvas.prototype.addControls = function(){
    primaryControls.update();
    renderer.render(scene, primaryCamera);
    this.controlsID = requestAnimationFrame(Canvas.prototype.addControls);
};

Canvas.prototype.resetControls = function() {
primaryControls.reset();

};

Canvas.prototype.addCameras = function() {
    for(var key in JSONObj.cameras){
        var _camera = JSONObj.cameras[key];

        switch(_camera.type){

        case "PerspectiveCamera":
            var _Camera = new THREE.PerspectiveCamera(
                                       _camera.fov, this.aspect_ratio,
                                         _camera.near, _camera.far );
            var _element = new Float32Array(_camera.simulation_matrix[0]);
            var initMatrix = new THREE.Matrix4();
            initMatrix.elements = _element;
            _Camera.applyMatrix(initMatrix);
        case "OrthoGraphicCamera":
            //TODO

        }
        console.log(_Camera);
        this.cameras.add(_Camera);

    }
    this.scene.add(this.cameras);
};

Canvas.prototype.addLights = function() {
    for(var key in JSONObj.lights){
        var _light = JSONObj.lights[key];

        switch(_light.type){

        case "PointLight":
            var color = new THREE.Color().setRGB(_light.color[0],
                                    _light.color[1], _light.color[2])
            var _Light = new THREE.PointLight(color);
            var _element = new Float32Array(_light.simulation_matrix[0]);
            var initMatrix = new THREE.Matrix4();
            initMatrix.elements = _element;
            _Light.applyMatrix(initMatrix);

            // For point of light ...
            var _geom = new THREE.SphereGeometry(1,100,100);
            var _material = new THREE.MeshBasicMaterial(color);
            var _lightPoint = new THREE.Mesh(_geom, _material);
            _lightPoint.position = _Light.position

        // case "MoreLights" ....

        }

        this.lights.add(_Light);
        this.lights.add(_lightPoint);

    }
    this.scene.add(this.lights);
};

Canvas.prototype.addFrames = function(){
    for(var key in JSONObj.frames){
        var _frame = JSONObj.frames[key];
        console.log(_frame);
        console.log(_frame.shape);
        switch(_frame.shape.type){

        case "Cylinder":
            var _color = new THREE.Color().setRGB(_frame.shape.color[0],
                           _frame.shape.color[1], _frame.shape.color[2])

            var _material = new THREE.MeshLambertMaterial({
                                    color:        _frame.shape.color,
                                    wireframe:          true,
                                    wireframeLinewidth: 0.1,
                                    opacity: 0.5
                                                     })

            var _geometry = new THREE.CylinderGeometry(
                                      _frame.shape.radius,
                                      _frame.shape.radius,
                                      _frame.shape.height,
                                      50,50);
            var _mesh = new THREE.Mesh(_geometry, _material);

            var _element = new Float32Array(_frame.simulation_matrix[0]);
            var initMatrix = new THREE.Matrix4();
            initMatrix.elements = _element;
            _mesh.matrix.identity();
            _mesh.applyMatrix(initMatrix);
            // case for more shapes ...

        }
        this.frames.add(_mesh);

    }
    this.scene.add(this.frames);
    for(var key in this.frames.children)
    {
    console.log("Auto Update activated");
    this.frames.children[key].matrixAutoUpdate = false;

    }

};
<|endoftext|>


<commit_before>/* eslint-disable no-use-before-define */
import {
  isCompositeComponent,
  getComponentDisplayName,
  isLazyType,
  isMemoType,
  isForwardType,
  isContextType,
} from './internal/reactUtils'
import { increment as incrementGeneration } from './global/generation'
import {
  updateProxyById,
  resetProxies,
  getProxyById,
  isTypeBlacklisted,
  registerComponent,
  updateFunctionProxyById,
} from './reconciler/proxies'
import configuration from './configuration'
import logger from './logger'

import { preactAdapter } from './adapters/preact'
import {
  updateContext,
  updateForward,
  updateLazy,
  updateMemo,
} from './reconciler/fiberUpdater'
import { resolveType } from './reconciler/resolver'
import { hotComponentCompare } from './reconciler/componentComparator'

const forceSimpleSFC = { proxy: { pureSFC: true } }

const reactHotLoader = {
  IS_REACT_MERGE_ENABLED: false,
  register(type, uniqueLocalName, fileName, options = {}) {
    const id = `${fileName}#${uniqueLocalName}`

    if (
      isCompositeComponent(type) &&
      typeof uniqueLocalName === 'string' &&
      uniqueLocalName &&
      typeof fileName === 'string' &&
      fileName
    ) {
      const proxy = getProxyById(id)

      if (proxy && proxy.getCurrent() !== type) {
        // component got replaced. Need to reconcile
        incrementGeneration()

        if (!reactHotLoader.IS_REACT_MERGE_ENABLED) {
          if (
            isTypeBlacklisted(type) ||
            isTypeBlacklisted(proxy.getCurrent())
          ) {
            logger.error(
              'React-hot-loader: Cold component',
              uniqueLocalName,
              'at',
              fileName,
              'has been updated',
            )
          }
        }
      }

      if (configuration.onComponentRegister) {
        configuration.onComponentRegister(type, uniqueLocalName, fileName)
      }
      if (configuration.onComponentCreate) {
        configuration.onComponentCreate(type, getComponentDisplayName(type))
      }

      registerComponent(updateProxyById(id, type, options).get(), 2)
      registerComponent(type)
    }
    if (isContextType({ type })) {
      updateFunctionProxyById(id, type, updateContext)
      updateFunctionProxyById(`${id}:provider`, type.Provider, updateContext)
      incrementGeneration()
    }
    if (isLazyType({ type })) {
      updateFunctionProxyById(id, type, updateLazy)
      incrementGeneration()
    }
    if (isForwardType({ type })) {
      updateFunctionProxyById(id, type, updateForward)
      incrementGeneration()
    }
    if (isMemoType({ type })) {
      reactHotLoader.register(
        type.type,
        `${uniqueLocalName}:memo`,
        fileName,
        forceSimpleSFC,
      )
      updateFunctionProxyById(id, type, updateMemo)
      incrementGeneration()
    }
  },

  reset() {
    resetProxies()
  },

  preact(instance) {
    preactAdapter(instance, resolveType)
  },

  resolveType(type) {
    return resolveType(type)
  },

  patch(React, ReactDOM) {
    /* eslint-disable no-console */
    if (ReactDOM && ReactDOM.setHotElementComparator) {
      ReactDOM.setHotElementComparator(hotComponentCompare)
      configuration.disableHotRenderer =
        configuration.disableHotRendererWhenInjected

      configuration.ignoreSFC = configuration.ignoreSFCWhenInjected

      reactHotLoader.IS_REACT_MERGE_ENABLED = true
    } else {
      // Actually everything works...
      console.warn(
        'React-Hot-Loader: react-🔥-dom patch is not detected. React 16.6+ features may not work.',
      )
    }
    /* eslint-enable */
    if (!React.createElement.isPatchedByReactHotLoader) {
      const originalCreateElement = React.createElement
      // Trick React into rendering a proxy so that
      // its state is preserved when the class changes.
      // This will update the proxy if it's for a known type.
      React.createElement = (type, ...args) =>
        originalCreateElement(resolveType(type), ...args)
      React.createElement.isPatchedByReactHotLoader = true
    }

    if (!React.cloneElement.isPatchedByReactHotLoader) {
      const originalCloneElement = React.cloneElement

      React.cloneElement = (element, ...args) => {
        const newType = element.type && resolveType(element.type)
        if (newType && newType !== element.type) {
          return originalCloneElement(
            {
              ...element,
              type: newType,
            },
            ...args,
          )
        }
        return originalCloneElement(element, ...args)
      }

      React.cloneElement.isPatchedByReactHotLoader = true
    }

    if (!React.createFactory.isPatchedByReactHotLoader) {
      // Patch React.createFactory to use patched createElement
      // because the original implementation uses the internal,
      // unpatched ReactElement.createElement
      React.createFactory = type => {
        const factory = React.createElement.bind(null, type)
        factory.type = type
        return factory
      }
      React.createFactory.isPatchedByReactHotLoader = true
    }

    if (!React.Children.only.isPatchedByReactHotLoader) {
      const originalChildrenOnly = React.Children.only
      // Use the same trick as React.createElement
      React.Children.only = children =>
        originalChildrenOnly({ ...children, type: resolveType(children.type) })
      React.Children.only.isPatchedByReactHotLoader = true
    }

    // reactHotLoader.reset()
  },
}

export default reactHotLoader
<commit_msg>fix: destructed Context.Provider breaking registrations. fixes #1184<commit_after>/* eslint-disable no-use-before-define */
import {
  isCompositeComponent,
  getComponentDisplayName,
  isLazyType,
  isMemoType,
  isForwardType,
  isContextType,
} from './internal/reactUtils'
import { increment as incrementGeneration } from './global/generation'
import {
  updateProxyById,
  resetProxies,
  getProxyById,
  isTypeBlacklisted,
  registerComponent,
  updateFunctionProxyById,
} from './reconciler/proxies'
import configuration from './configuration'
import logger from './logger'

import { preactAdapter } from './adapters/preact'
import {
  updateContext,
  updateForward,
  updateLazy,
  updateMemo,
} from './reconciler/fiberUpdater'
import { resolveType } from './reconciler/resolver'
import { hotComponentCompare } from './reconciler/componentComparator'

const forceSimpleSFC = { proxy: { pureSFC: true } }

const reactHotLoader = {
  IS_REACT_MERGE_ENABLED: false,
  register(type, uniqueLocalName, fileName, options = {}) {
    const id = `${fileName}#${uniqueLocalName}`

    if (
      isCompositeComponent(type) &&
      typeof uniqueLocalName === 'string' &&
      uniqueLocalName &&
      typeof fileName === 'string' &&
      fileName
    ) {
      const proxy = getProxyById(id)

      if (proxy && proxy.getCurrent() !== type) {
        // component got replaced. Need to reconcile
        incrementGeneration()

        if (!reactHotLoader.IS_REACT_MERGE_ENABLED) {
          if (
            isTypeBlacklisted(type) ||
            isTypeBlacklisted(proxy.getCurrent())
          ) {
            logger.error(
              'React-hot-loader: Cold component',
              uniqueLocalName,
              'at',
              fileName,
              'has been updated',
            )
          }
        }
      }

      if (configuration.onComponentRegister) {
        configuration.onComponentRegister(type, uniqueLocalName, fileName)
      }
      if (configuration.onComponentCreate) {
        configuration.onComponentCreate(type, getComponentDisplayName(type))
      }

      registerComponent(updateProxyById(id, type, options).get(), 2)
      registerComponent(type)
    }
    if (isContextType({ type })) {
      updateFunctionProxyById(id, type, updateContext)
      if (type.Provider) {
        updateFunctionProxyById(`${id}:provider`, type.Provider, updateContext)
      }
      incrementGeneration()
    }
    if (isLazyType({ type })) {
      updateFunctionProxyById(id, type, updateLazy)
      incrementGeneration()
    }
    if (isForwardType({ type })) {
      updateFunctionProxyById(id, type, updateForward)
      incrementGeneration()
    }
    if (isMemoType({ type })) {
      reactHotLoader.register(
        type.type,
        `${uniqueLocalName}:memo`,
        fileName,
        forceSimpleSFC,
      )
      updateFunctionProxyById(id, type, updateMemo)
      incrementGeneration()
    }
  },

  reset() {
    resetProxies()
  },

  preact(instance) {
    preactAdapter(instance, resolveType)
  },

  resolveType(type) {
    return resolveType(type)
  },

  patch(React, ReactDOM) {
    /* eslint-disable no-console */
    if (ReactDOM && ReactDOM.setHotElementComparator) {
      ReactDOM.setHotElementComparator(hotComponentCompare)
      configuration.disableHotRenderer =
        configuration.disableHotRendererWhenInjected

      configuration.ignoreSFC = configuration.ignoreSFCWhenInjected

      reactHotLoader.IS_REACT_MERGE_ENABLED = true
    } else {
      // Actually everything works...
      console.warn(
        'React-Hot-Loader: react-🔥-dom patch is not detected. React 16.6+ features may not work.',
      )
    }
    /* eslint-enable */
    if (!React.createElement.isPatchedByReactHotLoader) {
      const originalCreateElement = React.createElement
      // Trick React into rendering a proxy so that
      // its state is preserved when the class changes.
      // This will update the proxy if it's for a known type.
      React.createElement = (type, ...args) =>
        originalCreateElement(resolveType(type), ...args)
      React.createElement.isPatchedByReactHotLoader = true
    }

    if (!React.cloneElement.isPatchedByReactHotLoader) {
      const originalCloneElement = React.cloneElement

      React.cloneElement = (element, ...args) => {
        const newType = element.type && resolveType(element.type)
        if (newType && newType !== element.type) {
          return originalCloneElement(
            {
              ...element,
              type: newType,
            },
            ...args,
          )
        }
        return originalCloneElement(element, ...args)
      }

      React.cloneElement.isPatchedByReactHotLoader = true
    }

    if (!React.createFactory.isPatchedByReactHotLoader) {
      // Patch React.createFactory to use patched createElement
      // because the original implementation uses the internal,
      // unpatched ReactElement.createElement
      React.createFactory = type => {
        const factory = React.createElement.bind(null, type)
        factory.type = type
        return factory
      }
      React.createFactory.isPatchedByReactHotLoader = true
    }

    if (!React.Children.only.isPatchedByReactHotLoader) {
      const originalChildrenOnly = React.Children.only
      // Use the same trick as React.createElement
      React.Children.only = children =>
        originalChildrenOnly({ ...children, type: resolveType(children.type) })
      React.Children.only.isPatchedByReactHotLoader = true
    }

    // reactHotLoader.reset()
  },
}

export default reactHotLoader
<|endoftext|>


<commit_before>import { createSelector } from 'reselect'

import { getDisplayName } from '../actions/friendsActions'

import { getNames } from '../selectors/names'

export const loadNames = createSelector(
  [
    getNames
  ],
  names => {
    const shouldLoad = names.some(name => {
      if (name.willHaveDisplayName()) {
        return false
      } else {
        return true
      }
    })

    if (shouldLoad) {
      return getDisplayName()
    } else {
      return null
    }
  }
)
<commit_msg>refactor(names): refactor names reactor<commit_after>import { createSelector } from 'reselect'

import { getDisplayName } from '../actions/friendsActions'

import { getNames } from '../selectors/names'

export const loadNames = createSelector(
  [
    getNames
  ],
  names => names.some(name => !name.willHaveDisplayName())
    ? getDisplayName()
    : null
)
<|endoftext|>


<commit_before>var pluralize = require('pluralize');
var q = require('q');
var CollectionService = require('./collection-service.js');
var CaseConverter = require('./case-converter.js');
var caseConverter = new CaseConverter();

/**
 * A tool for interacting with data records
 * @class RecordService
 * @param {Object} provider the datastore provider which handles reads and writes
 * @param {string} type the type of collection to create
 * @param {string} id (optional) the id of the record
 * @returns {Record}
 */
var RecordService = function(provider, type, id) {

  /**
   * Deletes the record
   * @function delete
   * @memberof RecordService
   * @instance
   * @returns {Promise} resolves with no data
   */
  this.delete = deleteRecord;

  /**
   * Returns this record's locally stored data
   * @function getData
   * @memberOf RecordService
   * @instance
   * @return {object}
   */
  this.getData = getData;

  /**
   * Returns this record's ID
   * @function getID
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getID = getID;

  /**
   * Returns this record's type
   * @function getType
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getType = getType;

  /**
   * Associates related data
   *
   * Deep joins can be performed by passing
   * multiple config objects to this function
   * @function join
   * @memberof RecordService
   * @instance
   * @param {...(Object|Array)} config a map of properties to join on
   * @param {string} config.type the record type to join by
   * @param {boolean} config.many (optional) join with hasMany relation
   * @param {boolean} config.as (optional) join with named relation
   * @returns {Promise} promise resolves with the combined data object
   */
  this.join = join;

  /**
   * Reads the record's data from the datastore
   * @function load
   * @memberof RecordService
   * @instance
   * @returns {Promise} resolves with the record's data
   */
  this.load = load;

  /**
   * Gives this record the ability to link and traverse many related objects
   *
   * After calling this, the record will have addType(record) and
   * getTypes() methods. Example: Calling person.relateToMany('Device') will
   * expose addDevice(device) and getDevices() methods on the person record
   *
   * Note: the getTypes method is deprecated, please prefer the join method
   * @function relateToMany
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has many of
   * @param {string} as (optional) the name of the relation
   */
  this.relateToMany = relateToMany;

  /**
   * Gives this record the ability to link and traverse one related object
   *
   * After calling this, the record will have setType(record) and
   * getType() methods. Example: Calling person.relateToOne('Car') will
   * expose setCar(car) and getCar() methods on the person record
   *
   * Note: the getType method is deprecated, please prefer the join method
   * @function relateToOne
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has one of
   * @param {string} as (optional) the name of the relation
   */
  this.relateToOne = relateToOne;

  /**
   * Stores this record's data in the datastore
   *
   * Sets lastUpdatedAt on every save and
   * createdAt when saving a new record.
   * @function save
   * @memberof RecordService
   * @instance
   * @returns {Promise}
   */
  this.save = save;

  /**
   * Changes the record's data without saving to the datastore
   *
   * Useful for setting data on new records before adding relations
   * @function setData
   * @memberof RecordService
   * @instance
   * @param {Object} data the record's new data
   */
  this.setData = setData;

  /**
   * Syncs the record's data from the datastore
   * @function sync
   * @memberof RecordService
   * @instance
   * @param {Function} onDataChanged the callback that receives updates to the record's data
   * @returns {Promise} resolves with the record's data
   */
  this.sync = sync;

  /**
   * Removes the record's sync listener
   * @function unsync
   * @memberof RecordService
   * @instance
   */
  this.unsync = unsync;

  /**
   * Overwrite the record's data and save in the datastore
   * @function update
   * @memberof RecordService
   * @instance
   * @param {Object} data the record's new data
   * @returns {Promise}
   */
  this.update = update;

  if (!provider) {
    throw new Error('Provider required');
  }
  if (!type) {
    throw new Error('Type required');
  }
  var _provider = provider;
  var _type = caseConverter.toSnakeCase(type);
  var _id = id;
  var _data = {};

  var deletedRecordMessage = 'The record has been deleted';

  function getType() {
    return _type;
  }

  function getID() {
    return _id;
  }

  function getData() {
    return _data;
  }

  function setData(data) {
    var _record = this;
    if (!data) {
      return q.reject(new Error('Data required'));
    }
    var createdAt = _data.createdAt;
    _data = data;
    _data.createdAt = createdAt;
    return _record;
  };

  function save() {
    var record = this;
    if (_data._id) {
      delete _data._id
    }
    _data.lastUpdatedAt = new Date();
    var dataKey;
    for (dataKey in _data) {
      if (typeof _data[dataKey] == 'undefined') {
        delete _data[dataKey];
      }
    }
    return setCreatedAtOnData().then(function() {
      return _provider.save(pluralize(caseConverter.toCamelCase(_type)), _id, cloneProperties(_data))
        .then(function(id) {
          _id = id;
          return record;
        });
    });
  };

  function setCreatedAtOnData() {
    if (_id) {
      return _provider.load(pluralize(caseConverter.toCamelCase(_type)), _id)
        .then(function(data) {
          if (!data) {
            _data.createdAt = new Date();
          } else if (data.createdAt) {
            _data.createdAt = data.createdAt;
          }
        }, function(err) {
          console.log(err);
          if (!_data.createdAt) {
            _data.createdAt = new Date();
          }
        });
    } else {
      _data.createdAt = new Date();
      return q.resolve();
    }
  }

  function update(data) {
    if (!data) {
      return q.reject(new Error('Data required'));
    }
    var createdAt = _data.createdAt;
    _data = data;
    _data.createdAt = createdAt;
    return this.save();
  };

  function load() {
    var deferred = q.defer();
    var _record = this;
    if (!_id) {
      deferred.reject(new Error('Cannot load a record without an id'));
    }
    _provider.load(pluralize(caseConverter.toCamelCase(_type)), _id)
      .then(function(data) {
        if (!data) {
          deferred.reject(new Error('Specified record does not exist remotely'));
          return;
        }
        if (data.deletedAt) {
          deferred.reject(new Error(deletedRecordMessage));
          return;
        }
        _data = data;
        _data._id = _record.getID();
        deferred.resolve(_data);
      }, function(err) {
        deferred.reject(err);
      });
    return deferred.promise;
  };

  function deleteRecord() {
    var deferred = q.defer();
    this.load().then(function(data) {
      _data.deletedAt = new Date();
      save().then(function() {
        deferred.resolve();
      }, function(err) {
        deferred.reject(err);
      });

    }, function(err) {
      this.reject(err);
    });
    return deferred.promise;
  }

  function sync(onDataChanged) {
    if (!_id) {
      return q.reject(new Error('Cannot sync a record without an id'));
    }
    return _provider.sync(pluralize(caseConverter.toCamelCase(_type)), _id, function(data) {
      _data = data;
      onDataChanged(data);
    });
  };

  function unsync() {
    _provider.unsync(pluralize(caseConverter.toCamelCase(_type)), _id);
  }

  function relateToOne(type, as) {
    var _record = this;
    if (as) {
      this['get' + caseConverter.toSnakeCase(as)] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefer the join method for fetching related data');
        }
        var id = _data[caseConverter.toCamelCase(as)];
        if (!id) {
          return;
        }
        var record = new RecordService(_provider, type, id);
        return record;
      };
      this['set' + caseConverter.toSnakeCase(as)] = function(record) {
        if (record.getType() !== type) {
          throw new Error('Invalid type. Expecting "' + type + '", but saw "' + record.getType() + '"');
        }
        var id = record.getID();
        _data[caseConverter.toCamelCase(as)] = id;
        return _record;
      };
    } else {
      this['get' + caseConverter.toSnakeCase(type)] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefect the join method for fetching related data');
        }
        var id = _data[caseConverter.toCamelCase(type) + '_id'];
        if (!id) {
          return;
        }
        var record = new RecordService(_provider, type, id);
        return record;
      };
      this['set' + caseConverter.toSnakeCase(type)] = function(record) {
        var id = record.getID();
        _data[caseConverter.toCamelCase(record.getType()) + '_id'] = id;
        return _record;
      };
    }
  };

  function relateToMany(type, as) {
    var _record = this;
    var _collection;
    if (as) {
      this['get' + pluralize(caseConverter.toSnakeCase(as))] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefer the join method for fetching related data');
        }
        _collection = new CollectionService(_provider, type);
        if (_data[pluralize(caseConverter.toCamelCase(as))]) {
          var ids = Object.keys(_data[pluralize(caseConverter.toCamelCase(as))]);
          for (var i = 0; i < ids.length; i++) {
            var record = new RecordService(_provider, type, ids[i]);
            _collection.addRecord(record);
          }
        }
        return _collection;
      };
      this['add' + caseConverter.toSnakeCase(as)] = function(record) {
        if (record.getType() !== type) {
          throw new Error('Invalid type. Expecting "' + type + '", but saw "' + record.getType() + '"');
        }
        var id = record.getID();
        var ids = _data[pluralize(caseConverter.toCamelCase(as))];
        if (!ids) {
          _data[pluralize(caseConverter.toCamelCase(as))] = {};
        }
        _data[pluralize(caseConverter.toCamelCase(as))][id] = true;
        return _record;
      };
      this['remove' + caseConverter.toSnakeCase(as)] = function(record) {
        if (record.getType() !== type) {
          throw new Error('Invalid type. Expecting "' + type + '", but saw "' + record.getType() + '"');
        }
        var id = record.getID();
        if (_data[pluralize(caseConverter.toCamelCase(as))]) {
          delete _data[pluralize(caseConverter.toCamelCase(as))][id];
        }
        return _record;
      };
    } else {
      this['get' + pluralize(caseConverter.toSnakeCase(type))] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefer the join method for fetching related data');
        }
        _collection = new CollectionService(_provider, type);
        if (_data[caseConverter.toCamelCase(type) + '_ids']) {
          var ids = Object.keys(_data[caseConverter.toCamelCase(type) + '_ids']);
          for (var i = 0; i < ids.length; i++) {
            var record = new RecordService(_provider, type, ids[i]);
            _collection.addRecord(record);
          }
        }
        return _collection;
      };
      this['add' + caseConverter.toSnakeCase(type)] = function(record) {
        var id = record.getID();
        var ids = _data[caseConverter.toCamelCase(record.getType()) + '_ids'];
        if (!ids) {
          _data[caseConverter.toCamelCase(record.getType()) + '_ids'] = {};
        }
        _data[caseConverter.toCamelCase(record.getType()) + '_ids'][id] = true;
        return _record;
      };
      this['remove' + caseConverter.toSnakeCase(type)] = function(record) {
        var id = record.getID();
        delete _data[caseConverter.toCamelCase(record.getType()) + '_ids'][id];
        return _record;
      };
    }
  };

  function join() {
    var _record = this;
    var args = [].slice.call(arguments);
    var deferred = q.defer();
    var joinConfigs = args.shift();
    if (!Array.isArray(joinConfigs) && joinConfigs) {
      var array = [];
      array.push(joinConfigs);
      joinConfigs = array;
    }
    _record.load()
      .then(function(data) {
        var promises = [];
        if (joinConfigs) {
          for (var i = 0; i < joinConfigs.length; i += 1) {
            (function(type, many, as) {
              var relation;
              if (many) {
                if (as) {
                  _record.relateToMany(type, as);
                  relation = eval('_record.get' + pluralize(caseConverter.toSnakeCase(as)) + '(true)');
                } else {
                  _record.relateToMany(type);
                  relation = eval('_record.get' + pluralize(caseConverter.toSnakeCase(type)) + '(true)');
                }
              } else {
                if (as) {
                  _record.relateToOne(type, as);
                  relation = eval('_record.get' + caseConverter.toSnakeCase(as) + '(true)');
                } else {
                  _record.relateToOne(type);
                  relation = eval('_record.get' + caseConverter.toSnakeCase(type) + '(true)');
                }
              }
              if (relation) {
                var promise;
                if (args.length === 0) {
                  var loadDeferred = q.defer();
                  relation.load().then(function(data) {
                    loadDeferred.resolve(data);
                  }, function(err) {
                    if (err.message === deletedRecordMessage) {
                      loadDeferred.resolve();
                    } else {
                      loadDeferred.reject(err);
                    }
                  });
                  promise = loadDeferred.promise;
                } else {
                  promise = relation.join.apply(relation, args);
                }
                promise
                  .then(function(relatedData) {
                    if (relatedData) {
                      if (as) {
                        var key = many ? pluralize(caseConverter.toCamelCase(as)) : caseConverter.toCamelCase(as);
                      } else {
                        var key = many ? pluralize(caseConverter.toCamelCase(type)) : caseConverter.toCamelCase(type);
                      }
                      data[key] = relatedData;
                    }
                  });
                promises.push(promise);
              }
            })(joinConfigs[i].type, joinConfigs[i].many, joinConfigs[i].as);
          }
        }
        return q.all(promises)
          .then(function() {
            return data;
          }, function(err) {
            deferred.reject(err);
          });
      }, function(err) {
        deferred.reject(err);
      })
      .then(function(joinedData) {
        if (!joinedData) {
          deferred.reject();
        }
        deferred.resolve(joinedData);
      });
    return deferred.promise;
  };
};

function isDate(object) {
  return Object.prototype.toString.call(object) === '[object Date]'
}

function cloneProperties(obj) {
  if (obj == null || typeof(obj) != 'object' || isDate(obj)) {
    return obj;
  }
  var temp = new obj.constructor();
  for (var key in obj) {
    temp[key] = cloneProperties(obj[key]);
  }
  return temp;
}

module.exports = RecordService;<commit_msg>fix(StorageService): add type and id to doesn't exist error<commit_after>var pluralize = require('pluralize');
var q = require('q');
var CollectionService = require('./collection-service.js');
var CaseConverter = require('./case-converter.js');
var caseConverter = new CaseConverter();

/**
 * A tool for interacting with data records
 * @class RecordService
 * @param {Object} provider the datastore provider which handles reads and writes
 * @param {string} type the type of collection to create
 * @param {string} id (optional) the id of the record
 * @returns {Record}
 */
var RecordService = function(provider, type, id) {

  /**
   * Deletes the record
   * @function delete
   * @memberof RecordService
   * @instance
   * @returns {Promise} resolves with no data
   */
  this.delete = deleteRecord;

  /**
   * Returns this record's locally stored data
   * @function getData
   * @memberOf RecordService
   * @instance
   * @return {object}
   */
  this.getData = getData;

  /**
   * Returns this record's ID
   * @function getID
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getID = getID;

  /**
   * Returns this record's type
   * @function getType
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getType = getType;

  /**
   * Associates related data
   *
   * Deep joins can be performed by passing
   * multiple config objects to this function
   * @function join
   * @memberof RecordService
   * @instance
   * @param {...(Object|Array)} config a map of properties to join on
   * @param {string} config.type the record type to join by
   * @param {boolean} config.many (optional) join with hasMany relation
   * @param {boolean} config.as (optional) join with named relation
   * @returns {Promise} promise resolves with the combined data object
   */
  this.join = join;

  /**
   * Reads the record's data from the datastore
   * @function load
   * @memberof RecordService
   * @instance
   * @returns {Promise} resolves with the record's data
   */
  this.load = load;

  /**
   * Gives this record the ability to link and traverse many related objects
   *
   * After calling this, the record will have addType(record) and
   * getTypes() methods. Example: Calling person.relateToMany('Device') will
   * expose addDevice(device) and getDevices() methods on the person record
   *
   * Note: the getTypes method is deprecated, please prefer the join method
   * @function relateToMany
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has many of
   * @param {string} as (optional) the name of the relation
   */
  this.relateToMany = relateToMany;

  /**
   * Gives this record the ability to link and traverse one related object
   *
   * After calling this, the record will have setType(record) and
   * getType() methods. Example: Calling person.relateToOne('Car') will
   * expose setCar(car) and getCar() methods on the person record
   *
   * Note: the getType method is deprecated, please prefer the join method
   * @function relateToOne
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has one of
   * @param {string} as (optional) the name of the relation
   */
  this.relateToOne = relateToOne;

  /**
   * Stores this record's data in the datastore
   *
   * Sets lastUpdatedAt on every save and
   * createdAt when saving a new record.
   * @function save
   * @memberof RecordService
   * @instance
   * @returns {Promise}
   */
  this.save = save;

  /**
   * Changes the record's data without saving to the datastore
   *
   * Useful for setting data on new records before adding relations
   * @function setData
   * @memberof RecordService
   * @instance
   * @param {Object} data the record's new data
   */
  this.setData = setData;

  /**
   * Syncs the record's data from the datastore
   * @function sync
   * @memberof RecordService
   * @instance
   * @param {Function} onDataChanged the callback that receives updates to the record's data
   * @returns {Promise} resolves with the record's data
   */
  this.sync = sync;

  /**
   * Removes the record's sync listener
   * @function unsync
   * @memberof RecordService
   * @instance
   */
  this.unsync = unsync;

  /**
   * Overwrite the record's data and save in the datastore
   * @function update
   * @memberof RecordService
   * @instance
   * @param {Object} data the record's new data
   * @returns {Promise}
   */
  this.update = update;

  if (!provider) {
    throw new Error('Provider required');
  }
  if (!type) {
    throw new Error('Type required');
  }
  var _provider = provider;
  var _type = caseConverter.toSnakeCase(type);
  var _id = id;
  var _data = {};

  var deletedRecordMessage = 'The record has been deleted';

  function getType() {
    return _type;
  }

  function getID() {
    return _id;
  }

  function getData() {
    return _data;
  }

  function setData(data) {
    var _record = this;
    if (!data) {
      return q.reject(new Error('Data required'));
    }
    var createdAt = _data.createdAt;
    _data = data;
    _data.createdAt = createdAt;
    return _record;
  };

  function save() {
    var record = this;
    if (_data._id) {
      delete _data._id
    }
    _data.lastUpdatedAt = new Date();
    var dataKey;
    for (dataKey in _data) {
      if (typeof _data[dataKey] == 'undefined') {
        delete _data[dataKey];
      }
    }
    return setCreatedAtOnData().then(function() {
      return _provider.save(pluralize(caseConverter.toCamelCase(_type)), _id, cloneProperties(_data))
        .then(function(id) {
          _id = id;
          return record;
        });
    });
  };

  function setCreatedAtOnData() {
    if (_id) {
      return _provider.load(pluralize(caseConverter.toCamelCase(_type)), _id)
        .then(function(data) {
          if (!data) {
            _data.createdAt = new Date();
          } else if (data.createdAt) {
            _data.createdAt = data.createdAt;
          }
        }, function(err) {
          console.log(err);
          if (!_data.createdAt) {
            _data.createdAt = new Date();
          }
        });
    } else {
      _data.createdAt = new Date();
      return q.resolve();
    }
  }

  function update(data) {
    if (!data) {
      return q.reject(new Error('Data required'));
    }
    var createdAt = _data.createdAt;
    _data = data;
    _data.createdAt = createdAt;
    return this.save();
  };

  function load() {
    var deferred = q.defer();
    var _record = this;
    if (!_id) {
      deferred.reject(new Error('Cannot load a record without an id'));
    }
    _provider.load(pluralize(caseConverter.toCamelCase(_type)), _id)
      .then(function(data) {
        if (!data) {
          deferred.reject(new Error('Specified record does not exist remotely: ' + _type + ' ' + _id));
          return;
        }
        if (data.deletedAt) {
          deferred.reject(new Error(deletedRecordMessage));
          return;
        }
        _data = data;
        _data._id = _record.getID();
        deferred.resolve(_data);
      }, function(err) {
        deferred.reject(err);
      });
    return deferred.promise;
  };

  function deleteRecord() {
    var deferred = q.defer();
    this.load().then(function(data) {
      _data.deletedAt = new Date();
      save().then(function() {
        deferred.resolve();
      }, function(err) {
        deferred.reject(err);
      });

    }, function(err) {
      this.reject(err);
    });
    return deferred.promise;
  }

  function sync(onDataChanged) {
    if (!_id) {
      return q.reject(new Error('Cannot sync a record without an id'));
    }
    return _provider.sync(pluralize(caseConverter.toCamelCase(_type)), _id, function(data) {
      _data = data;
      onDataChanged(data);
    });
  };

  function unsync() {
    _provider.unsync(pluralize(caseConverter.toCamelCase(_type)), _id);
  }

  function relateToOne(type, as) {
    var _record = this;
    if (as) {
      this['get' + caseConverter.toSnakeCase(as)] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefer the join method for fetching related data');
        }
        var id = _data[caseConverter.toCamelCase(as)];
        if (!id) {
          return;
        }
        var record = new RecordService(_provider, type, id);
        return record;
      };
      this['set' + caseConverter.toSnakeCase(as)] = function(record) {
        if (record.getType() !== type) {
          throw new Error('Invalid type. Expecting "' + type + '", but saw "' + record.getType() + '"');
        }
        var id = record.getID();
        _data[caseConverter.toCamelCase(as)] = id;
        return _record;
      };
    } else {
      this['get' + caseConverter.toSnakeCase(type)] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefect the join method for fetching related data');
        }
        var id = _data[caseConverter.toCamelCase(type) + '_id'];
        if (!id) {
          return;
        }
        var record = new RecordService(_provider, type, id);
        return record;
      };
      this['set' + caseConverter.toSnakeCase(type)] = function(record) {
        var id = record.getID();
        _data[caseConverter.toCamelCase(record.getType()) + '_id'] = id;
        return _record;
      };
    }
  };

  function relateToMany(type, as) {
    var _record = this;
    var _collection;
    if (as) {
      this['get' + pluralize(caseConverter.toSnakeCase(as))] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefer the join method for fetching related data');
        }
        _collection = new CollectionService(_provider, type);
        if (_data[pluralize(caseConverter.toCamelCase(as))]) {
          var ids = Object.keys(_data[pluralize(caseConverter.toCamelCase(as))]);
          for (var i = 0; i < ids.length; i++) {
            var record = new RecordService(_provider, type, ids[i]);
            _collection.addRecord(record);
          }
        }
        return _collection;
      };
      this['add' + caseConverter.toSnakeCase(as)] = function(record) {
        if (record.getType() !== type) {
          throw new Error('Invalid type. Expecting "' + type + '", but saw "' + record.getType() + '"');
        }
        var id = record.getID();
        var ids = _data[pluralize(caseConverter.toCamelCase(as))];
        if (!ids) {
          _data[pluralize(caseConverter.toCamelCase(as))] = {};
        }
        _data[pluralize(caseConverter.toCamelCase(as))][id] = true;
        return _record;
      };
      this['remove' + caseConverter.toSnakeCase(as)] = function(record) {
        if (record.getType() !== type) {
          throw new Error('Invalid type. Expecting "' + type + '", but saw "' + record.getType() + '"');
        }
        var id = record.getID();
        if (_data[pluralize(caseConverter.toCamelCase(as))]) {
          delete _data[pluralize(caseConverter.toCamelCase(as))][id];
        }
        return _record;
      };
    } else {
      this['get' + pluralize(caseConverter.toSnakeCase(type))] = function(isPrivate) {
        if (!isPrivate) {
          console.warn('DEPRECATED. Please prefer the join method for fetching related data');
        }
        _collection = new CollectionService(_provider, type);
        if (_data[caseConverter.toCamelCase(type) + '_ids']) {
          var ids = Object.keys(_data[caseConverter.toCamelCase(type) + '_ids']);
          for (var i = 0; i < ids.length; i++) {
            var record = new RecordService(_provider, type, ids[i]);
            _collection.addRecord(record);
          }
        }
        return _collection;
      };
      this['add' + caseConverter.toSnakeCase(type)] = function(record) {
        var id = record.getID();
        var ids = _data[caseConverter.toCamelCase(record.getType()) + '_ids'];
        if (!ids) {
          _data[caseConverter.toCamelCase(record.getType()) + '_ids'] = {};
        }
        _data[caseConverter.toCamelCase(record.getType()) + '_ids'][id] = true;
        return _record;
      };
      this['remove' + caseConverter.toSnakeCase(type)] = function(record) {
        var id = record.getID();
        delete _data[caseConverter.toCamelCase(record.getType()) + '_ids'][id];
        return _record;
      };
    }
  };

  function join() {
    var _record = this;
    var args = [].slice.call(arguments);
    var deferred = q.defer();
    var joinConfigs = args.shift();
    if (!Array.isArray(joinConfigs) && joinConfigs) {
      var array = [];
      array.push(joinConfigs);
      joinConfigs = array;
    }
    _record.load()
      .then(function(data) {
        var promises = [];
        if (joinConfigs) {
          for (var i = 0; i < joinConfigs.length; i += 1) {
            (function(type, many, as) {
              var relation;
              if (many) {
                if (as) {
                  _record.relateToMany(type, as);
                  relation = eval('_record.get' + pluralize(caseConverter.toSnakeCase(as)) + '(true)');
                } else {
                  _record.relateToMany(type);
                  relation = eval('_record.get' + pluralize(caseConverter.toSnakeCase(type)) + '(true)');
                }
              } else {
                if (as) {
                  _record.relateToOne(type, as);
                  relation = eval('_record.get' + caseConverter.toSnakeCase(as) + '(true)');
                } else {
                  _record.relateToOne(type);
                  relation = eval('_record.get' + caseConverter.toSnakeCase(type) + '(true)');
                }
              }
              if (relation) {
                var promise;
                if (args.length === 0) {
                  var loadDeferred = q.defer();
                  relation.load().then(function(data) {
                    loadDeferred.resolve(data);
                  }, function(err) {
                    if (err.message === deletedRecordMessage) {
                      loadDeferred.resolve();
                    } else {
                      loadDeferred.reject(err);
                    }
                  });
                  promise = loadDeferred.promise;
                } else {
                  promise = relation.join.apply(relation, args);
                }
                promise
                  .then(function(relatedData) {
                    if (relatedData) {
                      if (as) {
                        var key = many ? pluralize(caseConverter.toCamelCase(as)) : caseConverter.toCamelCase(as);
                      } else {
                        var key = many ? pluralize(caseConverter.toCamelCase(type)) : caseConverter.toCamelCase(type);
                      }
                      data[key] = relatedData;
                    }
                  });
                promises.push(promise);
              }
            })(joinConfigs[i].type, joinConfigs[i].many, joinConfigs[i].as);
          }
        }
        return q.all(promises)
          .then(function() {
            return data;
          }, function(err) {
            deferred.reject(err);
          });
      }, function(err) {
        deferred.reject(err);
      })
      .then(function(joinedData) {
        if (!joinedData) {
          deferred.reject();
        }
        deferred.resolve(joinedData);
      });
    return deferred.promise;
  };
};

function isDate(object) {
  return Object.prototype.toString.call(object) === '[object Date]'
}

function cloneProperties(obj) {
  if (obj == null || typeof(obj) != 'object' || isDate(obj)) {
    return obj;
  }
  var temp = new obj.constructor();
  for (var key in obj) {
    temp[key] = cloneProperties(obj[key]);
  }
  return temp;
}

module.exports = RecordService;
<|endoftext|>


<commit_before>var pluralize = require('pluralize');
var q = require('q');
var CollectionService = require('./collection-service.js');
function isDate (object) {
  return Object.prototype.toString.call(object) === '[object Date]'
}
function toSnakeCase (string) {
  var words = string.split(' ');
  var output = '';
  for (var i = 0; i < words.length; i++) {
    output = output + words[i].charAt(0).toUpperCase() + words[i].slice(1);
  }
  return output;
}
function toCamelCase (string) {
  var snakeCase = toSnakeCase(string);
  return snakeCase.charAt(0).toLowerCase() + snakeCase.slice(1);
}
function cloneProperties (obj) {
  if (obj == null || typeof(obj) != 'object' || isDate(obj)) { return obj; }
  var temp = new obj.constructor();
  for(var key in obj) {
    temp[key] = cloneProperties(obj[key]);
  }
  return temp;
}
/**
 * A tool for interacting with data records
 * @class RecordService
 * @param {Object} provider the datastore provider which handles reads and writes
 * @param {string} type the type of collection to create
 * @param {string} id (optional) the id of the record
 * @returns {Record}
 */
var RecordService = function (provider, type, id) {
  if (!provider) { throw new Error('Provider required'); }
  if (!type) { throw new Error('Type required'); }
  var _provider = provider;
  var _type = toSnakeCase(type);
  var _id = id;
  var _data = {};
  /**
   * Returns this record's type
   * @function getType
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getType = function () { return _type; }
  /**
   * Returns this record's type
   * @function getID
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getID = function () { return _id; }
  /**
   * Stores this record's data in the datastore
   *
   * Sets lastUpdatedAt on every save and
   * createdAt when saving a new record.
   * @function save
   * @memberof RecordService
   * @instance
   * @returns {Promise}
   */
  this.save = function () {
    if (!_id) { _data.createdAt = new Date(); }
    _data.lastUpdatedAt = new Date();
    return _provider.save(pluralize(toCamelCase(_type)), _id, cloneProperties(_data))
    .then(function (id) {
      _id = id;
    });
  };
  /**
   * Overwrite the record's data and save in the datastore
   * @function update
   * @memberof RecordService
   * @instance
   * @param {Object} data the record's new data
   * @returns {Promise}
   */
  this.update = function (data) {
    if (!data) { return q.reject(new Error('Data required')); }
    var createdAt = _data.createdAt;
    _data = data;
    _data.createdAt = createdAt;
    return this.save();
  };
  /**
   * Reads the record's data from the datastore
   * @function load
   * @memberof RecordService
   * @instance
   * @returns {Promise} resolves with the record's data
   */
  this.load = function () {
    if (!_id) { return q.reject(new Error('Cannot load a record without an id')); }
    return _provider.load(pluralize(toCamelCase(_type)), _id)
    .then(function (data) {
     return _data = data;
    });
  };
  /**
   * Syncs the record's data from the datastore
   * @function sync
   * @memberof RecordService
   * @instance
   * @param {Function} onDataChanged the callback that receives updates to the record's data
   * @returns {Promise} resolves with the record's data
   */
  this.sync = function (onDataChanged) {
    if (!_id) { return q.reject(new Error('Cannot sync a record without an id')); }
    return _provider.sync(pluralize(toCamelCase(_type)), _id, function (data) {
      _data = data;
      onDataChanged(data);
    });
  };
  /**
   * Removes the record's sync listener
   * @function unsync
   * @memberof RecordService
   * @instance
   */
  this.unsync = function () {
    _provider.unsync(pluralize(toCamelCase(_type)), _id);
  }
  /**
   * Gives this record the ability to link and traverse one related object
   *
   * After calling this, the record will have setType(record) and
   * getType() methods. Example: Calling person.relateToOne('Car') will
   * expose setCar(car) and getCar() methods on the person record
   * @function relateToOne
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has one of
   */
  this.relateToOne = function (type) {
    var service = this;
    this['get' + toSnakeCase(type)] = function () {
      var id = _data[toCamelCase(type) + '_id'];
      var record = new RecordService(_provider, type, id);
      return record;
    }
    this['set' + toSnakeCase(type)] = function (record) {
      var id = record.getID();
      _data[toCamelCase(record.getType()) + '_id'] = id;
      return service.save();
    }
  };
  /**
   * Gives this record the ability to link and traverse many related objects
   *
   * After calling this, the record will have addType(record) and
   * getTypes() methods. Example: Calling person.relateToMany('Device') will
   * expose addDevice(device) and getDevices() methods on the person record
   * @function relateToMany
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has many of
   */
  this.relateToMany = function (type) {
    var _service = this;
    var _collection = new CollectionService(_provider, type);
    this['get' + pluralize(toSnakeCase(type))] = function () {
      _collection = new CollectionService(_provider, type);
      var ids = _data[toCamelCase(type) + '_ids'];
      for (var i = 0; i < ids.length; i++) {
        var record = new RecordService(_provider, type, ids[i]);
        _collection.addRecord(record);
      }
      return _collection;
    }
    this['add' + toSnakeCase(type)] = function (record) {
      var id = record.getID();
      var ids = _data[toCamelCase(record.getType()) + '_ids'];
      if(!ids || !ids.length) {
        _data[toCamelCase(record.getType()) + '_ids'] = [];
      }
      _data[toCamelCase(record.getType()) + '_ids'].push(id);
      var record = new RecordService(_provider, type, id);
      _collection.addRecord(record);
      return _service.save();
    }
  };
};

module.exports = RecordService;
<commit_msg>refactor(RecordServie): prefer boolean keys to arrays<commit_after>var pluralize = require('pluralize');
var q = require('q');
var CollectionService = require('./collection-service.js');
function isDate (object) {
  return Object.prototype.toString.call(object) === '[object Date]'
}
function toSnakeCase (string) {
  var words = string.split(' ');
  var output = '';
  for (var i = 0; i < words.length; i++) {
    output = output + words[i].charAt(0).toUpperCase() + words[i].slice(1);
  }
  return output;
}
function toCamelCase (string) {
  var snakeCase = toSnakeCase(string);
  return snakeCase.charAt(0).toLowerCase() + snakeCase.slice(1);
}
function cloneProperties (obj) {
  if (obj == null || typeof(obj) != 'object' || isDate(obj)) { return obj; }
  var temp = new obj.constructor();
  for(var key in obj) {
    temp[key] = cloneProperties(obj[key]);
  }
  return temp;
}
/**
 * A tool for interacting with data records
 * @class RecordService
 * @param {Object} provider the datastore provider which handles reads and writes
 * @param {string} type the type of collection to create
 * @param {string} id (optional) the id of the record
 * @returns {Record}
 */
var RecordService = function (provider, type, id) {
  if (!provider) { throw new Error('Provider required'); }
  if (!type) { throw new Error('Type required'); }
  var _provider = provider;
  var _type = toSnakeCase(type);
  var _id = id;
  var _data = {};
  /**
   * Returns this record's type
   * @function getType
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getType = function () { return _type; }
  /**
   * Returns this record's type
   * @function getID
   * @memberof RecordService
   * @instance
   * @returns {string}
   */
  this.getID = function () { return _id; }
  /**
   * Stores this record's data in the datastore
   *
   * Sets lastUpdatedAt on every save and
   * createdAt when saving a new record.
   * @function save
   * @memberof RecordService
   * @instance
   * @returns {Promise}
   */
  this.save = function () {
    if (!_id) { _data.createdAt = new Date(); }
    _data.lastUpdatedAt = new Date();
    return _provider.save(pluralize(toCamelCase(_type)), _id, cloneProperties(_data))
    .then(function (id) {
      _id = id;
    });
  };
  /**
   * Overwrite the record's data and save in the datastore
   * @function update
   * @memberof RecordService
   * @instance
   * @param {Object} data the record's new data
   * @returns {Promise}
   */
  this.update = function (data) {
    if (!data) { return q.reject(new Error('Data required')); }
    var createdAt = _data.createdAt;
    _data = data;
    _data.createdAt = createdAt;
    return this.save();
  };
  /**
   * Reads the record's data from the datastore
   * @function load
   * @memberof RecordService
   * @instance
   * @returns {Promise} resolves with the record's data
   */
  this.load = function () {
    if (!_id) { return q.reject(new Error('Cannot load a record without an id')); }
    return _provider.load(pluralize(toCamelCase(_type)), _id)
    .then(function (data) {
     return _data = data;
    });
  };
  /**
   * Syncs the record's data from the datastore
   * @function sync
   * @memberof RecordService
   * @instance
   * @param {Function} onDataChanged the callback that receives updates to the record's data
   * @returns {Promise} resolves with the record's data
   */
  this.sync = function (onDataChanged) {
    if (!_id) { return q.reject(new Error('Cannot sync a record without an id')); }
    return _provider.sync(pluralize(toCamelCase(_type)), _id, function (data) {
      _data = data;
      onDataChanged(data);
    });
  };
  /**
   * Removes the record's sync listener
   * @function unsync
   * @memberof RecordService
   * @instance
   */
  this.unsync = function () {
    _provider.unsync(pluralize(toCamelCase(_type)), _id);
  }
  /**
   * Gives this record the ability to link and traverse one related object
   *
   * After calling this, the record will have setType(record) and
   * getType() methods. Example: Calling person.relateToOne('Car') will
   * expose setCar(car) and getCar() methods on the person record
   * @function relateToOne
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has one of
   */
  this.relateToOne = function (type) {
    var service = this;
    this['get' + toSnakeCase(type)] = function () {
      var id = _data[toCamelCase(type) + '_id'];
      var record = new RecordService(_provider, type, id);
      return record;
    }
    this['set' + toSnakeCase(type)] = function (record) {
      var id = record.getID();
      _data[toCamelCase(record.getType()) + '_id'] = id;
      return service.save();
    }
  };
  /**
   * Gives this record the ability to link and traverse many related objects
   *
   * After calling this, the record will have addType(record) and
   * getTypes() methods. Example: Calling person.relateToMany('Device') will
   * expose addDevice(device) and getDevices() methods on the person record
   * @function relateToMany
   * @memberof RecordService
   * @instance
   * @param {string} type the type of record this record has many of
   */
  this.relateToMany = function (type) {
    var _service = this;
    var _collection = new CollectionService(_provider, type);
    this['get' + pluralize(toSnakeCase(type))] = function () {
      _collection = new CollectionService(_provider, type);
      var ids = Object.keys(_data[toCamelCase(type) + '_ids']);
      for (var i = 0; i < ids.length; i++) {
        var record = new RecordService(_provider, type, ids[i]);
        _collection.addRecord(record);
      }
      return _collection;
    }
    this['add' + toSnakeCase(type)] = function (record) {
      var id = record.getID();
      var ids = _data[toCamelCase(record.getType()) + '_ids'];
      if(!ids) {
        _data[toCamelCase(record.getType()) + '_ids'] = {};
      }
      _data[toCamelCase(record.getType()) + '_ids'][id] = true;
      var record = new RecordService(_provider, type, id);
      _collection.addRecord(record);
      return _service.save();
    }
  };
};

module.exports = RecordService;
<|endoftext|>


<commit_before>const initialState = {
  name: null,
  message: null,
  displayMessage: true,
  email: null,
  history: []
}

export default function update (state = initialState, action) {
  switch (action.type) {
    case '@@router/LOCATION_CHANGE': {
      let history = state.history.slice(0, 10)
      history.push(action.payload.pathname)

      return Object.assign({}, state, {
        history: history
      })
    }

    case 'REQUEST_TOKEN_FROM_LOCAL_STORAGE':
      return Object.assign({}, state, {
        message: 'Looking for user info in local storage...',
        displayMessage: true,
        loading: true
      })
    case 'REQUEST_TOKEN_FROM_FACEBOOK':
      return Object.assign({}, state, {
        message: 'Logging in with facebook...',
        displayMessage: true,
        loading: true
      })
    case 'REQUEST_TOKEN_FROM_AMODAHL':
      return Object.assign({}, state, {
        message: 'Logging in to amodahl.no...',
        displayMessage: true,
        loading: true
      })
    case 'REQUEST_TOKEN_FROM_SIGNERE':
      return Object.assign({}, state, {
        message: 'Logging in with signere.no...',
        displayMessage: true,
        loading: true
      })
    case 'REQUEST_TOKEN_FROM_GOOGLE':
      return Object.assign({}, state, {
        message: 'Logging in with google...',
        displayMessage: true,
        loading: true
      })
    case 'RECEIVE_TOKEN_FROM_AMODAHL':
      return Object.assign({}, state, {
        name: action.name,
        email: action.email,
        message: `You logged in as ${action.name}.`,
        displayMessage: true,
        loading: false
      })
    case 'RECEIVE_TOKEN_FROM_LOCAL_STORAGE':
      return Object.assign({}, state, {
        name: action.name,
        email: action.email,
        message: `You logged in as ${action.name}.`,
        displayMessage: true,
        loading: false
      })
    case 'REQUEST_TOKEN_FAILED':
      return Object.assign({}, state, {
        name: null,
        email: null,
        message: action.message,
        displayMessage: action.displayMessage,
        loading: false
      })
    case '@@login/DELETE_TOKEN':
      return Object.assign({}, state, {
        name: null,
        email: null,
        message: 'You logged out.',
        displayMessage: true
      })
    case '@@me/DELETE_TOKEN':
      return Object.assign({}, state, {
        name: null,
        email: null,
        message: null,
        displayMessage: false
      })
    default:
      return state
  }
}
<commit_msg>Changed some actions<commit_after>const initialState = {
  name: null,
  message: null,
  displayMessage: true,
  email: null,
  history: []
}

export default function update (state = initialState, action) {
  switch (action.type) {
    case '@@router/LOCATION_CHANGE': {
      let history = state.history.slice(0, 10)
      history.push(action.payload.pathname)

      return Object.assign({}, state, {
        history: history
      })
    }
    case 'UPDATE_LOGIN_INFO':
      return Object.assign({}, state, {
        message: action.message,
        displayMessage: action.displayMessage,
        loading: action.loading
      })
    case 'RECEIVE_AMODAHL_TOKEN':
      return Object.assign({}, state, {
        name: action.name,
        email: action.email
      })
    case '@@login/DELETE_AMODAHL_TOKEN':
      return Object.assign({}, state, {
        name: null,
        email: null,
        message: 'You logged out.',
        displayMessage: true
      })
    case '@@me/DELETE_AMODAHL_TOKEN':
      return Object.assign({}, state, {
        name: null,
        email: null,
        message: null,
        displayMessage: false
      })
    default:
      return state
  }
}
<|endoftext|>