有没有什么方法可以重构这个sails.js模型代码?

时间:2014-07-29 03:25:02

标签: javascript node.js sails.js

我以前是Rubyist,但现在我正在开发一个与Redis集成的Sails.js网站。下面是我从中删除的一些代码。它有效,但我不那么自信。我们都知道重复是邪恶的。什么是减少此代码中重复数量的正确方法?

// X Y Z W is faked for privacy 
childKey: function(userID) {
    return "X:" + userID +":Y:" + this.id 
},

parentKey: function(userID) {
    return "X:" + userID + ":Z:" + this.id
},

caseKey: function(userID) {
  return "X:" + userID + ":W:" this.id
},

// set is a noun
setMember: function(key, callback) {
    return client.smembers(key, callback);
},

setAdd: function(key, val) {
    return client.sadd(key, val.id, function(err, res){});
},


children: function(userID, callback) {
    return this.setMember(this.childKey(userID), callback);
},

parent: function(userID, callback) {
    return this.setMember(this.parentKey(userID), callback);
},

leaves: function(userID, callback) {
  return this.setMember(this.caseKey(userID), callback);
},


addChild: function(userID, dir) {
    return this.setAdd(this.childKey(userID), dir);
},

addParent: function(userID, dir) {
    return this.setAdd(this.parentKey(userID), dir);
},

addLeaf: function(userID, theCase) {
  return this.setAdd(this.caseKey(userID), theCase);
}

1 个答案:

答案 0 :(得分:0)

这个怎么样:

var MySet = {
  // some properties (id, clients, etc.)
  // list of items keys
  _itemKeys: { child: 'Y', parent: 'Z', leaf: 'W' },

  // private methods
  _getKey: function(type, userId) {
    return "X:" + userId + ":" + this._itemKeys[type] + ":" this.id
  },

  _setMember: function(key, callback) {
    return this.client.smembers(key, callback);
  },

  _setAdd: function(key, val) {
    return this.client.sadd(key, val.id, function(err, res) {});
  },

  // public methods
  add: function(type, userId, param) {
    return this._setAdd(this._getKey(type, userId), param);
  },

  member: function(type, userId, callback) {
    return this._setMember(this._getKey(type, userID), callback);
  }
};

现在您可以通过以下方式使用它:

MySet.add('child', 1, param);
MySet.add('parent', 1, param);
MySet.add('leaf', 1, param);

MySet.member('child', 1, function() {});
MySet.member('parent', 1, function() {});
MySet.member('leaf', 1, function() {});

希望有所帮助。