nodejs访问redis时的key helper封装
2016-07-26 本文已影响0人
tpglzu
前言
key helper
主要负责以下内容
- 定义redis访问时所需要的所有
key
的pattern
- 提供从
key pattern
中获取实际key
的函数
如从'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的转换函数
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;
}
}
调用方法
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;
}
}