Apigee BaaS:使用usergrid node.js创建多个实体sdk不起作用

时间:2014-06-20 17:26:45

标签: node.js apigee

我正在使用Apigee BaaS。从UI,即apigee.com/appservices,我可以使用JSON数组同时创建多个实体。例如,json数组在集合/雇员上创建了三个实体。

    [
        {
            "name": "John",
            "employeeId": "1"
        },
        {
            "name": "Doe",
            "employeeId": "2"
        },
        {
            "name": "Danny",
            "employeeId": "3"
        }
    ]

现在我尝试使用nodeJs SDK模拟相同的内容 - https://github.com/usergrid/usergrid/tree/master/sdks/nodejs

        client.createEntity(options, function(err, entity) {
            if (err) {
                //error - entity not created
            } else {
                    //set is additive, so previously set properties are not overwritten
                entity.set(entityJsonArr);

                //finally, call save on the object to save it back to the database
                entity.save(function(err) {
                    if (err) {
                        //error - entity not saved
                        console.log('failure');
                    } else {
                        //success - new entity is saved
                        console.log('success');
                    }
                });
            }
        });

这无助于同时创建多个实体。方法createCollection创建一个集合,而不一定是一堆实体。有人可以帮我这个吗?

或者我应该继续使用请求并在Apigee BaaS上发布HTTP帖子?在那种情况下,我不会使用sdk。

1 个答案:

答案 0 :(得分:2)

你是对的,现有的Node SDK不能处理这种情况。如果您需要并且对您有用,我现在使用以下猴子补丁来解决这个问题:

var Usergrid = require('usergrid');

Usergrid.client.prototype.batchCreate = function (type, entities, callback) {
  if (!entities.length) { callback(); }

  var data = _.map(entities, function(entity) {
    var data = (entity instanceof Usergrid.entity) ? entity.get() : entity;
    return _.omit(data, 'metadata', 'created', 'modified', 'type', 'activated');
  });

  var options =  {
    method: 'POST',
    endpoint: type,
    body: data
  };

  var self = this;
  this.request(options, function (err, data) {
    if (err && self.logging) {
      console.log('could not save entities');
      if (typeof(callback) === 'function') { callback(err, data); }
      return;
    }

    var entities = _.map(data.entities, function(data) {
      var options = {
        type: type,
        client: self,
        uuid: data.uuid,
        data: data || {}
      };
      var entity = new Usergrid.entity(options);
      entity._json = JSON.stringify(options.data, null, 2);
      return entity;
    });

    if (typeof(callback) === 'function') {
      return callback(err, entities);
    }
  });
};