nodejs訪問redis時的key helper封裝

前言

key helper主要負責(zé)以下內(nèi)容

  • 定義redis訪問時所需要的所有keypattern
  • 提供從key pattern中獲取實際key的函數(shù)
    如從'0x90:user:#userID#:score:#corseID#''0x90:user:0001:score:01'
  • 提供了從指定key pattern中獲取指定字段的值

定義key pattern

module.exports = {
  master: 'master',
  user: {
    count: '0x01:user:total',
    name: '0x01:user:#userID#',
    score: *'0x90:user:#userID#:score:#corseID#'
    getUserId: function(name) {
      return name.split(':')[2];
    },
    getCorseId: function(score) {
      return score.split(':')[4];
    },
  }
  // 省略
}

定義key pattern的轉(zhuǎn)換函數(shù)

module.exports = {
  // 省略
  getKey: function(key, json) {
    var params = key.match(/#.*?#/g);
    params.forEach(function(param, index) {
      var jsonKey = param.replace(/#/g, '');
      if (json[jsonKey] === undefined) {
        throw new Error('Invalid redis key...KEY:' + key + ' PARAMS:' +
          json);
      }
      key = key.replace(param, json[jsonKey]);
    });
    return key;
  }
}

調(diào)用方法

var keyHelper = require('./keyHelper');
var key = keyHelper.getKey(keyHelper.user.score, {
          userID: 0001,
          corseID: 01
        })
// redis訪問處理略

完整代碼如下

// keyHelper.js
module.exports = {
  master: 'master',
  user: {
    count: '0x01:user:total',
    name: '0x01:user:#userID#',
    score: *'0x90:user:#userID#:score:#corseID#'
    getUserId: function(name) {
      return name.split(':')[2];
    },
    getCorseId: function(score) {
      return score.split(':')[4];
    },
  }
  getKey: function(key, json) {
    var params = key.match(/#.*?#/g);
    params.forEach(function(param, index) {
      var jsonKey = param.replace(/#/g, '');
      if (json[jsonKey] === undefined) {
        throw new Error('Invalid redis key...KEY:' + key + ' PARAMS:' +
          json);
      }
      key = key.replace(param, json[jsonKey]);
    });
    return key;
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容